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