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