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