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