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