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