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