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