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