CGDebugInfo.cpp revision af3db7d9e4a702d8f072ae97f793be42177e898b
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.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 340 "objc_class", getOrCreateMainFile(), 341 0); 342 case BuiltinType::ObjCId: { 343 // typedef struct objc_class *Class; 344 // typedef struct objc_object { 345 // Class isa; 346 // } *id; 347 348 // TODO: Cache these two types to avoid duplicates. 349 llvm::DIType OCTy = 350 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 351 "objc_class", getOrCreateMainFile(), 352 0); 353 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 354 355 llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size); 356 357 SmallVector<llvm::Value *, 16> EltTys; 358 llvm::DIType FieldTy = 359 DBuilder.createMemberType(getOrCreateMainFile(), "isa", 360 getOrCreateMainFile(), 0, Size, 361 0, 0, 0, ISATy); 362 EltTys.push_back(FieldTy); 363 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 364 365 return DBuilder.createStructType(TheCU, "objc_object", 366 getOrCreateMainFile(), 367 0, 0, 0, 0, Elements); 368 } 369 case BuiltinType::ObjCSel: { 370 return 371 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 372 "objc_selector", getOrCreateMainFile(), 373 0); 374 } 375 case BuiltinType::UChar: 376 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break; 377 case BuiltinType::Char_S: 378 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break; 379 case BuiltinType::Char16: 380 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break; 381 case BuiltinType::UShort: 382 case BuiltinType::UInt: 383 case BuiltinType::UInt128: 384 case BuiltinType::ULong: 385 case BuiltinType::WChar_U: 386 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break; 387 case BuiltinType::Short: 388 case BuiltinType::Int: 389 case BuiltinType::Int128: 390 case BuiltinType::Long: 391 case BuiltinType::WChar_S: 392 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break; 393 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; 394 case BuiltinType::Half: 395 case BuiltinType::Float: 396 case BuiltinType::LongDouble: 397 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; 398 } 399 400 switch (BT->getKind()) { 401 case BuiltinType::Long: BTName = "long int"; break; 402 case BuiltinType::LongLong: BTName = "long long int"; break; 403 case BuiltinType::ULong: BTName = "long unsigned int"; break; 404 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break; 405 default: 406 BTName = BT->getName(CGM.getContext().getLangOptions()); 407 break; 408 } 409 // Bit size, align and offset of the type. 410 uint64_t Size = CGM.getContext().getTypeSize(BT); 411 uint64_t Align = CGM.getContext().getTypeAlign(BT); 412 llvm::DIType DbgTy = 413 DBuilder.createBasicType(BTName, Size, Align, Encoding); 414 return DbgTy; 415} 416 417llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) { 418 // Bit size, align and offset of the type. 419 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float; 420 if (Ty->isComplexIntegerType()) 421 Encoding = llvm::dwarf::DW_ATE_lo_user; 422 423 uint64_t Size = CGM.getContext().getTypeSize(Ty); 424 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 425 llvm::DIType DbgTy = 426 DBuilder.createBasicType("complex", Size, Align, Encoding); 427 428 return DbgTy; 429} 430 431/// CreateCVRType - Get the qualified type from the cache or create 432/// a new one if necessary. 433llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) { 434 QualifierCollector Qc; 435 const Type *T = Qc.strip(Ty); 436 437 // Ignore these qualifiers for now. 438 Qc.removeObjCGCAttr(); 439 Qc.removeAddressSpace(); 440 Qc.removeObjCLifetime(); 441 442 // We will create one Derived type for one qualifier and recurse to handle any 443 // additional ones. 444 unsigned Tag; 445 if (Qc.hasConst()) { 446 Tag = llvm::dwarf::DW_TAG_const_type; 447 Qc.removeConst(); 448 } else if (Qc.hasVolatile()) { 449 Tag = llvm::dwarf::DW_TAG_volatile_type; 450 Qc.removeVolatile(); 451 } else if (Qc.hasRestrict()) { 452 Tag = llvm::dwarf::DW_TAG_restrict_type; 453 Qc.removeRestrict(); 454 } else { 455 assert(Qc.empty() && "Unknown type qualifier for debug info"); 456 return getOrCreateType(QualType(T, 0), Unit); 457 } 458 459 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit); 460 461 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 462 // CVR derived types. 463 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy); 464 465 return DbgTy; 466} 467 468llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 469 llvm::DIFile Unit) { 470 llvm::DIType DbgTy = 471 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 472 Ty->getPointeeType(), Unit); 473 return DbgTy; 474} 475 476llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, 477 llvm::DIFile Unit) { 478 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 479 Ty->getPointeeType(), Unit); 480} 481 482// Creates a forward declaration for a RecordDecl in the given context. 483llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD, 484 llvm::DIDescriptor Ctx) { 485 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 486 unsigned Line = getLineNumber(RD->getLocation()); 487 StringRef RDName = RD->getName(); 488 489 // Get the tag. 490 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 491 unsigned Tag = 0; 492 if (CXXDecl) { 493 RDName = getClassName(RD); 494 Tag = llvm::dwarf::DW_TAG_class_type; 495 } 496 else if (RD->isStruct()) 497 Tag = llvm::dwarf::DW_TAG_structure_type; 498 else if (RD->isUnion()) 499 Tag = llvm::dwarf::DW_TAG_union_type; 500 else 501 llvm_unreachable("Unknown RecordDecl type!"); 502 503 // Create the type. 504 return DBuilder.createForwardDecl(Tag, RDName, DefUnit, Line); 505} 506 507// Walk up the context chain and create forward decls for record decls, 508// and normal descriptors for namespaces. 509llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) { 510 if (!Context) 511 return TheCU; 512 513 // See if we already have the parent. 514 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 515 I = RegionMap.find(Context); 516 if (I != RegionMap.end()) 517 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second)); 518 519 // Check namespace. 520 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 521 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl)); 522 523 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) { 524 if (!RD->isDependentType()) { 525 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD), 526 getOrCreateMainFile()); 527 return llvm::DIDescriptor(Ty); 528 } 529 } 530 return TheCU; 531} 532 533/// CreatePointeeType - Create Pointee type. If Pointee is a record 534/// then emit record's fwd if debug info size reduction is enabled. 535llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy, 536 llvm::DIFile Unit) { 537 if (!CGM.getCodeGenOpts().LimitDebugInfo) 538 return getOrCreateType(PointeeTy, Unit); 539 540 // Limit debug info for the pointee type. 541 542 // If we have an existing type, use that, it's still smaller than creating 543 // a new type. 544 llvm::DIType Ty = getTypeOrNull(PointeeTy); 545 if (Ty.Verify()) return Ty; 546 547 // Handle qualifiers. 548 if (PointeeTy.hasLocalQualifiers()) 549 return CreateQualifiedType(PointeeTy, Unit); 550 551 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) { 552 RecordDecl *RD = RTy->getDecl(); 553 llvm::DIDescriptor FDContext = 554 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 555 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext); 556 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy; 557 return RetTy; 558 } 559 return getOrCreateType(PointeeTy, Unit); 560 561} 562 563llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag, 564 const Type *Ty, 565 QualType PointeeTy, 566 llvm::DIFile Unit) { 567 if (Tag == llvm::dwarf::DW_TAG_reference_type) 568 return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit)); 569 570 // Bit size, align and offset of the type. 571 // Size is always the size of a pointer. We can't use getTypeSize here 572 // because that does not return the correct value for references. 573 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 574 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS); 575 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 576 577 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), 578 Size, Align); 579} 580 581llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, 582 llvm::DIFile Unit) { 583 if (BlockLiteralGenericSet) 584 return BlockLiteralGeneric; 585 586 SmallVector<llvm::Value *, 8> EltTys; 587 llvm::DIType FieldTy; 588 QualType FType; 589 uint64_t FieldSize, FieldOffset; 590 unsigned FieldAlign; 591 llvm::DIArray Elements; 592 llvm::DIType EltTy, DescTy; 593 594 FieldOffset = 0; 595 FType = CGM.getContext().UnsignedLongTy; 596 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 597 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 598 599 Elements = DBuilder.getOrCreateArray(EltTys); 600 EltTys.clear(); 601 602 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock; 603 unsigned LineNo = getLineNumber(CurLoc); 604 605 EltTy = DBuilder.createStructType(Unit, "__block_descriptor", 606 Unit, LineNo, FieldOffset, 0, 607 Flags, Elements); 608 609 // Bit size, align and offset of the type. 610 uint64_t Size = CGM.getContext().getTypeSize(Ty); 611 612 DescTy = DBuilder.createPointerType(EltTy, Size); 613 614 FieldOffset = 0; 615 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 616 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 617 FType = CGM.getContext().IntTy; 618 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 619 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 620 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 621 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 622 623 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 624 FieldTy = DescTy; 625 FieldSize = CGM.getContext().getTypeSize(Ty); 626 FieldAlign = CGM.getContext().getTypeAlign(Ty); 627 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit, 628 LineNo, FieldSize, FieldAlign, 629 FieldOffset, 0, FieldTy); 630 EltTys.push_back(FieldTy); 631 632 FieldOffset += FieldSize; 633 Elements = DBuilder.getOrCreateArray(EltTys); 634 635 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic", 636 Unit, LineNo, FieldOffset, 0, 637 Flags, Elements); 638 639 BlockLiteralGenericSet = true; 640 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size); 641 return BlockLiteralGeneric; 642} 643 644llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) { 645 // Typedefs are derived from some other type. If we have a typedef of a 646 // typedef, make sure to emit the whole chain. 647 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); 648 if (!Src.Verify()) 649 return llvm::DIType(); 650 // We don't set size information, but do specify where the typedef was 651 // declared. 652 unsigned Line = getLineNumber(Ty->getDecl()->getLocation()); 653 const TypedefNameDecl *TyDecl = Ty->getDecl(); 654 655 llvm::DIDescriptor TypedefContext = 656 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())); 657 658 return 659 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext); 660} 661 662llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, 663 llvm::DIFile Unit) { 664 SmallVector<llvm::Value *, 16> EltTys; 665 666 // Add the result type at least. 667 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); 668 669 // Set up remainder of arguments if there is a prototype. 670 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! 671 if (isa<FunctionNoProtoType>(Ty)) 672 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 673 else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) { 674 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 675 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit)); 676 } 677 678 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys); 679 680 llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray); 681 return DbgTy; 682} 683 684 685void CGDebugInfo:: 686CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) { 687 688 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 689 I != E; ++I) 690 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) { 691 if (V->getInit()) { 692 const APValue *Value = V->evaluateValue(); 693 if (Value && Value->isInt()) { 694 llvm::ConstantInt *CI 695 = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 696 697 // Create the descriptor for static variable. 698 llvm::DIFile VUnit = getOrCreateFile(V->getLocation()); 699 StringRef VName = V->getName(); 700 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit); 701 // Do not use DIGlobalVariable for enums. 702 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) { 703 DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit, 704 getLineNumber(V->getLocation()), 705 VTy, true, CI); 706 } 707 } 708 } 709 } 710} 711 712llvm::DIType CGDebugInfo::createFieldType(StringRef name, 713 QualType type, 714 uint64_t sizeInBitsOverride, 715 SourceLocation loc, 716 AccessSpecifier AS, 717 uint64_t offsetInBits, 718 llvm::DIFile tunit, 719 llvm::DIDescriptor scope) { 720 llvm::DIType debugType = getOrCreateType(type, tunit); 721 722 // Get the location for the field. 723 llvm::DIFile file = getOrCreateFile(loc); 724 unsigned line = getLineNumber(loc); 725 726 uint64_t sizeInBits = 0; 727 unsigned alignInBits = 0; 728 if (!type->isIncompleteArrayType()) { 729 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type); 730 731 if (sizeInBitsOverride) 732 sizeInBits = sizeInBitsOverride; 733 } 734 735 unsigned flags = 0; 736 if (AS == clang::AS_private) 737 flags |= llvm::DIDescriptor::FlagPrivate; 738 else if (AS == clang::AS_protected) 739 flags |= llvm::DIDescriptor::FlagProtected; 740 741 return DBuilder.createMemberType(scope, name, file, line, sizeInBits, 742 alignInBits, offsetInBits, flags, debugType); 743} 744 745/// CollectRecordFields - A helper function to collect debug info for 746/// record fields. This is used while creating debug info entry for a Record. 747void CGDebugInfo:: 748CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit, 749 SmallVectorImpl<llvm::Value *> &elements, 750 llvm::DIType RecordTy) { 751 unsigned fieldNo = 0; 752 const FieldDecl *LastFD = 0; 753 bool IsMsStruct = record->hasAttr<MsStructAttr>(); 754 755 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 756 for (RecordDecl::field_iterator I = record->field_begin(), 757 E = record->field_end(); 758 I != E; ++I, ++fieldNo) { 759 FieldDecl *field = *I; 760 if (IsMsStruct) { 761 // Zero-length bitfields following non-bitfield members are ignored 762 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) { 763 --fieldNo; 764 continue; 765 } 766 LastFD = field; 767 } 768 769 StringRef name = field->getName(); 770 QualType type = field->getType(); 771 772 // Ignore unnamed fields unless they're anonymous structs/unions. 773 if (name.empty() && !type->isRecordType()) { 774 LastFD = field; 775 continue; 776 } 777 778 uint64_t SizeInBitsOverride = 0; 779 if (field->isBitField()) { 780 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext()); 781 assert(SizeInBitsOverride && "found named 0-width bitfield"); 782 } 783 784 llvm::DIType fieldType 785 = createFieldType(name, type, SizeInBitsOverride, 786 field->getLocation(), field->getAccess(), 787 layout.getFieldOffset(fieldNo), tunit, RecordTy); 788 789 elements.push_back(fieldType); 790 } 791} 792 793/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 794/// function type is not updated to include implicit "this" pointer. Use this 795/// routine to get a method type which includes "this" pointer. 796llvm::DIType 797CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 798 llvm::DIFile Unit) { 799 llvm::DIType FnTy 800 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(), 801 0), 802 Unit); 803 804 // Add "this" pointer. 805 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray(); 806 assert (Args.getNumElements() && "Invalid number of arguments!"); 807 808 SmallVector<llvm::Value *, 16> Elts; 809 810 // First element is always return type. For 'void' functions it is NULL. 811 Elts.push_back(Args.getElement(0)); 812 813 if (!Method->isStatic()) { 814 // "this" pointer is always first argument. 815 QualType ThisPtr = Method->getThisType(CGM.getContext()); 816 817 const CXXRecordDecl *RD = Method->getParent(); 818 if (isa<ClassTemplateSpecializationDecl>(RD)) { 819 // Create pointer type directly in this case. 820 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 821 QualType PointeeTy = ThisPtrTy->getPointeeType(); 822 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 823 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS); 824 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy); 825 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit); 826 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align); 827 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 828 // TODO: This and the artificial type below are misleading, the 829 // types aren't artificial the argument is, but the current 830 // metadata doesn't represent that. 831 ThisPtrType = DBuilder.createArtificialType(ThisPtrType); 832 Elts.push_back(ThisPtrType); 833 } else { 834 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit); 835 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 836 ThisPtrType = DBuilder.createArtificialType(ThisPtrType); 837 Elts.push_back(ThisPtrType); 838 } 839 } 840 841 // Copy rest of the arguments. 842 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 843 Elts.push_back(Args.getElement(i)); 844 845 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 846 847 return DBuilder.createSubroutineType(Unit, EltTypeArray); 848} 849 850/// isFunctionLocalClass - Return true if CXXRecordDecl is defined 851/// inside a function. 852static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 853 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 854 return isFunctionLocalClass(NRD); 855 if (isa<FunctionDecl>(RD->getDeclContext())) 856 return true; 857 return false; 858} 859 860/// CreateCXXMemberFunction - A helper function to create a DISubprogram for 861/// a single member function GlobalDecl. 862llvm::DISubprogram 863CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 864 llvm::DIFile Unit, 865 llvm::DIType RecordTy) { 866 bool IsCtorOrDtor = 867 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 868 869 StringRef MethodName = getFunctionName(Method); 870 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit); 871 872 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 873 // make sense to give a single ctor/dtor a linkage name. 874 StringRef MethodLinkageName; 875 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 876 MethodLinkageName = CGM.getMangledName(Method); 877 878 // Get the location for the method. 879 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 880 unsigned MethodLine = getLineNumber(Method->getLocation()); 881 882 // Collect virtual method info. 883 llvm::DIType ContainingType; 884 unsigned Virtuality = 0; 885 unsigned VIndex = 0; 886 887 if (Method->isVirtual()) { 888 if (Method->isPure()) 889 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 890 else 891 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 892 893 // It doesn't make sense to give a virtual destructor a vtable index, 894 // since a single destructor has two entries in the vtable. 895 if (!isa<CXXDestructorDecl>(Method)) 896 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method); 897 ContainingType = RecordTy; 898 } 899 900 unsigned Flags = 0; 901 if (Method->isImplicit()) 902 Flags |= llvm::DIDescriptor::FlagArtificial; 903 AccessSpecifier Access = Method->getAccess(); 904 if (Access == clang::AS_private) 905 Flags |= llvm::DIDescriptor::FlagPrivate; 906 else if (Access == clang::AS_protected) 907 Flags |= llvm::DIDescriptor::FlagProtected; 908 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 909 if (CXXC->isExplicit()) 910 Flags |= llvm::DIDescriptor::FlagExplicit; 911 } else if (const CXXConversionDecl *CXXC = 912 dyn_cast<CXXConversionDecl>(Method)) { 913 if (CXXC->isExplicit()) 914 Flags |= llvm::DIDescriptor::FlagExplicit; 915 } 916 if (Method->hasPrototype()) 917 Flags |= llvm::DIDescriptor::FlagPrototyped; 918 919 llvm::DISubprogram SP = 920 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName, 921 MethodDefUnit, MethodLine, 922 MethodTy, /*isLocalToUnit=*/false, 923 /* isDefinition=*/ false, 924 Virtuality, VIndex, ContainingType, 925 Flags, CGM.getLangOptions().Optimize); 926 927 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP); 928 929 return SP; 930} 931 932/// CollectCXXMemberFunctions - A helper function to collect debug info for 933/// C++ member functions. This is used while creating debug info entry for 934/// a Record. 935void CGDebugInfo:: 936CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 937 SmallVectorImpl<llvm::Value *> &EltTys, 938 llvm::DIType RecordTy) { 939 for(CXXRecordDecl::method_iterator I = RD->method_begin(), 940 E = RD->method_end(); I != E; ++I) { 941 const CXXMethodDecl *Method = *I; 942 943 if (Method->isImplicit() && !Method->isUsed()) 944 continue; 945 946 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 947 } 948} 949 950/// CollectCXXFriends - A helper function to collect debug info for 951/// C++ base classes. This is used while creating debug info entry for 952/// a Record. 953void CGDebugInfo:: 954CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 955 SmallVectorImpl<llvm::Value *> &EltTys, 956 llvm::DIType RecordTy) { 957 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 958 BE = RD->friend_end(); BI != BE; ++BI) { 959 if ((*BI)->isUnsupportedFriend()) 960 continue; 961 if (TypeSourceInfo *TInfo = (*BI)->getFriendType()) 962 EltTys.push_back(DBuilder.createFriend(RecordTy, 963 getOrCreateType(TInfo->getType(), 964 Unit))); 965 } 966} 967 968/// CollectCXXBases - A helper function to collect debug info for 969/// C++ base classes. This is used while creating debug info entry for 970/// a Record. 971void CGDebugInfo:: 972CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 973 SmallVectorImpl<llvm::Value *> &EltTys, 974 llvm::DIType RecordTy) { 975 976 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 977 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 978 BE = RD->bases_end(); BI != BE; ++BI) { 979 unsigned BFlags = 0; 980 uint64_t BaseOffset; 981 982 const CXXRecordDecl *Base = 983 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 984 985 if (BI->isVirtual()) { 986 // virtual base offset offset is -ve. The code generator emits dwarf 987 // expression where it expects +ve number. 988 BaseOffset = 989 0 - CGM.getVTableContext() 990 .getVirtualBaseOffsetOffset(RD, Base).getQuantity(); 991 BFlags = llvm::DIDescriptor::FlagVirtual; 992 } else 993 BaseOffset = RL.getBaseClassOffsetInBits(Base); 994 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 995 // BI->isVirtual() and bits when not. 996 997 AccessSpecifier Access = BI->getAccessSpecifier(); 998 if (Access == clang::AS_private) 999 BFlags |= llvm::DIDescriptor::FlagPrivate; 1000 else if (Access == clang::AS_protected) 1001 BFlags |= llvm::DIDescriptor::FlagProtected; 1002 1003 llvm::DIType DTy = 1004 DBuilder.createInheritance(RecordTy, 1005 getOrCreateType(BI->getType(), Unit), 1006 BaseOffset, BFlags); 1007 EltTys.push_back(DTy); 1008 } 1009} 1010 1011/// CollectTemplateParams - A helper function to collect template parameters. 1012llvm::DIArray CGDebugInfo:: 1013CollectTemplateParams(const TemplateParameterList *TPList, 1014 const TemplateArgumentList &TAList, 1015 llvm::DIFile Unit) { 1016 SmallVector<llvm::Value *, 16> TemplateParams; 1017 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 1018 const TemplateArgument &TA = TAList[i]; 1019 const NamedDecl *ND = TPList->getParam(i); 1020 if (TA.getKind() == TemplateArgument::Type) { 1021 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 1022 llvm::DITemplateTypeParameter TTP = 1023 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy); 1024 TemplateParams.push_back(TTP); 1025 } else if (TA.getKind() == TemplateArgument::Integral) { 1026 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 1027 llvm::DITemplateValueParameter TVP = 1028 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, 1029 TA.getAsIntegral()->getZExtValue()); 1030 TemplateParams.push_back(TVP); 1031 } 1032 } 1033 return DBuilder.getOrCreateArray(TemplateParams); 1034} 1035 1036/// CollectFunctionTemplateParams - A helper function to collect debug 1037/// info for function template parameters. 1038llvm::DIArray CGDebugInfo:: 1039CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) { 1040 if (FD->getTemplatedKind() == 1041 FunctionDecl::TK_FunctionTemplateSpecialization) { 1042 const TemplateParameterList *TList = 1043 FD->getTemplateSpecializationInfo()->getTemplate() 1044 ->getTemplateParameters(); 1045 return 1046 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit); 1047 } 1048 return llvm::DIArray(); 1049} 1050 1051/// CollectCXXTemplateParams - A helper function to collect debug info for 1052/// template parameters. 1053llvm::DIArray CGDebugInfo:: 1054CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial, 1055 llvm::DIFile Unit) { 1056 llvm::PointerUnion<ClassTemplateDecl *, 1057 ClassTemplatePartialSpecializationDecl *> 1058 PU = TSpecial->getSpecializedTemplateOrPartial(); 1059 1060 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ? 1061 PU.get<ClassTemplateDecl *>()->getTemplateParameters() : 1062 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters(); 1063 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs(); 1064 return CollectTemplateParams(TPList, TAList, Unit); 1065} 1066 1067/// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 1068llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 1069 if (VTablePtrType.isValid()) 1070 return VTablePtrType; 1071 1072 ASTContext &Context = CGM.getContext(); 1073 1074 /* Function type */ 1075 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 1076 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy); 1077 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 1078 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1079 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0, 1080 "__vtbl_ptr_type"); 1081 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1082 return VTablePtrType; 1083} 1084 1085/// getVTableName - Get vtable name for the given Class. 1086StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1087 // Construct gdb compatible name name. 1088 std::string Name = "_vptr$" + RD->getNameAsString(); 1089 1090 // Copy this name on the side and use its reference. 1091 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 1092 memcpy(StrPtr, Name.data(), Name.length()); 1093 return StringRef(StrPtr, Name.length()); 1094} 1095 1096 1097/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 1098/// debug info entry in EltTys vector. 1099void CGDebugInfo:: 1100CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 1101 SmallVectorImpl<llvm::Value *> &EltTys) { 1102 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1103 1104 // If there is a primary base then it will hold vtable info. 1105 if (RL.getPrimaryBase()) 1106 return; 1107 1108 // If this class is not dynamic then there is not any vtable info to collect. 1109 if (!RD->isDynamicClass()) 1110 return; 1111 1112 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1113 llvm::DIType VPTR 1114 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 1115 0, Size, 0, 0, 0, 1116 getOrCreateVTablePtrType(Unit)); 1117 EltTys.push_back(VPTR); 1118} 1119 1120/// getOrCreateRecordType - Emit record type's standalone debug info. 1121llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 1122 SourceLocation Loc) { 1123 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1124 return T; 1125} 1126 1127/// CreateType - get structure or union type. 1128llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 1129 RecordDecl *RD = Ty->getDecl(); 1130 1131 // Get overall information about the record type for the debug info. 1132 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 1133 1134 // Records and classes and unions can all be recursive. To handle them, we 1135 // first generate a debug descriptor for the struct as a forward declaration. 1136 // Then (if it is a definition) we go through and get debug info for all of 1137 // its members. Finally, we create a descriptor for the complete type (which 1138 // may refer to the forward decl if the struct is recursive) and replace all 1139 // uses of the forward declaration with the final definition. 1140 1141 llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit); 1142 1143 if (FwdDecl.isForwardDecl()) 1144 return FwdDecl; 1145 1146 llvm::MDNode *MN = FwdDecl; 1147 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1148 1149 // Push the struct on region stack. 1150 LexicalBlockStack.push_back(FwdDeclNode); 1151 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1152 1153 // Add this to the completed types cache since we're completing it. 1154 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1155 1156 // Convert all the elements. 1157 SmallVector<llvm::Value *, 16> EltTys; 1158 1159 // Note: The split of CXXDecl information here is intentional, the 1160 // gdb tests will depend on a certain ordering at printout. The debug 1161 // information offsets are still correct if we merge them all together 1162 // though. 1163 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1164 if (CXXDecl) { 1165 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 1166 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 1167 } 1168 1169 // Collect static variables with initializers and other fields. 1170 CollectRecordStaticVars(RD, FwdDecl); 1171 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 1172 llvm::DIArray TParamsArray; 1173 if (CXXDecl) { 1174 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 1175 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl); 1176 if (const ClassTemplateSpecializationDecl *TSpecial 1177 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1178 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit); 1179 } 1180 1181 LexicalBlockStack.pop_back(); 1182 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1183 RegionMap.find(Ty->getDecl()); 1184 if (RI != RegionMap.end()) 1185 RegionMap.erase(RI); 1186 1187 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1188 // FIXME: Magic numbers ahoy! These should be changed when we 1189 // get some enums in llvm/Analysis/DebugInfo.h to refer to 1190 // them. 1191 if (RD->isUnion()) 1192 MN->replaceOperandWith(10, Elements); 1193 else if (CXXDecl) { 1194 MN->replaceOperandWith(10, Elements); 1195 MN->replaceOperandWith(13, TParamsArray); 1196 } else 1197 MN->replaceOperandWith(10, Elements); 1198 1199 RegionMap[Ty->getDecl()] = llvm::WeakVH(MN); 1200 return llvm::DIType(MN); 1201} 1202 1203/// CreateType - get objective-c object type. 1204llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1205 llvm::DIFile Unit) { 1206 // Ignore protocols. 1207 return getOrCreateType(Ty->getBaseType(), Unit); 1208} 1209 1210/// CreateType - get objective-c interface type. 1211llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1212 llvm::DIFile Unit) { 1213 ObjCInterfaceDecl *ID = Ty->getDecl(); 1214 if (!ID) 1215 return llvm::DIType(); 1216 1217 // Get overall information about the record type for the debug info. 1218 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1219 unsigned Line = getLineNumber(ID->getLocation()); 1220 unsigned RuntimeLang = TheCU.getLanguage(); 1221 1222 // If this is just a forward declaration return a special forward-declaration 1223 // debug type since we won't be able to lay out the entire type. 1224 ObjCInterfaceDecl *Def = ID->getDefinition(); 1225 if (!Def) { 1226 llvm::DIType FwdDecl = 1227 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1228 ID->getName(), DefUnit, Line, 1229 RuntimeLang); 1230 return FwdDecl; 1231 } 1232 ID = Def; 1233 1234 // Bit size, align and offset of the type. 1235 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1236 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1237 1238 unsigned Flags = 0; 1239 if (ID->getImplementation()) 1240 Flags |= llvm::DIDescriptor::FlagObjcClassComplete; 1241 1242 llvm::DIType RealDecl = 1243 DBuilder.createStructType(Unit, ID->getName(), DefUnit, 1244 Line, Size, Align, Flags, 1245 llvm::DIArray(), RuntimeLang); 1246 1247 // Otherwise, insert it into the CompletedTypeCache so that recursive uses 1248 // will find it and we're emitting the complete type. 1249 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; 1250 // Push the struct on region stack. 1251 llvm::MDNode *MN = RealDecl; 1252 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1253 1254 LexicalBlockStack.push_back(FwdDeclNode); 1255 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 1256 1257 // Convert all the elements. 1258 SmallVector<llvm::Value *, 16> EltTys; 1259 1260 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1261 if (SClass) { 1262 llvm::DIType SClassTy = 1263 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1264 if (!SClassTy.isValid()) 1265 return llvm::DIType(); 1266 1267 llvm::DIType InhTag = 1268 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 1269 EltTys.push_back(InhTag); 1270 } 1271 1272 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(), 1273 E = ID->prop_end(); I != E; ++I) { 1274 const ObjCPropertyDecl *PD = *I; 1275 llvm::MDNode *PropertyNode = 1276 DBuilder.createObjCProperty(PD->getName(), 1277 getSelectorName(PD->getGetterName()), 1278 getSelectorName(PD->getSetterName()), 1279 PD->getPropertyAttributes()); 1280 EltTys.push_back(PropertyNode); 1281 } 1282 1283 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1284 unsigned FieldNo = 0; 1285 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1286 Field = Field->getNextIvar(), ++FieldNo) { 1287 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1288 if (!FieldTy.isValid()) 1289 return llvm::DIType(); 1290 1291 StringRef FieldName = Field->getName(); 1292 1293 // Ignore unnamed fields. 1294 if (FieldName.empty()) 1295 continue; 1296 1297 // Get the location for the field. 1298 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1299 unsigned FieldLine = getLineNumber(Field->getLocation()); 1300 QualType FType = Field->getType(); 1301 uint64_t FieldSize = 0; 1302 unsigned FieldAlign = 0; 1303 1304 if (!FType->isIncompleteArrayType()) { 1305 1306 // Bit size, align and offset of the type. 1307 FieldSize = Field->isBitField() 1308 ? Field->getBitWidthValue(CGM.getContext()) 1309 : CGM.getContext().getTypeSize(FType); 1310 FieldAlign = CGM.getContext().getTypeAlign(FType); 1311 } 1312 1313 // We can't know the offset of our ivar in the structure if we're using 1314 // the non-fragile abi and the debugger should ignore the value anyways. 1315 // Call it the FieldNo+1 due to how debuggers use the information, 1316 // e.g. negating the value when it needs a lookup in the dynamic table. 1317 uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1 1318 : RL.getFieldOffset(FieldNo); 1319 1320 unsigned Flags = 0; 1321 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1322 Flags = llvm::DIDescriptor::FlagProtected; 1323 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1324 Flags = llvm::DIDescriptor::FlagPrivate; 1325 1326 llvm::MDNode *PropertyNode = NULL; 1327 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 1328 if (ObjCPropertyImplDecl *PImpD = 1329 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 1330 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 1331 PropertyNode = 1332 DBuilder.createObjCProperty(PD->getName(), 1333 getSelectorName(PD->getGetterName()), 1334 getSelectorName(PD->getSetterName()), 1335 PD->getPropertyAttributes()); 1336 } 1337 } 1338 } 1339 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, 1340 FieldLine, FieldSize, FieldAlign, 1341 FieldOffset, Flags, FieldTy, 1342 PropertyNode); 1343 EltTys.push_back(FieldTy); 1344 } 1345 1346 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1347 RealDecl->replaceOperandWith(10, Elements); 1348 1349 LexicalBlockStack.pop_back(); 1350 return RealDecl; 1351} 1352 1353llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) { 1354 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1355 int64_t NumElems = Ty->getNumElements(); 1356 int64_t LowerBound = 0; 1357 if (NumElems == 0) 1358 // If number of elements are not known then this is an unbounded array. 1359 // Use Low = 1, Hi = 0 to express such arrays. 1360 LowerBound = 1; 1361 else 1362 --NumElems; 1363 1364 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems); 1365 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1366 1367 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1368 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1369 1370 return 1371 DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1372} 1373 1374llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1375 llvm::DIFile Unit) { 1376 uint64_t Size; 1377 uint64_t Align; 1378 1379 1380 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1381 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1382 Size = 0; 1383 Align = 1384 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1385 } else if (Ty->isIncompleteArrayType()) { 1386 Size = 0; 1387 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1388 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) { 1389 Size = 0; 1390 Align = 0; 1391 } else { 1392 // Size and align of the whole array, not the element type. 1393 Size = CGM.getContext().getTypeSize(Ty); 1394 Align = CGM.getContext().getTypeAlign(Ty); 1395 } 1396 1397 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1398 // interior arrays, do we care? Why aren't nested arrays represented the 1399 // obvious/recursive way? 1400 SmallVector<llvm::Value *, 8> Subscripts; 1401 QualType EltTy(Ty, 0); 1402 if (Ty->isIncompleteArrayType()) 1403 EltTy = Ty->getElementType(); 1404 else { 1405 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1406 int64_t UpperBound = 0; 1407 int64_t LowerBound = 0; 1408 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) { 1409 if (CAT->getSize().getZExtValue()) 1410 UpperBound = CAT->getSize().getZExtValue() - 1; 1411 } else 1412 // This is an unbounded array. Use Low = 1, Hi = 0 to express such 1413 // arrays. 1414 LowerBound = 1; 1415 1416 // FIXME: Verify this is right for VLAs. 1417 Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, 1418 UpperBound)); 1419 EltTy = Ty->getElementType(); 1420 } 1421 } 1422 1423 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1424 1425 llvm::DIType DbgTy = 1426 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1427 SubscriptArray); 1428 return DbgTy; 1429} 1430 1431llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1432 llvm::DIFile Unit) { 1433 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1434 Ty, Ty->getPointeeType(), Unit); 1435} 1436 1437llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1438 llvm::DIFile Unit) { 1439 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 1440 Ty, Ty->getPointeeType(), Unit); 1441} 1442 1443llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1444 llvm::DIFile U) { 1445 QualType PointerDiffTy = CGM.getContext().getPointerDiffType(); 1446 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U); 1447 1448 if (!Ty->getPointeeType()->isFunctionType()) { 1449 // We have a data member pointer type. 1450 return PointerDiffDITy; 1451 } 1452 1453 // We have a member function pointer type. Treat it as a struct with two 1454 // ptrdiff_t members. 1455 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty); 1456 1457 uint64_t FieldOffset = 0; 1458 llvm::Value *ElementTypes[2]; 1459 1460 // FIXME: This should probably be a function type instead. 1461 ElementTypes[0] = 1462 DBuilder.createMemberType(U, "ptr", U, 0, 1463 Info.first, Info.second, FieldOffset, 0, 1464 PointerDiffDITy); 1465 FieldOffset += Info.first; 1466 1467 ElementTypes[1] = 1468 DBuilder.createMemberType(U, "ptr", U, 0, 1469 Info.first, Info.second, FieldOffset, 0, 1470 PointerDiffDITy); 1471 1472 llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes); 1473 1474 return DBuilder.createStructType(U, StringRef("test"), 1475 U, 0, FieldOffset, 1476 0, 0, Elements); 1477} 1478 1479llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, 1480 llvm::DIFile U) { 1481 // Ignore the atomic wrapping 1482 // FIXME: What is the correct representation? 1483 return getOrCreateType(Ty->getValueType(), U); 1484} 1485 1486/// CreateEnumType - get enumeration type. 1487llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) { 1488 llvm::DIFile Unit = getOrCreateFile(ED->getLocation()); 1489 SmallVector<llvm::Value *, 16> Enumerators; 1490 1491 // Create DIEnumerator elements for each enumerator. 1492 for (EnumDecl::enumerator_iterator 1493 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1494 Enum != EnumEnd; ++Enum) { 1495 Enumerators.push_back( 1496 DBuilder.createEnumerator(Enum->getName(), 1497 Enum->getInitVal().getZExtValue())); 1498 } 1499 1500 // Return a CompositeType for the enum itself. 1501 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1502 1503 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1504 unsigned Line = getLineNumber(ED->getLocation()); 1505 uint64_t Size = 0; 1506 uint64_t Align = 0; 1507 if (!ED->getTypeForDecl()->isIncompleteType()) { 1508 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1509 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1510 } 1511 llvm::DIDescriptor EnumContext = 1512 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1513 llvm::DIType DbgTy = 1514 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 1515 Size, Align, EltArray); 1516 return DbgTy; 1517} 1518 1519static QualType UnwrapTypeForDebugInfo(QualType T) { 1520 do { 1521 QualType LastT = T; 1522 switch (T->getTypeClass()) { 1523 default: 1524 return T; 1525 case Type::TemplateSpecialization: 1526 T = cast<TemplateSpecializationType>(T)->desugar(); 1527 break; 1528 case Type::TypeOfExpr: 1529 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1530 break; 1531 case Type::TypeOf: 1532 T = cast<TypeOfType>(T)->getUnderlyingType(); 1533 break; 1534 case Type::Decltype: 1535 T = cast<DecltypeType>(T)->getUnderlyingType(); 1536 break; 1537 case Type::UnaryTransform: 1538 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 1539 break; 1540 case Type::Attributed: 1541 T = cast<AttributedType>(T)->getEquivalentType(); 1542 break; 1543 case Type::Elaborated: 1544 T = cast<ElaboratedType>(T)->getNamedType(); 1545 break; 1546 case Type::Paren: 1547 T = cast<ParenType>(T)->getInnerType(); 1548 break; 1549 case Type::SubstTemplateTypeParm: 1550 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1551 break; 1552 case Type::Auto: 1553 T = cast<AutoType>(T)->getDeducedType(); 1554 break; 1555 } 1556 1557 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1558 if (T == LastT) 1559 return T; 1560 } while (true); 1561} 1562 1563/// getType - Get the type from the cache or return null type if it doesn't exist. 1564llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) { 1565 1566 // Unwrap the type as needed for debug information. 1567 Ty = UnwrapTypeForDebugInfo(Ty); 1568 1569 // Check for existing entry. 1570 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1571 TypeCache.find(Ty.getAsOpaquePtr()); 1572 if (it != TypeCache.end()) { 1573 // Verify that the debug info still exists. 1574 if (&*it->second) 1575 return llvm::DIType(cast<llvm::MDNode>(it->second)); 1576 } 1577 1578 return llvm::DIType(); 1579} 1580 1581/// getCompletedTypeOrNull - Get the type from the cache or return null if it 1582/// doesn't exist. 1583llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) { 1584 1585 // Unwrap the type as needed for debug information. 1586 Ty = UnwrapTypeForDebugInfo(Ty); 1587 1588 // Check for existing entry. 1589 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1590 CompletedTypeCache.find(Ty.getAsOpaquePtr()); 1591 if (it != CompletedTypeCache.end()) { 1592 // Verify that the debug info still exists. 1593 if (&*it->second) 1594 return llvm::DIType(cast<llvm::MDNode>(it->second)); 1595 } 1596 1597 return llvm::DIType(); 1598} 1599 1600 1601/// getOrCreateType - Get the type from the cache or create a new 1602/// one if necessary. 1603llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 1604 if (Ty.isNull()) 1605 return llvm::DIType(); 1606 1607 // Unwrap the type as needed for debug information. 1608 Ty = UnwrapTypeForDebugInfo(Ty); 1609 1610 llvm::DIType T = getCompletedTypeOrNull(Ty); 1611 1612 if (T.Verify()) return T; 1613 1614 // Otherwise create the type. 1615 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1616 1617 llvm::DIType TC = getTypeOrNull(Ty); 1618 if (TC.Verify() && TC.isForwardDecl()) 1619 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), TC)); 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 if (T.Verify() && T.isForwardDecl()) 1730 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), T)); 1731 1732 // And update the type cache. 1733 TypeCache[Ty.getAsOpaquePtr()] = Res; 1734 return Res; 1735} 1736 1737// TODO: Currently used for context chains when limiting debug info. 1738llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 1739 RecordDecl *RD = Ty->getDecl(); 1740 1741 // Get overall information about the record type for the debug info. 1742 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 1743 unsigned Line = getLineNumber(RD->getLocation()); 1744 StringRef RDName = RD->getName(); 1745 1746 llvm::DIDescriptor RDContext; 1747 if (CGM.getCodeGenOpts().LimitDebugInfo) 1748 RDContext = createContextChain(cast<Decl>(RD->getDeclContext())); 1749 else 1750 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext())); 1751 1752 // If this is just a forward declaration, construct an appropriately 1753 // marked node and just return it. 1754 if (!RD->getDefinition()) 1755 return createRecordFwdDecl(RD, RDContext); 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(), llvm::DIType(), 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 2566void CGDebugInfo::finalize(void) { 2567 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI 2568 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) { 2569 llvm::DIType Ty, RepTy; 2570 // Verify that the debug info still exists. 2571 if (&*VI->second) 2572 Ty = llvm::DIType(cast<llvm::MDNode>(VI->second)); 2573 2574 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2575 TypeCache.find(VI->first); 2576 if (it != TypeCache.end()) { 2577 // Verify that the debug info still exists. 2578 if (&*it->second) 2579 RepTy = llvm::DIType(cast<llvm::MDNode>(it->second)); 2580 } 2581 2582 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) { 2583 Ty.replaceAllUsesWith(RepTy); 2584 } 2585 } 2586 DBuilder.finalize(); 2587} 2588