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 MSInheritanceAttr::Keyword_single_inheritance: 2737 Flags |= llvm::DINode::FlagSingleInheritance; 2738 break; 2739 case MSInheritanceAttr::Keyword_multiple_inheritance: 2740 Flags |= llvm::DINode::FlagMultipleInheritance; 2741 break; 2742 case MSInheritanceAttr::Keyword_virtual_inheritance: 2743 Flags |= llvm::DINode::FlagVirtualInheritance; 2744 break; 2745 case MSInheritanceAttr::Keyword_unspecified_inheritance: 2746 break; 2747 case MSInheritanceAttr::SpellingNotCalculated: 2748 llvm_unreachable("Spelling not yet calculated"); 2749 } 2750 } 2751 } 2752 2753 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 2754 if (Ty->isMemberDataPointerType()) 2755 return DBuilder.createMemberPointerType( 2756 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0, 2757 Flags); 2758 2759 const FunctionProtoType *FPT = 2760 Ty->getPointeeType()->getAs<FunctionProtoType>(); 2761 return DBuilder.createMemberPointerType( 2762 getOrCreateInstanceMethodType( 2763 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()), 2764 FPT, U), 2765 ClassType, Size, /*Align=*/0, Flags); 2766 } 2767 2768 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { 2769 auto *FromTy = getOrCreateType(Ty->getValueType(), U); 2770 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy); 2771 } 2772 2773 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) { 2774 return getOrCreateType(Ty->getElementType(), U); 2775 } 2776 2777 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { 2778 const EnumDecl *ED = Ty->getDecl(); 2779 2780 uint64_t Size = 0; 2781 uint32_t Align = 0; 2782 if (!ED->getTypeForDecl()->isIncompleteType()) { 2783 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 2784 Align = getDeclAlignIfRequired(ED, CGM.getContext()); 2785 } 2786 2787 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 2788 2789 bool isImportedFromModule = 2790 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition(); 2791 2792 // If this is just a forward declaration, construct an appropriately 2793 // marked node and just return it. 2794 if (isImportedFromModule || !ED->getDefinition()) { 2795 // Note that it is possible for enums to be created as part of 2796 // their own declcontext. In this case a FwdDecl will be created 2797 // twice. This doesn't cause a problem because both FwdDecls are 2798 // entered into the ReplaceMap: finalize() will replace the first 2799 // FwdDecl with the second and then replace the second with 2800 // complete type. 2801 llvm::DIScope *EDContext = getDeclContextDescriptor(ED); 2802 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 2803 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( 2804 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0)); 2805 2806 unsigned Line = getLineNumber(ED->getLocation()); 2807 StringRef EDName = ED->getName(); 2808 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( 2809 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line, 2810 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier); 2811 2812 ReplaceMap.emplace_back( 2813 std::piecewise_construct, std::make_tuple(Ty), 2814 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 2815 return RetTy; 2816 } 2817 2818 return CreateTypeDefinition(Ty); 2819 } 2820 2821 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { 2822 const EnumDecl *ED = Ty->getDecl(); 2823 uint64_t Size = 0; 2824 uint32_t Align = 0; 2825 if (!ED->getTypeForDecl()->isIncompleteType()) { 2826 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 2827 Align = getDeclAlignIfRequired(ED, CGM.getContext()); 2828 } 2829 2830 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 2831 2832 // Create elements for each enumerator. 2833 SmallVector<llvm::Metadata *, 16> Enumerators; 2834 ED = ED->getDefinition(); 2835 bool IsSigned = ED->getIntegerType()->isSignedIntegerType(); 2836 for (const auto *Enum : ED->enumerators()) { 2837 const auto &InitVal = Enum->getInitVal(); 2838 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue(); 2839 Enumerators.push_back( 2840 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned)); 2841 } 2842 2843 // Return a CompositeType for the enum itself. 2844 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators); 2845 2846 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 2847 unsigned Line = getLineNumber(ED->getLocation()); 2848 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); 2849 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit); 2850 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, 2851 Line, Size, Align, EltArray, ClassTy, 2852 Identifier, ED->isScoped()); 2853 } 2854 2855 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent, 2856 unsigned MType, SourceLocation LineLoc, 2857 StringRef Name, StringRef Value) { 2858 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 2859 return DBuilder.createMacro(Parent, Line, MType, Name, Value); 2860 } 2861 2862 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, 2863 SourceLocation LineLoc, 2864 SourceLocation FileLoc) { 2865 llvm::DIFile *FName = getOrCreateFile(FileLoc); 2866 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 2867 return DBuilder.createTempMacroFile(Parent, Line, FName); 2868 } 2869 2870 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 2871 Qualifiers Quals; 2872 do { 2873 Qualifiers InnerQuals = T.getLocalQualifiers(); 2874 // Qualifiers::operator+() doesn't like it if you add a Qualifier 2875 // that is already there. 2876 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 2877 Quals += InnerQuals; 2878 QualType LastT = T; 2879 switch (T->getTypeClass()) { 2880 default: 2881 return C.getQualifiedType(T.getTypePtr(), Quals); 2882 case Type::TemplateSpecialization: { 2883 const auto *Spec = cast<TemplateSpecializationType>(T); 2884 if (Spec->isTypeAlias()) 2885 return C.getQualifiedType(T.getTypePtr(), Quals); 2886 T = Spec->desugar(); 2887 break; 2888 } 2889 case Type::TypeOfExpr: 2890 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 2891 break; 2892 case Type::TypeOf: 2893 T = cast<TypeOfType>(T)->getUnderlyingType(); 2894 break; 2895 case Type::Decltype: 2896 T = cast<DecltypeType>(T)->getUnderlyingType(); 2897 break; 2898 case Type::UnaryTransform: 2899 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 2900 break; 2901 case Type::Attributed: 2902 T = cast<AttributedType>(T)->getEquivalentType(); 2903 break; 2904 case Type::Elaborated: 2905 T = cast<ElaboratedType>(T)->getNamedType(); 2906 break; 2907 case Type::Paren: 2908 T = cast<ParenType>(T)->getInnerType(); 2909 break; 2910 case Type::MacroQualified: 2911 T = cast<MacroQualifiedType>(T)->getUnderlyingType(); 2912 break; 2913 case Type::SubstTemplateTypeParm: 2914 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 2915 break; 2916 case Type::Auto: 2917 case Type::DeducedTemplateSpecialization: { 2918 QualType DT = cast<DeducedType>(T)->getDeducedType(); 2919 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 2920 T = DT; 2921 break; 2922 } 2923 case Type::Adjusted: 2924 case Type::Decayed: 2925 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 2926 T = cast<AdjustedType>(T)->getAdjustedType(); 2927 break; 2928 } 2929 2930 assert(T != LastT && "Type unwrapping failed to unwrap!"); 2931 (void)LastT; 2932 } while (true); 2933 } 2934 2935 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { 2936 2937 // Unwrap the type as needed for debug information. 2938 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2939 2940 auto It = TypeCache.find(Ty.getAsOpaquePtr()); 2941 if (It != TypeCache.end()) { 2942 // Verify that the debug info still exists. 2943 if (llvm::Metadata *V = It->second) 2944 return cast<llvm::DIType>(V); 2945 } 2946 2947 return nullptr; 2948 } 2949 2950 void CGDebugInfo::completeTemplateDefinition( 2951 const ClassTemplateSpecializationDecl &SD) { 2952 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2953 return; 2954 completeUnusedClass(SD); 2955 } 2956 2957 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) { 2958 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2959 return; 2960 2961 completeClassData(&D); 2962 // In case this type has no member function definitions being emitted, ensure 2963 // it is retained 2964 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr()); 2965 } 2966 2967 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { 2968 if (Ty.isNull()) 2969 return nullptr; 2970 2971 llvm::TimeTraceScope TimeScope("DebugType", [&]() { 2972 std::string Name; 2973 llvm::raw_string_ostream OS(Name); 2974 Ty.print(OS, getPrintingPolicy()); 2975 return Name; 2976 }); 2977 2978 // Unwrap the type as needed for debug information. 2979 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2980 2981 if (auto *T = getTypeOrNull(Ty)) 2982 return T; 2983 2984 llvm::DIType *Res = CreateTypeNode(Ty, Unit); 2985 void *TyPtr = Ty.getAsOpaquePtr(); 2986 2987 // And update the type cache. 2988 TypeCache[TyPtr].reset(Res); 2989 2990 return Res; 2991 } 2992 2993 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { 2994 // A forward declaration inside a module header does not belong to the module. 2995 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition()) 2996 return nullptr; 2997 if (DebugTypeExtRefs && D->isFromASTFile()) { 2998 // Record a reference to an imported clang module or precompiled header. 2999 auto *Reader = CGM.getContext().getExternalSource(); 3000 auto Idx = D->getOwningModuleID(); 3001 auto Info = Reader->getSourceDescriptor(Idx); 3002 if (Info) 3003 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true); 3004 } else if (ClangModuleMap) { 3005 // We are building a clang module or a precompiled header. 3006 // 3007 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies 3008 // and it wouldn't be necessary to specify the parent scope 3009 // because the type is already unique by definition (it would look 3010 // like the output of -fno-standalone-debug). On the other hand, 3011 // the parent scope helps a consumer to quickly locate the object 3012 // file where the type's definition is located, so it might be 3013 // best to make this behavior a command line or debugger tuning 3014 // option. 3015 if (Module *M = D->getOwningModule()) { 3016 // This is a (sub-)module. 3017 auto Info = ExternalASTSource::ASTSourceDescriptor(*M); 3018 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false); 3019 } else { 3020 // This the precompiled header being built. 3021 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false); 3022 } 3023 } 3024 3025 return nullptr; 3026 } 3027 3028 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { 3029 // Handle qualifiers, which recursively handles what they refer to. 3030 if (Ty.hasLocalQualifiers()) 3031 return CreateQualifiedType(Ty, Unit); 3032 3033 // Work out details of type. 3034 switch (Ty->getTypeClass()) { 3035 #define TYPE(Class, Base) 3036 #define ABSTRACT_TYPE(Class, Base) 3037 #define NON_CANONICAL_TYPE(Class, Base) 3038 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3039 #include "clang/AST/TypeNodes.inc" 3040 llvm_unreachable("Dependent types cannot show up in debug information"); 3041 3042 case Type::ExtVector: 3043 case Type::Vector: 3044 return CreateType(cast<VectorType>(Ty), Unit); 3045 case Type::ObjCObjectPointer: 3046 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 3047 case Type::ObjCObject: 3048 return CreateType(cast<ObjCObjectType>(Ty), Unit); 3049 case Type::ObjCTypeParam: 3050 return CreateType(cast<ObjCTypeParamType>(Ty), Unit); 3051 case Type::ObjCInterface: 3052 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 3053 case Type::Builtin: 3054 return CreateType(cast<BuiltinType>(Ty)); 3055 case Type::Complex: 3056 return CreateType(cast<ComplexType>(Ty)); 3057 case Type::Pointer: 3058 return CreateType(cast<PointerType>(Ty), Unit); 3059 case Type::BlockPointer: 3060 return CreateType(cast<BlockPointerType>(Ty), Unit); 3061 case Type::Typedef: 3062 return CreateType(cast<TypedefType>(Ty), Unit); 3063 case Type::Record: 3064 return CreateType(cast<RecordType>(Ty)); 3065 case Type::Enum: 3066 return CreateEnumType(cast<EnumType>(Ty)); 3067 case Type::FunctionProto: 3068 case Type::FunctionNoProto: 3069 return CreateType(cast<FunctionType>(Ty), Unit); 3070 case Type::ConstantArray: 3071 case Type::VariableArray: 3072 case Type::IncompleteArray: 3073 return CreateType(cast<ArrayType>(Ty), Unit); 3074 3075 case Type::LValueReference: 3076 return CreateType(cast<LValueReferenceType>(Ty), Unit); 3077 case Type::RValueReference: 3078 return CreateType(cast<RValueReferenceType>(Ty), Unit); 3079 3080 case Type::MemberPointer: 3081 return CreateType(cast<MemberPointerType>(Ty), Unit); 3082 3083 case Type::Atomic: 3084 return CreateType(cast<AtomicType>(Ty), Unit); 3085 3086 case Type::Pipe: 3087 return CreateType(cast<PipeType>(Ty), Unit); 3088 3089 case Type::TemplateSpecialization: 3090 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 3091 3092 case Type::Auto: 3093 case Type::Attributed: 3094 case Type::Adjusted: 3095 case Type::Decayed: 3096 case Type::DeducedTemplateSpecialization: 3097 case Type::Elaborated: 3098 case Type::Paren: 3099 case Type::MacroQualified: 3100 case Type::SubstTemplateTypeParm: 3101 case Type::TypeOfExpr: 3102 case Type::TypeOf: 3103 case Type::Decltype: 3104 case Type::UnaryTransform: 3105 case Type::PackExpansion: 3106 break; 3107 } 3108 3109 llvm_unreachable("type should have been unwrapped!"); 3110 } 3111 3112 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 3113 llvm::DIFile *Unit) { 3114 QualType QTy(Ty, 0); 3115 3116 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy)); 3117 3118 // We may have cached a forward decl when we could have created 3119 // a non-forward decl. Go ahead and create a non-forward decl 3120 // now. 3121 if (T && !T->isForwardDecl()) 3122 return T; 3123 3124 // Otherwise create the type. 3125 llvm::DICompositeType *Res = CreateLimitedType(Ty); 3126 3127 // Propagate members from the declaration to the definition 3128 // CreateType(const RecordType*) will overwrite this with the members in the 3129 // correct order if the full type is needed. 3130 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray()); 3131 3132 // And update the type cache. 3133 TypeCache[QTy.getAsOpaquePtr()].reset(Res); 3134 return Res; 3135 } 3136 3137 // TODO: Currently used for context chains when limiting debug info. 3138 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 3139 RecordDecl *RD = Ty->getDecl(); 3140 3141 // Get overall information about the record type for the debug info. 3142 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 3143 unsigned Line = getLineNumber(RD->getLocation()); 3144 StringRef RDName = getClassName(RD); 3145 3146 llvm::DIScope *RDContext = getDeclContextDescriptor(RD); 3147 3148 // If we ended up creating the type during the context chain construction, 3149 // just return that. 3150 auto *T = cast_or_null<llvm::DICompositeType>( 3151 getTypeOrNull(CGM.getContext().getRecordType(RD))); 3152 if (T && (!T->isForwardDecl() || !RD->getDefinition())) 3153 return T; 3154 3155 // If this is just a forward or incomplete declaration, construct an 3156 // appropriately marked node and just return it. 3157 const RecordDecl *D = RD->getDefinition(); 3158 if (!D || !D->isCompleteDefinition()) 3159 return getOrCreateRecordFwdDecl(Ty, RDContext); 3160 3161 uint64_t Size = CGM.getContext().getTypeSize(Ty); 3162 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 3163 3164 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 3165 3166 // Explicitly record the calling convention and export symbols for C++ 3167 // records. 3168 auto Flags = llvm::DINode::FlagZero; 3169 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3170 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect) 3171 Flags |= llvm::DINode::FlagTypePassByReference; 3172 else 3173 Flags |= llvm::DINode::FlagTypePassByValue; 3174 3175 // Record if a C++ record is non-trivial type. 3176 if (!CXXRD->isTrivial()) 3177 Flags |= llvm::DINode::FlagNonTrivial; 3178 3179 // Record exports it symbols to the containing structure. 3180 if (CXXRD->isAnonymousStructOrUnion()) 3181 Flags |= llvm::DINode::FlagExportSymbols; 3182 } 3183 3184 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( 3185 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 3186 Flags, Identifier); 3187 3188 // Elements of composite types usually have back to the type, creating 3189 // uniquing cycles. Distinct nodes are more efficient. 3190 switch (RealDecl->getTag()) { 3191 default: 3192 llvm_unreachable("invalid composite type tag"); 3193 3194 case llvm::dwarf::DW_TAG_array_type: 3195 case llvm::dwarf::DW_TAG_enumeration_type: 3196 // Array elements and most enumeration elements don't have back references, 3197 // so they don't tend to be involved in uniquing cycles and there is some 3198 // chance of merging them when linking together two modules. Only make 3199 // them distinct if they are ODR-uniqued. 3200 if (Identifier.empty()) 3201 break; 3202 LLVM_FALLTHROUGH; 3203 3204 case llvm::dwarf::DW_TAG_structure_type: 3205 case llvm::dwarf::DW_TAG_union_type: 3206 case llvm::dwarf::DW_TAG_class_type: 3207 // Immediately resolve to a distinct node. 3208 RealDecl = 3209 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl)); 3210 break; 3211 } 3212 3213 RegionMap[Ty->getDecl()].reset(RealDecl); 3214 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl); 3215 3216 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 3217 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(), 3218 CollectCXXTemplateParams(TSpecial, DefUnit)); 3219 return RealDecl; 3220 } 3221 3222 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 3223 llvm::DICompositeType *RealDecl) { 3224 // A class's primary base or the class itself contains the vtable. 3225 llvm::DICompositeType *ContainingType = nullptr; 3226 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 3227 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 3228 // Seek non-virtual primary base root. 3229 while (1) { 3230 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 3231 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 3232 if (PBT && !BRL.isPrimaryBaseVirtual()) 3233 PBase = PBT; 3234 else 3235 break; 3236 } 3237 ContainingType = cast<llvm::DICompositeType>( 3238 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 3239 getOrCreateFile(RD->getLocation()))); 3240 } else if (RD->isDynamicClass()) 3241 ContainingType = RealDecl; 3242 3243 DBuilder.replaceVTableHolder(RealDecl, ContainingType); 3244 } 3245 3246 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, 3247 StringRef Name, uint64_t *Offset) { 3248 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 3249 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 3250 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext()); 3251 llvm::DIType *Ty = 3252 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign, 3253 *Offset, llvm::DINode::FlagZero, FieldTy); 3254 *Offset += FieldSize; 3255 return Ty; 3256 } 3257 3258 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, 3259 StringRef &Name, 3260 StringRef &LinkageName, 3261 llvm::DIScope *&FDContext, 3262 llvm::DINodeArray &TParamsArray, 3263 llvm::DINode::DIFlags &Flags) { 3264 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3265 Name = getFunctionName(FD); 3266 // Use mangled name as linkage name for C/C++ functions. 3267 if (FD->hasPrototype()) { 3268 LinkageName = CGM.getMangledName(GD); 3269 Flags |= llvm::DINode::FlagPrototyped; 3270 } 3271 // No need to replicate the linkage name if it isn't different from the 3272 // subprogram name, no need to have it at all unless coverage is enabled or 3273 // debug is set to more than just line tables or extra debug info is needed. 3274 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs && 3275 !CGM.getCodeGenOpts().EmitGcovNotes && 3276 !CGM.getCodeGenOpts().DebugInfoForProfiling && 3277 DebugKind <= codegenoptions::DebugLineTablesOnly)) 3278 LinkageName = StringRef(); 3279 3280 if (DebugKind >= codegenoptions::LimitedDebugInfo) { 3281 if (const NamespaceDecl *NSDecl = 3282 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 3283 FDContext = getOrCreateNamespace(NSDecl); 3284 else if (const RecordDecl *RDecl = 3285 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { 3286 llvm::DIScope *Mod = getParentModuleOrNull(RDecl); 3287 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU); 3288 } 3289 // Check if it is a noreturn-marked function 3290 if (FD->isNoReturn()) 3291 Flags |= llvm::DINode::FlagNoReturn; 3292 // Collect template parameters. 3293 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 3294 } 3295 } 3296 3297 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, 3298 unsigned &LineNo, QualType &T, 3299 StringRef &Name, StringRef &LinkageName, 3300 llvm::MDTuple *&TemplateParameters, 3301 llvm::DIScope *&VDContext) { 3302 Unit = getOrCreateFile(VD->getLocation()); 3303 LineNo = getLineNumber(VD->getLocation()); 3304 3305 setLocation(VD->getLocation()); 3306 3307 T = VD->getType(); 3308 if (T->isIncompleteArrayType()) { 3309 // CodeGen turns int[] into int[1] so we'll do the same here. 3310 llvm::APInt ConstVal(32, 1); 3311 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 3312 3313 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr, 3314 ArrayType::Normal, 0); 3315 } 3316 3317 Name = VD->getName(); 3318 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 3319 !isa<ObjCMethodDecl>(VD->getDeclContext())) 3320 LinkageName = CGM.getMangledName(VD); 3321 if (LinkageName == Name) 3322 LinkageName = StringRef(); 3323 3324 if (isa<VarTemplateSpecializationDecl>(VD)) { 3325 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit); 3326 TemplateParameters = parameterNodes.get(); 3327 } else { 3328 TemplateParameters = nullptr; 3329 } 3330 3331 // Since we emit declarations (DW_AT_members) for static members, place the 3332 // definition of those static members in the namespace they were declared in 3333 // in the source code (the lexical decl context). 3334 // FIXME: Generalize this for even non-member global variables where the 3335 // declaration and definition may have different lexical decl contexts, once 3336 // we have support for emitting declarations of (non-member) global variables. 3337 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() 3338 : VD->getDeclContext(); 3339 // When a record type contains an in-line initialization of a static data 3340 // member, and the record type is marked as __declspec(dllexport), an implicit 3341 // definition of the member will be created in the record context. DWARF 3342 // doesn't seem to have a nice way to describe this in a form that consumers 3343 // are likely to understand, so fake the "normal" situation of a definition 3344 // outside the class by putting it in the global scope. 3345 if (DC->isRecord()) 3346 DC = CGM.getContext().getTranslationUnitDecl(); 3347 3348 llvm::DIScope *Mod = getParentModuleOrNull(VD); 3349 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU); 3350 } 3351 3352 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD, 3353 bool Stub) { 3354 llvm::DINodeArray TParamsArray; 3355 StringRef Name, LinkageName; 3356 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3357 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3358 SourceLocation Loc = GD.getDecl()->getLocation(); 3359 llvm::DIFile *Unit = getOrCreateFile(Loc); 3360 llvm::DIScope *DContext = Unit; 3361 unsigned Line = getLineNumber(Loc); 3362 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray, 3363 Flags); 3364 auto *FD = cast<FunctionDecl>(GD.getDecl()); 3365 3366 // Build function type. 3367 SmallVector<QualType, 16> ArgTypes; 3368 for (const ParmVarDecl *Parm : FD->parameters()) 3369 ArgTypes.push_back(Parm->getType()); 3370 3371 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 3372 QualType FnType = CGM.getContext().getFunctionType( 3373 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 3374 if (!FD->isExternallyVisible()) 3375 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 3376 if (CGM.getLangOpts().Optimize) 3377 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3378 3379 if (Stub) { 3380 Flags |= getCallSiteRelatedAttrs(); 3381 SPFlags |= llvm::DISubprogram::SPFlagDefinition; 3382 return DBuilder.createFunction( 3383 DContext, Name, LinkageName, Unit, Line, 3384 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags, 3385 TParamsArray.get(), getFunctionDeclaration(FD)); 3386 } 3387 3388 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( 3389 DContext, Name, LinkageName, Unit, Line, 3390 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags, 3391 TParamsArray.get(), getFunctionDeclaration(FD)); 3392 const FunctionDecl *CanonDecl = FD->getCanonicalDecl(); 3393 FwdDeclReplaceMap.emplace_back(std::piecewise_construct, 3394 std::make_tuple(CanonDecl), 3395 std::make_tuple(SP)); 3396 return SP; 3397 } 3398 3399 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) { 3400 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false); 3401 } 3402 3403 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) { 3404 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true); 3405 } 3406 3407 llvm::DIGlobalVariable * 3408 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 3409 QualType T; 3410 StringRef Name, LinkageName; 3411 SourceLocation Loc = VD->getLocation(); 3412 llvm::DIFile *Unit = getOrCreateFile(Loc); 3413 llvm::DIScope *DContext = Unit; 3414 unsigned Line = getLineNumber(Loc); 3415 llvm::MDTuple *TemplateParameters = nullptr; 3416 3417 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters, 3418 DContext); 3419 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3420 auto *GV = DBuilder.createTempGlobalVariableFwdDecl( 3421 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit), 3422 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align); 3423 FwdDeclReplaceMap.emplace_back( 3424 std::piecewise_construct, 3425 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())), 3426 std::make_tuple(static_cast<llvm::Metadata *>(GV))); 3427 return GV; 3428 } 3429 3430 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 3431 // We only need a declaration (not a definition) of the type - so use whatever 3432 // we would otherwise do to get a type for a pointee. (forward declarations in 3433 // limited debug info, full definitions (if the type definition is available) 3434 // in unlimited debug info) 3435 if (const auto *TD = dyn_cast<TypeDecl>(D)) 3436 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 3437 getOrCreateFile(TD->getLocation())); 3438 auto I = DeclCache.find(D->getCanonicalDecl()); 3439 3440 if (I != DeclCache.end()) { 3441 auto N = I->second; 3442 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N)) 3443 return GVE->getVariable(); 3444 return dyn_cast_or_null<llvm::DINode>(N); 3445 } 3446 3447 // No definition for now. Emit a forward definition that might be 3448 // merged with a potential upcoming definition. 3449 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 3450 return getFunctionForwardDeclaration(FD); 3451 else if (const auto *VD = dyn_cast<VarDecl>(D)) 3452 return getGlobalVariableForwardDeclaration(VD); 3453 3454 return nullptr; 3455 } 3456 3457 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { 3458 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3459 return nullptr; 3460 3461 const auto *FD = dyn_cast<FunctionDecl>(D); 3462 if (!FD) 3463 return nullptr; 3464 3465 // Setup context. 3466 auto *S = getDeclContextDescriptor(D); 3467 3468 auto MI = SPCache.find(FD->getCanonicalDecl()); 3469 if (MI == SPCache.end()) { 3470 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 3471 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), 3472 cast<llvm::DICompositeType>(S)); 3473 } 3474 } 3475 if (MI != SPCache.end()) { 3476 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 3477 if (SP && !SP->isDefinition()) 3478 return SP; 3479 } 3480 3481 for (auto NextFD : FD->redecls()) { 3482 auto MI = SPCache.find(NextFD->getCanonicalDecl()); 3483 if (MI != SPCache.end()) { 3484 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 3485 if (SP && !SP->isDefinition()) 3486 return SP; 3487 } 3488 } 3489 return nullptr; 3490 } 3491 3492 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration( 3493 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo, 3494 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) { 3495 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3496 return nullptr; 3497 3498 if (CGM.getCodeGenOpts().DwarfVersion < 5) 3499 return nullptr; 3500 3501 // Starting with DWARF V5 method declarations are emitted as children of 3502 // the interface type. 3503 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 3504 if (!OMD) 3505 return nullptr; 3506 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext()); 3507 if (!ID) 3508 ID = OMD->getClassInterface(); 3509 if (!ID) 3510 return nullptr; 3511 QualType QTy(ID->getTypeForDecl(), 0); 3512 auto It = TypeCache.find(QTy.getAsOpaquePtr()); 3513 if (It == TypeCache.end()) 3514 return nullptr; 3515 auto *InterfaceType = cast<llvm::DICompositeType>(It->second); 3516 llvm::DISubprogram *FD = DBuilder.createFunction( 3517 InterfaceType, getObjCMethodName(OMD), StringRef(), 3518 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags); 3519 DBuilder.finalizeSubprogram(FD); 3520 ObjCMethodCache[ID].push_back(FD); 3521 return FD; 3522 } 3523 3524 // getOrCreateFunctionType - Construct type. If it is a c++ method, include 3525 // implicit parameter "this". 3526 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, 3527 QualType FnType, 3528 llvm::DIFile *F) { 3529 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3530 // Create fake but valid subroutine type. Otherwise -verify would fail, and 3531 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. 3532 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None)); 3533 3534 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) 3535 return getOrCreateMethodType(Method, F); 3536 3537 const auto *FTy = FnType->getAs<FunctionType>(); 3538 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C; 3539 3540 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 3541 // Add "self" and "_cmd" 3542 SmallVector<llvm::Metadata *, 16> Elts; 3543 3544 // First element is always return type. For 'void' functions it is NULL. 3545 QualType ResultTy = OMethod->getReturnType(); 3546 3547 // Replace the instancetype keyword with the actual type. 3548 if (ResultTy == CGM.getContext().getObjCInstanceType()) 3549 ResultTy = CGM.getContext().getPointerType( 3550 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 3551 3552 Elts.push_back(getOrCreateType(ResultTy, F)); 3553 // "self" pointer is always first argument. 3554 QualType SelfDeclTy; 3555 if (auto *SelfDecl = OMethod->getSelfDecl()) 3556 SelfDeclTy = SelfDecl->getType(); 3557 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 3558 if (FPT->getNumParams() > 1) 3559 SelfDeclTy = FPT->getParamType(0); 3560 if (!SelfDeclTy.isNull()) 3561 Elts.push_back( 3562 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F))); 3563 // "_cmd" pointer is always second argument. 3564 Elts.push_back(DBuilder.createArtificialType( 3565 getOrCreateType(CGM.getContext().getObjCSelType(), F))); 3566 // Get rest of the arguments. 3567 for (const auto *PI : OMethod->parameters()) 3568 Elts.push_back(getOrCreateType(PI->getType(), F)); 3569 // Variadic methods need a special marker at the end of the type list. 3570 if (OMethod->isVariadic()) 3571 Elts.push_back(DBuilder.createUnspecifiedParameter()); 3572 3573 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 3574 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 3575 getDwarfCC(CC)); 3576 } 3577 3578 // Handle variadic function types; they need an additional 3579 // unspecified parameter. 3580 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 3581 if (FD->isVariadic()) { 3582 SmallVector<llvm::Metadata *, 16> EltTys; 3583 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 3584 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 3585 for (QualType ParamType : FPT->param_types()) 3586 EltTys.push_back(getOrCreateType(ParamType, F)); 3587 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 3588 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 3589 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 3590 getDwarfCC(CC)); 3591 } 3592 3593 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F)); 3594 } 3595 3596 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, 3597 SourceLocation ScopeLoc, QualType FnType, 3598 llvm::Function *Fn, bool CurFuncIsThunk, 3599 CGBuilderTy &Builder) { 3600 3601 StringRef Name; 3602 StringRef LinkageName; 3603 3604 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 3605 3606 const Decl *D = GD.getDecl(); 3607 bool HasDecl = (D != nullptr); 3608 3609 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3610 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3611 llvm::DIFile *Unit = getOrCreateFile(Loc); 3612 llvm::DIScope *FDContext = Unit; 3613 llvm::DINodeArray TParamsArray; 3614 if (!HasDecl) { 3615 // Use llvm function name. 3616 LinkageName = Fn->getName(); 3617 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3618 // If there is a subprogram for this function available then use it. 3619 auto FI = SPCache.find(FD->getCanonicalDecl()); 3620 if (FI != SPCache.end()) { 3621 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 3622 if (SP && SP->isDefinition()) { 3623 LexicalBlockStack.emplace_back(SP); 3624 RegionMap[D].reset(SP); 3625 return; 3626 } 3627 } 3628 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 3629 TParamsArray, Flags); 3630 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 3631 Name = getObjCMethodName(OMD); 3632 Flags |= llvm::DINode::FlagPrototyped; 3633 } else if (isa<VarDecl>(D) && 3634 GD.getDynamicInitKind() != DynamicInitKind::NoStub) { 3635 // This is a global initializer or atexit destructor for a global variable. 3636 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(), 3637 Fn); 3638 } else { 3639 // Use llvm function name. 3640 Name = Fn->getName(); 3641 Flags |= llvm::DINode::FlagPrototyped; 3642 } 3643 if (Name.startswith("\01")) 3644 Name = Name.substr(1); 3645 3646 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) { 3647 Flags |= llvm::DINode::FlagArtificial; 3648 // Artificial functions should not silently reuse CurLoc. 3649 CurLoc = SourceLocation(); 3650 } 3651 3652 if (CurFuncIsThunk) 3653 Flags |= llvm::DINode::FlagThunk; 3654 3655 if (Fn->hasLocalLinkage()) 3656 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 3657 if (CGM.getLangOpts().Optimize) 3658 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3659 3660 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs(); 3661 llvm::DISubprogram::DISPFlags SPFlagsForDef = 3662 SPFlags | llvm::DISubprogram::SPFlagDefinition; 3663 3664 unsigned LineNo = getLineNumber(Loc); 3665 unsigned ScopeLine = getLineNumber(ScopeLoc); 3666 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit); 3667 llvm::DISubprogram *Decl = nullptr; 3668 if (D) 3669 Decl = isa<ObjCMethodDecl>(D) 3670 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags) 3671 : getFunctionDeclaration(D); 3672 3673 // FIXME: The function declaration we're constructing here is mostly reusing 3674 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 3675 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 3676 // all subprograms instead of the actual context since subprogram definitions 3677 // are emitted as CU level entities by the backend. 3678 llvm::DISubprogram *SP = DBuilder.createFunction( 3679 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine, 3680 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl); 3681 Fn->setSubprogram(SP); 3682 // We might get here with a VarDecl in the case we're generating 3683 // code for the initialization of globals. Do not record these decls 3684 // as they will overwrite the actual VarDecl Decl in the cache. 3685 if (HasDecl && isa<FunctionDecl>(D)) 3686 DeclCache[D->getCanonicalDecl()].reset(SP); 3687 3688 // Push the function onto the lexical block stack. 3689 LexicalBlockStack.emplace_back(SP); 3690 3691 if (HasDecl) 3692 RegionMap[D].reset(SP); 3693 } 3694 3695 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, 3696 QualType FnType, llvm::Function *Fn) { 3697 StringRef Name; 3698 StringRef LinkageName; 3699 3700 const Decl *D = GD.getDecl(); 3701 if (!D) 3702 return; 3703 3704 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() { 3705 std::string Name; 3706 llvm::raw_string_ostream OS(Name); 3707 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3708 ND->getNameForDiagnostic(OS, getPrintingPolicy(), 3709 /*Qualified=*/true); 3710 return Name; 3711 }); 3712 3713 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3714 llvm::DIFile *Unit = getOrCreateFile(Loc); 3715 bool IsDeclForCallSite = Fn ? true : false; 3716 llvm::DIScope *FDContext = 3717 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D); 3718 llvm::DINodeArray TParamsArray; 3719 if (isa<FunctionDecl>(D)) { 3720 // If there is a DISubprogram for this function available then use it. 3721 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 3722 TParamsArray, Flags); 3723 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 3724 Name = getObjCMethodName(OMD); 3725 Flags |= llvm::DINode::FlagPrototyped; 3726 } else { 3727 llvm_unreachable("not a function or ObjC method"); 3728 } 3729 if (!Name.empty() && Name[0] == '\01') 3730 Name = Name.substr(1); 3731 3732 if (D->isImplicit()) { 3733 Flags |= llvm::DINode::FlagArtificial; 3734 // Artificial functions without a location should not silently reuse CurLoc. 3735 if (Loc.isInvalid()) 3736 CurLoc = SourceLocation(); 3737 } 3738 unsigned LineNo = getLineNumber(Loc); 3739 unsigned ScopeLine = 0; 3740 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3741 if (CGM.getLangOpts().Optimize) 3742 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3743 3744 llvm::DISubprogram *SP = DBuilder.createFunction( 3745 FDContext, Name, LinkageName, Unit, LineNo, 3746 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags, 3747 TParamsArray.get(), getFunctionDeclaration(D)); 3748 3749 if (IsDeclForCallSite) 3750 Fn->setSubprogram(SP); 3751 3752 DBuilder.retainType(SP); 3753 } 3754 3755 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, 3756 QualType CalleeType, 3757 const FunctionDecl *CalleeDecl) { 3758 if (!CallOrInvoke) 3759 return; 3760 auto *Func = CallOrInvoke->getCalledFunction(); 3761 if (!Func) 3762 return; 3763 if (Func->getSubprogram()) 3764 return; 3765 3766 // Do not emit a declaration subprogram for a builtin or if call site info 3767 // isn't required. Also, elide declarations for functions with reserved names, 3768 // as call site-related features aren't interesting in this case (& also, the 3769 // compiler may emit calls to these functions without debug locations, which 3770 // makes the verifier complain). 3771 if (CalleeDecl->getBuiltinID() != 0 || 3772 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero) 3773 return; 3774 if (const auto *Id = CalleeDecl->getIdentifier()) 3775 if (Id->isReservedName()) 3776 return; 3777 3778 // If there is no DISubprogram attached to the function being called, 3779 // create the one describing the function in order to have complete 3780 // call site debug info. 3781 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) 3782 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func); 3783 } 3784 3785 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) { 3786 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3787 // If there is a subprogram for this function available then use it. 3788 auto FI = SPCache.find(FD->getCanonicalDecl()); 3789 llvm::DISubprogram *SP = nullptr; 3790 if (FI != SPCache.end()) 3791 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 3792 if (!SP || !SP->isDefinition()) 3793 SP = getFunctionStub(GD); 3794 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 3795 LexicalBlockStack.emplace_back(SP); 3796 setInlinedAt(Builder.getCurrentDebugLocation()); 3797 EmitLocation(Builder, FD->getLocation()); 3798 } 3799 3800 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) { 3801 assert(CurInlinedAt && "unbalanced inline scope stack"); 3802 EmitFunctionEnd(Builder, nullptr); 3803 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt()); 3804 } 3805 3806 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 3807 // Update our current location 3808 setLocation(Loc); 3809 3810 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty()) 3811 return; 3812 3813 llvm::MDNode *Scope = LexicalBlockStack.back(); 3814 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 3815 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt)); 3816 } 3817 3818 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 3819 llvm::MDNode *Back = nullptr; 3820 if (!LexicalBlockStack.empty()) 3821 Back = LexicalBlockStack.back().get(); 3822 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock( 3823 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc), 3824 getColumnNumber(CurLoc))); 3825 } 3826 3827 void CGDebugInfo::AppendAddressSpaceXDeref( 3828 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const { 3829 Optional<unsigned> DWARFAddressSpace = 3830 CGM.getTarget().getDWARFAddressSpace(AddressSpace); 3831 if (!DWARFAddressSpace) 3832 return; 3833 3834 Expr.push_back(llvm::dwarf::DW_OP_constu); 3835 Expr.push_back(DWARFAddressSpace.getValue()); 3836 Expr.push_back(llvm::dwarf::DW_OP_swap); 3837 Expr.push_back(llvm::dwarf::DW_OP_xderef); 3838 } 3839 3840 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 3841 SourceLocation Loc) { 3842 // Set our current location. 3843 setLocation(Loc); 3844 3845 // Emit a line table change for the current location inside the new scope. 3846 Builder.SetCurrentDebugLocation( 3847 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), 3848 LexicalBlockStack.back(), CurInlinedAt)); 3849 3850 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3851 return; 3852 3853 // Create a new lexical block and push it on the stack. 3854 CreateLexicalBlock(Loc); 3855 } 3856 3857 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 3858 SourceLocation Loc) { 3859 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3860 3861 // Provide an entry in the line table for the end of the block. 3862 EmitLocation(Builder, Loc); 3863 3864 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3865 return; 3866 3867 LexicalBlockStack.pop_back(); 3868 } 3869 3870 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) { 3871 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3872 unsigned RCount = FnBeginRegionCount.back(); 3873 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 3874 3875 // Pop all regions for this function. 3876 while (LexicalBlockStack.size() != RCount) { 3877 // Provide an entry in the line table for the end of the block. 3878 EmitLocation(Builder, CurLoc); 3879 LexicalBlockStack.pop_back(); 3880 } 3881 FnBeginRegionCount.pop_back(); 3882 3883 if (Fn && Fn->getSubprogram()) 3884 DBuilder.finalizeSubprogram(Fn->getSubprogram()); 3885 } 3886 3887 CGDebugInfo::BlockByRefType 3888 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 3889 uint64_t *XOffset) { 3890 SmallVector<llvm::Metadata *, 5> EltTys; 3891 QualType FType; 3892 uint64_t FieldSize, FieldOffset; 3893 uint32_t FieldAlign; 3894 3895 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3896 QualType Type = VD->getType(); 3897 3898 FieldOffset = 0; 3899 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3900 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 3901 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 3902 FType = CGM.getContext().IntTy; 3903 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 3904 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 3905 3906 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 3907 if (HasCopyAndDispose) { 3908 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3909 EltTys.push_back( 3910 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 3911 EltTys.push_back( 3912 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 3913 } 3914 bool HasByrefExtendedLayout; 3915 Qualifiers::ObjCLifetime Lifetime; 3916 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 3917 HasByrefExtendedLayout) && 3918 HasByrefExtendedLayout) { 3919 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3920 EltTys.push_back( 3921 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 3922 } 3923 3924 CharUnits Align = CGM.getContext().getDeclAlign(VD); 3925 if (Align > CGM.getContext().toCharUnitsFromBits( 3926 CGM.getTarget().getPointerAlign(0))) { 3927 CharUnits FieldOffsetInBytes = 3928 CGM.getContext().toCharUnitsFromBits(FieldOffset); 3929 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align); 3930 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 3931 3932 if (NumPaddingBytes.isPositive()) { 3933 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 3934 FType = CGM.getContext().getConstantArrayType( 3935 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0); 3936 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 3937 } 3938 } 3939 3940 FType = Type; 3941 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit); 3942 FieldSize = CGM.getContext().getTypeSize(FType); 3943 FieldAlign = CGM.getContext().toBits(Align); 3944 3945 *XOffset = FieldOffset; 3946 llvm::DIType *FieldTy = DBuilder.createMemberType( 3947 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset, 3948 llvm::DINode::FlagZero, WrappedTy); 3949 EltTys.push_back(FieldTy); 3950 FieldOffset += FieldSize; 3951 3952 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 3953 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, 3954 llvm::DINode::FlagZero, nullptr, Elements), 3955 WrappedTy}; 3956 } 3957 3958 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, 3959 llvm::Value *Storage, 3960 llvm::Optional<unsigned> ArgNo, 3961 CGBuilderTy &Builder, 3962 const bool UsePointerValue) { 3963 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3964 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3965 if (VD->hasAttr<NoDebugAttr>()) 3966 return nullptr; 3967 3968 bool Unwritten = 3969 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 3970 cast<Decl>(VD->getDeclContext())->isImplicit()); 3971 llvm::DIFile *Unit = nullptr; 3972 if (!Unwritten) 3973 Unit = getOrCreateFile(VD->getLocation()); 3974 llvm::DIType *Ty; 3975 uint64_t XOffset = 0; 3976 if (VD->hasAttr<BlocksAttr>()) 3977 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType; 3978 else 3979 Ty = getOrCreateType(VD->getType(), Unit); 3980 3981 // If there is no debug info for this type then do not emit debug info 3982 // for this variable. 3983 if (!Ty) 3984 return nullptr; 3985 3986 // Get location information. 3987 unsigned Line = 0; 3988 unsigned Column = 0; 3989 if (!Unwritten) { 3990 Line = getLineNumber(VD->getLocation()); 3991 Column = getColumnNumber(VD->getLocation()); 3992 } 3993 SmallVector<int64_t, 13> Expr; 3994 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3995 if (VD->isImplicit()) 3996 Flags |= llvm::DINode::FlagArtificial; 3997 3998 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3999 4000 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType()); 4001 AppendAddressSpaceXDeref(AddressSpace, Expr); 4002 4003 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an 4004 // object pointer flag. 4005 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) { 4006 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis || 4007 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf) 4008 Flags |= llvm::DINode::FlagObjectPointer; 4009 } 4010 4011 // Note: Older versions of clang used to emit byval references with an extra 4012 // DW_OP_deref, because they referenced the IR arg directly instead of 4013 // referencing an alloca. Newer versions of LLVM don't treat allocas 4014 // differently from other function arguments when used in a dbg.declare. 4015 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 4016 StringRef Name = VD->getName(); 4017 if (!Name.empty()) { 4018 if (VD->hasAttr<BlocksAttr>()) { 4019 // Here, we need an offset *into* the alloca. 4020 CharUnits offset = CharUnits::fromQuantity(32); 4021 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4022 // offset of __forwarding field 4023 offset = CGM.getContext().toCharUnitsFromBits( 4024 CGM.getTarget().getPointerWidth(0)); 4025 Expr.push_back(offset.getQuantity()); 4026 Expr.push_back(llvm::dwarf::DW_OP_deref); 4027 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4028 // offset of x field 4029 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 4030 Expr.push_back(offset.getQuantity()); 4031 } 4032 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) { 4033 // If VD is an anonymous union then Storage represents value for 4034 // all union fields. 4035 const RecordDecl *RD = RT->getDecl(); 4036 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 4037 // GDB has trouble finding local variables in anonymous unions, so we emit 4038 // artificial local variables for each of the members. 4039 // 4040 // FIXME: Remove this code as soon as GDB supports this. 4041 // The debug info verifier in LLVM operates based on the assumption that a 4042 // variable has the same size as its storage and we had to disable the 4043 // check for artificial variables. 4044 for (const auto *Field : RD->fields()) { 4045 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 4046 StringRef FieldName = Field->getName(); 4047 4048 // Ignore unnamed fields. Do not ignore unnamed records. 4049 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 4050 continue; 4051 4052 // Use VarDecl's Tag, Scope and Line number. 4053 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext()); 4054 auto *D = DBuilder.createAutoVariable( 4055 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize, 4056 Flags | llvm::DINode::FlagArtificial, FieldAlign); 4057 4058 // Insert an llvm.dbg.declare into the current block. 4059 DBuilder.insertDeclare( 4060 Storage, D, DBuilder.createExpression(Expr), 4061 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt), 4062 Builder.GetInsertBlock()); 4063 } 4064 } 4065 } 4066 4067 // Clang stores the sret pointer provided by the caller in a static alloca. 4068 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as 4069 // the address of the variable. 4070 if (UsePointerValue) { 4071 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) == 4072 Expr.end() && 4073 "Debug info already contains DW_OP_deref."); 4074 Expr.push_back(llvm::dwarf::DW_OP_deref); 4075 } 4076 4077 // Create the descriptor for the variable. 4078 auto *D = ArgNo ? DBuilder.createParameterVariable( 4079 Scope, Name, *ArgNo, Unit, Line, Ty, 4080 CGM.getLangOpts().Optimize, Flags) 4081 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty, 4082 CGM.getLangOpts().Optimize, 4083 Flags, Align); 4084 4085 // Insert an llvm.dbg.declare into the current block. 4086 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 4087 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt), 4088 Builder.GetInsertBlock()); 4089 4090 return D; 4091 } 4092 4093 llvm::DILocalVariable * 4094 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage, 4095 CGBuilderTy &Builder, 4096 const bool UsePointerValue) { 4097 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4098 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue); 4099 } 4100 4101 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) { 4102 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4103 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4104 4105 if (D->hasAttr<NoDebugAttr>()) 4106 return; 4107 4108 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 4109 llvm::DIFile *Unit = getOrCreateFile(D->getLocation()); 4110 4111 // Get location information. 4112 unsigned Line = getLineNumber(D->getLocation()); 4113 unsigned Column = getColumnNumber(D->getLocation()); 4114 4115 StringRef Name = D->getName(); 4116 4117 // Create the descriptor for the label. 4118 auto *L = 4119 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize); 4120 4121 // Insert an llvm.dbg.label into the current block. 4122 DBuilder.insertLabel(L, 4123 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt), 4124 Builder.GetInsertBlock()); 4125 } 4126 4127 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, 4128 llvm::DIType *Ty) { 4129 llvm::DIType *CachedTy = getTypeOrNull(QualTy); 4130 if (CachedTy) 4131 Ty = CachedTy; 4132 return DBuilder.createObjectPointerType(Ty); 4133 } 4134 4135 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 4136 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 4137 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { 4138 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4139 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4140 4141 if (Builder.GetInsertBlock() == nullptr) 4142 return; 4143 if (VD->hasAttr<NoDebugAttr>()) 4144 return; 4145 4146 bool isByRef = VD->hasAttr<BlocksAttr>(); 4147 4148 uint64_t XOffset = 0; 4149 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 4150 llvm::DIType *Ty; 4151 if (isByRef) 4152 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType; 4153 else 4154 Ty = getOrCreateType(VD->getType(), Unit); 4155 4156 // Self is passed along as an implicit non-arg variable in a 4157 // block. Mark it as the object pointer. 4158 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) 4159 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf) 4160 Ty = CreateSelfType(VD->getType(), Ty); 4161 4162 // Get location information. 4163 unsigned Line = getLineNumber(VD->getLocation()); 4164 unsigned Column = getColumnNumber(VD->getLocation()); 4165 4166 const llvm::DataLayout &target = CGM.getDataLayout(); 4167 4168 CharUnits offset = CharUnits::fromQuantity( 4169 target.getStructLayout(blockInfo.StructureType) 4170 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 4171 4172 SmallVector<int64_t, 9> addr; 4173 addr.push_back(llvm::dwarf::DW_OP_deref); 4174 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4175 addr.push_back(offset.getQuantity()); 4176 if (isByRef) { 4177 addr.push_back(llvm::dwarf::DW_OP_deref); 4178 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4179 // offset of __forwarding field 4180 offset = 4181 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 4182 addr.push_back(offset.getQuantity()); 4183 addr.push_back(llvm::dwarf::DW_OP_deref); 4184 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4185 // offset of x field 4186 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 4187 addr.push_back(offset.getQuantity()); 4188 } 4189 4190 // Create the descriptor for the variable. 4191 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 4192 auto *D = DBuilder.createAutoVariable( 4193 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit, 4194 Line, Ty, false, llvm::DINode::FlagZero, Align); 4195 4196 // Insert an llvm.dbg.declare into the current block. 4197 auto DL = 4198 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt); 4199 auto *Expr = DBuilder.createExpression(addr); 4200 if (InsertPoint) 4201 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint); 4202 else 4203 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock()); 4204 } 4205 4206 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 4207 unsigned ArgNo, 4208 CGBuilderTy &Builder) { 4209 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4210 EmitDeclare(VD, AI, ArgNo, Builder); 4211 } 4212 4213 namespace { 4214 struct BlockLayoutChunk { 4215 uint64_t OffsetInBits; 4216 const BlockDecl::Capture *Capture; 4217 }; 4218 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 4219 return l.OffsetInBits < r.OffsetInBits; 4220 } 4221 } // namespace 4222 4223 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare( 4224 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc, 4225 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit, 4226 SmallVectorImpl<llvm::Metadata *> &Fields) { 4227 // Blocks in OpenCL have unique constraints which make the standard fields 4228 // redundant while requiring size and align fields for enqueue_kernel. See 4229 // initializeForBlockHeader in CGBlocks.cpp 4230 if (CGM.getLangOpts().OpenCL) { 4231 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public, 4232 BlockLayout.getElementOffsetInBits(0), 4233 Unit, Unit)); 4234 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public, 4235 BlockLayout.getElementOffsetInBits(1), 4236 Unit, Unit)); 4237 } else { 4238 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public, 4239 BlockLayout.getElementOffsetInBits(0), 4240 Unit, Unit)); 4241 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public, 4242 BlockLayout.getElementOffsetInBits(1), 4243 Unit, Unit)); 4244 Fields.push_back( 4245 createFieldType("__reserved", Context.IntTy, Loc, AS_public, 4246 BlockLayout.getElementOffsetInBits(2), Unit, Unit)); 4247 auto *FnTy = Block.getBlockExpr()->getFunctionType(); 4248 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 4249 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public, 4250 BlockLayout.getElementOffsetInBits(3), 4251 Unit, Unit)); 4252 Fields.push_back(createFieldType( 4253 "__descriptor", 4254 Context.getPointerType(Block.NeedsCopyDispose 4255 ? Context.getBlockDescriptorExtendedType() 4256 : Context.getBlockDescriptorType()), 4257 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit)); 4258 } 4259 } 4260 4261 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 4262 StringRef Name, 4263 unsigned ArgNo, 4264 llvm::AllocaInst *Alloca, 4265 CGBuilderTy &Builder) { 4266 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4267 ASTContext &C = CGM.getContext(); 4268 const BlockDecl *blockDecl = block.getBlockDecl(); 4269 4270 // Collect some general information about the block's location. 4271 SourceLocation loc = blockDecl->getCaretLocation(); 4272 llvm::DIFile *tunit = getOrCreateFile(loc); 4273 unsigned line = getLineNumber(loc); 4274 unsigned column = getColumnNumber(loc); 4275 4276 // Build the debug-info type for the block literal. 4277 getDeclContextDescriptor(blockDecl); 4278 4279 const llvm::StructLayout *blockLayout = 4280 CGM.getDataLayout().getStructLayout(block.StructureType); 4281 4282 SmallVector<llvm::Metadata *, 16> fields; 4283 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit, 4284 fields); 4285 4286 // We want to sort the captures by offset, not because DWARF 4287 // requires this, but because we're paranoid about debuggers. 4288 SmallVector<BlockLayoutChunk, 8> chunks; 4289 4290 // 'this' capture. 4291 if (blockDecl->capturesCXXThis()) { 4292 BlockLayoutChunk chunk; 4293 chunk.OffsetInBits = 4294 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 4295 chunk.Capture = nullptr; 4296 chunks.push_back(chunk); 4297 } 4298 4299 // Variable captures. 4300 for (const auto &capture : blockDecl->captures()) { 4301 const VarDecl *variable = capture.getVariable(); 4302 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 4303 4304 // Ignore constant captures. 4305 if (captureInfo.isConstant()) 4306 continue; 4307 4308 BlockLayoutChunk chunk; 4309 chunk.OffsetInBits = 4310 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 4311 chunk.Capture = &capture; 4312 chunks.push_back(chunk); 4313 } 4314 4315 // Sort by offset. 4316 llvm::array_pod_sort(chunks.begin(), chunks.end()); 4317 4318 for (const BlockLayoutChunk &Chunk : chunks) { 4319 uint64_t offsetInBits = Chunk.OffsetInBits; 4320 const BlockDecl::Capture *capture = Chunk.Capture; 4321 4322 // If we have a null capture, this must be the C++ 'this' capture. 4323 if (!capture) { 4324 QualType type; 4325 if (auto *Method = 4326 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext())) 4327 type = Method->getThisType(); 4328 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent())) 4329 type = QualType(RDecl->getTypeForDecl(), 0); 4330 else 4331 llvm_unreachable("unexpected block declcontext"); 4332 4333 fields.push_back(createFieldType("this", type, loc, AS_public, 4334 offsetInBits, tunit, tunit)); 4335 continue; 4336 } 4337 4338 const VarDecl *variable = capture->getVariable(); 4339 StringRef name = variable->getName(); 4340 4341 llvm::DIType *fieldType; 4342 if (capture->isByRef()) { 4343 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 4344 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0; 4345 // FIXME: This recomputes the layout of the BlockByRefWrapper. 4346 uint64_t xoffset; 4347 fieldType = 4348 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper; 4349 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 4350 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 4351 PtrInfo.Width, Align, offsetInBits, 4352 llvm::DINode::FlagZero, fieldType); 4353 } else { 4354 auto Align = getDeclAlignIfRequired(variable, CGM.getContext()); 4355 fieldType = createFieldType(name, variable->getType(), loc, AS_public, 4356 offsetInBits, Align, tunit, tunit); 4357 } 4358 fields.push_back(fieldType); 4359 } 4360 4361 SmallString<36> typeName; 4362 llvm::raw_svector_ostream(typeName) 4363 << "__block_literal_" << CGM.getUniqueBlockCount(); 4364 4365 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields); 4366 4367 llvm::DIType *type = 4368 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 4369 CGM.getContext().toBits(block.BlockSize), 0, 4370 llvm::DINode::FlagZero, nullptr, fieldsArray); 4371 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 4372 4373 // Get overall information about the block. 4374 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial; 4375 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back()); 4376 4377 // Create the descriptor for the parameter. 4378 auto *debugVar = DBuilder.createParameterVariable( 4379 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags); 4380 4381 // Insert an llvm.dbg.declare into the current block. 4382 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(), 4383 llvm::DebugLoc::get(line, column, scope, CurInlinedAt), 4384 Builder.GetInsertBlock()); 4385 } 4386 4387 llvm::DIDerivedType * 4388 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 4389 if (!D || !D->isStaticDataMember()) 4390 return nullptr; 4391 4392 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 4393 if (MI != StaticDataMemberCache.end()) { 4394 assert(MI->second && "Static data member declaration should still exist"); 4395 return MI->second; 4396 } 4397 4398 // If the member wasn't found in the cache, lazily construct and add it to the 4399 // type (used when a limited form of the type is emitted). 4400 auto DC = D->getDeclContext(); 4401 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D)); 4402 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 4403 } 4404 4405 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls( 4406 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, 4407 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { 4408 llvm::DIGlobalVariableExpression *GVE = nullptr; 4409 4410 for (const auto *Field : RD->fields()) { 4411 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 4412 StringRef FieldName = Field->getName(); 4413 4414 // Ignore unnamed fields, but recurse into anonymous records. 4415 if (FieldName.empty()) { 4416 if (const auto *RT = dyn_cast<RecordType>(Field->getType())) 4417 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 4418 Var, DContext); 4419 continue; 4420 } 4421 // Use VarDecl's Tag, Scope and Line number. 4422 GVE = DBuilder.createGlobalVariableExpression( 4423 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy, 4424 Var->hasLocalLinkage()); 4425 Var->addDebugInfo(GVE); 4426 } 4427 return GVE; 4428 } 4429 4430 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 4431 const VarDecl *D) { 4432 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4433 if (D->hasAttr<NoDebugAttr>()) 4434 return; 4435 4436 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() { 4437 std::string Name; 4438 llvm::raw_string_ostream OS(Name); 4439 D->getNameForDiagnostic(OS, getPrintingPolicy(), 4440 /*Qualified=*/true); 4441 return Name; 4442 }); 4443 4444 // If we already created a DIGlobalVariable for this declaration, just attach 4445 // it to the llvm::GlobalVariable. 4446 auto Cached = DeclCache.find(D->getCanonicalDecl()); 4447 if (Cached != DeclCache.end()) 4448 return Var->addDebugInfo( 4449 cast<llvm::DIGlobalVariableExpression>(Cached->second)); 4450 4451 // Create global variable debug descriptor. 4452 llvm::DIFile *Unit = nullptr; 4453 llvm::DIScope *DContext = nullptr; 4454 unsigned LineNo; 4455 StringRef DeclName, LinkageName; 4456 QualType T; 4457 llvm::MDTuple *TemplateParameters = nullptr; 4458 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, 4459 TemplateParameters, DContext); 4460 4461 // Attempt to store one global variable for the declaration - even if we 4462 // emit a lot of fields. 4463 llvm::DIGlobalVariableExpression *GVE = nullptr; 4464 4465 // If this is an anonymous union then we'll want to emit a global 4466 // variable for each member of the anonymous union so that it's possible 4467 // to find the name of any field in the union. 4468 if (T->isUnionType() && DeclName.empty()) { 4469 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 4470 assert(RD->isAnonymousStructOrUnion() && 4471 "unnamed non-anonymous struct or union?"); 4472 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 4473 } else { 4474 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 4475 4476 SmallVector<int64_t, 4> Expr; 4477 unsigned AddressSpace = 4478 CGM.getContext().getTargetAddressSpace(D->getType()); 4479 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) { 4480 if (D->hasAttr<CUDASharedAttr>()) 4481 AddressSpace = 4482 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared); 4483 else if (D->hasAttr<CUDAConstantAttr>()) 4484 AddressSpace = 4485 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant); 4486 } 4487 AppendAddressSpaceXDeref(AddressSpace, Expr); 4488 4489 GVE = DBuilder.createGlobalVariableExpression( 4490 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 4491 Var->hasLocalLinkage(), 4492 Expr.empty() ? nullptr : DBuilder.createExpression(Expr), 4493 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters, 4494 Align); 4495 Var->addDebugInfo(GVE); 4496 } 4497 DeclCache[D->getCanonicalDecl()].reset(GVE); 4498 } 4499 4500 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) { 4501 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 4502 if (VD->hasAttr<NoDebugAttr>()) 4503 return; 4504 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() { 4505 std::string Name; 4506 llvm::raw_string_ostream OS(Name); 4507 VD->getNameForDiagnostic(OS, getPrintingPolicy(), 4508 /*Qualified=*/true); 4509 return Name; 4510 }); 4511 4512 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 4513 // Create the descriptor for the variable. 4514 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 4515 StringRef Name = VD->getName(); 4516 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit); 4517 4518 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) { 4519 const auto *ED = cast<EnumDecl>(ECD->getDeclContext()); 4520 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 4521 4522 if (CGM.getCodeGenOpts().EmitCodeView) { 4523 // If CodeView, emit enums as global variables, unless they are defined 4524 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for 4525 // enums in classes, and because it is difficult to attach this scope 4526 // information to the global variable. 4527 if (isa<RecordDecl>(ED->getDeclContext())) 4528 return; 4529 } else { 4530 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For 4531 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the 4532 // first time `ZERO` is referenced in a function. 4533 llvm::DIType *EDTy = 4534 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 4535 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type); 4536 (void)EDTy; 4537 return; 4538 } 4539 } 4540 4541 llvm::DIScope *DContext = nullptr; 4542 4543 // Do not emit separate definitions for function local consts. 4544 if (isa<FunctionDecl>(VD->getDeclContext())) 4545 return; 4546 4547 // Emit definition for static members in CodeView. 4548 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 4549 auto *VarD = dyn_cast<VarDecl>(VD); 4550 if (VarD && VarD->isStaticDataMember()) { 4551 auto *RD = cast<RecordDecl>(VarD->getDeclContext()); 4552 getDeclContextDescriptor(VarD); 4553 // Ensure that the type is retained even though it's otherwise unreferenced. 4554 // 4555 // FIXME: This is probably unnecessary, since Ty should reference RD 4556 // through its scope. 4557 RetainedTypes.push_back( 4558 CGM.getContext().getRecordType(RD).getAsOpaquePtr()); 4559 4560 if (!CGM.getCodeGenOpts().EmitCodeView) 4561 return; 4562 4563 // Use the global scope for static members. 4564 DContext = getContextDescriptor( 4565 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU); 4566 } else { 4567 DContext = getDeclContextDescriptor(VD); 4568 } 4569 4570 auto &GV = DeclCache[VD]; 4571 if (GV) 4572 return; 4573 llvm::DIExpression *InitExpr = nullptr; 4574 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) { 4575 // FIXME: Add a representation for integer constants wider than 64 bits. 4576 if (Init.isInt()) 4577 InitExpr = 4578 DBuilder.createConstantValueExpression(Init.getInt().getExtValue()); 4579 else if (Init.isFloat()) 4580 InitExpr = DBuilder.createConstantValueExpression( 4581 Init.getFloat().bitcastToAPInt().getZExtValue()); 4582 } 4583 4584 llvm::MDTuple *TemplateParameters = nullptr; 4585 4586 if (isa<VarTemplateSpecializationDecl>(VD)) 4587 if (VarD) { 4588 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit); 4589 TemplateParameters = parameterNodes.get(); 4590 } 4591 4592 GV.reset(DBuilder.createGlobalVariableExpression( 4593 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 4594 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD), 4595 TemplateParameters, Align)); 4596 } 4597 4598 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 4599 if (!LexicalBlockStack.empty()) 4600 return LexicalBlockStack.back(); 4601 llvm::DIScope *Mod = getParentModuleOrNull(D); 4602 return getContextDescriptor(D, Mod ? Mod : TheCU); 4603 } 4604 4605 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 4606 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4607 return; 4608 const NamespaceDecl *NSDecl = UD.getNominatedNamespace(); 4609 if (!NSDecl->isAnonymousNamespace() || 4610 CGM.getCodeGenOpts().DebugExplicitImport) { 4611 auto Loc = UD.getLocation(); 4612 DBuilder.createImportedModule( 4613 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 4614 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc)); 4615 } 4616 } 4617 4618 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 4619 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4620 return; 4621 assert(UD.shadow_size() && 4622 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 4623 // Emitting one decl is sufficient - debuggers can detect that this is an 4624 // overloaded name & provide lookup for all the overloads. 4625 const UsingShadowDecl &USD = **UD.shadow_begin(); 4626 4627 // FIXME: Skip functions with undeduced auto return type for now since we 4628 // don't currently have the plumbing for separate declarations & definitions 4629 // of free functions and mismatched types (auto in the declaration, concrete 4630 // return type in the definition) 4631 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl())) 4632 if (const auto *AT = 4633 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType()) 4634 if (AT->getDeducedType().isNull()) 4635 return; 4636 if (llvm::DINode *Target = 4637 getDeclarationOrDefinition(USD.getUnderlyingDecl())) { 4638 auto Loc = USD.getLocation(); 4639 DBuilder.createImportedDeclaration( 4640 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 4641 getOrCreateFile(Loc), getLineNumber(Loc)); 4642 } 4643 } 4644 4645 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { 4646 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB) 4647 return; 4648 if (Module *M = ID.getImportedModule()) { 4649 auto Info = ExternalASTSource::ASTSourceDescriptor(*M); 4650 auto Loc = ID.getLocation(); 4651 DBuilder.createImportedDeclaration( 4652 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())), 4653 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc), 4654 getLineNumber(Loc)); 4655 } 4656 } 4657 4658 llvm::DIImportedEntity * 4659 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 4660 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4661 return nullptr; 4662 auto &VH = NamespaceAliasCache[&NA]; 4663 if (VH) 4664 return cast<llvm::DIImportedEntity>(VH); 4665 llvm::DIImportedEntity *R; 4666 auto Loc = NA.getLocation(); 4667 if (const auto *Underlying = 4668 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 4669 // This could cache & dedup here rather than relying on metadata deduping. 4670 R = DBuilder.createImportedDeclaration( 4671 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 4672 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc), 4673 getLineNumber(Loc), NA.getName()); 4674 else 4675 R = DBuilder.createImportedDeclaration( 4676 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 4677 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 4678 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName()); 4679 VH.reset(R); 4680 return R; 4681 } 4682 4683 llvm::DINamespace * 4684 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) { 4685 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued 4686 // if necessary, and this way multiple declarations of the same namespace in 4687 // different parent modules stay distinct. 4688 auto I = NamespaceCache.find(NSDecl); 4689 if (I != NamespaceCache.end()) 4690 return cast<llvm::DINamespace>(I->second); 4691 4692 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); 4693 // Don't trust the context if it is a DIModule (see comment above). 4694 llvm::DINamespace *NS = 4695 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline()); 4696 NamespaceCache[NSDecl].reset(NS); 4697 return NS; 4698 } 4699 4700 void CGDebugInfo::setDwoId(uint64_t Signature) { 4701 assert(TheCU && "no main compile unit"); 4702 TheCU->setDWOId(Signature); 4703 } 4704 4705 void CGDebugInfo::finalize() { 4706 // Creating types might create further types - invalidating the current 4707 // element and the size(), so don't cache/reference them. 4708 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 4709 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 4710 llvm::DIType *Ty = E.Type->getDecl()->getDefinition() 4711 ? CreateTypeDefinition(E.Type, E.Unit) 4712 : E.Decl; 4713 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty); 4714 } 4715 4716 if (CGM.getCodeGenOpts().DwarfVersion >= 5) { 4717 // Add methods to interface. 4718 for (const auto &P : ObjCMethodCache) { 4719 if (P.second.empty()) 4720 continue; 4721 4722 QualType QTy(P.first->getTypeForDecl(), 0); 4723 auto It = TypeCache.find(QTy.getAsOpaquePtr()); 4724 assert(It != TypeCache.end()); 4725 4726 llvm::DICompositeType *InterfaceDecl = 4727 cast<llvm::DICompositeType>(It->second); 4728 4729 SmallVector<llvm::Metadata *, 16> EltTys; 4730 auto CurrenetElts = InterfaceDecl->getElements(); 4731 EltTys.append(CurrenetElts.begin(), CurrenetElts.end()); 4732 for (auto &MD : P.second) 4733 EltTys.push_back(MD); 4734 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 4735 DBuilder.replaceArrays(InterfaceDecl, Elements); 4736 } 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