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