CGDebugInfo.cpp revision bd0152fb251e84c6f335c66322b83a9af09fed0c
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, bool Force) { 266 // We may not want column information at all. 267 if (!Force && !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 RetainedTypes.push_back(D.getAsOpaquePtr()); 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 if (Ty->getTypeClass() == Type::ObjCInterface) { 1782 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty); 1783 if (V) 1784 return llvm::DIType(cast<llvm::MDNode>(V)); 1785 else return llvm::DIType(); 1786 } 1787 1788 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1789 TypeCache.find(Ty.getAsOpaquePtr()); 1790 if (it != TypeCache.end()) { 1791 // Verify that the debug info still exists. 1792 if (llvm::Value *V = it->second) 1793 return llvm::DIType(cast<llvm::MDNode>(V)); 1794 } 1795 1796 return llvm::DIType(); 1797} 1798 1799/// getCompletedTypeOrNull - Get the type from the cache or return null if it 1800/// doesn't exist. 1801llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) { 1802 1803 // Unwrap the type as needed for debug information. 1804 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1805 1806 // Check for existing entry. 1807 llvm::Value *V = 0; 1808 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1809 CompletedTypeCache.find(Ty.getAsOpaquePtr()); 1810 if (it != CompletedTypeCache.end()) 1811 V = it->second; 1812 else { 1813 V = getCachedInterfaceTypeOrNull(Ty); 1814 } 1815 1816 // Verify that any cached debug info still exists. 1817 if (V != 0) 1818 return llvm::DIType(cast<llvm::MDNode>(V)); 1819 1820 return llvm::DIType(); 1821} 1822 1823/// getCachedInterfaceTypeOrNull - Get the type from the interface 1824/// cache, unless it needs to regenerated. Otherwise return null. 1825llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) { 1826 // Is there a cached interface that hasn't changed? 1827 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > > 1828 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr()); 1829 1830 if (it1 != ObjCInterfaceCache.end()) 1831 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) 1832 if (Checksum(Decl) == it1->second.second) 1833 // Return cached forward declaration. 1834 return it1->second.first; 1835 1836 return 0; 1837} 1838 1839/// getOrCreateType - Get the type from the cache or create a new 1840/// one if necessary. 1841llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 1842 if (Ty.isNull()) 1843 return llvm::DIType(); 1844 1845 // Unwrap the type as needed for debug information. 1846 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1847 1848 llvm::DIType T = getCompletedTypeOrNull(Ty); 1849 1850 if (T.Verify()) 1851 return T; 1852 1853 // Otherwise create the type. 1854 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1855 void* TyPtr = Ty.getAsOpaquePtr(); 1856 1857 // And update the type cache. 1858 TypeCache[TyPtr] = Res; 1859 1860 llvm::DIType TC = getTypeOrNull(Ty); 1861 if (TC.Verify() && TC.isForwardDecl()) 1862 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 1863 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) { 1864 // Interface types may have elements added to them by a 1865 // subsequent implementation or extension, so we keep them in 1866 // the ObjCInterfaceCache together with a checksum. Instead of 1867 // the (possibly) incomplete interace type, we return a forward 1868 // declaration that gets RAUW'd in CGDebugInfo::finalize(). 1869 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > > 1870 ::iterator it = ObjCInterfaceCache.find(TyPtr); 1871 if (it != ObjCInterfaceCache.end()) 1872 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first)); 1873 else 1874 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1875 Decl->getName(), TheCU, Unit, 1876 getLineNumber(Decl->getLocation()), 1877 TheCU.getLanguage()); 1878 // Store the forward declaration in the cache. 1879 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl)); 1880 1881 // Register the type for replacement in finalize(). 1882 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 1883 return TC; 1884 } 1885 1886 if (!Res.isForwardDecl()) 1887 CompletedTypeCache[TyPtr] = Res; 1888 1889 return Res; 1890} 1891 1892/// Currently the checksum merely consists of the number of ivars. 1893unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl 1894 *InterfaceDecl) { 1895 unsigned IvarNo = 0; 1896 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin(); 1897 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo; 1898 return IvarNo; 1899} 1900 1901ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 1902 switch (Ty->getTypeClass()) { 1903 case Type::ObjCObjectPointer: 1904 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 1905 case Type::ObjCInterface: 1906 return cast<ObjCInterfaceType>(Ty)->getDecl(); 1907 default: 1908 return 0; 1909 } 1910} 1911 1912/// CreateTypeNode - Create a new debug type node. 1913llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) { 1914 // Handle qualifiers, which recursively handles what they refer to. 1915 if (Ty.hasLocalQualifiers()) 1916 return CreateQualifiedType(Ty, Unit); 1917 1918 const char *Diag = 0; 1919 1920 // Work out details of type. 1921 switch (Ty->getTypeClass()) { 1922#define TYPE(Class, Base) 1923#define ABSTRACT_TYPE(Class, Base) 1924#define NON_CANONICAL_TYPE(Class, Base) 1925#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1926#include "clang/AST/TypeNodes.def" 1927 llvm_unreachable("Dependent types cannot show up in debug information"); 1928 1929 case Type::ExtVector: 1930 case Type::Vector: 1931 return CreateType(cast<VectorType>(Ty), Unit); 1932 case Type::ObjCObjectPointer: 1933 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 1934 case Type::ObjCObject: 1935 return CreateType(cast<ObjCObjectType>(Ty), Unit); 1936 case Type::ObjCInterface: 1937 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 1938 case Type::Builtin: 1939 return CreateType(cast<BuiltinType>(Ty)); 1940 case Type::Complex: 1941 return CreateType(cast<ComplexType>(Ty)); 1942 case Type::Pointer: 1943 return CreateType(cast<PointerType>(Ty), Unit); 1944 case Type::BlockPointer: 1945 return CreateType(cast<BlockPointerType>(Ty), Unit); 1946 case Type::Typedef: 1947 return CreateType(cast<TypedefType>(Ty), Unit); 1948 case Type::Record: 1949 return CreateType(cast<RecordType>(Ty)); 1950 case Type::Enum: 1951 return CreateEnumType(cast<EnumType>(Ty)->getDecl()); 1952 case Type::FunctionProto: 1953 case Type::FunctionNoProto: 1954 return CreateType(cast<FunctionType>(Ty), Unit); 1955 case Type::ConstantArray: 1956 case Type::VariableArray: 1957 case Type::IncompleteArray: 1958 return CreateType(cast<ArrayType>(Ty), Unit); 1959 1960 case Type::LValueReference: 1961 return CreateType(cast<LValueReferenceType>(Ty), Unit); 1962 case Type::RValueReference: 1963 return CreateType(cast<RValueReferenceType>(Ty), Unit); 1964 1965 case Type::MemberPointer: 1966 return CreateType(cast<MemberPointerType>(Ty), Unit); 1967 1968 case Type::Atomic: 1969 return CreateType(cast<AtomicType>(Ty), Unit); 1970 1971 case Type::Attributed: 1972 case Type::TemplateSpecialization: 1973 case Type::Elaborated: 1974 case Type::Paren: 1975 case Type::SubstTemplateTypeParm: 1976 case Type::TypeOfExpr: 1977 case Type::TypeOf: 1978 case Type::Decltype: 1979 case Type::UnaryTransform: 1980 case Type::Auto: 1981 llvm_unreachable("type should have been unwrapped!"); 1982 } 1983 1984 assert(Diag && "Fall through without a diagnostic?"); 1985 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1986 "debug information for %0 is not yet supported"); 1987 CGM.getDiags().Report(DiagID) 1988 << Diag; 1989 return llvm::DIType(); 1990} 1991 1992/// getOrCreateLimitedType - Get the type from the cache or create a new 1993/// limited type if necessary. 1994llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty, 1995 llvm::DIFile Unit) { 1996 if (Ty.isNull()) 1997 return llvm::DIType(); 1998 1999 // Unwrap the type as needed for debug information. 2000 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2001 2002 llvm::DIType T = getTypeOrNull(Ty); 2003 2004 // We may have cached a forward decl when we could have created 2005 // a non-forward decl. Go ahead and create a non-forward decl 2006 // now. 2007 if (T.Verify() && !T.isForwardDecl()) return T; 2008 2009 // Otherwise create the type. 2010 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit); 2011 2012 if (T.Verify() && T.isForwardDecl()) 2013 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), 2014 static_cast<llvm::Value*>(T))); 2015 2016 // And update the type cache. 2017 TypeCache[Ty.getAsOpaquePtr()] = Res; 2018 return Res; 2019} 2020 2021// TODO: Currently used for context chains when limiting debug info. 2022llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2023 RecordDecl *RD = Ty->getDecl(); 2024 2025 // Get overall information about the record type for the debug info. 2026 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 2027 unsigned Line = getLineNumber(RD->getLocation()); 2028 StringRef RDName = getClassName(RD); 2029 2030 llvm::DIDescriptor RDContext; 2031 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) 2032 RDContext = createContextChain(cast<Decl>(RD->getDeclContext())); 2033 else 2034 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext())); 2035 2036 // If this is just a forward declaration, construct an appropriately 2037 // marked node and just return it. 2038 if (!RD->getDefinition()) 2039 return createRecordFwdDecl(RD, RDContext); 2040 2041 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2042 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 2043 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2044 llvm::DICompositeType RealDecl; 2045 2046 if (RD->isUnion()) 2047 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, 2048 Size, Align, 0, llvm::DIArray()); 2049 else if (RD->isClass()) { 2050 // FIXME: This could be a struct type giving a default visibility different 2051 // than C++ class type, but needs llvm metadata changes first. 2052 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line, 2053 Size, Align, 0, 0, llvm::DIType(), 2054 llvm::DIArray(), llvm::DIType(), 2055 llvm::DIArray()); 2056 } else 2057 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line, 2058 Size, Align, 0, llvm::DIType(), llvm::DIArray()); 2059 2060 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 2061 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; 2062 2063 if (CXXDecl) { 2064 // A class's primary base or the class itself contains the vtable. 2065 llvm::DICompositeType ContainingType; 2066 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2067 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2068 // Seek non virtual primary base root. 2069 while (1) { 2070 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2071 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2072 if (PBT && !BRL.isPrimaryBaseVirtual()) 2073 PBase = PBT; 2074 else 2075 break; 2076 } 2077 ContainingType = llvm::DICompositeType( 2078 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit)); 2079 } else if (CXXDecl->isDynamicClass()) 2080 ContainingType = RealDecl; 2081 2082 RealDecl.setContainingType(ContainingType); 2083 } 2084 return llvm::DIType(RealDecl); 2085} 2086 2087/// CreateLimitedTypeNode - Create a new debug type node, but only forward 2088/// declare composite types that haven't been processed yet. 2089llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) { 2090 2091 // Work out details of type. 2092 switch (Ty->getTypeClass()) { 2093#define TYPE(Class, Base) 2094#define ABSTRACT_TYPE(Class, Base) 2095#define NON_CANONICAL_TYPE(Class, Base) 2096#define DEPENDENT_TYPE(Class, Base) case Type::Class: 2097 #include "clang/AST/TypeNodes.def" 2098 llvm_unreachable("Dependent types cannot show up in debug information"); 2099 2100 case Type::Record: 2101 return CreateLimitedType(cast<RecordType>(Ty)); 2102 default: 2103 return CreateTypeNode(Ty, Unit); 2104 } 2105} 2106 2107/// CreateMemberType - Create new member and increase Offset by FType's size. 2108llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 2109 StringRef Name, 2110 uint64_t *Offset) { 2111 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2112 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2113 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 2114 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, 2115 FieldSize, FieldAlign, 2116 *Offset, 0, FieldTy); 2117 *Offset += FieldSize; 2118 return Ty; 2119} 2120 2121/// getFunctionDeclaration - Return debug info descriptor to describe method 2122/// declaration for the given method definition. 2123llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2124 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2125 if (!FD) return llvm::DISubprogram(); 2126 2127 // Setup context. 2128 getContextDescriptor(cast<Decl>(D->getDeclContext())); 2129 2130 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2131 MI = SPCache.find(FD->getCanonicalDecl()); 2132 if (MI != SPCache.end()) { 2133 llvm::Value *V = MI->second; 2134 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2135 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 2136 return SP; 2137 } 2138 2139 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(), 2140 E = FD->redecls_end(); I != E; ++I) { 2141 const FunctionDecl *NextFD = *I; 2142 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2143 MI = SPCache.find(NextFD->getCanonicalDecl()); 2144 if (MI != SPCache.end()) { 2145 llvm::Value *V = MI->second; 2146 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2147 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 2148 return SP; 2149 } 2150 } 2151 return llvm::DISubprogram(); 2152} 2153 2154// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include 2155// implicit parameter "this". 2156llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2157 QualType FnType, 2158 llvm::DIFile F) { 2159 2160 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 2161 return getOrCreateMethodType(Method, F); 2162 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 2163 // Add "self" and "_cmd" 2164 SmallVector<llvm::Value *, 16> Elts; 2165 2166 // First element is always return type. For 'void' functions it is NULL. 2167 Elts.push_back(getOrCreateType(OMethod->getResultType(), F)); 2168 // "self" pointer is always first argument. 2169 QualType SelfDeclTy = OMethod->getSelfDecl()->getType(); 2170 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F); 2171 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy)); 2172 // "_cmd" pointer is always second argument. 2173 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F); 2174 Elts.push_back(DBuilder.createArtificialType(CmdTy)); 2175 // Get rest of the arguments. 2176 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(), 2177 PE = OMethod->param_end(); PI != PE; ++PI) 2178 Elts.push_back(getOrCreateType((*PI)->getType(), F)); 2179 2180 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2181 return DBuilder.createSubroutineType(F, EltTypeArray); 2182 } 2183 return getOrCreateType(FnType, F); 2184} 2185 2186/// EmitFunctionStart - Constructs the debug code for entering a function. 2187void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 2188 llvm::Function *Fn, 2189 CGBuilderTy &Builder) { 2190 2191 StringRef Name; 2192 StringRef LinkageName; 2193 2194 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 2195 2196 const Decl *D = GD.getDecl(); 2197 // Function may lack declaration in source code if it is created by Clang 2198 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 2199 bool HasDecl = (D != 0); 2200 // Use the location of the declaration. 2201 SourceLocation Loc; 2202 if (HasDecl) 2203 Loc = D->getLocation(); 2204 2205 unsigned Flags = 0; 2206 llvm::DIFile Unit = getOrCreateFile(Loc); 2207 llvm::DIDescriptor FDContext(Unit); 2208 llvm::DIArray TParamsArray; 2209 if (!HasDecl) { 2210 // Use llvm function name. 2211 Name = Fn->getName(); 2212 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2213 // If there is a DISubprogram for this function available then use it. 2214 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2215 FI = SPCache.find(FD->getCanonicalDecl()); 2216 if (FI != SPCache.end()) { 2217 llvm::Value *V = FI->second; 2218 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V)); 2219 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 2220 llvm::MDNode *SPN = SP; 2221 LexicalBlockStack.push_back(SPN); 2222 RegionMap[D] = llvm::WeakVH(SP); 2223 return; 2224 } 2225 } 2226 Name = getFunctionName(FD); 2227 // Use mangled name as linkage name for C/C++ functions. 2228 if (FD->hasPrototype()) { 2229 LinkageName = CGM.getMangledName(GD); 2230 Flags |= llvm::DIDescriptor::FlagPrototyped; 2231 } 2232 // No need to replicate the linkage name if it isn't different from the 2233 // subprogram name, no need to have it at all unless coverage is enabled or 2234 // debug is set to more than just line tables. 2235 if (LinkageName == Name || 2236 (!CGM.getCodeGenOpts().EmitGcovArcs && 2237 !CGM.getCodeGenOpts().EmitGcovNotes && 2238 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly)) 2239 LinkageName = StringRef(); 2240 2241 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 2242 if (const NamespaceDecl *NSDecl = 2243 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2244 FDContext = getOrCreateNameSpace(NSDecl); 2245 else if (const RecordDecl *RDecl = 2246 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 2247 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext())); 2248 2249 // Collect template parameters. 2250 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2251 } 2252 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2253 Name = getObjCMethodName(OMD); 2254 Flags |= llvm::DIDescriptor::FlagPrototyped; 2255 } else { 2256 // Use llvm function name. 2257 Name = Fn->getName(); 2258 Flags |= llvm::DIDescriptor::FlagPrototyped; 2259 } 2260 if (!Name.empty() && Name[0] == '\01') 2261 Name = Name.substr(1); 2262 2263 unsigned LineNo = getLineNumber(Loc); 2264 if (!HasDecl || D->isImplicit()) 2265 Flags |= llvm::DIDescriptor::FlagArtificial; 2266 2267 llvm::DIType DIFnType; 2268 llvm::DISubprogram SPDecl; 2269 if (HasDecl && 2270 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 2271 DIFnType = getOrCreateFunctionType(D, FnType, Unit); 2272 SPDecl = getFunctionDeclaration(D); 2273 } else { 2274 // Create fake but valid subroutine type. Otherwise 2275 // llvm::DISubprogram::Verify() would return false, and 2276 // subprogram DIE will miss DW_AT_decl_file and 2277 // DW_AT_decl_line fields. 2278 SmallVector<llvm::Value*, 16> Elts; 2279 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2280 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray); 2281 } 2282 llvm::DISubprogram SP; 2283 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit, 2284 LineNo, DIFnType, 2285 Fn->hasInternalLinkage(), true/*definition*/, 2286 getLineNumber(CurLoc), Flags, 2287 CGM.getLangOpts().Optimize, 2288 Fn, TParamsArray, SPDecl); 2289 2290 // Push function on region stack. 2291 llvm::MDNode *SPN = SP; 2292 LexicalBlockStack.push_back(SPN); 2293 if (HasDecl) 2294 RegionMap[D] = llvm::WeakVH(SP); 2295} 2296 2297/// EmitLocation - Emit metadata to indicate a change in line/column 2298/// information in the source file. 2299void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc, 2300 bool ForceColumnInfo) { 2301 2302 // Update our current location 2303 setLocation(Loc); 2304 2305 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 2306 2307 // Don't bother if things are the same as last time. 2308 SourceManager &SM = CGM.getContext().getSourceManager(); 2309 if (CurLoc == PrevLoc || 2310 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc)) 2311 // New Builder may not be in sync with CGDebugInfo. 2312 if (!Builder.getCurrentDebugLocation().isUnknown() && 2313 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) == 2314 LexicalBlockStack.back()) 2315 return; 2316 2317 // Update last state. 2318 PrevLoc = CurLoc; 2319 2320 llvm::MDNode *Scope = LexicalBlockStack.back(); 2321 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get 2322 (getLineNumber(CurLoc), 2323 getColumnNumber(CurLoc, ForceColumnInfo), 2324 Scope)); 2325} 2326 2327/// CreateLexicalBlock - Creates a new lexical block node and pushes it on 2328/// the stack. 2329void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 2330 llvm::DIDescriptor D = 2331 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ? 2332 llvm::DIDescriptor() : 2333 llvm::DIDescriptor(LexicalBlockStack.back()), 2334 getOrCreateFile(CurLoc), 2335 getLineNumber(CurLoc), 2336 getColumnNumber(CurLoc)); 2337 llvm::MDNode *DN = D; 2338 LexicalBlockStack.push_back(DN); 2339} 2340 2341/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 2342/// region - beginning of a DW_TAG_lexical_block. 2343void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) { 2344 // Set our current location. 2345 setLocation(Loc); 2346 2347 // Create a new lexical block and push it on the stack. 2348 CreateLexicalBlock(Loc); 2349 2350 // Emit a line table change for the current location inside the new scope. 2351 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc), 2352 getColumnNumber(Loc), 2353 LexicalBlockStack.back())); 2354} 2355 2356/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 2357/// region - end of a DW_TAG_lexical_block. 2358void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) { 2359 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2360 2361 // Provide an entry in the line table for the end of the block. 2362 EmitLocation(Builder, Loc); 2363 2364 LexicalBlockStack.pop_back(); 2365} 2366 2367/// EmitFunctionEnd - Constructs the debug code for exiting a function. 2368void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 2369 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2370 unsigned RCount = FnBeginRegionCount.back(); 2371 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 2372 2373 // Pop all regions for this function. 2374 while (LexicalBlockStack.size() != RCount) 2375 EmitLexicalBlockEnd(Builder, CurLoc); 2376 FnBeginRegionCount.pop_back(); 2377} 2378 2379// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 2380// See BuildByRefType. 2381llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 2382 uint64_t *XOffset) { 2383 2384 SmallVector<llvm::Value *, 5> EltTys; 2385 QualType FType; 2386 uint64_t FieldSize, FieldOffset; 2387 unsigned FieldAlign; 2388 2389 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2390 QualType Type = VD->getType(); 2391 2392 FieldOffset = 0; 2393 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2394 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 2395 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 2396 FType = CGM.getContext().IntTy; 2397 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 2398 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 2399 2400 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 2401 if (HasCopyAndDispose) { 2402 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2403 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 2404 &FieldOffset)); 2405 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 2406 &FieldOffset)); 2407 } 2408 bool HasByrefExtendedLayout; 2409 Qualifiers::ObjCLifetime Lifetime; 2410 if (CGM.getContext().getByrefLifetime(Type, 2411 Lifetime, HasByrefExtendedLayout) 2412 && HasByrefExtendedLayout) 2413 EltTys.push_back(CreateMemberType(Unit, FType, 2414 "__byref_variable_layout", 2415 &FieldOffset)); 2416 2417 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2418 if (Align > CGM.getContext().toCharUnitsFromBits( 2419 CGM.getContext().getTargetInfo().getPointerAlign(0))) { 2420 CharUnits FieldOffsetInBytes 2421 = CGM.getContext().toCharUnitsFromBits(FieldOffset); 2422 CharUnits AlignedOffsetInBytes 2423 = FieldOffsetInBytes.RoundUpToAlignment(Align); 2424 CharUnits NumPaddingBytes 2425 = AlignedOffsetInBytes - FieldOffsetInBytes; 2426 2427 if (NumPaddingBytes.isPositive()) { 2428 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2429 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2430 pad, ArrayType::Normal, 0); 2431 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2432 } 2433 } 2434 2435 FType = Type; 2436 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2437 FieldSize = CGM.getContext().getTypeSize(FType); 2438 FieldAlign = CGM.getContext().toBits(Align); 2439 2440 *XOffset = FieldOffset; 2441 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 2442 0, FieldSize, FieldAlign, 2443 FieldOffset, 0, FieldTy); 2444 EltTys.push_back(FieldTy); 2445 FieldOffset += FieldSize; 2446 2447 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 2448 2449 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 2450 2451 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2452 llvm::DIType(), Elements); 2453} 2454 2455/// EmitDeclare - Emit local variable declaration debug info. 2456void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 2457 llvm::Value *Storage, 2458 unsigned ArgNo, CGBuilderTy &Builder) { 2459 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2460 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2461 2462 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2463 llvm::DIType Ty; 2464 uint64_t XOffset = 0; 2465 if (VD->hasAttr<BlocksAttr>()) 2466 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2467 else 2468 Ty = getOrCreateType(VD->getType(), Unit); 2469 2470 // If there is no debug info for this type then do not emit debug info 2471 // for this variable. 2472 if (!Ty) 2473 return; 2474 2475 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) { 2476 // If Storage is an aggregate returned as 'sret' then let debugger know 2477 // about this. 2478 if (Arg->hasStructRetAttr()) 2479 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty); 2480 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) { 2481 // If an aggregate variable has non trivial destructor or non trivial copy 2482 // constructor than it is pass indirectly. Let debug info know about this 2483 // by using reference of the aggregate type as a argument type. 2484 if (Record->hasNonTrivialCopyConstructor() || 2485 !Record->hasTrivialDestructor()) 2486 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty); 2487 } 2488 } 2489 2490 // Get location information. 2491 unsigned Line = getLineNumber(VD->getLocation()); 2492 unsigned Column = getColumnNumber(VD->getLocation()); 2493 unsigned Flags = 0; 2494 if (VD->isImplicit()) 2495 Flags |= llvm::DIDescriptor::FlagArtificial; 2496 // If this is the first argument and it is implicit then 2497 // give it an object pointer flag. 2498 // FIXME: There has to be a better way to do this, but for static 2499 // functions there won't be an implicit param at arg1 and 2500 // otherwise it is 'self' or 'this'. 2501 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1) 2502 Flags |= llvm::DIDescriptor::FlagObjectPointer; 2503 2504 llvm::MDNode *Scope = LexicalBlockStack.back(); 2505 2506 StringRef Name = VD->getName(); 2507 if (!Name.empty()) { 2508 if (VD->hasAttr<BlocksAttr>()) { 2509 CharUnits offset = CharUnits::fromQuantity(32); 2510 SmallVector<llvm::Value *, 9> addr; 2511 llvm::Type *Int64Ty = CGM.Int64Ty; 2512 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2513 // offset of __forwarding field 2514 offset = CGM.getContext().toCharUnitsFromBits( 2515 CGM.getContext().getTargetInfo().getPointerWidth(0)); 2516 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2517 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2518 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2519 // offset of x field 2520 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2521 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2522 2523 // Create the descriptor for the variable. 2524 llvm::DIVariable D = 2525 DBuilder.createComplexVariable(Tag, 2526 llvm::DIDescriptor(Scope), 2527 VD->getName(), Unit, Line, Ty, 2528 addr, ArgNo); 2529 2530 // Insert an llvm.dbg.declare into the current block. 2531 llvm::Instruction *Call = 2532 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2533 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2534 return; 2535 } else if (isa<VariableArrayType>(VD->getType())) { 2536 // These are "complex" variables in that they need an op_deref. 2537 // Create the descriptor for the variable. 2538 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty, 2539 llvm::DIBuilder::OpDeref); 2540 llvm::DIVariable D = 2541 DBuilder.createComplexVariable(Tag, 2542 llvm::DIDescriptor(Scope), 2543 Name, Unit, Line, Ty, 2544 Addr, ArgNo); 2545 2546 // Insert an llvm.dbg.declare into the current block. 2547 llvm::Instruction *Call = 2548 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2549 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2550 return; 2551 } 2552 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2553 // If VD is an anonymous union then Storage represents value for 2554 // all union fields. 2555 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2556 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 2557 for (RecordDecl::field_iterator I = RD->field_begin(), 2558 E = RD->field_end(); 2559 I != E; ++I) { 2560 FieldDecl *Field = *I; 2561 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 2562 StringRef FieldName = Field->getName(); 2563 2564 // Ignore unnamed fields. Do not ignore unnamed records. 2565 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2566 continue; 2567 2568 // Use VarDecl's Tag, Scope and Line number. 2569 llvm::DIVariable D = 2570 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2571 FieldName, Unit, Line, FieldTy, 2572 CGM.getLangOpts().Optimize, Flags, 2573 ArgNo); 2574 2575 // Insert an llvm.dbg.declare into the current block. 2576 llvm::Instruction *Call = 2577 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2578 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2579 } 2580 return; 2581 } 2582 } 2583 2584 // Create the descriptor for the variable. 2585 llvm::DIVariable D = 2586 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2587 Name, Unit, Line, Ty, 2588 CGM.getLangOpts().Optimize, Flags, ArgNo); 2589 2590 // Insert an llvm.dbg.declare into the current block. 2591 llvm::Instruction *Call = 2592 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2593 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2594} 2595 2596void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2597 llvm::Value *Storage, 2598 CGBuilderTy &Builder) { 2599 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2600 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 2601} 2602 2603/// Look up the completed type for a self pointer in the TypeCache and 2604/// create a copy of it with the ObjectPointer and Artificial flags 2605/// set. If the type is not cached, a new one is created. This should 2606/// never happen though, since creating a type for the implicit self 2607/// argument implies that we already parsed the interface definition 2608/// and the ivar declarations in the implementation. 2609llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) { 2610 llvm::DIType CachedTy = getTypeOrNull(QualTy); 2611 if (CachedTy.Verify()) Ty = CachedTy; 2612 else DEBUG(llvm::dbgs() << "No cached type for self."); 2613 return DBuilder.createObjectPointerType(Ty); 2614} 2615 2616void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD, 2617 llvm::Value *Storage, 2618 CGBuilderTy &Builder, 2619 const CGBlockInfo &blockInfo) { 2620 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2621 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2622 2623 if (Builder.GetInsertBlock() == 0) 2624 return; 2625 2626 bool isByRef = VD->hasAttr<BlocksAttr>(); 2627 2628 uint64_t XOffset = 0; 2629 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2630 llvm::DIType Ty; 2631 if (isByRef) 2632 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2633 else 2634 Ty = getOrCreateType(VD->getType(), Unit); 2635 2636 // Self is passed along as an implicit non-arg variable in a 2637 // block. Mark it as the object pointer. 2638 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 2639 Ty = CreateSelfType(VD->getType(), Ty); 2640 2641 // Get location information. 2642 unsigned Line = getLineNumber(VD->getLocation()); 2643 unsigned Column = getColumnNumber(VD->getLocation()); 2644 2645 const llvm::DataLayout &target = CGM.getDataLayout(); 2646 2647 CharUnits offset = CharUnits::fromQuantity( 2648 target.getStructLayout(blockInfo.StructureType) 2649 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 2650 2651 SmallVector<llvm::Value *, 9> addr; 2652 llvm::Type *Int64Ty = CGM.Int64Ty; 2653 if (isa<llvm::AllocaInst>(Storage)) 2654 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2655 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2656 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2657 if (isByRef) { 2658 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2659 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2660 // offset of __forwarding field 2661 offset = CGM.getContext() 2662 .toCharUnitsFromBits(target.getPointerSizeInBits(0)); 2663 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2664 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2665 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2666 // offset of x field 2667 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2668 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2669 } 2670 2671 // Create the descriptor for the variable. 2672 llvm::DIVariable D = 2673 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable, 2674 llvm::DIDescriptor(LexicalBlockStack.back()), 2675 VD->getName(), Unit, Line, Ty, addr); 2676 2677 // Insert an llvm.dbg.declare into the current block. 2678 llvm::Instruction *Call = 2679 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint()); 2680 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, 2681 LexicalBlockStack.back())); 2682} 2683 2684/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2685/// variable declaration. 2686void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2687 unsigned ArgNo, 2688 CGBuilderTy &Builder) { 2689 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2690 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2691} 2692 2693namespace { 2694 struct BlockLayoutChunk { 2695 uint64_t OffsetInBits; 2696 const BlockDecl::Capture *Capture; 2697 }; 2698 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2699 return l.OffsetInBits < r.OffsetInBits; 2700 } 2701} 2702 2703void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2704 llvm::Value *Arg, 2705 llvm::Value *LocalAddr, 2706 CGBuilderTy &Builder) { 2707 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2708 ASTContext &C = CGM.getContext(); 2709 const BlockDecl *blockDecl = block.getBlockDecl(); 2710 2711 // Collect some general information about the block's location. 2712 SourceLocation loc = blockDecl->getCaretLocation(); 2713 llvm::DIFile tunit = getOrCreateFile(loc); 2714 unsigned line = getLineNumber(loc); 2715 unsigned column = getColumnNumber(loc); 2716 2717 // Build the debug-info type for the block literal. 2718 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 2719 2720 const llvm::StructLayout *blockLayout = 2721 CGM.getDataLayout().getStructLayout(block.StructureType); 2722 2723 SmallVector<llvm::Value*, 16> fields; 2724 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 2725 blockLayout->getElementOffsetInBits(0), 2726 tunit, tunit)); 2727 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 2728 blockLayout->getElementOffsetInBits(1), 2729 tunit, tunit)); 2730 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 2731 blockLayout->getElementOffsetInBits(2), 2732 tunit, tunit)); 2733 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public, 2734 blockLayout->getElementOffsetInBits(3), 2735 tunit, tunit)); 2736 fields.push_back(createFieldType("__descriptor", 2737 C.getPointerType(block.NeedsCopyDispose ? 2738 C.getBlockDescriptorExtendedType() : 2739 C.getBlockDescriptorType()), 2740 0, loc, AS_public, 2741 blockLayout->getElementOffsetInBits(4), 2742 tunit, tunit)); 2743 2744 // We want to sort the captures by offset, not because DWARF 2745 // requires this, but because we're paranoid about debuggers. 2746 SmallVector<BlockLayoutChunk, 8> chunks; 2747 2748 // 'this' capture. 2749 if (blockDecl->capturesCXXThis()) { 2750 BlockLayoutChunk chunk; 2751 chunk.OffsetInBits = 2752 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 2753 chunk.Capture = 0; 2754 chunks.push_back(chunk); 2755 } 2756 2757 // Variable captures. 2758 for (BlockDecl::capture_const_iterator 2759 i = blockDecl->capture_begin(), e = blockDecl->capture_end(); 2760 i != e; ++i) { 2761 const BlockDecl::Capture &capture = *i; 2762 const VarDecl *variable = capture.getVariable(); 2763 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 2764 2765 // Ignore constant captures. 2766 if (captureInfo.isConstant()) 2767 continue; 2768 2769 BlockLayoutChunk chunk; 2770 chunk.OffsetInBits = 2771 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 2772 chunk.Capture = &capture; 2773 chunks.push_back(chunk); 2774 } 2775 2776 // Sort by offset. 2777 llvm::array_pod_sort(chunks.begin(), chunks.end()); 2778 2779 for (SmallVectorImpl<BlockLayoutChunk>::iterator 2780 i = chunks.begin(), e = chunks.end(); i != e; ++i) { 2781 uint64_t offsetInBits = i->OffsetInBits; 2782 const BlockDecl::Capture *capture = i->Capture; 2783 2784 // If we have a null capture, this must be the C++ 'this' capture. 2785 if (!capture) { 2786 const CXXMethodDecl *method = 2787 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 2788 QualType type = method->getThisType(C); 2789 2790 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 2791 offsetInBits, tunit, tunit)); 2792 continue; 2793 } 2794 2795 const VarDecl *variable = capture->getVariable(); 2796 StringRef name = variable->getName(); 2797 2798 llvm::DIType fieldType; 2799 if (capture->isByRef()) { 2800 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy); 2801 2802 // FIXME: this creates a second copy of this type! 2803 uint64_t xoffset; 2804 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 2805 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first); 2806 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 2807 ptrInfo.first, ptrInfo.second, 2808 offsetInBits, 0, fieldType); 2809 } else { 2810 fieldType = createFieldType(name, variable->getType(), 0, 2811 loc, AS_public, offsetInBits, tunit, tunit); 2812 } 2813 fields.push_back(fieldType); 2814 } 2815 2816 SmallString<36> typeName; 2817 llvm::raw_svector_ostream(typeName) 2818 << "__block_literal_" << CGM.getUniqueBlockCount(); 2819 2820 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields); 2821 2822 llvm::DIType type = 2823 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 2824 CGM.getContext().toBits(block.BlockSize), 2825 CGM.getContext().toBits(block.BlockAlign), 2826 0, llvm::DIType(), fieldsArray); 2827 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 2828 2829 // Get overall information about the block. 2830 unsigned flags = llvm::DIDescriptor::FlagArtificial; 2831 llvm::MDNode *scope = LexicalBlockStack.back(); 2832 2833 // Create the descriptor for the parameter. 2834 llvm::DIVariable debugVar = 2835 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable, 2836 llvm::DIDescriptor(scope), 2837 Arg->getName(), tunit, line, type, 2838 CGM.getLangOpts().Optimize, flags, 2839 cast<llvm::Argument>(Arg)->getArgNo() + 1); 2840 2841 if (LocalAddr) { 2842 // Insert an llvm.dbg.value into the current block. 2843 llvm::Instruction *DbgVal = 2844 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar, 2845 Builder.GetInsertBlock()); 2846 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2847 } 2848 2849 // Insert an llvm.dbg.declare into the current block. 2850 llvm::Instruction *DbgDecl = 2851 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock()); 2852 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2853} 2854 2855/// getStaticDataMemberDeclaration - If D is an out-of-class definition of 2856/// a static data member of a class, find its corresponding in-class 2857/// declaration. 2858llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) { 2859 if (cast<VarDecl>(D)->isStaticDataMember()) { 2860 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 2861 MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 2862 if (MI != StaticDataMemberCache.end()) 2863 // Verify the info still exists. 2864 if (llvm::Value *V = MI->second) 2865 return llvm::DIDerivedType(cast<llvm::MDNode>(V)); 2866 } 2867 return llvm::DIDerivedType(); 2868} 2869 2870/// EmitGlobalVariable - Emit information about a global variable. 2871void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2872 const VarDecl *D) { 2873 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2874 // Create global variable debug descriptor. 2875 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 2876 unsigned LineNo = getLineNumber(D->getLocation()); 2877 2878 setLocation(D->getLocation()); 2879 2880 QualType T = D->getType(); 2881 if (T->isIncompleteArrayType()) { 2882 2883 // CodeGen turns int[] into int[1] so we'll do the same here. 2884 llvm::APInt ConstVal(32, 1); 2885 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2886 2887 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2888 ArrayType::Normal, 0); 2889 } 2890 StringRef DeclName = D->getName(); 2891 StringRef LinkageName; 2892 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) 2893 && !isa<ObjCMethodDecl>(D->getDeclContext())) 2894 LinkageName = Var->getName(); 2895 if (LinkageName == DeclName) 2896 LinkageName = StringRef(); 2897 llvm::DIDescriptor DContext = 2898 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext())); 2899 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, 2900 Unit, LineNo, getOrCreateType(T, Unit), 2901 Var->hasInternalLinkage(), Var, 2902 getStaticDataMemberDeclaration(D)); 2903} 2904 2905/// EmitGlobalVariable - Emit information about an objective-c interface. 2906void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2907 ObjCInterfaceDecl *ID) { 2908 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2909 // Create global variable debug descriptor. 2910 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 2911 unsigned LineNo = getLineNumber(ID->getLocation()); 2912 2913 StringRef Name = ID->getName(); 2914 2915 QualType T = CGM.getContext().getObjCInterfaceType(ID); 2916 if (T->isIncompleteArrayType()) { 2917 2918 // CodeGen turns int[] into int[1] so we'll do the same here. 2919 llvm::APInt ConstVal(32, 1); 2920 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2921 2922 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2923 ArrayType::Normal, 0); 2924 } 2925 2926 DBuilder.createGlobalVariable(Name, Unit, LineNo, 2927 getOrCreateType(T, Unit), 2928 Var->hasInternalLinkage(), Var); 2929} 2930 2931/// EmitGlobalVariable - Emit global variable's debug info. 2932void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 2933 llvm::Constant *Init) { 2934 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2935 // Create the descriptor for the variable. 2936 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2937 StringRef Name = VD->getName(); 2938 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 2939 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 2940 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 2941 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 2942 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 2943 } 2944 // Do not use DIGlobalVariable for enums. 2945 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 2946 return; 2947 DBuilder.createStaticVariable(Unit, Name, Name, Unit, 2948 getLineNumber(VD->getLocation()), 2949 Ty, true, Init, 2950 getStaticDataMemberDeclaration(VD)); 2951} 2952 2953/// getOrCreateNamesSpace - Return namespace descriptor for the given 2954/// namespace decl. 2955llvm::DINameSpace 2956CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 2957 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 2958 NameSpaceCache.find(NSDecl); 2959 if (I != NameSpaceCache.end()) 2960 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 2961 2962 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 2963 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 2964 llvm::DIDescriptor Context = 2965 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 2966 llvm::DINameSpace NS = 2967 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 2968 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 2969 return NS; 2970} 2971 2972void CGDebugInfo::finalize() { 2973 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI 2974 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) { 2975 llvm::DIType Ty, RepTy; 2976 // Verify that the debug info still exists. 2977 if (llvm::Value *V = VI->second) 2978 Ty = llvm::DIType(cast<llvm::MDNode>(V)); 2979 2980 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2981 TypeCache.find(VI->first); 2982 if (it != TypeCache.end()) { 2983 // Verify that the debug info still exists. 2984 if (llvm::Value *V = it->second) 2985 RepTy = llvm::DIType(cast<llvm::MDNode>(V)); 2986 } 2987 2988 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) 2989 Ty.replaceAllUsesWith(RepTy); 2990 } 2991 2992 // We keep our own list of retained types, because we need to look 2993 // up the final type in the type cache. 2994 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(), 2995 RE = RetainedTypes.end(); RI != RE; ++RI) 2996 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI]))); 2997 2998 DBuilder.finalize(); 2999} 3000