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