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