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