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