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