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