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