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