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