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