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