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