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