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