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