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