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