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