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