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