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