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