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