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 "CGRecordLayout.h" 19 #include "CodeGenFunction.h" 20 #include "CodeGenModule.h" 21 #include "ConstantEmitter.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/DeclFriend.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/DeclTemplate.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/RecordLayout.h" 28 #include "clang/Basic/FileManager.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/Version.h" 31 #include "clang/Frontend/CodeGenOptions.h" 32 #include "clang/Frontend/FrontendOptions.h" 33 #include "clang/Lex/HeaderSearchOptions.h" 34 #include "clang/Lex/ModuleMap.h" 35 #include "clang/Lex/PreprocessorOptions.h" 36 #include "llvm/ADT/DenseSet.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DerivedTypes.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/Intrinsics.h" 44 #include "llvm/IR/Metadata.h" 45 #include "llvm/IR/Module.h" 46 #include "llvm/Support/FileSystem.h" 47 #include "llvm/Support/MD5.h" 48 #include "llvm/Support/Path.h" 49 using namespace clang; 50 using namespace clang::CodeGen; 51 52 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) { 53 auto TI = Ctx.getTypeInfo(Ty); 54 return TI.AlignIsRequired ? TI.Align : 0; 55 } 56 57 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) { 58 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx); 59 } 60 61 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) { 62 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0; 63 } 64 65 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 66 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()), 67 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs), 68 DBuilder(CGM.getModule()) { 69 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap) 70 DebugPrefixMap[KV.first] = KV.second; 71 CreateCompileUnit(); 72 } 73 74 CGDebugInfo::~CGDebugInfo() { 75 assert(LexicalBlockStack.empty() && 76 "Region stack mismatch, stack not empty!"); 77 } 78 79 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, 80 SourceLocation TemporaryLocation) 81 : CGF(&CGF) { 82 init(TemporaryLocation); 83 } 84 85 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, 86 bool DefaultToEmpty, 87 SourceLocation TemporaryLocation) 88 : CGF(&CGF) { 89 init(TemporaryLocation, DefaultToEmpty); 90 } 91 92 void ApplyDebugLocation::init(SourceLocation TemporaryLocation, 93 bool DefaultToEmpty) { 94 auto *DI = CGF->getDebugInfo(); 95 if (!DI) { 96 CGF = nullptr; 97 return; 98 } 99 100 OriginalLocation = CGF->Builder.getCurrentDebugLocation(); 101 102 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled()) 103 return; 104 105 if (TemporaryLocation.isValid()) { 106 DI->EmitLocation(CGF->Builder, TemporaryLocation); 107 return; 108 } 109 110 if (DefaultToEmpty) { 111 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 112 return; 113 } 114 115 // Construct a location that has a valid scope, but no line info. 116 assert(!DI->LexicalBlockStack.empty()); 117 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 118 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt())); 119 } 120 121 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E) 122 : CGF(&CGF) { 123 init(E->getExprLoc()); 124 } 125 126 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc) 127 : CGF(&CGF) { 128 if (!CGF.getDebugInfo()) { 129 this->CGF = nullptr; 130 return; 131 } 132 OriginalLocation = CGF.Builder.getCurrentDebugLocation(); 133 if (Loc) 134 CGF.Builder.SetCurrentDebugLocation(std::move(Loc)); 135 } 136 137 ApplyDebugLocation::~ApplyDebugLocation() { 138 // Query CGF so the location isn't overwritten when location updates are 139 // temporarily disabled (for C++ default function arguments) 140 if (CGF) 141 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation)); 142 } 143 144 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF, 145 GlobalDecl InlinedFn) 146 : CGF(&CGF) { 147 if (!CGF.getDebugInfo()) { 148 this->CGF = nullptr; 149 return; 150 } 151 auto &DI = *CGF.getDebugInfo(); 152 SavedLocation = DI.getLocation(); 153 assert((DI.getInlinedAt() == 154 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) && 155 "CGDebugInfo and IRBuilder are out of sync"); 156 157 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn); 158 } 159 160 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() { 161 if (!CGF) 162 return; 163 auto &DI = *CGF->getDebugInfo(); 164 DI.EmitInlineFunctionEnd(CGF->Builder); 165 DI.EmitLocation(CGF->Builder, SavedLocation); 166 } 167 168 void CGDebugInfo::setLocation(SourceLocation Loc) { 169 // If the new location isn't valid return. 170 if (Loc.isInvalid()) 171 return; 172 173 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc); 174 175 // If we've changed files in the middle of a lexical scope go ahead 176 // and create a new lexical scope with file node if it's different 177 // from the one in the scope. 178 if (LexicalBlockStack.empty()) 179 return; 180 181 SourceManager &SM = CGM.getContext().getSourceManager(); 182 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 183 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 184 185 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename()) 186 return; 187 188 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) { 189 LexicalBlockStack.pop_back(); 190 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile( 191 LBF->getScope(), getOrCreateFile(CurLoc))); 192 } else if (isa<llvm::DILexicalBlock>(Scope) || 193 isa<llvm::DISubprogram>(Scope)) { 194 LexicalBlockStack.pop_back(); 195 LexicalBlockStack.emplace_back( 196 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc))); 197 } 198 } 199 200 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) { 201 llvm::DIScope *Mod = getParentModuleOrNull(D); 202 return getContextDescriptor(cast<Decl>(D->getDeclContext()), 203 Mod ? Mod : TheCU); 204 } 205 206 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context, 207 llvm::DIScope *Default) { 208 if (!Context) 209 return Default; 210 211 auto I = RegionMap.find(Context); 212 if (I != RegionMap.end()) { 213 llvm::Metadata *V = I->second; 214 return dyn_cast_or_null<llvm::DIScope>(V); 215 } 216 217 // Check namespace. 218 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context)) 219 return getOrCreateNamespace(NSDecl); 220 221 if (const auto *RDecl = dyn_cast<RecordDecl>(Context)) 222 if (!RDecl->isDependentType()) 223 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 224 getOrCreateMainFile()); 225 return Default; 226 } 227 228 PrintingPolicy CGDebugInfo::getPrintingPolicy() const { 229 PrintingPolicy PP = CGM.getContext().getPrintingPolicy(); 230 231 // If we're emitting codeview, it's important to try to match MSVC's naming so 232 // that visualizers written for MSVC will trigger for our class names. In 233 // particular, we can't have spaces between arguments of standard templates 234 // like basic_string and vector. 235 if (CGM.getCodeGenOpts().EmitCodeView) 236 PP.MSVCFormatting = true; 237 238 return PP; 239 } 240 241 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 242 assert(FD && "Invalid FunctionDecl!"); 243 IdentifierInfo *FII = FD->getIdentifier(); 244 FunctionTemplateSpecializationInfo *Info = 245 FD->getTemplateSpecializationInfo(); 246 247 // Emit the unqualified name in normal operation. LLVM and the debugger can 248 // compute the fully qualified name from the scope chain. If we're only 249 // emitting line table info, there won't be any scope chains, so emit the 250 // fully qualified name here so that stack traces are more accurate. 251 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after 252 // evaluating the size impact. 253 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly && 254 CGM.getCodeGenOpts().EmitCodeView; 255 256 if (!Info && FII && !UseQualifiedName) 257 return FII->getName(); 258 259 SmallString<128> NS; 260 llvm::raw_svector_ostream OS(NS); 261 if (!UseQualifiedName) 262 FD->printName(OS); 263 else 264 FD->printQualifiedName(OS, getPrintingPolicy()); 265 266 // Add any template specialization args. 267 if (Info) { 268 const TemplateArgumentList *TArgs = Info->TemplateArguments; 269 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy()); 270 } 271 272 // Copy this name on the side and use its reference. 273 return internString(OS.str()); 274 } 275 276 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 277 SmallString<256> MethodName; 278 llvm::raw_svector_ostream OS(MethodName); 279 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 280 const DeclContext *DC = OMD->getDeclContext(); 281 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) { 282 OS << OID->getName(); 283 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) { 284 OS << OID->getName(); 285 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) { 286 if (OC->IsClassExtension()) { 287 OS << OC->getClassInterface()->getName(); 288 } else { 289 OS << OC->getIdentifier()->getNameStart() << '(' 290 << OC->getIdentifier()->getNameStart() << ')'; 291 } 292 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) { 293 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')'; 294 } else if (isa<ObjCProtocolDecl>(DC)) { 295 // We can extract the type of the class from the self pointer. 296 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) { 297 QualType ClassTy = 298 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType(); 299 ClassTy.print(OS, PrintingPolicy(LangOptions())); 300 } 301 } 302 OS << ' ' << OMD->getSelector().getAsString() << ']'; 303 304 return internString(OS.str()); 305 } 306 307 StringRef CGDebugInfo::getSelectorName(Selector S) { 308 return internString(S.getAsString()); 309 } 310 311 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) { 312 if (isa<ClassTemplateSpecializationDecl>(RD)) { 313 SmallString<128> Name; 314 llvm::raw_svector_ostream OS(Name); 315 RD->getNameForDiagnostic(OS, getPrintingPolicy(), 316 /*Qualified*/ false); 317 318 // Copy this name on the side and use its reference. 319 return internString(Name); 320 } 321 322 // quick optimization to avoid having to intern strings that are already 323 // stored reliably elsewhere 324 if (const IdentifierInfo *II = RD->getIdentifier()) 325 return II->getName(); 326 327 // The CodeView printer in LLVM wants to see the names of unnamed types: it is 328 // used to reconstruct the fully qualified type names. 329 if (CGM.getCodeGenOpts().EmitCodeView) { 330 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) { 331 assert(RD->getDeclContext() == D->getDeclContext() && 332 "Typedef should not be in another decl context!"); 333 assert(D->getDeclName().getAsIdentifierInfo() && 334 "Typedef was not named!"); 335 return D->getDeclName().getAsIdentifierInfo()->getName(); 336 } 337 338 if (CGM.getLangOpts().CPlusPlus) { 339 StringRef Name; 340 341 ASTContext &Context = CGM.getContext(); 342 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD)) 343 // Anonymous types without a name for linkage purposes have their 344 // declarator mangled in if they have one. 345 Name = DD->getName(); 346 else if (const TypedefNameDecl *TND = 347 Context.getTypedefNameForUnnamedTagDecl(RD)) 348 // Anonymous types without a name for linkage purposes have their 349 // associate typedef mangled in if they have one. 350 Name = TND->getName(); 351 352 if (!Name.empty()) { 353 SmallString<256> UnnamedType("<unnamed-type-"); 354 UnnamedType += Name; 355 UnnamedType += '>'; 356 return internString(UnnamedType); 357 } 358 } 359 } 360 361 return StringRef(); 362 } 363 364 Optional<llvm::DIFile::ChecksumKind> 365 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const { 366 Checksum.clear(); 367 368 if (!CGM.getCodeGenOpts().EmitCodeView && 369 CGM.getCodeGenOpts().DwarfVersion < 5) 370 return None; 371 372 SourceManager &SM = CGM.getContext().getSourceManager(); 373 bool Invalid; 374 llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid); 375 if (Invalid) 376 return None; 377 378 llvm::MD5 Hash; 379 llvm::MD5::MD5Result Result; 380 381 Hash.update(MemBuffer->getBuffer()); 382 Hash.final(Result); 383 384 Hash.stringifyResult(Result, Checksum); 385 return llvm::DIFile::CSK_MD5; 386 } 387 388 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM, 389 FileID FID) { 390 if (!CGM.getCodeGenOpts().EmbedSource) 391 return None; 392 393 bool SourceInvalid = false; 394 StringRef Source = SM.getBufferData(FID, &SourceInvalid); 395 396 if (SourceInvalid) 397 return None; 398 399 return Source; 400 } 401 402 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 403 if (!Loc.isValid()) 404 // If Location is not valid then use main input file. 405 return getOrCreateMainFile(); 406 407 SourceManager &SM = CGM.getContext().getSourceManager(); 408 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 409 410 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty()) 411 // If the location is not valid then use main input file. 412 return getOrCreateMainFile(); 413 414 // Cache the results. 415 const char *fname = PLoc.getFilename(); 416 auto It = DIFileCache.find(fname); 417 418 if (It != DIFileCache.end()) { 419 // Verify that the information still exists. 420 if (llvm::Metadata *V = It->second) 421 return cast<llvm::DIFile>(V); 422 } 423 424 SmallString<32> Checksum; 425 Optional<llvm::DIFile::ChecksumKind> CSKind = 426 computeChecksum(SM.getFileID(Loc), Checksum); 427 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo; 428 if (CSKind) 429 CSInfo.emplace(*CSKind, Checksum); 430 431 llvm::DIFile *F = DBuilder.createFile( 432 remapDIPath(PLoc.getFilename()), remapDIPath(getCurrentDirname()), CSInfo, 433 getSource(SM, SM.getFileID(Loc))); 434 435 DIFileCache[fname].reset(F); 436 return F; 437 } 438 439 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() { 440 return DBuilder.createFile( 441 remapDIPath(TheCU->getFilename()), remapDIPath(TheCU->getDirectory()), 442 TheCU->getFile()->getChecksum(), 443 CGM.getCodeGenOpts().EmbedSource ? TheCU->getSource() : None); 444 } 445 446 std::string CGDebugInfo::remapDIPath(StringRef Path) const { 447 for (const auto &Entry : DebugPrefixMap) 448 if (Path.startswith(Entry.first)) 449 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str(); 450 return Path.str(); 451 } 452 453 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 454 if (Loc.isInvalid() && CurLoc.isInvalid()) 455 return 0; 456 SourceManager &SM = CGM.getContext().getSourceManager(); 457 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 458 return PLoc.isValid() ? PLoc.getLine() : 0; 459 } 460 461 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { 462 // We may not want column information at all. 463 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) 464 return 0; 465 466 // If the location is invalid then use the current column. 467 if (Loc.isInvalid() && CurLoc.isInvalid()) 468 return 0; 469 SourceManager &SM = CGM.getContext().getSourceManager(); 470 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 471 return PLoc.isValid() ? PLoc.getColumn() : 0; 472 } 473 474 StringRef CGDebugInfo::getCurrentDirname() { 475 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) 476 return CGM.getCodeGenOpts().DebugCompilationDir; 477 478 if (!CWDName.empty()) 479 return CWDName; 480 SmallString<256> CWD; 481 llvm::sys::fs::current_path(CWD); 482 return CWDName = internString(CWD); 483 } 484 485 void CGDebugInfo::CreateCompileUnit() { 486 SmallString<32> Checksum; 487 Optional<llvm::DIFile::ChecksumKind> CSKind; 488 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo; 489 490 // Should we be asking the SourceManager for the main file name, instead of 491 // accepting it as an argument? This just causes the main file name to 492 // mismatch with source locations and create extra lexical scopes or 493 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what 494 // the driver passed, but functions/other things have DW_AT_file of "<stdin>" 495 // because that's what the SourceManager says) 496 497 // Get absolute path name. 498 SourceManager &SM = CGM.getContext().getSourceManager(); 499 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 500 if (MainFileName.empty()) 501 MainFileName = "<stdin>"; 502 503 // The main file name provided via the "-main-file-name" option contains just 504 // the file name itself with no path information. This file name may have had 505 // a relative path, so we look into the actual file entry for the main 506 // file to determine the real absolute path for the file. 507 std::string MainFileDir; 508 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 509 MainFileDir = remapDIPath(MainFile->getDir()->getName()); 510 if (MainFileDir != ".") { 511 llvm::SmallString<1024> MainFileDirSS(MainFileDir); 512 llvm::sys::path::append(MainFileDirSS, MainFileName); 513 MainFileName = MainFileDirSS.str(); 514 } 515 // If the main file name provided is identical to the input file name, and 516 // if the input file is a preprocessed source, use the module name for 517 // debug info. The module name comes from the name specified in the first 518 // linemarker if the input is a preprocessed source. 519 if (MainFile->getName() == MainFileName && 520 FrontendOptions::getInputKindForExtension( 521 MainFile->getName().rsplit('.').second) 522 .isPreprocessed()) 523 MainFileName = CGM.getModule().getName().str(); 524 525 CSKind = computeChecksum(SM.getMainFileID(), Checksum); 526 } 527 528 llvm::dwarf::SourceLanguage LangTag; 529 const LangOptions &LO = CGM.getLangOpts(); 530 if (LO.CPlusPlus) { 531 if (LO.ObjC) 532 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 533 else 534 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 535 } else if (LO.ObjC) { 536 LangTag = llvm::dwarf::DW_LANG_ObjC; 537 } else if (LO.RenderScript) { 538 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript; 539 } else if (LO.C99) { 540 LangTag = llvm::dwarf::DW_LANG_C99; 541 } else { 542 LangTag = llvm::dwarf::DW_LANG_C89; 543 } 544 545 std::string Producer = getClangFullVersion(); 546 547 // Figure out which version of the ObjC runtime we have. 548 unsigned RuntimeVers = 0; 549 if (LO.ObjC) 550 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; 551 552 llvm::DICompileUnit::DebugEmissionKind EmissionKind; 553 switch (DebugKind) { 554 case codegenoptions::NoDebugInfo: 555 case codegenoptions::LocTrackingOnly: 556 EmissionKind = llvm::DICompileUnit::NoDebug; 557 break; 558 case codegenoptions::DebugLineTablesOnly: 559 EmissionKind = llvm::DICompileUnit::LineTablesOnly; 560 break; 561 case codegenoptions::DebugDirectivesOnly: 562 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly; 563 break; 564 case codegenoptions::LimitedDebugInfo: 565 case codegenoptions::FullDebugInfo: 566 EmissionKind = llvm::DICompileUnit::FullDebug; 567 break; 568 } 569 570 if (CSKind) 571 CSInfo.emplace(*CSKind, Checksum); 572 573 // Create new compile unit. 574 // FIXME - Eliminate TheCU. 575 auto &CGOpts = CGM.getCodeGenOpts(); 576 TheCU = DBuilder.createCompileUnit( 577 LangTag, 578 DBuilder.createFile(remapDIPath(MainFileName), 579 remapDIPath(getCurrentDirname()), CSInfo, 580 getSource(SM, SM.getMainFileID())), 581 CGOpts.EmitVersionIdentMetadata ? Producer : "", 582 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO, 583 CGOpts.DwarfDebugFlags, RuntimeVers, 584 (CGOpts.getSplitDwarfMode() != CodeGenOptions::NoFission) 585 ? "" 586 : CGOpts.SplitDwarfFile, 587 EmissionKind, 0 /* DWOid */, CGOpts.SplitDwarfInlining, 588 CGOpts.DebugInfoForProfiling, 589 CGM.getTarget().getTriple().isNVPTX() 590 ? llvm::DICompileUnit::DebugNameTableKind::None 591 : static_cast<llvm::DICompileUnit::DebugNameTableKind>( 592 CGOpts.DebugNameTable), 593 CGOpts.DebugRangesBaseAddress); 594 } 595 596 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) { 597 llvm::dwarf::TypeKind Encoding; 598 StringRef BTName; 599 switch (BT->getKind()) { 600 #define BUILTIN_TYPE(Id, SingletonId) 601 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 602 #include "clang/AST/BuiltinTypes.def" 603 case BuiltinType::Dependent: 604 llvm_unreachable("Unexpected builtin type"); 605 case BuiltinType::NullPtr: 606 return DBuilder.createNullPtrType(); 607 case BuiltinType::Void: 608 return nullptr; 609 case BuiltinType::ObjCClass: 610 if (!ClassTy) 611 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 612 "objc_class", TheCU, 613 getOrCreateMainFile(), 0); 614 return ClassTy; 615 case BuiltinType::ObjCId: { 616 // typedef struct objc_class *Class; 617 // typedef struct objc_object { 618 // Class isa; 619 // } *id; 620 621 if (ObjTy) 622 return ObjTy; 623 624 if (!ClassTy) 625 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 626 "objc_class", TheCU, 627 getOrCreateMainFile(), 0); 628 629 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 630 631 auto *ISATy = DBuilder.createPointerType(ClassTy, Size); 632 633 ObjTy = DBuilder.createStructType( 634 TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0, 635 llvm::DINode::FlagZero, nullptr, llvm::DINodeArray()); 636 637 DBuilder.replaceArrays( 638 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType( 639 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 640 llvm::DINode::FlagZero, ISATy))); 641 return ObjTy; 642 } 643 case BuiltinType::ObjCSel: { 644 if (!SelTy) 645 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 646 "objc_selector", TheCU, 647 getOrCreateMainFile(), 0); 648 return SelTy; 649 } 650 651 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 652 case BuiltinType::Id: \ 653 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \ 654 SingletonId); 655 #include "clang/Basic/OpenCLImageTypes.def" 656 case BuiltinType::OCLSampler: 657 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy); 658 case BuiltinType::OCLEvent: 659 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy); 660 case BuiltinType::OCLClkEvent: 661 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy); 662 case BuiltinType::OCLQueue: 663 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy); 664 case BuiltinType::OCLReserveID: 665 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy); 666 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 667 case BuiltinType::Id: \ 668 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty); 669 #include "clang/Basic/OpenCLExtensionTypes.def" 670 671 case BuiltinType::UChar: 672 case BuiltinType::Char_U: 673 Encoding = llvm::dwarf::DW_ATE_unsigned_char; 674 break; 675 case BuiltinType::Char_S: 676 case BuiltinType::SChar: 677 Encoding = llvm::dwarf::DW_ATE_signed_char; 678 break; 679 case BuiltinType::Char8: 680 case BuiltinType::Char16: 681 case BuiltinType::Char32: 682 Encoding = llvm::dwarf::DW_ATE_UTF; 683 break; 684 case BuiltinType::UShort: 685 case BuiltinType::UInt: 686 case BuiltinType::UInt128: 687 case BuiltinType::ULong: 688 case BuiltinType::WChar_U: 689 case BuiltinType::ULongLong: 690 Encoding = llvm::dwarf::DW_ATE_unsigned; 691 break; 692 case BuiltinType::Short: 693 case BuiltinType::Int: 694 case BuiltinType::Int128: 695 case BuiltinType::Long: 696 case BuiltinType::WChar_S: 697 case BuiltinType::LongLong: 698 Encoding = llvm::dwarf::DW_ATE_signed; 699 break; 700 case BuiltinType::Bool: 701 Encoding = llvm::dwarf::DW_ATE_boolean; 702 break; 703 case BuiltinType::Half: 704 case BuiltinType::Float: 705 case BuiltinType::LongDouble: 706 case BuiltinType::Float16: 707 case BuiltinType::Float128: 708 case BuiltinType::Double: 709 // FIXME: For targets where long double and __float128 have the same size, 710 // they are currently indistinguishable in the debugger without some 711 // special treatment. However, there is currently no consensus on encoding 712 // and this should be updated once a DWARF encoding exists for distinct 713 // floating point types of the same size. 714 Encoding = llvm::dwarf::DW_ATE_float; 715 break; 716 case BuiltinType::ShortAccum: 717 case BuiltinType::Accum: 718 case BuiltinType::LongAccum: 719 case BuiltinType::ShortFract: 720 case BuiltinType::Fract: 721 case BuiltinType::LongFract: 722 case BuiltinType::SatShortFract: 723 case BuiltinType::SatFract: 724 case BuiltinType::SatLongFract: 725 case BuiltinType::SatShortAccum: 726 case BuiltinType::SatAccum: 727 case BuiltinType::SatLongAccum: 728 Encoding = llvm::dwarf::DW_ATE_signed_fixed; 729 break; 730 case BuiltinType::UShortAccum: 731 case BuiltinType::UAccum: 732 case BuiltinType::ULongAccum: 733 case BuiltinType::UShortFract: 734 case BuiltinType::UFract: 735 case BuiltinType::ULongFract: 736 case BuiltinType::SatUShortAccum: 737 case BuiltinType::SatUAccum: 738 case BuiltinType::SatULongAccum: 739 case BuiltinType::SatUShortFract: 740 case BuiltinType::SatUFract: 741 case BuiltinType::SatULongFract: 742 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed; 743 break; 744 } 745 746 switch (BT->getKind()) { 747 case BuiltinType::Long: 748 BTName = "long int"; 749 break; 750 case BuiltinType::LongLong: 751 BTName = "long long int"; 752 break; 753 case BuiltinType::ULong: 754 BTName = "long unsigned int"; 755 break; 756 case BuiltinType::ULongLong: 757 BTName = "long long unsigned int"; 758 break; 759 default: 760 BTName = BT->getName(CGM.getLangOpts()); 761 break; 762 } 763 // Bit size and offset of the type. 764 uint64_t Size = CGM.getContext().getTypeSize(BT); 765 return DBuilder.createBasicType(BTName, Size, Encoding); 766 } 767 768 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) { 769 // Bit size and offset of the type. 770 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float; 771 if (Ty->isComplexIntegerType()) 772 Encoding = llvm::dwarf::DW_ATE_lo_user; 773 774 uint64_t Size = CGM.getContext().getTypeSize(Ty); 775 return DBuilder.createBasicType("complex", Size, Encoding); 776 } 777 778 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty, 779 llvm::DIFile *Unit) { 780 QualifierCollector Qc; 781 const Type *T = Qc.strip(Ty); 782 783 // Ignore these qualifiers for now. 784 Qc.removeObjCGCAttr(); 785 Qc.removeAddressSpace(); 786 Qc.removeObjCLifetime(); 787 788 // We will create one Derived type for one qualifier and recurse to handle any 789 // additional ones. 790 llvm::dwarf::Tag Tag; 791 if (Qc.hasConst()) { 792 Tag = llvm::dwarf::DW_TAG_const_type; 793 Qc.removeConst(); 794 } else if (Qc.hasVolatile()) { 795 Tag = llvm::dwarf::DW_TAG_volatile_type; 796 Qc.removeVolatile(); 797 } else if (Qc.hasRestrict()) { 798 Tag = llvm::dwarf::DW_TAG_restrict_type; 799 Qc.removeRestrict(); 800 } else { 801 assert(Qc.empty() && "Unknown type qualifier for debug info"); 802 return getOrCreateType(QualType(T, 0), Unit); 803 } 804 805 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit); 806 807 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 808 // CVR derived types. 809 return DBuilder.createQualifiedType(Tag, FromTy); 810 } 811 812 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 813 llvm::DIFile *Unit) { 814 815 // The frontend treats 'id' as a typedef to an ObjCObjectType, 816 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the 817 // debug info, we want to emit 'id' in both cases. 818 if (Ty->isObjCQualifiedIdType()) 819 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit); 820 821 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 822 Ty->getPointeeType(), Unit); 823 } 824 825 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty, 826 llvm::DIFile *Unit) { 827 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 828 Ty->getPointeeType(), Unit); 829 } 830 831 /// \return whether a C++ mangling exists for the type defined by TD. 832 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) { 833 switch (TheCU->getSourceLanguage()) { 834 case llvm::dwarf::DW_LANG_C_plus_plus: 835 return true; 836 case llvm::dwarf::DW_LANG_ObjC_plus_plus: 837 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD); 838 default: 839 return false; 840 } 841 } 842 843 // Determines if the debug info for this tag declaration needs a type 844 // identifier. The purpose of the unique identifier is to deduplicate type 845 // information for identical types across TUs. Because of the C++ one definition 846 // rule (ODR), it is valid to assume that the type is defined the same way in 847 // every TU and its debug info is equivalent. 848 // 849 // C does not have the ODR, and it is common for codebases to contain multiple 850 // different definitions of a struct with the same name in different TUs. 851 // Therefore, if the type doesn't have a C++ mangling, don't give it an 852 // identifer. Type information in C is smaller and simpler than C++ type 853 // information, so the increase in debug info size is negligible. 854 // 855 // If the type is not externally visible, it should be unique to the current TU, 856 // and should not need an identifier to participate in type deduplication. 857 // However, when emitting CodeView, the format internally uses these 858 // unique type name identifers for references between debug info. For example, 859 // the method of a class in an anonymous namespace uses the identifer to refer 860 // to its parent class. The Microsoft C++ ABI attempts to provide unique names 861 // for such types, so when emitting CodeView, always use identifiers for C++ 862 // types. This may create problems when attempting to emit CodeView when the MS 863 // C++ ABI is not in use. 864 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, 865 llvm::DICompileUnit *TheCU) { 866 // We only add a type identifier for types with C++ name mangling. 867 if (!hasCXXMangling(TD, TheCU)) 868 return false; 869 870 // Externally visible types with C++ mangling need a type identifier. 871 if (TD->isExternallyVisible()) 872 return true; 873 874 // CodeView types with C++ mangling need a type identifier. 875 if (CGM.getCodeGenOpts().EmitCodeView) 876 return true; 877 878 return false; 879 } 880 881 // Returns a unique type identifier string if one exists, or an empty string. 882 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, 883 llvm::DICompileUnit *TheCU) { 884 SmallString<256> Identifier; 885 const TagDecl *TD = Ty->getDecl(); 886 887 if (!needsTypeIdentifier(TD, CGM, TheCU)) 888 return Identifier; 889 890 // TODO: This is using the RTTI name. Is there a better way to get 891 // a unique string for a type? 892 llvm::raw_svector_ostream Out(Identifier); 893 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out); 894 return Identifier; 895 } 896 897 /// \return the appropriate DWARF tag for a composite type. 898 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) { 899 llvm::dwarf::Tag Tag; 900 if (RD->isStruct() || RD->isInterface()) 901 Tag = llvm::dwarf::DW_TAG_structure_type; 902 else if (RD->isUnion()) 903 Tag = llvm::dwarf::DW_TAG_union_type; 904 else { 905 // FIXME: This could be a struct type giving a default visibility different 906 // than C++ class type, but needs llvm metadata changes first. 907 assert(RD->isClass()); 908 Tag = llvm::dwarf::DW_TAG_class_type; 909 } 910 return Tag; 911 } 912 913 llvm::DICompositeType * 914 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, 915 llvm::DIScope *Ctx) { 916 const RecordDecl *RD = Ty->getDecl(); 917 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD))) 918 return cast<llvm::DICompositeType>(T); 919 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 920 unsigned Line = getLineNumber(RD->getLocation()); 921 StringRef RDName = getClassName(RD); 922 923 uint64_t Size = 0; 924 uint32_t Align = 0; 925 926 // Create the type. 927 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 928 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( 929 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, 930 llvm::DINode::FlagFwdDecl, Identifier); 931 if (CGM.getCodeGenOpts().DebugFwdTemplateParams) 932 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 933 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(), 934 CollectCXXTemplateParams(TSpecial, DefUnit)); 935 ReplaceMap.emplace_back( 936 std::piecewise_construct, std::make_tuple(Ty), 937 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 938 return RetTy; 939 } 940 941 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag, 942 const Type *Ty, 943 QualType PointeeTy, 944 llvm::DIFile *Unit) { 945 // Bit size, align and offset of the type. 946 // Size is always the size of a pointer. We can't use getTypeSize here 947 // because that does not return the correct value for references. 948 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy); 949 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace); 950 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 951 Optional<unsigned> DWARFAddressSpace = 952 CGM.getTarget().getDWARFAddressSpace(AddressSpace); 953 954 if (Tag == llvm::dwarf::DW_TAG_reference_type || 955 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) 956 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit), 957 Size, Align, DWARFAddressSpace); 958 else 959 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size, 960 Align, DWARFAddressSpace); 961 } 962 963 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name, 964 llvm::DIType *&Cache) { 965 if (Cache) 966 return Cache; 967 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, 968 TheCU, getOrCreateMainFile(), 0); 969 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 970 Cache = DBuilder.createPointerType(Cache, Size); 971 return Cache; 972 } 973 974 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer( 975 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy, 976 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) { 977 QualType FType; 978 979 // Advanced by calls to CreateMemberType in increments of FType, then 980 // returned as the overall size of the default elements. 981 uint64_t FieldOffset = 0; 982 983 // Blocks in OpenCL have unique constraints which make the standard fields 984 // redundant while requiring size and align fields for enqueue_kernel. See 985 // initializeForBlockHeader in CGBlocks.cpp 986 if (CGM.getLangOpts().OpenCL) { 987 FType = CGM.getContext().IntTy; 988 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 989 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset)); 990 } else { 991 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 992 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 993 FType = CGM.getContext().IntTy; 994 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 995 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 996 FType = CGM.getContext().getPointerType(Ty->getPointeeType()); 997 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 998 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 999 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty); 1000 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty); 1001 EltTys.push_back(DBuilder.createMemberType( 1002 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, 1003 FieldOffset, llvm::DINode::FlagZero, DescTy)); 1004 FieldOffset += FieldSize; 1005 } 1006 1007 return FieldOffset; 1008 } 1009 1010 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, 1011 llvm::DIFile *Unit) { 1012 SmallVector<llvm::Metadata *, 8> EltTys; 1013 QualType FType; 1014 uint64_t FieldOffset; 1015 llvm::DINodeArray Elements; 1016 1017 FieldOffset = 0; 1018 FType = CGM.getContext().UnsignedLongTy; 1019 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 1020 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 1021 1022 Elements = DBuilder.getOrCreateArray(EltTys); 1023 EltTys.clear(); 1024 1025 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock; 1026 1027 auto *EltTy = 1028 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0, 1029 FieldOffset, 0, Flags, nullptr, Elements); 1030 1031 // Bit size, align and offset of the type. 1032 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1033 1034 auto *DescTy = DBuilder.createPointerType(EltTy, Size); 1035 1036 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy, 1037 0, EltTys); 1038 1039 Elements = DBuilder.getOrCreateArray(EltTys); 1040 1041 // The __block_literal_generic structs are marked with a special 1042 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only 1043 // the debugger needs to know about. To allow type uniquing, emit 1044 // them without a name or a location. 1045 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0, 1046 Flags, nullptr, Elements); 1047 1048 return DBuilder.createPointerType(EltTy, Size); 1049 } 1050 1051 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, 1052 llvm::DIFile *Unit) { 1053 assert(Ty->isTypeAlias()); 1054 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit); 1055 1056 SmallString<128> NS; 1057 llvm::raw_svector_ostream OS(NS); 1058 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false); 1059 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy()); 1060 1061 auto *AliasDecl = 1062 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl()) 1063 ->getTemplatedDecl(); 1064 1065 SourceLocation Loc = AliasDecl->getLocation(); 1066 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc), 1067 getLineNumber(Loc), 1068 getDeclContextDescriptor(AliasDecl)); 1069 } 1070 1071 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty, 1072 llvm::DIFile *Unit) { 1073 // We don't set size information, but do specify where the typedef was 1074 // declared. 1075 SourceLocation Loc = Ty->getDecl()->getLocation(); 1076 1077 // Typedefs are derived from some other type. 1078 return DBuilder.createTypedef( 1079 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit), 1080 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc), 1081 getDeclContextDescriptor(Ty->getDecl())); 1082 } 1083 1084 static unsigned getDwarfCC(CallingConv CC) { 1085 switch (CC) { 1086 case CC_C: 1087 // Avoid emitting DW_AT_calling_convention if the C convention was used. 1088 return 0; 1089 1090 case CC_X86StdCall: 1091 return llvm::dwarf::DW_CC_BORLAND_stdcall; 1092 case CC_X86FastCall: 1093 return llvm::dwarf::DW_CC_BORLAND_msfastcall; 1094 case CC_X86ThisCall: 1095 return llvm::dwarf::DW_CC_BORLAND_thiscall; 1096 case CC_X86VectorCall: 1097 return llvm::dwarf::DW_CC_LLVM_vectorcall; 1098 case CC_X86Pascal: 1099 return llvm::dwarf::DW_CC_BORLAND_pascal; 1100 case CC_Win64: 1101 return llvm::dwarf::DW_CC_LLVM_Win64; 1102 case CC_X86_64SysV: 1103 return llvm::dwarf::DW_CC_LLVM_X86_64SysV; 1104 case CC_AAPCS: 1105 return llvm::dwarf::DW_CC_LLVM_AAPCS; 1106 case CC_AAPCS_VFP: 1107 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP; 1108 case CC_IntelOclBicc: 1109 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc; 1110 case CC_SpirFunction: 1111 return llvm::dwarf::DW_CC_LLVM_SpirFunction; 1112 case CC_OpenCLKernel: 1113 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel; 1114 case CC_Swift: 1115 return llvm::dwarf::DW_CC_LLVM_Swift; 1116 case CC_PreserveMost: 1117 return llvm::dwarf::DW_CC_LLVM_PreserveMost; 1118 case CC_PreserveAll: 1119 return llvm::dwarf::DW_CC_LLVM_PreserveAll; 1120 case CC_X86RegCall: 1121 return llvm::dwarf::DW_CC_LLVM_X86RegCall; 1122 } 1123 return 0; 1124 } 1125 1126 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty, 1127 llvm::DIFile *Unit) { 1128 SmallVector<llvm::Metadata *, 16> EltTys; 1129 1130 // Add the result type at least. 1131 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit)); 1132 1133 // Set up remainder of arguments if there is a prototype. 1134 // otherwise emit it as a variadic function. 1135 if (isa<FunctionNoProtoType>(Ty)) 1136 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 1137 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) { 1138 for (const QualType &ParamType : FPT->param_types()) 1139 EltTys.push_back(getOrCreateType(ParamType, Unit)); 1140 if (FPT->isVariadic()) 1141 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 1142 } 1143 1144 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 1145 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 1146 getDwarfCC(Ty->getCallConv())); 1147 } 1148 1149 /// Convert an AccessSpecifier into the corresponding DINode flag. 1150 /// As an optimization, return 0 if the access specifier equals the 1151 /// default for the containing type. 1152 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, 1153 const RecordDecl *RD) { 1154 AccessSpecifier Default = clang::AS_none; 1155 if (RD && RD->isClass()) 1156 Default = clang::AS_private; 1157 else if (RD && (RD->isStruct() || RD->isUnion())) 1158 Default = clang::AS_public; 1159 1160 if (Access == Default) 1161 return llvm::DINode::FlagZero; 1162 1163 switch (Access) { 1164 case clang::AS_private: 1165 return llvm::DINode::FlagPrivate; 1166 case clang::AS_protected: 1167 return llvm::DINode::FlagProtected; 1168 case clang::AS_public: 1169 return llvm::DINode::FlagPublic; 1170 case clang::AS_none: 1171 return llvm::DINode::FlagZero; 1172 } 1173 llvm_unreachable("unexpected access enumerator"); 1174 } 1175 1176 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl, 1177 llvm::DIScope *RecordTy, 1178 const RecordDecl *RD) { 1179 StringRef Name = BitFieldDecl->getName(); 1180 QualType Ty = BitFieldDecl->getType(); 1181 SourceLocation Loc = BitFieldDecl->getLocation(); 1182 llvm::DIFile *VUnit = getOrCreateFile(Loc); 1183 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit); 1184 1185 // Get the location for the field. 1186 llvm::DIFile *File = getOrCreateFile(Loc); 1187 unsigned Line = getLineNumber(Loc); 1188 1189 const CGBitFieldInfo &BitFieldInfo = 1190 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl); 1191 uint64_t SizeInBits = BitFieldInfo.Size; 1192 assert(SizeInBits > 0 && "found named 0-width bitfield"); 1193 uint64_t StorageOffsetInBits = 1194 CGM.getContext().toBits(BitFieldInfo.StorageOffset); 1195 uint64_t Offset = BitFieldInfo.Offset; 1196 // The bit offsets for big endian machines are reversed for big 1197 // endian target, compensate for that as the DIDerivedType requires 1198 // un-reversed offsets. 1199 if (CGM.getDataLayout().isBigEndian()) 1200 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset; 1201 uint64_t OffsetInBits = StorageOffsetInBits + Offset; 1202 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD); 1203 return DBuilder.createBitFieldMemberType( 1204 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits, 1205 Flags, DebugType); 1206 } 1207 1208 llvm::DIType * 1209 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc, 1210 AccessSpecifier AS, uint64_t offsetInBits, 1211 uint32_t AlignInBits, llvm::DIFile *tunit, 1212 llvm::DIScope *scope, const RecordDecl *RD) { 1213 llvm::DIType *debugType = getOrCreateType(type, tunit); 1214 1215 // Get the location for the field. 1216 llvm::DIFile *file = getOrCreateFile(loc); 1217 unsigned line = getLineNumber(loc); 1218 1219 uint64_t SizeInBits = 0; 1220 auto Align = AlignInBits; 1221 if (!type->isIncompleteArrayType()) { 1222 TypeInfo TI = CGM.getContext().getTypeInfo(type); 1223 SizeInBits = TI.Width; 1224 if (!Align) 1225 Align = getTypeAlignIfRequired(type, CGM.getContext()); 1226 } 1227 1228 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD); 1229 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align, 1230 offsetInBits, flags, debugType); 1231 } 1232 1233 void CGDebugInfo::CollectRecordLambdaFields( 1234 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements, 1235 llvm::DIType *RecordTy) { 1236 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture 1237 // has the name and the location of the variable so we should iterate over 1238 // both concurrently. 1239 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); 1240 RecordDecl::field_iterator Field = CXXDecl->field_begin(); 1241 unsigned fieldno = 0; 1242 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), 1243 E = CXXDecl->captures_end(); 1244 I != E; ++I, ++Field, ++fieldno) { 1245 const LambdaCapture &C = *I; 1246 if (C.capturesVariable()) { 1247 SourceLocation Loc = C.getLocation(); 1248 assert(!Field->isBitField() && "lambdas don't have bitfield members!"); 1249 VarDecl *V = C.getCapturedVar(); 1250 StringRef VName = V->getName(); 1251 llvm::DIFile *VUnit = getOrCreateFile(Loc); 1252 auto Align = getDeclAlignIfRequired(V, CGM.getContext()); 1253 llvm::DIType *FieldType = createFieldType( 1254 VName, Field->getType(), Loc, Field->getAccess(), 1255 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl); 1256 elements.push_back(FieldType); 1257 } else if (C.capturesThis()) { 1258 // TODO: Need to handle 'this' in some way by probably renaming the 1259 // this of the lambda class and having a field member of 'this' or 1260 // by using AT_object_pointer for the function and having that be 1261 // used as 'this' for semantic references. 1262 FieldDecl *f = *Field; 1263 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation()); 1264 QualType type = f->getType(); 1265 llvm::DIType *fieldType = createFieldType( 1266 "this", type, f->getLocation(), f->getAccess(), 1267 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl); 1268 1269 elements.push_back(fieldType); 1270 } 1271 } 1272 } 1273 1274 llvm::DIDerivedType * 1275 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy, 1276 const RecordDecl *RD) { 1277 // Create the descriptor for the static variable, with or without 1278 // constant initializers. 1279 Var = Var->getCanonicalDecl(); 1280 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation()); 1281 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit); 1282 1283 unsigned LineNumber = getLineNumber(Var->getLocation()); 1284 StringRef VName = Var->getName(); 1285 llvm::Constant *C = nullptr; 1286 if (Var->getInit()) { 1287 const APValue *Value = Var->evaluateValue(); 1288 if (Value) { 1289 if (Value->isInt()) 1290 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 1291 if (Value->isFloat()) 1292 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat()); 1293 } 1294 } 1295 1296 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD); 1297 auto Align = getDeclAlignIfRequired(Var, CGM.getContext()); 1298 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType( 1299 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align); 1300 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV); 1301 return GV; 1302 } 1303 1304 void CGDebugInfo::CollectRecordNormalField( 1305 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit, 1306 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy, 1307 const RecordDecl *RD) { 1308 StringRef name = field->getName(); 1309 QualType type = field->getType(); 1310 1311 // Ignore unnamed fields unless they're anonymous structs/unions. 1312 if (name.empty() && !type->isRecordType()) 1313 return; 1314 1315 llvm::DIType *FieldType; 1316 if (field->isBitField()) { 1317 FieldType = createBitFieldType(field, RecordTy, RD); 1318 } else { 1319 auto Align = getDeclAlignIfRequired(field, CGM.getContext()); 1320 FieldType = 1321 createFieldType(name, type, field->getLocation(), field->getAccess(), 1322 OffsetInBits, Align, tunit, RecordTy, RD); 1323 } 1324 1325 elements.push_back(FieldType); 1326 } 1327 1328 void CGDebugInfo::CollectRecordNestedType( 1329 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) { 1330 QualType Ty = CGM.getContext().getTypeDeclType(TD); 1331 // Injected class names are not considered nested records. 1332 if (isa<InjectedClassNameType>(Ty)) 1333 return; 1334 SourceLocation Loc = TD->getLocation(); 1335 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc)); 1336 elements.push_back(nestedType); 1337 } 1338 1339 void CGDebugInfo::CollectRecordFields( 1340 const RecordDecl *record, llvm::DIFile *tunit, 1341 SmallVectorImpl<llvm::Metadata *> &elements, 1342 llvm::DICompositeType *RecordTy) { 1343 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record); 1344 1345 if (CXXDecl && CXXDecl->isLambda()) 1346 CollectRecordLambdaFields(CXXDecl, elements, RecordTy); 1347 else { 1348 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 1349 1350 // Field number for non-static fields. 1351 unsigned fieldNo = 0; 1352 1353 // Static and non-static members should appear in the same order as 1354 // the corresponding declarations in the source program. 1355 for (const auto *I : record->decls()) 1356 if (const auto *V = dyn_cast<VarDecl>(I)) { 1357 if (V->hasAttr<NoDebugAttr>()) 1358 continue; 1359 1360 // Skip variable template specializations when emitting CodeView. MSVC 1361 // doesn't emit them. 1362 if (CGM.getCodeGenOpts().EmitCodeView && 1363 isa<VarTemplateSpecializationDecl>(V)) 1364 continue; 1365 1366 // Reuse the existing static member declaration if one exists 1367 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl()); 1368 if (MI != StaticDataMemberCache.end()) { 1369 assert(MI->second && 1370 "Static data member declaration should still exist"); 1371 elements.push_back(MI->second); 1372 } else { 1373 auto Field = CreateRecordStaticField(V, RecordTy, record); 1374 elements.push_back(Field); 1375 } 1376 } else if (const auto *field = dyn_cast<FieldDecl>(I)) { 1377 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit, 1378 elements, RecordTy, record); 1379 1380 // Bump field number for next field. 1381 ++fieldNo; 1382 } else if (CGM.getCodeGenOpts().EmitCodeView) { 1383 // Debug info for nested types is included in the member list only for 1384 // CodeView. 1385 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) 1386 if (!nestedType->isImplicit() && 1387 nestedType->getDeclContext() == record) 1388 CollectRecordNestedType(nestedType, elements); 1389 } 1390 } 1391 } 1392 1393 llvm::DISubroutineType * 1394 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 1395 llvm::DIFile *Unit) { 1396 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 1397 if (Method->isStatic()) 1398 return cast_or_null<llvm::DISubroutineType>( 1399 getOrCreateType(QualType(Func, 0), Unit)); 1400 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()), 1401 Func, Unit); 1402 } 1403 1404 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType( 1405 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) { 1406 // Add "this" pointer. 1407 llvm::DITypeRefArray Args( 1408 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit)) 1409 ->getTypeArray()); 1410 assert(Args.size() && "Invalid number of arguments!"); 1411 1412 SmallVector<llvm::Metadata *, 16> Elts; 1413 1414 // First element is always return type. For 'void' functions it is NULL. 1415 Elts.push_back(Args[0]); 1416 1417 // "this" pointer is always first argument. 1418 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); 1419 if (isa<ClassTemplateSpecializationDecl>(RD)) { 1420 // Create pointer type directly in this case. 1421 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 1422 QualType PointeeTy = ThisPtrTy->getPointeeType(); 1423 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 1424 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 1425 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext()); 1426 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit); 1427 llvm::DIType *ThisPtrType = 1428 DBuilder.createPointerType(PointeeType, Size, Align); 1429 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); 1430 // TODO: This and the artificial type below are misleading, the 1431 // types aren't artificial the argument is, but the current 1432 // metadata doesn't represent that. 1433 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1434 Elts.push_back(ThisPtrType); 1435 } else { 1436 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit); 1437 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); 1438 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1439 Elts.push_back(ThisPtrType); 1440 } 1441 1442 // Copy rest of the arguments. 1443 for (unsigned i = 1, e = Args.size(); i != e; ++i) 1444 Elts.push_back(Args[i]); 1445 1446 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 1447 1448 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 1449 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue) 1450 Flags |= llvm::DINode::FlagLValueReference; 1451 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue) 1452 Flags |= llvm::DINode::FlagRValueReference; 1453 1454 return DBuilder.createSubroutineType(EltTypeArray, Flags, 1455 getDwarfCC(Func->getCallConv())); 1456 } 1457 1458 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 1459 /// inside a function. 1460 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 1461 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 1462 return isFunctionLocalClass(NRD); 1463 if (isa<FunctionDecl>(RD->getDeclContext())) 1464 return true; 1465 return false; 1466 } 1467 1468 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction( 1469 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) { 1470 bool IsCtorOrDtor = 1471 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 1472 1473 StringRef MethodName = getFunctionName(Method); 1474 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit); 1475 1476 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 1477 // make sense to give a single ctor/dtor a linkage name. 1478 StringRef MethodLinkageName; 1479 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional 1480 // property to use here. It may've been intended to model "is non-external 1481 // type" but misses cases of non-function-local but non-external classes such 1482 // as those in anonymous namespaces as well as the reverse - external types 1483 // that are function local, such as those in (non-local) inline functions. 1484 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 1485 MethodLinkageName = CGM.getMangledName(Method); 1486 1487 // Get the location for the method. 1488 llvm::DIFile *MethodDefUnit = nullptr; 1489 unsigned MethodLine = 0; 1490 if (!Method->isImplicit()) { 1491 MethodDefUnit = getOrCreateFile(Method->getLocation()); 1492 MethodLine = getLineNumber(Method->getLocation()); 1493 } 1494 1495 // Collect virtual method info. 1496 llvm::DIType *ContainingType = nullptr; 1497 unsigned VIndex = 0; 1498 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 1499 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 1500 int ThisAdjustment = 0; 1501 1502 if (Method->isVirtual()) { 1503 if (Method->isPure()) 1504 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual; 1505 else 1506 SPFlags |= llvm::DISubprogram::SPFlagVirtual; 1507 1508 if (CGM.getTarget().getCXXABI().isItaniumFamily()) { 1509 // It doesn't make sense to give a virtual destructor a vtable index, 1510 // since a single destructor has two entries in the vtable. 1511 if (!isa<CXXDestructorDecl>(Method)) 1512 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method); 1513 } else { 1514 // Emit MS ABI vftable information. There is only one entry for the 1515 // deleting dtor. 1516 const auto *DD = dyn_cast<CXXDestructorDecl>(Method); 1517 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method); 1518 MethodVFTableLocation ML = 1519 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 1520 VIndex = ML.Index; 1521 1522 // CodeView only records the vftable offset in the class that introduces 1523 // the virtual method. This is possible because, unlike Itanium, the MS 1524 // C++ ABI does not include all virtual methods from non-primary bases in 1525 // the vtable for the most derived class. For example, if C inherits from 1526 // A and B, C's primary vftable will not include B's virtual methods. 1527 if (Method->size_overridden_methods() == 0) 1528 Flags |= llvm::DINode::FlagIntroducedVirtual; 1529 1530 // The 'this' adjustment accounts for both the virtual and non-virtual 1531 // portions of the adjustment. Presumably the debugger only uses it when 1532 // it knows the dynamic type of an object. 1533 ThisAdjustment = CGM.getCXXABI() 1534 .getVirtualFunctionPrologueThisAdjustment(GD) 1535 .getQuantity(); 1536 } 1537 ContainingType = RecordTy; 1538 } 1539 1540 if (Method->isStatic()) 1541 Flags |= llvm::DINode::FlagStaticMember; 1542 if (Method->isImplicit()) 1543 Flags |= llvm::DINode::FlagArtificial; 1544 Flags |= getAccessFlag(Method->getAccess(), Method->getParent()); 1545 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 1546 if (CXXC->isExplicit()) 1547 Flags |= llvm::DINode::FlagExplicit; 1548 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) { 1549 if (CXXC->isExplicit()) 1550 Flags |= llvm::DINode::FlagExplicit; 1551 } 1552 if (Method->hasPrototype()) 1553 Flags |= llvm::DINode::FlagPrototyped; 1554 if (Method->getRefQualifier() == RQ_LValue) 1555 Flags |= llvm::DINode::FlagLValueReference; 1556 if (Method->getRefQualifier() == RQ_RValue) 1557 Flags |= llvm::DINode::FlagRValueReference; 1558 if (CGM.getLangOpts().Optimize) 1559 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 1560 1561 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 1562 llvm::DISubprogram *SP = DBuilder.createMethod( 1563 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine, 1564 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags, 1565 TParamsArray.get()); 1566 1567 SPCache[Method->getCanonicalDecl()].reset(SP); 1568 1569 return SP; 1570 } 1571 1572 void CGDebugInfo::CollectCXXMemberFunctions( 1573 const CXXRecordDecl *RD, llvm::DIFile *Unit, 1574 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) { 1575 1576 // Since we want more than just the individual member decls if we 1577 // have templated functions iterate over every declaration to gather 1578 // the functions. 1579 for (const auto *I : RD->decls()) { 1580 const auto *Method = dyn_cast<CXXMethodDecl>(I); 1581 // If the member is implicit, don't add it to the member list. This avoids 1582 // the member being added to type units by LLVM, while still allowing it 1583 // to be emitted into the type declaration/reference inside the compile 1584 // unit. 1585 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp. 1586 // FIXME: Handle Using(Shadow?)Decls here to create 1587 // DW_TAG_imported_declarations inside the class for base decls brought into 1588 // derived classes. GDB doesn't seem to notice/leverage these when I tried 1589 // it, so I'm not rushing to fix this. (GCC seems to produce them, if 1590 // referenced) 1591 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>()) 1592 continue; 1593 1594 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType()) 1595 continue; 1596 1597 // Reuse the existing member function declaration if it exists. 1598 // It may be associated with the declaration of the type & should be 1599 // reused as we're building the definition. 1600 // 1601 // This situation can arise in the vtable-based debug info reduction where 1602 // implicit members are emitted in a non-vtable TU. 1603 auto MI = SPCache.find(Method->getCanonicalDecl()); 1604 EltTys.push_back(MI == SPCache.end() 1605 ? CreateCXXMemberFunction(Method, Unit, RecordTy) 1606 : static_cast<llvm::Metadata *>(MI->second)); 1607 } 1608 } 1609 1610 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit, 1611 SmallVectorImpl<llvm::Metadata *> &EltTys, 1612 llvm::DIType *RecordTy) { 1613 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes; 1614 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes, 1615 llvm::DINode::FlagZero); 1616 1617 // If we are generating CodeView debug info, we also need to emit records for 1618 // indirect virtual base classes. 1619 if (CGM.getCodeGenOpts().EmitCodeView) { 1620 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes, 1621 llvm::DINode::FlagIndirectVirtualBase); 1622 } 1623 } 1624 1625 void CGDebugInfo::CollectCXXBasesAux( 1626 const CXXRecordDecl *RD, llvm::DIFile *Unit, 1627 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy, 1628 const CXXRecordDecl::base_class_const_range &Bases, 1629 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes, 1630 llvm::DINode::DIFlags StartingFlags) { 1631 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1632 for (const auto &BI : Bases) { 1633 const auto *Base = 1634 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl()); 1635 if (!SeenTypes.insert(Base).second) 1636 continue; 1637 auto *BaseTy = getOrCreateType(BI.getType(), Unit); 1638 llvm::DINode::DIFlags BFlags = StartingFlags; 1639 uint64_t BaseOffset; 1640 uint32_t VBPtrOffset = 0; 1641 1642 if (BI.isVirtual()) { 1643 if (CGM.getTarget().getCXXABI().isItaniumFamily()) { 1644 // virtual base offset offset is -ve. The code generator emits dwarf 1645 // expression where it expects +ve number. 1646 BaseOffset = 0 - CGM.getItaniumVTableContext() 1647 .getVirtualBaseOffsetOffset(RD, Base) 1648 .getQuantity(); 1649 } else { 1650 // In the MS ABI, store the vbtable offset, which is analogous to the 1651 // vbase offset offset in Itanium. 1652 BaseOffset = 1653 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base); 1654 VBPtrOffset = CGM.getContext() 1655 .getASTRecordLayout(RD) 1656 .getVBPtrOffset() 1657 .getQuantity(); 1658 } 1659 BFlags |= llvm::DINode::FlagVirtual; 1660 } else 1661 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 1662 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 1663 // BI->isVirtual() and bits when not. 1664 1665 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD); 1666 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset, 1667 VBPtrOffset, BFlags); 1668 EltTys.push_back(DTy); 1669 } 1670 } 1671 1672 llvm::DINodeArray 1673 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList, 1674 ArrayRef<TemplateArgument> TAList, 1675 llvm::DIFile *Unit) { 1676 SmallVector<llvm::Metadata *, 16> TemplateParams; 1677 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 1678 const TemplateArgument &TA = TAList[i]; 1679 StringRef Name; 1680 if (TPList) 1681 Name = TPList->getParam(i)->getName(); 1682 switch (TA.getKind()) { 1683 case TemplateArgument::Type: { 1684 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit); 1685 TemplateParams.push_back( 1686 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy)); 1687 } break; 1688 case TemplateArgument::Integral: { 1689 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit); 1690 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1691 TheCU, Name, TTy, 1692 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()))); 1693 } break; 1694 case TemplateArgument::Declaration: { 1695 const ValueDecl *D = TA.getAsDecl(); 1696 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext()); 1697 llvm::DIType *TTy = getOrCreateType(T, Unit); 1698 llvm::Constant *V = nullptr; 1699 const CXXMethodDecl *MD; 1700 // Variable pointer template parameters have a value that is the address 1701 // of the variable. 1702 if (const auto *VD = dyn_cast<VarDecl>(D)) 1703 V = CGM.GetAddrOfGlobalVar(VD); 1704 // Member function pointers have special support for building them, though 1705 // this is currently unsupported in LLVM CodeGen. 1706 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance()) 1707 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD); 1708 else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 1709 V = CGM.GetAddrOfFunction(FD); 1710 // Member data pointers have special handling too to compute the fixed 1711 // offset within the object. 1712 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) { 1713 // These five lines (& possibly the above member function pointer 1714 // handling) might be able to be refactored to use similar code in 1715 // CodeGenModule::getMemberPointerConstant 1716 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 1717 CharUnits chars = 1718 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset); 1719 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars); 1720 } 1721 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1722 TheCU, Name, TTy, 1723 cast_or_null<llvm::Constant>(V->stripPointerCasts()))); 1724 } break; 1725 case TemplateArgument::NullPtr: { 1726 QualType T = TA.getNullPtrType(); 1727 llvm::DIType *TTy = getOrCreateType(T, Unit); 1728 llvm::Constant *V = nullptr; 1729 // Special case member data pointer null values since they're actually -1 1730 // instead of zero. 1731 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) 1732 // But treat member function pointers as simple zero integers because 1733 // it's easier than having a special case in LLVM's CodeGen. If LLVM 1734 // CodeGen grows handling for values of non-null member function 1735 // pointers then perhaps we could remove this special case and rely on 1736 // EmitNullMemberPointer for member function pointers. 1737 if (MPT->isMemberDataPointer()) 1738 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 1739 if (!V) 1740 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 1741 TemplateParams.push_back( 1742 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V)); 1743 } break; 1744 case TemplateArgument::Template: 1745 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter( 1746 TheCU, Name, nullptr, 1747 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString())); 1748 break; 1749 case TemplateArgument::Pack: 1750 TemplateParams.push_back(DBuilder.createTemplateParameterPack( 1751 TheCU, Name, nullptr, 1752 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit))); 1753 break; 1754 case TemplateArgument::Expression: { 1755 const Expr *E = TA.getAsExpr(); 1756 QualType T = E->getType(); 1757 if (E->isGLValue()) 1758 T = CGM.getContext().getLValueReferenceType(T); 1759 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T); 1760 assert(V && "Expression in template argument isn't constant"); 1761 llvm::DIType *TTy = getOrCreateType(T, Unit); 1762 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1763 TheCU, Name, TTy, V->stripPointerCasts())); 1764 } break; 1765 // And the following should never occur: 1766 case TemplateArgument::TemplateExpansion: 1767 case TemplateArgument::Null: 1768 llvm_unreachable( 1769 "These argument types shouldn't exist in concrete types"); 1770 } 1771 } 1772 return DBuilder.getOrCreateArray(TemplateParams); 1773 } 1774 1775 llvm::DINodeArray 1776 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, 1777 llvm::DIFile *Unit) { 1778 if (FD->getTemplatedKind() == 1779 FunctionDecl::TK_FunctionTemplateSpecialization) { 1780 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() 1781 ->getTemplate() 1782 ->getTemplateParameters(); 1783 return CollectTemplateParams( 1784 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit); 1785 } 1786 return llvm::DINodeArray(); 1787 } 1788 1789 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL, 1790 llvm::DIFile *Unit) { 1791 if (auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL)) { 1792 auto T = TS->getSpecializedTemplateOrPartial(); 1793 auto TA = TS->getTemplateArgs().asArray(); 1794 // Collect parameters for a partial specialization 1795 if (T.is<VarTemplatePartialSpecializationDecl *>()) { 1796 const TemplateParameterList *TList = 1797 T.get<VarTemplatePartialSpecializationDecl *>() 1798 ->getTemplateParameters(); 1799 return CollectTemplateParams(TList, TA, Unit); 1800 } 1801 1802 // Collect parameters for an explicit specialization 1803 if (T.is<VarTemplateDecl *>()) { 1804 const TemplateParameterList *TList = T.get<VarTemplateDecl *>() 1805 ->getTemplateParameters(); 1806 return CollectTemplateParams(TList, TA, Unit); 1807 } 1808 } 1809 return llvm::DINodeArray(); 1810 } 1811 1812 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams( 1813 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) { 1814 // Always get the full list of parameters, not just the ones from 1815 // the specialization. 1816 TemplateParameterList *TPList = 1817 TSpecial->getSpecializedTemplate()->getTemplateParameters(); 1818 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); 1819 return CollectTemplateParams(TPList, TAList.asArray(), Unit); 1820 } 1821 1822 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) { 1823 if (VTablePtrType) 1824 return VTablePtrType; 1825 1826 ASTContext &Context = CGM.getContext(); 1827 1828 /* Function type */ 1829 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit); 1830 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy); 1831 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements); 1832 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1833 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); 1834 Optional<unsigned> DWARFAddressSpace = 1835 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace); 1836 1837 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType( 1838 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type"); 1839 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1840 return VTablePtrType; 1841 } 1842 1843 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1844 // Copy the gdb compatible name on the side and use its reference. 1845 return internString("_vptr$", RD->getNameAsString()); 1846 } 1847 1848 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit, 1849 SmallVectorImpl<llvm::Metadata *> &EltTys, 1850 llvm::DICompositeType *RecordTy) { 1851 // If this class is not dynamic then there is not any vtable info to collect. 1852 if (!RD->isDynamicClass()) 1853 return; 1854 1855 // Don't emit any vtable shape or vptr info if this class doesn't have an 1856 // extendable vfptr. This can happen if the class doesn't have virtual 1857 // methods, or in the MS ABI if those virtual methods only come from virtually 1858 // inherited bases. 1859 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1860 if (!RL.hasExtendableVFPtr()) 1861 return; 1862 1863 // CodeView needs to know how large the vtable of every dynamic class is, so 1864 // emit a special named pointer type into the element list. The vptr type 1865 // points to this type as well. 1866 llvm::DIType *VPtrTy = nullptr; 1867 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView && 1868 CGM.getTarget().getCXXABI().isMicrosoft(); 1869 if (NeedVTableShape) { 1870 uint64_t PtrWidth = 1871 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1872 const VTableLayout &VFTLayout = 1873 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero()); 1874 unsigned VSlotCount = 1875 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData; 1876 unsigned VTableWidth = PtrWidth * VSlotCount; 1877 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); 1878 Optional<unsigned> DWARFAddressSpace = 1879 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace); 1880 1881 // Create a very wide void* type and insert it directly in the element list. 1882 llvm::DIType *VTableType = DBuilder.createPointerType( 1883 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type"); 1884 EltTys.push_back(VTableType); 1885 1886 // The vptr is a pointer to this special vtable type. 1887 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth); 1888 } 1889 1890 // If there is a primary base then the artificial vptr member lives there. 1891 if (RL.getPrimaryBase()) 1892 return; 1893 1894 if (!VPtrTy) 1895 VPtrTy = getOrCreateVTablePtrType(Unit); 1896 1897 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1898 llvm::DIType *VPtrMember = 1899 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0, 1900 llvm::DINode::FlagArtificial, VPtrTy); 1901 EltTys.push_back(VPtrMember); 1902 } 1903 1904 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy, 1905 SourceLocation Loc) { 1906 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 1907 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1908 return T; 1909 } 1910 1911 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D, 1912 SourceLocation Loc) { 1913 return getOrCreateStandaloneType(D, Loc); 1914 } 1915 1916 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D, 1917 SourceLocation Loc) { 1918 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 1919 assert(!D.isNull() && "null type"); 1920 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc)); 1921 assert(T && "could not create debug info for type"); 1922 1923 RetainedTypes.push_back(D.getAsOpaquePtr()); 1924 return T; 1925 } 1926 1927 void CGDebugInfo::completeType(const EnumDecl *ED) { 1928 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 1929 return; 1930 QualType Ty = CGM.getContext().getEnumType(ED); 1931 void *TyPtr = Ty.getAsOpaquePtr(); 1932 auto I = TypeCache.find(TyPtr); 1933 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl()) 1934 return; 1935 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>()); 1936 assert(!Res->isForwardDecl()); 1937 TypeCache[TyPtr].reset(Res); 1938 } 1939 1940 void CGDebugInfo::completeType(const RecordDecl *RD) { 1941 if (DebugKind > codegenoptions::LimitedDebugInfo || 1942 !CGM.getLangOpts().CPlusPlus) 1943 completeRequiredType(RD); 1944 } 1945 1946 /// Return true if the class or any of its methods are marked dllimport. 1947 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) { 1948 if (RD->hasAttr<DLLImportAttr>()) 1949 return true; 1950 for (const CXXMethodDecl *MD : RD->methods()) 1951 if (MD->hasAttr<DLLImportAttr>()) 1952 return true; 1953 return false; 1954 } 1955 1956 /// Does a type definition exist in an imported clang module? 1957 static bool isDefinedInClangModule(const RecordDecl *RD) { 1958 // Only definitions that where imported from an AST file come from a module. 1959 if (!RD || !RD->isFromASTFile()) 1960 return false; 1961 // Anonymous entities cannot be addressed. Treat them as not from module. 1962 if (!RD->isExternallyVisible() && RD->getName().empty()) 1963 return false; 1964 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) { 1965 if (!CXXDecl->isCompleteDefinition()) 1966 return false; 1967 // Check wether RD is a template. 1968 auto TemplateKind = CXXDecl->getTemplateSpecializationKind(); 1969 if (TemplateKind != TSK_Undeclared) { 1970 // Unfortunately getOwningModule() isn't accurate enough to find the 1971 // owning module of a ClassTemplateSpecializationDecl that is inside a 1972 // namespace spanning multiple modules. 1973 bool Explicit = false; 1974 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl)) 1975 Explicit = TD->isExplicitInstantiationOrSpecialization(); 1976 if (!Explicit && CXXDecl->getEnclosingNamespaceContext()) 1977 return false; 1978 // This is a template, check the origin of the first member. 1979 if (CXXDecl->field_begin() == CXXDecl->field_end()) 1980 return TemplateKind == TSK_ExplicitInstantiationDeclaration; 1981 if (!CXXDecl->field_begin()->isFromASTFile()) 1982 return false; 1983 } 1984 } 1985 return true; 1986 } 1987 1988 void CGDebugInfo::completeClassData(const RecordDecl *RD) { 1989 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1990 if (CXXRD->isDynamicClass() && 1991 CGM.getVTableLinkage(CXXRD) == 1992 llvm::GlobalValue::AvailableExternallyLinkage && 1993 !isClassOrMethodDLLImport(CXXRD)) 1994 return; 1995 1996 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition())) 1997 return; 1998 1999 completeClass(RD); 2000 } 2001 2002 void CGDebugInfo::completeClass(const RecordDecl *RD) { 2003 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2004 return; 2005 QualType Ty = CGM.getContext().getRecordType(RD); 2006 void *TyPtr = Ty.getAsOpaquePtr(); 2007 auto I = TypeCache.find(TyPtr); 2008 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl()) 2009 return; 2010 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>()); 2011 assert(!Res->isForwardDecl()); 2012 TypeCache[TyPtr].reset(Res); 2013 } 2014 2015 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, 2016 CXXRecordDecl::method_iterator End) { 2017 for (CXXMethodDecl *MD : llvm::make_range(I, End)) 2018 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction()) 2019 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && 2020 !MD->getMemberSpecializationInfo()->isExplicitSpecialization()) 2021 return true; 2022 return false; 2023 } 2024 2025 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind, 2026 bool DebugTypeExtRefs, const RecordDecl *RD, 2027 const LangOptions &LangOpts) { 2028 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition())) 2029 return true; 2030 2031 if (auto *ES = RD->getASTContext().getExternalSource()) 2032 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always) 2033 return true; 2034 2035 if (DebugKind > codegenoptions::LimitedDebugInfo) 2036 return false; 2037 2038 if (!LangOpts.CPlusPlus) 2039 return false; 2040 2041 if (!RD->isCompleteDefinitionRequired()) 2042 return true; 2043 2044 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2045 2046 if (!CXXDecl) 2047 return false; 2048 2049 // Only emit complete debug info for a dynamic class when its vtable is 2050 // emitted. However, Microsoft debuggers don't resolve type information 2051 // across DLL boundaries, so skip this optimization if the class or any of its 2052 // methods are marked dllimport. This isn't a complete solution, since objects 2053 // without any dllimport methods can be used in one DLL and constructed in 2054 // another, but it is the current behavior of LimitedDebugInfo. 2055 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() && 2056 !isClassOrMethodDLLImport(CXXDecl)) 2057 return true; 2058 2059 TemplateSpecializationKind Spec = TSK_Undeclared; 2060 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 2061 Spec = SD->getSpecializationKind(); 2062 2063 if (Spec == TSK_ExplicitInstantiationDeclaration && 2064 hasExplicitMemberDefinition(CXXDecl->method_begin(), 2065 CXXDecl->method_end())) 2066 return true; 2067 2068 return false; 2069 } 2070 2071 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { 2072 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts())) 2073 return; 2074 2075 QualType Ty = CGM.getContext().getRecordType(RD); 2076 llvm::DIType *T = getTypeOrNull(Ty); 2077 if (T && T->isForwardDecl()) 2078 completeClassData(RD); 2079 } 2080 2081 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) { 2082 RecordDecl *RD = Ty->getDecl(); 2083 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0))); 2084 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, 2085 CGM.getLangOpts())) { 2086 if (!T) 2087 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD)); 2088 return T; 2089 } 2090 2091 return CreateTypeDefinition(Ty); 2092 } 2093 2094 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { 2095 RecordDecl *RD = Ty->getDecl(); 2096 2097 // Get overall information about the record type for the debug info. 2098 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 2099 2100 // Records and classes and unions can all be recursive. To handle them, we 2101 // first generate a debug descriptor for the struct as a forward declaration. 2102 // Then (if it is a definition) we go through and get debug info for all of 2103 // its members. Finally, we create a descriptor for the complete type (which 2104 // may refer to the forward decl if the struct is recursive) and replace all 2105 // uses of the forward declaration with the final definition. 2106 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit); 2107 2108 const RecordDecl *D = RD->getDefinition(); 2109 if (!D || !D->isCompleteDefinition()) 2110 return FwdDecl; 2111 2112 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 2113 CollectContainingType(CXXDecl, FwdDecl); 2114 2115 // Push the struct on region stack. 2116 LexicalBlockStack.emplace_back(&*FwdDecl); 2117 RegionMap[Ty->getDecl()].reset(FwdDecl); 2118 2119 // Convert all the elements. 2120 SmallVector<llvm::Metadata *, 16> EltTys; 2121 // what about nested types? 2122 2123 // Note: The split of CXXDecl information here is intentional, the 2124 // gdb tests will depend on a certain ordering at printout. The debug 2125 // information offsets are still correct if we merge them all together 2126 // though. 2127 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2128 if (CXXDecl) { 2129 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 2130 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl); 2131 } 2132 2133 // Collect data fields (including static variables and any initializers). 2134 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 2135 if (CXXDecl) 2136 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 2137 2138 LexicalBlockStack.pop_back(); 2139 RegionMap.erase(Ty->getDecl()); 2140 2141 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 2142 DBuilder.replaceArrays(FwdDecl, Elements); 2143 2144 if (FwdDecl->isTemporary()) 2145 FwdDecl = 2146 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl)); 2147 2148 RegionMap[Ty->getDecl()].reset(FwdDecl); 2149 return FwdDecl; 2150 } 2151 2152 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty, 2153 llvm::DIFile *Unit) { 2154 // Ignore protocols. 2155 return getOrCreateType(Ty->getBaseType(), Unit); 2156 } 2157 2158 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty, 2159 llvm::DIFile *Unit) { 2160 // Ignore protocols. 2161 SourceLocation Loc = Ty->getDecl()->getLocation(); 2162 2163 // Use Typedefs to represent ObjCTypeParamType. 2164 return DBuilder.createTypedef( 2165 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit), 2166 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc), 2167 getDeclContextDescriptor(Ty->getDecl())); 2168 } 2169 2170 /// \return true if Getter has the default name for the property PD. 2171 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, 2172 const ObjCMethodDecl *Getter) { 2173 assert(PD); 2174 if (!Getter) 2175 return true; 2176 2177 assert(Getter->getDeclName().isObjCZeroArgSelector()); 2178 return PD->getName() == 2179 Getter->getDeclName().getObjCSelector().getNameForSlot(0); 2180 } 2181 2182 /// \return true if Setter has the default name for the property PD. 2183 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, 2184 const ObjCMethodDecl *Setter) { 2185 assert(PD); 2186 if (!Setter) 2187 return true; 2188 2189 assert(Setter->getDeclName().isObjCOneArgSelector()); 2190 return SelectorTable::constructSetterName(PD->getName()) == 2191 Setter->getDeclName().getObjCSelector().getNameForSlot(0); 2192 } 2193 2194 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 2195 llvm::DIFile *Unit) { 2196 ObjCInterfaceDecl *ID = Ty->getDecl(); 2197 if (!ID) 2198 return nullptr; 2199 2200 // Return a forward declaration if this type was imported from a clang module, 2201 // and this is not the compile unit with the implementation of the type (which 2202 // may contain hidden ivars). 2203 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() && 2204 !ID->getImplementation()) 2205 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 2206 ID->getName(), 2207 getDeclContextDescriptor(ID), Unit, 0); 2208 2209 // Get overall information about the record type for the debug info. 2210 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 2211 unsigned Line = getLineNumber(ID->getLocation()); 2212 auto RuntimeLang = 2213 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage()); 2214 2215 // If this is just a forward declaration return a special forward-declaration 2216 // debug type since we won't be able to lay out the entire type. 2217 ObjCInterfaceDecl *Def = ID->getDefinition(); 2218 if (!Def || !Def->getImplementation()) { 2219 llvm::DIScope *Mod = getParentModuleOrNull(ID); 2220 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType( 2221 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU, 2222 DefUnit, Line, RuntimeLang); 2223 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); 2224 return FwdDecl; 2225 } 2226 2227 return CreateTypeDefinition(Ty, Unit); 2228 } 2229 2230 llvm::DIModule * 2231 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod, 2232 bool CreateSkeletonCU) { 2233 // Use the Module pointer as the key into the cache. This is a 2234 // nullptr if the "Module" is a PCH, which is safe because we don't 2235 // support chained PCH debug info, so there can only be a single PCH. 2236 const Module *M = Mod.getModuleOrNull(); 2237 auto ModRef = ModuleCache.find(M); 2238 if (ModRef != ModuleCache.end()) 2239 return cast<llvm::DIModule>(ModRef->second); 2240 2241 // Macro definitions that were defined with "-D" on the command line. 2242 SmallString<128> ConfigMacros; 2243 { 2244 llvm::raw_svector_ostream OS(ConfigMacros); 2245 const auto &PPOpts = CGM.getPreprocessorOpts(); 2246 unsigned I = 0; 2247 // Translate the macro definitions back into a command line. 2248 for (auto &M : PPOpts.Macros) { 2249 if (++I > 1) 2250 OS << " "; 2251 const std::string &Macro = M.first; 2252 bool Undef = M.second; 2253 OS << "\"-" << (Undef ? 'U' : 'D'); 2254 for (char c : Macro) 2255 switch (c) { 2256 case '\\': 2257 OS << "\\\\"; 2258 break; 2259 case '"': 2260 OS << "\\\""; 2261 break; 2262 default: 2263 OS << c; 2264 } 2265 OS << '\"'; 2266 } 2267 } 2268 2269 bool IsRootModule = M ? !M->Parent : true; 2270 if (CreateSkeletonCU && IsRootModule) { 2271 // PCH files don't have a signature field in the control block, 2272 // but LLVM detects skeleton CUs by looking for a non-zero DWO id. 2273 // We use the lower 64 bits for debug info. 2274 uint64_t Signature = 2275 Mod.getSignature() 2276 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0] 2277 : ~1ULL; 2278 llvm::DIBuilder DIB(CGM.getModule()); 2279 DIB.createCompileUnit(TheCU->getSourceLanguage(), 2280 // TODO: Support "Source" from external AST providers? 2281 DIB.createFile(Mod.getModuleName(), Mod.getPath()), 2282 TheCU->getProducer(), true, StringRef(), 0, 2283 Mod.getASTFile(), llvm::DICompileUnit::FullDebug, 2284 Signature); 2285 DIB.finalize(); 2286 } 2287 llvm::DIModule *Parent = 2288 IsRootModule ? nullptr 2289 : getOrCreateModuleRef( 2290 ExternalASTSource::ASTSourceDescriptor(*M->Parent), 2291 CreateSkeletonCU); 2292 llvm::DIModule *DIMod = 2293 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros, 2294 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot); 2295 ModuleCache[M].reset(DIMod); 2296 return DIMod; 2297 } 2298 2299 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, 2300 llvm::DIFile *Unit) { 2301 ObjCInterfaceDecl *ID = Ty->getDecl(); 2302 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 2303 unsigned Line = getLineNumber(ID->getLocation()); 2304 unsigned RuntimeLang = TheCU->getSourceLanguage(); 2305 2306 // Bit size, align and offset of the type. 2307 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2308 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 2309 2310 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 2311 if (ID->getImplementation()) 2312 Flags |= llvm::DINode::FlagObjcClassComplete; 2313 2314 llvm::DIScope *Mod = getParentModuleOrNull(ID); 2315 llvm::DICompositeType *RealDecl = DBuilder.createStructType( 2316 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, 2317 nullptr, llvm::DINodeArray(), RuntimeLang); 2318 2319 QualType QTy(Ty, 0); 2320 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl); 2321 2322 // Push the struct on region stack. 2323 LexicalBlockStack.emplace_back(RealDecl); 2324 RegionMap[Ty->getDecl()].reset(RealDecl); 2325 2326 // Convert all the elements. 2327 SmallVector<llvm::Metadata *, 16> EltTys; 2328 2329 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 2330 if (SClass) { 2331 llvm::DIType *SClassTy = 2332 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 2333 if (!SClassTy) 2334 return nullptr; 2335 2336 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0, 2337 llvm::DINode::FlagZero); 2338 EltTys.push_back(InhTag); 2339 } 2340 2341 // Create entries for all of the properties. 2342 auto AddProperty = [&](const ObjCPropertyDecl *PD) { 2343 SourceLocation Loc = PD->getLocation(); 2344 llvm::DIFile *PUnit = getOrCreateFile(Loc); 2345 unsigned PLine = getLineNumber(Loc); 2346 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 2347 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 2348 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( 2349 PD->getName(), PUnit, PLine, 2350 hasDefaultGetterName(PD, Getter) ? "" 2351 : getSelectorName(PD->getGetterName()), 2352 hasDefaultSetterName(PD, Setter) ? "" 2353 : getSelectorName(PD->getSetterName()), 2354 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit)); 2355 EltTys.push_back(PropertyNode); 2356 }; 2357 { 2358 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet; 2359 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions()) 2360 for (auto *PD : ClassExt->properties()) { 2361 PropertySet.insert(PD->getIdentifier()); 2362 AddProperty(PD); 2363 } 2364 for (const auto *PD : ID->properties()) { 2365 // Don't emit duplicate metadata for properties that were already in a 2366 // class extension. 2367 if (!PropertySet.insert(PD->getIdentifier()).second) 2368 continue; 2369 AddProperty(PD); 2370 } 2371 } 2372 2373 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 2374 unsigned FieldNo = 0; 2375 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 2376 Field = Field->getNextIvar(), ++FieldNo) { 2377 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 2378 if (!FieldTy) 2379 return nullptr; 2380 2381 StringRef FieldName = Field->getName(); 2382 2383 // Ignore unnamed fields. 2384 if (FieldName.empty()) 2385 continue; 2386 2387 // Get the location for the field. 2388 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation()); 2389 unsigned FieldLine = getLineNumber(Field->getLocation()); 2390 QualType FType = Field->getType(); 2391 uint64_t FieldSize = 0; 2392 uint32_t FieldAlign = 0; 2393 2394 if (!FType->isIncompleteArrayType()) { 2395 2396 // Bit size, align and offset of the type. 2397 FieldSize = Field->isBitField() 2398 ? Field->getBitWidthValue(CGM.getContext()) 2399 : CGM.getContext().getTypeSize(FType); 2400 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext()); 2401 } 2402 2403 uint64_t FieldOffset; 2404 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2405 // We don't know the runtime offset of an ivar if we're using the 2406 // non-fragile ABI. For bitfields, use the bit offset into the first 2407 // byte of storage of the bitfield. For other fields, use zero. 2408 if (Field->isBitField()) { 2409 FieldOffset = 2410 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field); 2411 FieldOffset %= CGM.getContext().getCharWidth(); 2412 } else { 2413 FieldOffset = 0; 2414 } 2415 } else { 2416 FieldOffset = RL.getFieldOffset(FieldNo); 2417 } 2418 2419 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 2420 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 2421 Flags = llvm::DINode::FlagProtected; 2422 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 2423 Flags = llvm::DINode::FlagPrivate; 2424 else if (Field->getAccessControl() == ObjCIvarDecl::Public) 2425 Flags = llvm::DINode::FlagPublic; 2426 2427 llvm::MDNode *PropertyNode = nullptr; 2428 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 2429 if (ObjCPropertyImplDecl *PImpD = 2430 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 2431 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 2432 SourceLocation Loc = PD->getLocation(); 2433 llvm::DIFile *PUnit = getOrCreateFile(Loc); 2434 unsigned PLine = getLineNumber(Loc); 2435 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 2436 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 2437 PropertyNode = DBuilder.createObjCProperty( 2438 PD->getName(), PUnit, PLine, 2439 hasDefaultGetterName(PD, Getter) 2440 ? "" 2441 : getSelectorName(PD->getGetterName()), 2442 hasDefaultSetterName(PD, Setter) 2443 ? "" 2444 : getSelectorName(PD->getSetterName()), 2445 PD->getPropertyAttributes(), 2446 getOrCreateType(PD->getType(), PUnit)); 2447 } 2448 } 2449 } 2450 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine, 2451 FieldSize, FieldAlign, FieldOffset, Flags, 2452 FieldTy, PropertyNode); 2453 EltTys.push_back(FieldTy); 2454 } 2455 2456 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 2457 DBuilder.replaceArrays(RealDecl, Elements); 2458 2459 LexicalBlockStack.pop_back(); 2460 return RealDecl; 2461 } 2462 2463 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty, 2464 llvm::DIFile *Unit) { 2465 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit); 2466 int64_t Count = Ty->getNumElements(); 2467 2468 llvm::Metadata *Subscript; 2469 QualType QTy(Ty, 0); 2470 auto SizeExpr = SizeExprCache.find(QTy); 2471 if (SizeExpr != SizeExprCache.end()) 2472 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond()); 2473 else 2474 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1); 2475 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 2476 2477 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2478 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 2479 2480 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 2481 } 2482 2483 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) { 2484 uint64_t Size; 2485 uint32_t Align; 2486 2487 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 2488 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) { 2489 Size = 0; 2490 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT), 2491 CGM.getContext()); 2492 } else if (Ty->isIncompleteArrayType()) { 2493 Size = 0; 2494 if (Ty->getElementType()->isIncompleteType()) 2495 Align = 0; 2496 else 2497 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext()); 2498 } else if (Ty->isIncompleteType()) { 2499 Size = 0; 2500 Align = 0; 2501 } else { 2502 // Size and align of the whole array, not the element type. 2503 Size = CGM.getContext().getTypeSize(Ty); 2504 Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 2505 } 2506 2507 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 2508 // interior arrays, do we care? Why aren't nested arrays represented the 2509 // obvious/recursive way? 2510 SmallVector<llvm::Metadata *, 8> Subscripts; 2511 QualType EltTy(Ty, 0); 2512 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 2513 // If the number of elements is known, then count is that number. Otherwise, 2514 // it's -1. This allows us to represent a subrange with an array of 0 2515 // elements, like this: 2516 // 2517 // struct foo { 2518 // int x[0]; 2519 // }; 2520 int64_t Count = -1; // Count == -1 is an unbounded array. 2521 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty)) 2522 Count = CAT->getSize().getZExtValue(); 2523 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) { 2524 if (Expr *Size = VAT->getSizeExpr()) { 2525 llvm::APSInt V; 2526 if (Size->EvaluateAsInt(V, CGM.getContext())) 2527 Count = V.getExtValue(); 2528 } 2529 } 2530 2531 auto SizeNode = SizeExprCache.find(EltTy); 2532 if (SizeNode != SizeExprCache.end()) 2533 Subscripts.push_back( 2534 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond())); 2535 else 2536 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 2537 EltTy = Ty->getElementType(); 2538 } 2539 2540 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 2541 2542 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 2543 SubscriptArray); 2544 } 2545 2546 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty, 2547 llvm::DIFile *Unit) { 2548 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty, 2549 Ty->getPointeeType(), Unit); 2550 } 2551 2552 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty, 2553 llvm::DIFile *Unit) { 2554 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty, 2555 Ty->getPointeeType(), Unit); 2556 } 2557 2558 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty, 2559 llvm::DIFile *U) { 2560 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 2561 uint64_t Size = 0; 2562 2563 if (!Ty->isIncompleteType()) { 2564 Size = CGM.getContext().getTypeSize(Ty); 2565 2566 // Set the MS inheritance model. There is no flag for the unspecified model. 2567 if (CGM.getTarget().getCXXABI().isMicrosoft()) { 2568 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) { 2569 case MSInheritanceAttr::Keyword_single_inheritance: 2570 Flags |= llvm::DINode::FlagSingleInheritance; 2571 break; 2572 case MSInheritanceAttr::Keyword_multiple_inheritance: 2573 Flags |= llvm::DINode::FlagMultipleInheritance; 2574 break; 2575 case MSInheritanceAttr::Keyword_virtual_inheritance: 2576 Flags |= llvm::DINode::FlagVirtualInheritance; 2577 break; 2578 case MSInheritanceAttr::Keyword_unspecified_inheritance: 2579 break; 2580 } 2581 } 2582 } 2583 2584 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 2585 if (Ty->isMemberDataPointerType()) 2586 return DBuilder.createMemberPointerType( 2587 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0, 2588 Flags); 2589 2590 const FunctionProtoType *FPT = 2591 Ty->getPointeeType()->getAs<FunctionProtoType>(); 2592 return DBuilder.createMemberPointerType( 2593 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType( 2594 Ty->getClass(), FPT->getTypeQuals())), 2595 FPT, U), 2596 ClassType, Size, /*Align=*/0, Flags); 2597 } 2598 2599 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { 2600 auto *FromTy = getOrCreateType(Ty->getValueType(), U); 2601 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy); 2602 } 2603 2604 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) { 2605 return getOrCreateType(Ty->getElementType(), U); 2606 } 2607 2608 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { 2609 const EnumDecl *ED = Ty->getDecl(); 2610 2611 uint64_t Size = 0; 2612 uint32_t Align = 0; 2613 if (!ED->getTypeForDecl()->isIncompleteType()) { 2614 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 2615 Align = getDeclAlignIfRequired(ED, CGM.getContext()); 2616 } 2617 2618 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 2619 2620 bool isImportedFromModule = 2621 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition(); 2622 2623 // If this is just a forward declaration, construct an appropriately 2624 // marked node and just return it. 2625 if (isImportedFromModule || !ED->getDefinition()) { 2626 // Note that it is possible for enums to be created as part of 2627 // their own declcontext. In this case a FwdDecl will be created 2628 // twice. This doesn't cause a problem because both FwdDecls are 2629 // entered into the ReplaceMap: finalize() will replace the first 2630 // FwdDecl with the second and then replace the second with 2631 // complete type. 2632 llvm::DIScope *EDContext = getDeclContextDescriptor(ED); 2633 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 2634 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( 2635 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0)); 2636 2637 unsigned Line = getLineNumber(ED->getLocation()); 2638 StringRef EDName = ED->getName(); 2639 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( 2640 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line, 2641 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier); 2642 2643 ReplaceMap.emplace_back( 2644 std::piecewise_construct, std::make_tuple(Ty), 2645 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 2646 return RetTy; 2647 } 2648 2649 return CreateTypeDefinition(Ty); 2650 } 2651 2652 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { 2653 const EnumDecl *ED = Ty->getDecl(); 2654 uint64_t Size = 0; 2655 uint32_t Align = 0; 2656 if (!ED->getTypeForDecl()->isIncompleteType()) { 2657 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 2658 Align = getDeclAlignIfRequired(ED, CGM.getContext()); 2659 } 2660 2661 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 2662 2663 // Create elements for each enumerator. 2664 SmallVector<llvm::Metadata *, 16> Enumerators; 2665 ED = ED->getDefinition(); 2666 bool IsSigned = ED->getIntegerType()->isSignedIntegerType(); 2667 for (const auto *Enum : ED->enumerators()) { 2668 const auto &InitVal = Enum->getInitVal(); 2669 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue(); 2670 Enumerators.push_back( 2671 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned)); 2672 } 2673 2674 // Return a CompositeType for the enum itself. 2675 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators); 2676 2677 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 2678 unsigned Line = getLineNumber(ED->getLocation()); 2679 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); 2680 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit); 2681 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, 2682 Line, Size, Align, EltArray, ClassTy, 2683 Identifier, ED->isFixed()); 2684 } 2685 2686 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent, 2687 unsigned MType, SourceLocation LineLoc, 2688 StringRef Name, StringRef Value) { 2689 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 2690 return DBuilder.createMacro(Parent, Line, MType, Name, Value); 2691 } 2692 2693 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, 2694 SourceLocation LineLoc, 2695 SourceLocation FileLoc) { 2696 llvm::DIFile *FName = getOrCreateFile(FileLoc); 2697 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 2698 return DBuilder.createTempMacroFile(Parent, Line, FName); 2699 } 2700 2701 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 2702 Qualifiers Quals; 2703 do { 2704 Qualifiers InnerQuals = T.getLocalQualifiers(); 2705 // Qualifiers::operator+() doesn't like it if you add a Qualifier 2706 // that is already there. 2707 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 2708 Quals += InnerQuals; 2709 QualType LastT = T; 2710 switch (T->getTypeClass()) { 2711 default: 2712 return C.getQualifiedType(T.getTypePtr(), Quals); 2713 case Type::TemplateSpecialization: { 2714 const auto *Spec = cast<TemplateSpecializationType>(T); 2715 if (Spec->isTypeAlias()) 2716 return C.getQualifiedType(T.getTypePtr(), Quals); 2717 T = Spec->desugar(); 2718 break; 2719 } 2720 case Type::TypeOfExpr: 2721 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 2722 break; 2723 case Type::TypeOf: 2724 T = cast<TypeOfType>(T)->getUnderlyingType(); 2725 break; 2726 case Type::Decltype: 2727 T = cast<DecltypeType>(T)->getUnderlyingType(); 2728 break; 2729 case Type::UnaryTransform: 2730 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 2731 break; 2732 case Type::Attributed: 2733 T = cast<AttributedType>(T)->getEquivalentType(); 2734 break; 2735 case Type::Elaborated: 2736 T = cast<ElaboratedType>(T)->getNamedType(); 2737 break; 2738 case Type::Paren: 2739 T = cast<ParenType>(T)->getInnerType(); 2740 break; 2741 case Type::SubstTemplateTypeParm: 2742 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 2743 break; 2744 case Type::Auto: 2745 case Type::DeducedTemplateSpecialization: { 2746 QualType DT = cast<DeducedType>(T)->getDeducedType(); 2747 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 2748 T = DT; 2749 break; 2750 } 2751 case Type::Adjusted: 2752 case Type::Decayed: 2753 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 2754 T = cast<AdjustedType>(T)->getAdjustedType(); 2755 break; 2756 } 2757 2758 assert(T != LastT && "Type unwrapping failed to unwrap!"); 2759 (void)LastT; 2760 } while (true); 2761 } 2762 2763 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { 2764 2765 // Unwrap the type as needed for debug information. 2766 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2767 2768 auto It = TypeCache.find(Ty.getAsOpaquePtr()); 2769 if (It != TypeCache.end()) { 2770 // Verify that the debug info still exists. 2771 if (llvm::Metadata *V = It->second) 2772 return cast<llvm::DIType>(V); 2773 } 2774 2775 return nullptr; 2776 } 2777 2778 void CGDebugInfo::completeTemplateDefinition( 2779 const ClassTemplateSpecializationDecl &SD) { 2780 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2781 return; 2782 completeUnusedClass(SD); 2783 } 2784 2785 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) { 2786 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2787 return; 2788 2789 completeClassData(&D); 2790 // In case this type has no member function definitions being emitted, ensure 2791 // it is retained 2792 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr()); 2793 } 2794 2795 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { 2796 if (Ty.isNull()) 2797 return nullptr; 2798 2799 // Unwrap the type as needed for debug information. 2800 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2801 2802 if (auto *T = getTypeOrNull(Ty)) 2803 return T; 2804 2805 llvm::DIType *Res = CreateTypeNode(Ty, Unit); 2806 void *TyPtr = Ty.getAsOpaquePtr(); 2807 2808 // And update the type cache. 2809 TypeCache[TyPtr].reset(Res); 2810 2811 return Res; 2812 } 2813 2814 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { 2815 // A forward declaration inside a module header does not belong to the module. 2816 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition()) 2817 return nullptr; 2818 if (DebugTypeExtRefs && D->isFromASTFile()) { 2819 // Record a reference to an imported clang module or precompiled header. 2820 auto *Reader = CGM.getContext().getExternalSource(); 2821 auto Idx = D->getOwningModuleID(); 2822 auto Info = Reader->getSourceDescriptor(Idx); 2823 if (Info) 2824 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true); 2825 } else if (ClangModuleMap) { 2826 // We are building a clang module or a precompiled header. 2827 // 2828 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies 2829 // and it wouldn't be necessary to specify the parent scope 2830 // because the type is already unique by definition (it would look 2831 // like the output of -fno-standalone-debug). On the other hand, 2832 // the parent scope helps a consumer to quickly locate the object 2833 // file where the type's definition is located, so it might be 2834 // best to make this behavior a command line or debugger tuning 2835 // option. 2836 if (Module *M = D->getOwningModule()) { 2837 // This is a (sub-)module. 2838 auto Info = ExternalASTSource::ASTSourceDescriptor(*M); 2839 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false); 2840 } else { 2841 // This the precompiled header being built. 2842 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false); 2843 } 2844 } 2845 2846 return nullptr; 2847 } 2848 2849 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { 2850 // Handle qualifiers, which recursively handles what they refer to. 2851 if (Ty.hasLocalQualifiers()) 2852 return CreateQualifiedType(Ty, Unit); 2853 2854 // Work out details of type. 2855 switch (Ty->getTypeClass()) { 2856 #define TYPE(Class, Base) 2857 #define ABSTRACT_TYPE(Class, Base) 2858 #define NON_CANONICAL_TYPE(Class, Base) 2859 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2860 #include "clang/AST/TypeNodes.def" 2861 llvm_unreachable("Dependent types cannot show up in debug information"); 2862 2863 case Type::ExtVector: 2864 case Type::Vector: 2865 return CreateType(cast<VectorType>(Ty), Unit); 2866 case Type::ObjCObjectPointer: 2867 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 2868 case Type::ObjCObject: 2869 return CreateType(cast<ObjCObjectType>(Ty), Unit); 2870 case Type::ObjCTypeParam: 2871 return CreateType(cast<ObjCTypeParamType>(Ty), Unit); 2872 case Type::ObjCInterface: 2873 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 2874 case Type::Builtin: 2875 return CreateType(cast<BuiltinType>(Ty)); 2876 case Type::Complex: 2877 return CreateType(cast<ComplexType>(Ty)); 2878 case Type::Pointer: 2879 return CreateType(cast<PointerType>(Ty), Unit); 2880 case Type::BlockPointer: 2881 return CreateType(cast<BlockPointerType>(Ty), Unit); 2882 case Type::Typedef: 2883 return CreateType(cast<TypedefType>(Ty), Unit); 2884 case Type::Record: 2885 return CreateType(cast<RecordType>(Ty)); 2886 case Type::Enum: 2887 return CreateEnumType(cast<EnumType>(Ty)); 2888 case Type::FunctionProto: 2889 case Type::FunctionNoProto: 2890 return CreateType(cast<FunctionType>(Ty), Unit); 2891 case Type::ConstantArray: 2892 case Type::VariableArray: 2893 case Type::IncompleteArray: 2894 return CreateType(cast<ArrayType>(Ty), Unit); 2895 2896 case Type::LValueReference: 2897 return CreateType(cast<LValueReferenceType>(Ty), Unit); 2898 case Type::RValueReference: 2899 return CreateType(cast<RValueReferenceType>(Ty), Unit); 2900 2901 case Type::MemberPointer: 2902 return CreateType(cast<MemberPointerType>(Ty), Unit); 2903 2904 case Type::Atomic: 2905 return CreateType(cast<AtomicType>(Ty), Unit); 2906 2907 case Type::Pipe: 2908 return CreateType(cast<PipeType>(Ty), Unit); 2909 2910 case Type::TemplateSpecialization: 2911 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 2912 2913 case Type::Auto: 2914 case Type::Attributed: 2915 case Type::Adjusted: 2916 case Type::Decayed: 2917 case Type::DeducedTemplateSpecialization: 2918 case Type::Elaborated: 2919 case Type::Paren: 2920 case Type::SubstTemplateTypeParm: 2921 case Type::TypeOfExpr: 2922 case Type::TypeOf: 2923 case Type::Decltype: 2924 case Type::UnaryTransform: 2925 case Type::PackExpansion: 2926 break; 2927 } 2928 2929 llvm_unreachable("type should have been unwrapped!"); 2930 } 2931 2932 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 2933 llvm::DIFile *Unit) { 2934 QualType QTy(Ty, 0); 2935 2936 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy)); 2937 2938 // We may have cached a forward decl when we could have created 2939 // a non-forward decl. Go ahead and create a non-forward decl 2940 // now. 2941 if (T && !T->isForwardDecl()) 2942 return T; 2943 2944 // Otherwise create the type. 2945 llvm::DICompositeType *Res = CreateLimitedType(Ty); 2946 2947 // Propagate members from the declaration to the definition 2948 // CreateType(const RecordType*) will overwrite this with the members in the 2949 // correct order if the full type is needed. 2950 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray()); 2951 2952 // And update the type cache. 2953 TypeCache[QTy.getAsOpaquePtr()].reset(Res); 2954 return Res; 2955 } 2956 2957 // TODO: Currently used for context chains when limiting debug info. 2958 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2959 RecordDecl *RD = Ty->getDecl(); 2960 2961 // Get overall information about the record type for the debug info. 2962 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 2963 unsigned Line = getLineNumber(RD->getLocation()); 2964 StringRef RDName = getClassName(RD); 2965 2966 llvm::DIScope *RDContext = getDeclContextDescriptor(RD); 2967 2968 // If we ended up creating the type during the context chain construction, 2969 // just return that. 2970 auto *T = cast_or_null<llvm::DICompositeType>( 2971 getTypeOrNull(CGM.getContext().getRecordType(RD))); 2972 if (T && (!T->isForwardDecl() || !RD->getDefinition())) 2973 return T; 2974 2975 // If this is just a forward or incomplete declaration, construct an 2976 // appropriately marked node and just return it. 2977 const RecordDecl *D = RD->getDefinition(); 2978 if (!D || !D->isCompleteDefinition()) 2979 return getOrCreateRecordFwdDecl(Ty, RDContext); 2980 2981 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2982 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 2983 2984 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 2985 2986 // Explicitly record the calling convention for C++ records. 2987 auto Flags = llvm::DINode::FlagZero; 2988 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2989 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect) 2990 Flags |= llvm::DINode::FlagTypePassByReference; 2991 else 2992 Flags |= llvm::DINode::FlagTypePassByValue; 2993 2994 // Record if a C++ record is trivial type. 2995 if (CXXRD->isTrivial()) 2996 Flags |= llvm::DINode::FlagTrivial; 2997 } 2998 2999 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( 3000 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 3001 Flags, Identifier); 3002 3003 // Elements of composite types usually have back to the type, creating 3004 // uniquing cycles. Distinct nodes are more efficient. 3005 switch (RealDecl->getTag()) { 3006 default: 3007 llvm_unreachable("invalid composite type tag"); 3008 3009 case llvm::dwarf::DW_TAG_array_type: 3010 case llvm::dwarf::DW_TAG_enumeration_type: 3011 // Array elements and most enumeration elements don't have back references, 3012 // so they don't tend to be involved in uniquing cycles and there is some 3013 // chance of merging them when linking together two modules. Only make 3014 // them distinct if they are ODR-uniqued. 3015 if (Identifier.empty()) 3016 break; 3017 LLVM_FALLTHROUGH; 3018 3019 case llvm::dwarf::DW_TAG_structure_type: 3020 case llvm::dwarf::DW_TAG_union_type: 3021 case llvm::dwarf::DW_TAG_class_type: 3022 // Immediately resolve to a distinct node. 3023 RealDecl = 3024 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl)); 3025 break; 3026 } 3027 3028 RegionMap[Ty->getDecl()].reset(RealDecl); 3029 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl); 3030 3031 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 3032 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(), 3033 CollectCXXTemplateParams(TSpecial, DefUnit)); 3034 return RealDecl; 3035 } 3036 3037 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 3038 llvm::DICompositeType *RealDecl) { 3039 // A class's primary base or the class itself contains the vtable. 3040 llvm::DICompositeType *ContainingType = nullptr; 3041 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 3042 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 3043 // Seek non-virtual primary base root. 3044 while (1) { 3045 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 3046 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 3047 if (PBT && !BRL.isPrimaryBaseVirtual()) 3048 PBase = PBT; 3049 else 3050 break; 3051 } 3052 ContainingType = cast<llvm::DICompositeType>( 3053 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 3054 getOrCreateFile(RD->getLocation()))); 3055 } else if (RD->isDynamicClass()) 3056 ContainingType = RealDecl; 3057 3058 DBuilder.replaceVTableHolder(RealDecl, ContainingType); 3059 } 3060 3061 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, 3062 StringRef Name, uint64_t *Offset) { 3063 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 3064 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 3065 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext()); 3066 llvm::DIType *Ty = 3067 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign, 3068 *Offset, llvm::DINode::FlagZero, FieldTy); 3069 *Offset += FieldSize; 3070 return Ty; 3071 } 3072 3073 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, 3074 StringRef &Name, 3075 StringRef &LinkageName, 3076 llvm::DIScope *&FDContext, 3077 llvm::DINodeArray &TParamsArray, 3078 llvm::DINode::DIFlags &Flags) { 3079 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3080 Name = getFunctionName(FD); 3081 // Use mangled name as linkage name for C/C++ functions. 3082 if (FD->hasPrototype()) { 3083 LinkageName = CGM.getMangledName(GD); 3084 Flags |= llvm::DINode::FlagPrototyped; 3085 } 3086 // No need to replicate the linkage name if it isn't different from the 3087 // subprogram name, no need to have it at all unless coverage is enabled or 3088 // debug is set to more than just line tables or extra debug info is needed. 3089 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs && 3090 !CGM.getCodeGenOpts().EmitGcovNotes && 3091 !CGM.getCodeGenOpts().DebugInfoForProfiling && 3092 DebugKind <= codegenoptions::DebugLineTablesOnly)) 3093 LinkageName = StringRef(); 3094 3095 if (DebugKind >= codegenoptions::LimitedDebugInfo) { 3096 if (const NamespaceDecl *NSDecl = 3097 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 3098 FDContext = getOrCreateNamespace(NSDecl); 3099 else if (const RecordDecl *RDecl = 3100 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { 3101 llvm::DIScope *Mod = getParentModuleOrNull(RDecl); 3102 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU); 3103 } 3104 // Check if it is a noreturn-marked function 3105 if (FD->isNoReturn()) 3106 Flags |= llvm::DINode::FlagNoReturn; 3107 // Collect template parameters. 3108 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 3109 } 3110 } 3111 3112 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, 3113 unsigned &LineNo, QualType &T, 3114 StringRef &Name, StringRef &LinkageName, 3115 llvm::MDTuple *&TemplateParameters, 3116 llvm::DIScope *&VDContext) { 3117 Unit = getOrCreateFile(VD->getLocation()); 3118 LineNo = getLineNumber(VD->getLocation()); 3119 3120 setLocation(VD->getLocation()); 3121 3122 T = VD->getType(); 3123 if (T->isIncompleteArrayType()) { 3124 // CodeGen turns int[] into int[1] so we'll do the same here. 3125 llvm::APInt ConstVal(32, 1); 3126 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 3127 3128 T = CGM.getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal, 3129 0); 3130 } 3131 3132 Name = VD->getName(); 3133 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 3134 !isa<ObjCMethodDecl>(VD->getDeclContext())) 3135 LinkageName = CGM.getMangledName(VD); 3136 if (LinkageName == Name) 3137 LinkageName = StringRef(); 3138 3139 if (isa<VarTemplateSpecializationDecl>(VD)) { 3140 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit); 3141 TemplateParameters = parameterNodes.get(); 3142 } else { 3143 TemplateParameters = nullptr; 3144 } 3145 3146 // Since we emit declarations (DW_AT_members) for static members, place the 3147 // definition of those static members in the namespace they were declared in 3148 // in the source code (the lexical decl context). 3149 // FIXME: Generalize this for even non-member global variables where the 3150 // declaration and definition may have different lexical decl contexts, once 3151 // we have support for emitting declarations of (non-member) global variables. 3152 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() 3153 : VD->getDeclContext(); 3154 // When a record type contains an in-line initialization of a static data 3155 // member, and the record type is marked as __declspec(dllexport), an implicit 3156 // definition of the member will be created in the record context. DWARF 3157 // doesn't seem to have a nice way to describe this in a form that consumers 3158 // are likely to understand, so fake the "normal" situation of a definition 3159 // outside the class by putting it in the global scope. 3160 if (DC->isRecord()) 3161 DC = CGM.getContext().getTranslationUnitDecl(); 3162 3163 llvm::DIScope *Mod = getParentModuleOrNull(VD); 3164 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU); 3165 } 3166 3167 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD, 3168 bool Stub) { 3169 llvm::DINodeArray TParamsArray; 3170 StringRef Name, LinkageName; 3171 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3172 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3173 SourceLocation Loc = GD.getDecl()->getLocation(); 3174 llvm::DIFile *Unit = getOrCreateFile(Loc); 3175 llvm::DIScope *DContext = Unit; 3176 unsigned Line = getLineNumber(Loc); 3177 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray, 3178 Flags); 3179 auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()); 3180 3181 // Build function type. 3182 SmallVector<QualType, 16> ArgTypes; 3183 if (FD) 3184 for (const ParmVarDecl *Parm : FD->parameters()) 3185 ArgTypes.push_back(Parm->getType()); 3186 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 3187 QualType FnType = CGM.getContext().getFunctionType( 3188 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 3189 if (!FD->isExternallyVisible()) 3190 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 3191 if (CGM.getLangOpts().Optimize) 3192 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3193 3194 if (Stub) { 3195 Flags |= getCallSiteRelatedAttrs(); 3196 SPFlags |= llvm::DISubprogram::SPFlagDefinition; 3197 return DBuilder.createFunction( 3198 DContext, Name, LinkageName, Unit, Line, 3199 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags, 3200 TParamsArray.get(), getFunctionDeclaration(FD)); 3201 } 3202 3203 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( 3204 DContext, Name, LinkageName, Unit, Line, 3205 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags, 3206 TParamsArray.get(), getFunctionDeclaration(FD)); 3207 const FunctionDecl *CanonDecl = FD->getCanonicalDecl(); 3208 FwdDeclReplaceMap.emplace_back(std::piecewise_construct, 3209 std::make_tuple(CanonDecl), 3210 std::make_tuple(SP)); 3211 return SP; 3212 } 3213 3214 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) { 3215 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false); 3216 } 3217 3218 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) { 3219 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true); 3220 } 3221 3222 llvm::DIGlobalVariable * 3223 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 3224 QualType T; 3225 StringRef Name, LinkageName; 3226 SourceLocation Loc = VD->getLocation(); 3227 llvm::DIFile *Unit = getOrCreateFile(Loc); 3228 llvm::DIScope *DContext = Unit; 3229 unsigned Line = getLineNumber(Loc); 3230 llvm::MDTuple *TemplateParameters = nullptr; 3231 3232 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters, 3233 DContext); 3234 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3235 auto *GV = DBuilder.createTempGlobalVariableFwdDecl( 3236 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit), 3237 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align); 3238 FwdDeclReplaceMap.emplace_back( 3239 std::piecewise_construct, 3240 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())), 3241 std::make_tuple(static_cast<llvm::Metadata *>(GV))); 3242 return GV; 3243 } 3244 3245 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 3246 // We only need a declaration (not a definition) of the type - so use whatever 3247 // we would otherwise do to get a type for a pointee. (forward declarations in 3248 // limited debug info, full definitions (if the type definition is available) 3249 // in unlimited debug info) 3250 if (const auto *TD = dyn_cast<TypeDecl>(D)) 3251 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 3252 getOrCreateFile(TD->getLocation())); 3253 auto I = DeclCache.find(D->getCanonicalDecl()); 3254 3255 if (I != DeclCache.end()) { 3256 auto N = I->second; 3257 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N)) 3258 return GVE->getVariable(); 3259 return dyn_cast_or_null<llvm::DINode>(N); 3260 } 3261 3262 // No definition for now. Emit a forward definition that might be 3263 // merged with a potential upcoming definition. 3264 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 3265 return getFunctionForwardDeclaration(FD); 3266 else if (const auto *VD = dyn_cast<VarDecl>(D)) 3267 return getGlobalVariableForwardDeclaration(VD); 3268 3269 return nullptr; 3270 } 3271 3272 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { 3273 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3274 return nullptr; 3275 3276 const auto *FD = dyn_cast<FunctionDecl>(D); 3277 if (!FD) 3278 return nullptr; 3279 3280 // Setup context. 3281 auto *S = getDeclContextDescriptor(D); 3282 3283 auto MI = SPCache.find(FD->getCanonicalDecl()); 3284 if (MI == SPCache.end()) { 3285 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 3286 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), 3287 cast<llvm::DICompositeType>(S)); 3288 } 3289 } 3290 if (MI != SPCache.end()) { 3291 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 3292 if (SP && !SP->isDefinition()) 3293 return SP; 3294 } 3295 3296 for (auto NextFD : FD->redecls()) { 3297 auto MI = SPCache.find(NextFD->getCanonicalDecl()); 3298 if (MI != SPCache.end()) { 3299 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 3300 if (SP && !SP->isDefinition()) 3301 return SP; 3302 } 3303 } 3304 return nullptr; 3305 } 3306 3307 // getOrCreateFunctionType - Construct type. If it is a c++ method, include 3308 // implicit parameter "this". 3309 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, 3310 QualType FnType, 3311 llvm::DIFile *F) { 3312 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3313 // Create fake but valid subroutine type. Otherwise -verify would fail, and 3314 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. 3315 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None)); 3316 3317 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) 3318 return getOrCreateMethodType(Method, F); 3319 3320 const auto *FTy = FnType->getAs<FunctionType>(); 3321 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C; 3322 3323 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 3324 // Add "self" and "_cmd" 3325 SmallVector<llvm::Metadata *, 16> Elts; 3326 3327 // First element is always return type. For 'void' functions it is NULL. 3328 QualType ResultTy = OMethod->getReturnType(); 3329 3330 // Replace the instancetype keyword with the actual type. 3331 if (ResultTy == CGM.getContext().getObjCInstanceType()) 3332 ResultTy = CGM.getContext().getPointerType( 3333 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 3334 3335 Elts.push_back(getOrCreateType(ResultTy, F)); 3336 // "self" pointer is always first argument. 3337 QualType SelfDeclTy; 3338 if (auto *SelfDecl = OMethod->getSelfDecl()) 3339 SelfDeclTy = SelfDecl->getType(); 3340 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 3341 if (FPT->getNumParams() > 1) 3342 SelfDeclTy = FPT->getParamType(0); 3343 if (!SelfDeclTy.isNull()) 3344 Elts.push_back( 3345 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F))); 3346 // "_cmd" pointer is always second argument. 3347 Elts.push_back(DBuilder.createArtificialType( 3348 getOrCreateType(CGM.getContext().getObjCSelType(), F))); 3349 // Get rest of the arguments. 3350 for (const auto *PI : OMethod->parameters()) 3351 Elts.push_back(getOrCreateType(PI->getType(), F)); 3352 // Variadic methods need a special marker at the end of the type list. 3353 if (OMethod->isVariadic()) 3354 Elts.push_back(DBuilder.createUnspecifiedParameter()); 3355 3356 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 3357 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 3358 getDwarfCC(CC)); 3359 } 3360 3361 // Handle variadic function types; they need an additional 3362 // unspecified parameter. 3363 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 3364 if (FD->isVariadic()) { 3365 SmallVector<llvm::Metadata *, 16> EltTys; 3366 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 3367 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 3368 for (QualType ParamType : FPT->param_types()) 3369 EltTys.push_back(getOrCreateType(ParamType, F)); 3370 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 3371 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 3372 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 3373 getDwarfCC(CC)); 3374 } 3375 3376 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F)); 3377 } 3378 3379 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, 3380 SourceLocation ScopeLoc, QualType FnType, 3381 llvm::Function *Fn, bool CurFuncIsThunk, 3382 CGBuilderTy &Builder) { 3383 3384 StringRef Name; 3385 StringRef LinkageName; 3386 3387 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 3388 3389 const Decl *D = GD.getDecl(); 3390 bool HasDecl = (D != nullptr); 3391 3392 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3393 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3394 llvm::DIFile *Unit = getOrCreateFile(Loc); 3395 llvm::DIScope *FDContext = Unit; 3396 llvm::DINodeArray TParamsArray; 3397 if (!HasDecl) { 3398 // Use llvm function name. 3399 LinkageName = Fn->getName(); 3400 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3401 // If there is a subprogram for this function available then use it. 3402 auto FI = SPCache.find(FD->getCanonicalDecl()); 3403 if (FI != SPCache.end()) { 3404 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 3405 if (SP && SP->isDefinition()) { 3406 LexicalBlockStack.emplace_back(SP); 3407 RegionMap[D].reset(SP); 3408 return; 3409 } 3410 } 3411 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 3412 TParamsArray, Flags); 3413 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 3414 Name = getObjCMethodName(OMD); 3415 Flags |= llvm::DINode::FlagPrototyped; 3416 } else { 3417 // Use llvm function name. 3418 Name = Fn->getName(); 3419 Flags |= llvm::DINode::FlagPrototyped; 3420 } 3421 if (Name.startswith("\01")) 3422 Name = Name.substr(1); 3423 3424 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) { 3425 Flags |= llvm::DINode::FlagArtificial; 3426 // Artificial functions should not silently reuse CurLoc. 3427 CurLoc = SourceLocation(); 3428 } 3429 3430 if (CurFuncIsThunk) 3431 Flags |= llvm::DINode::FlagThunk; 3432 3433 if (Fn->hasLocalLinkage()) 3434 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 3435 if (CGM.getLangOpts().Optimize) 3436 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3437 3438 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs(); 3439 llvm::DISubprogram::DISPFlags SPFlagsForDef = 3440 SPFlags | llvm::DISubprogram::SPFlagDefinition; 3441 3442 unsigned LineNo = getLineNumber(Loc); 3443 unsigned ScopeLine = getLineNumber(ScopeLoc); 3444 3445 // FIXME: The function declaration we're constructing here is mostly reusing 3446 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 3447 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 3448 // all subprograms instead of the actual context since subprogram definitions 3449 // are emitted as CU level entities by the backend. 3450 llvm::DISubprogram *SP = DBuilder.createFunction( 3451 FDContext, Name, LinkageName, Unit, LineNo, 3452 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, FlagsForDef, 3453 SPFlagsForDef, TParamsArray.get(), getFunctionDeclaration(D)); 3454 Fn->setSubprogram(SP); 3455 // We might get here with a VarDecl in the case we're generating 3456 // code for the initialization of globals. Do not record these decls 3457 // as they will overwrite the actual VarDecl Decl in the cache. 3458 if (HasDecl && isa<FunctionDecl>(D)) 3459 DeclCache[D->getCanonicalDecl()].reset(SP); 3460 3461 if (CGM.getCodeGenOpts().DwarfVersion >= 5) { 3462 // Starting with DWARF V5 method declarations are emitted as children of 3463 // the interface type. 3464 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 3465 const ObjCInterfaceDecl *ID = OMD->getClassInterface(); 3466 QualType QTy(ID->getTypeForDecl(), 0); 3467 auto It = TypeCache.find(QTy.getAsOpaquePtr()); 3468 if (It != TypeCache.end()) { 3469 llvm::DICompositeType *InterfaceDecl = 3470 cast<llvm::DICompositeType>(It->second); 3471 llvm::DISubprogram *FD = DBuilder.createFunction( 3472 InterfaceDecl, Name, LinkageName, Unit, LineNo, 3473 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags, 3474 TParamsArray.get()); 3475 DBuilder.finalizeSubprogram(FD); 3476 ObjCMethodCache[ID].push_back(FD); 3477 } 3478 } 3479 } 3480 3481 // Push the function onto the lexical block stack. 3482 LexicalBlockStack.emplace_back(SP); 3483 3484 if (HasDecl) 3485 RegionMap[D].reset(SP); 3486 } 3487 3488 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, 3489 QualType FnType) { 3490 StringRef Name; 3491 StringRef LinkageName; 3492 3493 const Decl *D = GD.getDecl(); 3494 if (!D) 3495 return; 3496 3497 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3498 llvm::DIFile *Unit = getOrCreateFile(Loc); 3499 llvm::DIScope *FDContext = getDeclContextDescriptor(D); 3500 llvm::DINodeArray TParamsArray; 3501 if (isa<FunctionDecl>(D)) { 3502 // If there is a DISubprogram for this function available then use it. 3503 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 3504 TParamsArray, Flags); 3505 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 3506 Name = getObjCMethodName(OMD); 3507 Flags |= llvm::DINode::FlagPrototyped; 3508 } else { 3509 llvm_unreachable("not a function or ObjC method"); 3510 } 3511 if (!Name.empty() && Name[0] == '\01') 3512 Name = Name.substr(1); 3513 3514 if (D->isImplicit()) { 3515 Flags |= llvm::DINode::FlagArtificial; 3516 // Artificial functions without a location should not silently reuse CurLoc. 3517 if (Loc.isInvalid()) 3518 CurLoc = SourceLocation(); 3519 } 3520 unsigned LineNo = getLineNumber(Loc); 3521 unsigned ScopeLine = 0; 3522 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3523 if (CGM.getLangOpts().Optimize) 3524 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3525 3526 DBuilder.retainType(DBuilder.createFunction( 3527 FDContext, Name, LinkageName, Unit, LineNo, 3528 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags, 3529 TParamsArray.get(), getFunctionDeclaration(D))); 3530 } 3531 3532 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) { 3533 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3534 // If there is a subprogram for this function available then use it. 3535 auto FI = SPCache.find(FD->getCanonicalDecl()); 3536 llvm::DISubprogram *SP = nullptr; 3537 if (FI != SPCache.end()) 3538 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 3539 if (!SP || !SP->isDefinition()) 3540 SP = getFunctionStub(GD); 3541 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 3542 LexicalBlockStack.emplace_back(SP); 3543 setInlinedAt(Builder.getCurrentDebugLocation()); 3544 EmitLocation(Builder, FD->getLocation()); 3545 } 3546 3547 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) { 3548 assert(CurInlinedAt && "unbalanced inline scope stack"); 3549 EmitFunctionEnd(Builder, nullptr); 3550 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt()); 3551 } 3552 3553 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 3554 // Update our current location 3555 setLocation(Loc); 3556 3557 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty()) 3558 return; 3559 3560 llvm::MDNode *Scope = LexicalBlockStack.back(); 3561 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 3562 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt)); 3563 } 3564 3565 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 3566 llvm::MDNode *Back = nullptr; 3567 if (!LexicalBlockStack.empty()) 3568 Back = LexicalBlockStack.back().get(); 3569 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock( 3570 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc), 3571 getColumnNumber(CurLoc))); 3572 } 3573 3574 void CGDebugInfo::AppendAddressSpaceXDeref( 3575 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const { 3576 Optional<unsigned> DWARFAddressSpace = 3577 CGM.getTarget().getDWARFAddressSpace(AddressSpace); 3578 if (!DWARFAddressSpace) 3579 return; 3580 3581 Expr.push_back(llvm::dwarf::DW_OP_constu); 3582 Expr.push_back(DWARFAddressSpace.getValue()); 3583 Expr.push_back(llvm::dwarf::DW_OP_swap); 3584 Expr.push_back(llvm::dwarf::DW_OP_xderef); 3585 } 3586 3587 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 3588 SourceLocation Loc) { 3589 // Set our current location. 3590 setLocation(Loc); 3591 3592 // Emit a line table change for the current location inside the new scope. 3593 Builder.SetCurrentDebugLocation( 3594 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), 3595 LexicalBlockStack.back(), CurInlinedAt)); 3596 3597 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3598 return; 3599 3600 // Create a new lexical block and push it on the stack. 3601 CreateLexicalBlock(Loc); 3602 } 3603 3604 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 3605 SourceLocation Loc) { 3606 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3607 3608 // Provide an entry in the line table for the end of the block. 3609 EmitLocation(Builder, Loc); 3610 3611 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3612 return; 3613 3614 LexicalBlockStack.pop_back(); 3615 } 3616 3617 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) { 3618 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3619 unsigned RCount = FnBeginRegionCount.back(); 3620 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 3621 3622 // Pop all regions for this function. 3623 while (LexicalBlockStack.size() != RCount) { 3624 // Provide an entry in the line table for the end of the block. 3625 EmitLocation(Builder, CurLoc); 3626 LexicalBlockStack.pop_back(); 3627 } 3628 FnBeginRegionCount.pop_back(); 3629 3630 if (Fn && Fn->getSubprogram()) 3631 DBuilder.finalizeSubprogram(Fn->getSubprogram()); 3632 } 3633 3634 CGDebugInfo::BlockByRefType 3635 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 3636 uint64_t *XOffset) { 3637 SmallVector<llvm::Metadata *, 5> EltTys; 3638 QualType FType; 3639 uint64_t FieldSize, FieldOffset; 3640 uint32_t FieldAlign; 3641 3642 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3643 QualType Type = VD->getType(); 3644 3645 FieldOffset = 0; 3646 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3647 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 3648 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 3649 FType = CGM.getContext().IntTy; 3650 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 3651 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 3652 3653 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 3654 if (HasCopyAndDispose) { 3655 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3656 EltTys.push_back( 3657 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 3658 EltTys.push_back( 3659 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 3660 } 3661 bool HasByrefExtendedLayout; 3662 Qualifiers::ObjCLifetime Lifetime; 3663 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 3664 HasByrefExtendedLayout) && 3665 HasByrefExtendedLayout) { 3666 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3667 EltTys.push_back( 3668 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 3669 } 3670 3671 CharUnits Align = CGM.getContext().getDeclAlign(VD); 3672 if (Align > CGM.getContext().toCharUnitsFromBits( 3673 CGM.getTarget().getPointerAlign(0))) { 3674 CharUnits FieldOffsetInBytes = 3675 CGM.getContext().toCharUnitsFromBits(FieldOffset); 3676 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align); 3677 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 3678 3679 if (NumPaddingBytes.isPositive()) { 3680 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 3681 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 3682 pad, ArrayType::Normal, 0); 3683 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 3684 } 3685 } 3686 3687 FType = Type; 3688 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit); 3689 FieldSize = CGM.getContext().getTypeSize(FType); 3690 FieldAlign = CGM.getContext().toBits(Align); 3691 3692 *XOffset = FieldOffset; 3693 llvm::DIType *FieldTy = DBuilder.createMemberType( 3694 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset, 3695 llvm::DINode::FlagZero, WrappedTy); 3696 EltTys.push_back(FieldTy); 3697 FieldOffset += FieldSize; 3698 3699 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 3700 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, 3701 llvm::DINode::FlagZero, nullptr, Elements), 3702 WrappedTy}; 3703 } 3704 3705 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, 3706 llvm::Value *Storage, 3707 llvm::Optional<unsigned> ArgNo, 3708 CGBuilderTy &Builder) { 3709 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3710 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3711 if (VD->hasAttr<NoDebugAttr>()) 3712 return nullptr; 3713 3714 bool Unwritten = 3715 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 3716 cast<Decl>(VD->getDeclContext())->isImplicit()); 3717 llvm::DIFile *Unit = nullptr; 3718 if (!Unwritten) 3719 Unit = getOrCreateFile(VD->getLocation()); 3720 llvm::DIType *Ty; 3721 uint64_t XOffset = 0; 3722 if (VD->hasAttr<BlocksAttr>()) 3723 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType; 3724 else 3725 Ty = getOrCreateType(VD->getType(), Unit); 3726 3727 // If there is no debug info for this type then do not emit debug info 3728 // for this variable. 3729 if (!Ty) 3730 return nullptr; 3731 3732 // Get location information. 3733 unsigned Line = 0; 3734 unsigned Column = 0; 3735 if (!Unwritten) { 3736 Line = getLineNumber(VD->getLocation()); 3737 Column = getColumnNumber(VD->getLocation()); 3738 } 3739 SmallVector<int64_t, 13> Expr; 3740 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3741 if (VD->isImplicit()) 3742 Flags |= llvm::DINode::FlagArtificial; 3743 3744 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3745 3746 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType()); 3747 AppendAddressSpaceXDeref(AddressSpace, Expr); 3748 3749 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an 3750 // object pointer flag. 3751 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) { 3752 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis || 3753 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf) 3754 Flags |= llvm::DINode::FlagObjectPointer; 3755 } 3756 3757 // Note: Older versions of clang used to emit byval references with an extra 3758 // DW_OP_deref, because they referenced the IR arg directly instead of 3759 // referencing an alloca. Newer versions of LLVM don't treat allocas 3760 // differently from other function arguments when used in a dbg.declare. 3761 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 3762 StringRef Name = VD->getName(); 3763 if (!Name.empty()) { 3764 if (VD->hasAttr<BlocksAttr>()) { 3765 // Here, we need an offset *into* the alloca. 3766 CharUnits offset = CharUnits::fromQuantity(32); 3767 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst); 3768 // offset of __forwarding field 3769 offset = CGM.getContext().toCharUnitsFromBits( 3770 CGM.getTarget().getPointerWidth(0)); 3771 Expr.push_back(offset.getQuantity()); 3772 Expr.push_back(llvm::dwarf::DW_OP_deref); 3773 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst); 3774 // offset of x field 3775 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 3776 Expr.push_back(offset.getQuantity()); 3777 } 3778 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) { 3779 // If VD is an anonymous union then Storage represents value for 3780 // all union fields. 3781 const RecordDecl *RD = RT->getDecl(); 3782 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 3783 // GDB has trouble finding local variables in anonymous unions, so we emit 3784 // artificial local variables for each of the members. 3785 // 3786 // FIXME: Remove this code as soon as GDB supports this. 3787 // The debug info verifier in LLVM operates based on the assumption that a 3788 // variable has the same size as its storage and we had to disable the 3789 // check for artificial variables. 3790 for (const auto *Field : RD->fields()) { 3791 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 3792 StringRef FieldName = Field->getName(); 3793 3794 // Ignore unnamed fields. Do not ignore unnamed records. 3795 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 3796 continue; 3797 3798 // Use VarDecl's Tag, Scope and Line number. 3799 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext()); 3800 auto *D = DBuilder.createAutoVariable( 3801 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize, 3802 Flags | llvm::DINode::FlagArtificial, FieldAlign); 3803 3804 // Insert an llvm.dbg.declare into the current block. 3805 DBuilder.insertDeclare( 3806 Storage, D, DBuilder.createExpression(Expr), 3807 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt), 3808 Builder.GetInsertBlock()); 3809 } 3810 } 3811 } 3812 3813 // Create the descriptor for the variable. 3814 auto *D = ArgNo ? DBuilder.createParameterVariable( 3815 Scope, Name, *ArgNo, Unit, Line, Ty, 3816 CGM.getLangOpts().Optimize, Flags) 3817 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty, 3818 CGM.getLangOpts().Optimize, 3819 Flags, Align); 3820 3821 // Insert an llvm.dbg.declare into the current block. 3822 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 3823 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt), 3824 Builder.GetInsertBlock()); 3825 3826 return D; 3827 } 3828 3829 llvm::DILocalVariable * 3830 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage, 3831 CGBuilderTy &Builder) { 3832 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3833 return EmitDeclare(VD, Storage, llvm::None, Builder); 3834 } 3835 3836 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, 3837 llvm::DIType *Ty) { 3838 llvm::DIType *CachedTy = getTypeOrNull(QualTy); 3839 if (CachedTy) 3840 Ty = CachedTy; 3841 return DBuilder.createObjectPointerType(Ty); 3842 } 3843 3844 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 3845 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 3846 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { 3847 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3848 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3849 3850 if (Builder.GetInsertBlock() == nullptr) 3851 return; 3852 if (VD->hasAttr<NoDebugAttr>()) 3853 return; 3854 3855 bool isByRef = VD->hasAttr<BlocksAttr>(); 3856 3857 uint64_t XOffset = 0; 3858 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3859 llvm::DIType *Ty; 3860 if (isByRef) 3861 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType; 3862 else 3863 Ty = getOrCreateType(VD->getType(), Unit); 3864 3865 // Self is passed along as an implicit non-arg variable in a 3866 // block. Mark it as the object pointer. 3867 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) 3868 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf) 3869 Ty = CreateSelfType(VD->getType(), Ty); 3870 3871 // Get location information. 3872 unsigned Line = getLineNumber(VD->getLocation()); 3873 unsigned Column = getColumnNumber(VD->getLocation()); 3874 3875 const llvm::DataLayout &target = CGM.getDataLayout(); 3876 3877 CharUnits offset = CharUnits::fromQuantity( 3878 target.getStructLayout(blockInfo.StructureType) 3879 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 3880 3881 SmallVector<int64_t, 9> addr; 3882 addr.push_back(llvm::dwarf::DW_OP_deref); 3883 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 3884 addr.push_back(offset.getQuantity()); 3885 if (isByRef) { 3886 addr.push_back(llvm::dwarf::DW_OP_deref); 3887 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 3888 // offset of __forwarding field 3889 offset = 3890 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 3891 addr.push_back(offset.getQuantity()); 3892 addr.push_back(llvm::dwarf::DW_OP_deref); 3893 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 3894 // offset of x field 3895 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 3896 addr.push_back(offset.getQuantity()); 3897 } 3898 3899 // Create the descriptor for the variable. 3900 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3901 auto *D = DBuilder.createAutoVariable( 3902 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit, 3903 Line, Ty, false, llvm::DINode::FlagZero, Align); 3904 3905 // Insert an llvm.dbg.declare into the current block. 3906 auto DL = 3907 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt); 3908 auto *Expr = DBuilder.createExpression(addr); 3909 if (InsertPoint) 3910 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint); 3911 else 3912 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock()); 3913 } 3914 3915 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 3916 unsigned ArgNo, 3917 CGBuilderTy &Builder) { 3918 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3919 EmitDeclare(VD, AI, ArgNo, Builder); 3920 } 3921 3922 namespace { 3923 struct BlockLayoutChunk { 3924 uint64_t OffsetInBits; 3925 const BlockDecl::Capture *Capture; 3926 }; 3927 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 3928 return l.OffsetInBits < r.OffsetInBits; 3929 } 3930 } // namespace 3931 3932 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare( 3933 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc, 3934 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit, 3935 SmallVectorImpl<llvm::Metadata *> &Fields) { 3936 // Blocks in OpenCL have unique constraints which make the standard fields 3937 // redundant while requiring size and align fields for enqueue_kernel. See 3938 // initializeForBlockHeader in CGBlocks.cpp 3939 if (CGM.getLangOpts().OpenCL) { 3940 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public, 3941 BlockLayout.getElementOffsetInBits(0), 3942 Unit, Unit)); 3943 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public, 3944 BlockLayout.getElementOffsetInBits(1), 3945 Unit, Unit)); 3946 } else { 3947 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public, 3948 BlockLayout.getElementOffsetInBits(0), 3949 Unit, Unit)); 3950 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public, 3951 BlockLayout.getElementOffsetInBits(1), 3952 Unit, Unit)); 3953 Fields.push_back( 3954 createFieldType("__reserved", Context.IntTy, Loc, AS_public, 3955 BlockLayout.getElementOffsetInBits(2), Unit, Unit)); 3956 auto *FnTy = Block.getBlockExpr()->getFunctionType(); 3957 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 3958 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public, 3959 BlockLayout.getElementOffsetInBits(3), 3960 Unit, Unit)); 3961 Fields.push_back(createFieldType( 3962 "__descriptor", 3963 Context.getPointerType(Block.NeedsCopyDispose 3964 ? Context.getBlockDescriptorExtendedType() 3965 : Context.getBlockDescriptorType()), 3966 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit)); 3967 } 3968 } 3969 3970 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 3971 StringRef Name, 3972 unsigned ArgNo, 3973 llvm::AllocaInst *Alloca, 3974 CGBuilderTy &Builder) { 3975 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3976 ASTContext &C = CGM.getContext(); 3977 const BlockDecl *blockDecl = block.getBlockDecl(); 3978 3979 // Collect some general information about the block's location. 3980 SourceLocation loc = blockDecl->getCaretLocation(); 3981 llvm::DIFile *tunit = getOrCreateFile(loc); 3982 unsigned line = getLineNumber(loc); 3983 unsigned column = getColumnNumber(loc); 3984 3985 // Build the debug-info type for the block literal. 3986 getDeclContextDescriptor(blockDecl); 3987 3988 const llvm::StructLayout *blockLayout = 3989 CGM.getDataLayout().getStructLayout(block.StructureType); 3990 3991 SmallVector<llvm::Metadata *, 16> fields; 3992 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit, 3993 fields); 3994 3995 // We want to sort the captures by offset, not because DWARF 3996 // requires this, but because we're paranoid about debuggers. 3997 SmallVector<BlockLayoutChunk, 8> chunks; 3998 3999 // 'this' capture. 4000 if (blockDecl->capturesCXXThis()) { 4001 BlockLayoutChunk chunk; 4002 chunk.OffsetInBits = 4003 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 4004 chunk.Capture = nullptr; 4005 chunks.push_back(chunk); 4006 } 4007 4008 // Variable captures. 4009 for (const auto &capture : blockDecl->captures()) { 4010 const VarDecl *variable = capture.getVariable(); 4011 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 4012 4013 // Ignore constant captures. 4014 if (captureInfo.isConstant()) 4015 continue; 4016 4017 BlockLayoutChunk chunk; 4018 chunk.OffsetInBits = 4019 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 4020 chunk.Capture = &capture; 4021 chunks.push_back(chunk); 4022 } 4023 4024 // Sort by offset. 4025 llvm::array_pod_sort(chunks.begin(), chunks.end()); 4026 4027 for (const BlockLayoutChunk &Chunk : chunks) { 4028 uint64_t offsetInBits = Chunk.OffsetInBits; 4029 const BlockDecl::Capture *capture = Chunk.Capture; 4030 4031 // If we have a null capture, this must be the C++ 'this' capture. 4032 if (!capture) { 4033 QualType type; 4034 if (auto *Method = 4035 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext())) 4036 type = Method->getThisType(C); 4037 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent())) 4038 type = QualType(RDecl->getTypeForDecl(), 0); 4039 else 4040 llvm_unreachable("unexpected block declcontext"); 4041 4042 fields.push_back(createFieldType("this", type, loc, AS_public, 4043 offsetInBits, tunit, tunit)); 4044 continue; 4045 } 4046 4047 const VarDecl *variable = capture->getVariable(); 4048 StringRef name = variable->getName(); 4049 4050 llvm::DIType *fieldType; 4051 if (capture->isByRef()) { 4052 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 4053 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0; 4054 // FIXME: This recomputes the layout of the BlockByRefWrapper. 4055 uint64_t xoffset; 4056 fieldType = 4057 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper; 4058 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 4059 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 4060 PtrInfo.Width, Align, offsetInBits, 4061 llvm::DINode::FlagZero, fieldType); 4062 } else { 4063 auto Align = getDeclAlignIfRequired(variable, CGM.getContext()); 4064 fieldType = createFieldType(name, variable->getType(), loc, AS_public, 4065 offsetInBits, Align, tunit, tunit); 4066 } 4067 fields.push_back(fieldType); 4068 } 4069 4070 SmallString<36> typeName; 4071 llvm::raw_svector_ostream(typeName) 4072 << "__block_literal_" << CGM.getUniqueBlockCount(); 4073 4074 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields); 4075 4076 llvm::DIType *type = 4077 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 4078 CGM.getContext().toBits(block.BlockSize), 0, 4079 llvm::DINode::FlagZero, nullptr, fieldsArray); 4080 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 4081 4082 // Get overall information about the block. 4083 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial; 4084 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back()); 4085 4086 // Create the descriptor for the parameter. 4087 auto *debugVar = DBuilder.createParameterVariable( 4088 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags); 4089 4090 // Insert an llvm.dbg.declare into the current block. 4091 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(), 4092 llvm::DebugLoc::get(line, column, scope, CurInlinedAt), 4093 Builder.GetInsertBlock()); 4094 } 4095 4096 llvm::DIDerivedType * 4097 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 4098 if (!D->isStaticDataMember()) 4099 return nullptr; 4100 4101 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 4102 if (MI != StaticDataMemberCache.end()) { 4103 assert(MI->second && "Static data member declaration should still exist"); 4104 return MI->second; 4105 } 4106 4107 // If the member wasn't found in the cache, lazily construct and add it to the 4108 // type (used when a limited form of the type is emitted). 4109 auto DC = D->getDeclContext(); 4110 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D)); 4111 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 4112 } 4113 4114 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls( 4115 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, 4116 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { 4117 llvm::DIGlobalVariableExpression *GVE = nullptr; 4118 4119 for (const auto *Field : RD->fields()) { 4120 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 4121 StringRef FieldName = Field->getName(); 4122 4123 // Ignore unnamed fields, but recurse into anonymous records. 4124 if (FieldName.empty()) { 4125 if (const auto *RT = dyn_cast<RecordType>(Field->getType())) 4126 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 4127 Var, DContext); 4128 continue; 4129 } 4130 // Use VarDecl's Tag, Scope and Line number. 4131 GVE = DBuilder.createGlobalVariableExpression( 4132 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy, 4133 Var->hasLocalLinkage()); 4134 Var->addDebugInfo(GVE); 4135 } 4136 return GVE; 4137 } 4138 4139 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 4140 const VarDecl *D) { 4141 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4142 if (D->hasAttr<NoDebugAttr>()) 4143 return; 4144 4145 // If we already created a DIGlobalVariable for this declaration, just attach 4146 // it to the llvm::GlobalVariable. 4147 auto Cached = DeclCache.find(D->getCanonicalDecl()); 4148 if (Cached != DeclCache.end()) 4149 return Var->addDebugInfo( 4150 cast<llvm::DIGlobalVariableExpression>(Cached->second)); 4151 4152 // Create global variable debug descriptor. 4153 llvm::DIFile *Unit = nullptr; 4154 llvm::DIScope *DContext = nullptr; 4155 unsigned LineNo; 4156 StringRef DeclName, LinkageName; 4157 QualType T; 4158 llvm::MDTuple *TemplateParameters = nullptr; 4159 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, 4160 TemplateParameters, DContext); 4161 4162 // Attempt to store one global variable for the declaration - even if we 4163 // emit a lot of fields. 4164 llvm::DIGlobalVariableExpression *GVE = nullptr; 4165 4166 // If this is an anonymous union then we'll want to emit a global 4167 // variable for each member of the anonymous union so that it's possible 4168 // to find the name of any field in the union. 4169 if (T->isUnionType() && DeclName.empty()) { 4170 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 4171 assert(RD->isAnonymousStructOrUnion() && 4172 "unnamed non-anonymous struct or union?"); 4173 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 4174 } else { 4175 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 4176 4177 SmallVector<int64_t, 4> Expr; 4178 unsigned AddressSpace = 4179 CGM.getContext().getTargetAddressSpace(D->getType()); 4180 AppendAddressSpaceXDeref(AddressSpace, Expr); 4181 4182 GVE = DBuilder.createGlobalVariableExpression( 4183 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 4184 Var->hasLocalLinkage(), 4185 Expr.empty() ? nullptr : DBuilder.createExpression(Expr), 4186 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters, 4187 Align); 4188 Var->addDebugInfo(GVE); 4189 } 4190 DeclCache[D->getCanonicalDecl()].reset(GVE); 4191 } 4192 4193 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) { 4194 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4195 if (VD->hasAttr<NoDebugAttr>()) 4196 return; 4197 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 4198 // Create the descriptor for the variable. 4199 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 4200 StringRef Name = VD->getName(); 4201 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit); 4202 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) { 4203 const auto *ED = cast<EnumDecl>(ECD->getDeclContext()); 4204 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 4205 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 4206 } 4207 // Do not use global variables for enums. 4208 // 4209 // FIXME: why not? 4210 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type) 4211 return; 4212 // Do not emit separate definitions for function local const/statics. 4213 if (isa<FunctionDecl>(VD->getDeclContext())) 4214 return; 4215 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 4216 auto *VarD = cast<VarDecl>(VD); 4217 if (VarD->isStaticDataMember()) { 4218 auto *RD = cast<RecordDecl>(VarD->getDeclContext()); 4219 getDeclContextDescriptor(VarD); 4220 // Ensure that the type is retained even though it's otherwise unreferenced. 4221 // 4222 // FIXME: This is probably unnecessary, since Ty should reference RD 4223 // through its scope. 4224 RetainedTypes.push_back( 4225 CGM.getContext().getRecordType(RD).getAsOpaquePtr()); 4226 return; 4227 } 4228 4229 llvm::DIScope *DContext = getDeclContextDescriptor(VD); 4230 4231 auto &GV = DeclCache[VD]; 4232 if (GV) 4233 return; 4234 llvm::DIExpression *InitExpr = nullptr; 4235 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) { 4236 // FIXME: Add a representation for integer constants wider than 64 bits. 4237 if (Init.isInt()) 4238 InitExpr = 4239 DBuilder.createConstantValueExpression(Init.getInt().getExtValue()); 4240 else if (Init.isFloat()) 4241 InitExpr = DBuilder.createConstantValueExpression( 4242 Init.getFloat().bitcastToAPInt().getZExtValue()); 4243 } 4244 4245 llvm::MDTuple *TemplateParameters = nullptr; 4246 4247 if (isa<VarTemplateSpecializationDecl>(VD)) 4248 if (VarD) { 4249 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit); 4250 TemplateParameters = parameterNodes.get(); 4251 } 4252 4253 GV.reset(DBuilder.createGlobalVariableExpression( 4254 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 4255 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD), 4256 TemplateParameters, Align)); 4257 } 4258 4259 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 4260 if (!LexicalBlockStack.empty()) 4261 return LexicalBlockStack.back(); 4262 llvm::DIScope *Mod = getParentModuleOrNull(D); 4263 return getContextDescriptor(D, Mod ? Mod : TheCU); 4264 } 4265 4266 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 4267 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4268 return; 4269 const NamespaceDecl *NSDecl = UD.getNominatedNamespace(); 4270 if (!NSDecl->isAnonymousNamespace() || 4271 CGM.getCodeGenOpts().DebugExplicitImport) { 4272 auto Loc = UD.getLocation(); 4273 DBuilder.createImportedModule( 4274 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 4275 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc)); 4276 } 4277 } 4278 4279 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 4280 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4281 return; 4282 assert(UD.shadow_size() && 4283 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 4284 // Emitting one decl is sufficient - debuggers can detect that this is an 4285 // overloaded name & provide lookup for all the overloads. 4286 const UsingShadowDecl &USD = **UD.shadow_begin(); 4287 4288 // FIXME: Skip functions with undeduced auto return type for now since we 4289 // don't currently have the plumbing for separate declarations & definitions 4290 // of free functions and mismatched types (auto in the declaration, concrete 4291 // return type in the definition) 4292 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl())) 4293 if (const auto *AT = 4294 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType()) 4295 if (AT->getDeducedType().isNull()) 4296 return; 4297 if (llvm::DINode *Target = 4298 getDeclarationOrDefinition(USD.getUnderlyingDecl())) { 4299 auto Loc = USD.getLocation(); 4300 DBuilder.createImportedDeclaration( 4301 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 4302 getOrCreateFile(Loc), getLineNumber(Loc)); 4303 } 4304 } 4305 4306 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { 4307 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB) 4308 return; 4309 if (Module *M = ID.getImportedModule()) { 4310 auto Info = ExternalASTSource::ASTSourceDescriptor(*M); 4311 auto Loc = ID.getLocation(); 4312 DBuilder.createImportedDeclaration( 4313 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())), 4314 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc), 4315 getLineNumber(Loc)); 4316 } 4317 } 4318 4319 llvm::DIImportedEntity * 4320 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 4321 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4322 return nullptr; 4323 auto &VH = NamespaceAliasCache[&NA]; 4324 if (VH) 4325 return cast<llvm::DIImportedEntity>(VH); 4326 llvm::DIImportedEntity *R; 4327 auto Loc = NA.getLocation(); 4328 if (const auto *Underlying = 4329 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 4330 // This could cache & dedup here rather than relying on metadata deduping. 4331 R = DBuilder.createImportedDeclaration( 4332 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 4333 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc), 4334 getLineNumber(Loc), NA.getName()); 4335 else 4336 R = DBuilder.createImportedDeclaration( 4337 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 4338 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 4339 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName()); 4340 VH.reset(R); 4341 return R; 4342 } 4343 4344 llvm::DINamespace * 4345 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) { 4346 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued 4347 // if necessary, and this way multiple declarations of the same namespace in 4348 // different parent modules stay distinct. 4349 auto I = NamespaceCache.find(NSDecl); 4350 if (I != NamespaceCache.end()) 4351 return cast<llvm::DINamespace>(I->second); 4352 4353 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); 4354 // Don't trust the context if it is a DIModule (see comment above). 4355 llvm::DINamespace *NS = 4356 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline()); 4357 NamespaceCache[NSDecl].reset(NS); 4358 return NS; 4359 } 4360 4361 void CGDebugInfo::setDwoId(uint64_t Signature) { 4362 assert(TheCU && "no main compile unit"); 4363 TheCU->setDWOId(Signature); 4364 } 4365 4366 void CGDebugInfo::finalize() { 4367 // Creating types might create further types - invalidating the current 4368 // element and the size(), so don't cache/reference them. 4369 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 4370 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 4371 llvm::DIType *Ty = E.Type->getDecl()->getDefinition() 4372 ? CreateTypeDefinition(E.Type, E.Unit) 4373 : E.Decl; 4374 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty); 4375 } 4376 4377 if (CGM.getCodeGenOpts().DwarfVersion >= 5) { 4378 // Add methods to interface. 4379 for (const auto &P : ObjCMethodCache) { 4380 if (P.second.empty()) 4381 continue; 4382 4383 QualType QTy(P.first->getTypeForDecl(), 0); 4384 auto It = TypeCache.find(QTy.getAsOpaquePtr()); 4385 assert(It != TypeCache.end()); 4386 4387 llvm::DICompositeType *InterfaceDecl = 4388 cast<llvm::DICompositeType>(It->second); 4389 4390 SmallVector<llvm::Metadata *, 16> EltTys; 4391 auto CurrenetElts = InterfaceDecl->getElements(); 4392 EltTys.append(CurrenetElts.begin(), CurrenetElts.end()); 4393 for (auto &MD : P.second) 4394 EltTys.push_back(MD); 4395 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 4396 DBuilder.replaceArrays(InterfaceDecl, Elements); 4397 } 4398 } 4399 4400 for (const auto &P : ReplaceMap) { 4401 assert(P.second); 4402 auto *Ty = cast<llvm::DIType>(P.second); 4403 assert(Ty->isForwardDecl()); 4404 4405 auto It = TypeCache.find(P.first); 4406 assert(It != TypeCache.end()); 4407 assert(It->second); 4408 4409 DBuilder.replaceTemporary(llvm::TempDIType(Ty), 4410 cast<llvm::DIType>(It->second)); 4411 } 4412 4413 for (const auto &P : FwdDeclReplaceMap) { 4414 assert(P.second); 4415 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second)); 4416 llvm::Metadata *Repl; 4417 4418 auto It = DeclCache.find(P.first); 4419 // If there has been no definition for the declaration, call RAUW 4420 // with ourselves, that will destroy the temporary MDNode and 4421 // replace it with a standard one, avoiding leaking memory. 4422 if (It == DeclCache.end()) 4423 Repl = P.second; 4424 else 4425 Repl = It->second; 4426 4427 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl)) 4428 Repl = GVE->getVariable(); 4429 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl)); 4430 } 4431 4432 // We keep our own list of retained types, because we need to look 4433 // up the final type in the type cache. 4434 for (auto &RT : RetainedTypes) 4435 if (auto MD = TypeCache[RT]) 4436 DBuilder.retainType(cast<llvm::DIType>(MD)); 4437 4438 DBuilder.finalize(); 4439 } 4440 4441 void CGDebugInfo::EmitExplicitCastType(QualType Ty) { 4442 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4443 return; 4444 4445 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile())) 4446 // Don't ignore in case of explicit cast where it is referenced indirectly. 4447 DBuilder.retainType(DieTy); 4448 } 4449 4450 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) { 4451 if (LexicalBlockStack.empty()) 4452 return llvm::DebugLoc(); 4453 4454 llvm::MDNode *Scope = LexicalBlockStack.back(); 4455 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope); 4456 } 4457 4458 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const { 4459 // Call site-related attributes are only useful in optimized programs, and 4460 // when there's a possibility of debugging backtraces. 4461 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo || 4462 DebugKind == codegenoptions::LocTrackingOnly) 4463 return llvm::DINode::FlagZero; 4464 4465 // Call site-related attributes are available in DWARF v5. Some debuggers, 4466 // while not fully DWARF v5-compliant, may accept these attributes as if they 4467 // were part of DWARF v4. 4468 bool SupportsDWARFv4Ext = 4469 CGM.getCodeGenOpts().DwarfVersion == 4 && 4470 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB; 4471 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5) 4472 return llvm::DINode::FlagZero; 4473 4474 return llvm::DINode::FlagAllCallsDescribed; 4475 } 4476