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