CGDebugInfo.cpp revision f1d1d9ad72507a8ef1e97d2dccad8445f035e762
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 "clang/AST/ASTContext.h" 18#include "clang/AST/DeclFriend.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/Basic/SourceManager.h" 24#include "clang/Basic/FileManager.h" 25#include "clang/Basic/Version.h" 26#include "clang/Frontend/CodeGenOptions.h" 27#include "llvm/Constants.h" 28#include "llvm/DerivedTypes.h" 29#include "llvm/Instructions.h" 30#include "llvm/Intrinsics.h" 31#include "llvm/Module.h" 32#include "llvm/ADT/StringExtras.h" 33#include "llvm/ADT/SmallVector.h" 34#include "llvm/Support/Dwarf.h" 35#include "llvm/System/Path.h" 36#include "llvm/Target/TargetMachine.h" 37using namespace clang; 38using namespace clang::CodeGen; 39 40CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 41 : CGM(CGM), DebugFactory(CGM.getModule()), 42 BlockLiteralGenericSet(false) { 43 CreateCompileUnit(); 44} 45 46CGDebugInfo::~CGDebugInfo() { 47 assert(RegionStack.empty() && "Region stack mismatch, stack not empty!"); 48} 49 50void CGDebugInfo::setLocation(SourceLocation Loc) { 51 if (Loc.isValid()) 52 CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc); 53} 54 55/// getContextDescriptor - Get context info for the decl. 56llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context, 57 llvm::DIDescriptor &CompileUnit) { 58 if (!Context) 59 return CompileUnit; 60 61 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 62 I = RegionMap.find(Context); 63 if (I != RegionMap.end()) 64 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second)); 65 66 // Check namespace. 67 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 68 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit)); 69 70 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) { 71 if (!RDecl->isDependentType()) { 72 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 73 llvm::DIFile(CompileUnit)); 74 return llvm::DIDescriptor(Ty); 75 } 76 } 77 return CompileUnit; 78} 79 80/// getFunctionName - Get function name for the given FunctionDecl. If the 81/// name is constructred on demand (e.g. C++ destructor) then the name 82/// is stored on the side. 83llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 84 assert (FD && "Invalid FunctionDecl!"); 85 IdentifierInfo *FII = FD->getIdentifier(); 86 if (FII) 87 return FII->getName(); 88 89 // Otherwise construct human readable name for debug info. 90 std::string NS = FD->getNameAsString(); 91 92 // Copy this name on the side and use its reference. 93 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length()); 94 memcpy(StrPtr, NS.data(), NS.length()); 95 return llvm::StringRef(StrPtr, NS.length()); 96} 97 98llvm::StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 99 llvm::SmallString<256> MethodName; 100 llvm::raw_svector_ostream OS(MethodName); 101 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 102 const DeclContext *DC = OMD->getDeclContext(); 103 if (const ObjCImplementationDecl *OID = 104 dyn_cast<const ObjCImplementationDecl>(DC)) { 105 OS << OID->getName(); 106 } else if (const ObjCInterfaceDecl *OID = 107 dyn_cast<const ObjCInterfaceDecl>(DC)) { 108 OS << OID->getName(); 109 } else if (const ObjCCategoryImplDecl *OCD = 110 dyn_cast<const ObjCCategoryImplDecl>(DC)){ 111 OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' << 112 OCD->getIdentifier()->getNameStart() << ')'; 113 } 114 OS << ' ' << OMD->getSelector().getAsString() << ']'; 115 116 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell()); 117 memcpy(StrPtr, MethodName.begin(), OS.tell()); 118 return llvm::StringRef(StrPtr, OS.tell()); 119} 120 121/// getClassName - Get class name including template argument list. 122llvm::StringRef 123CGDebugInfo::getClassName(RecordDecl *RD) { 124 ClassTemplateSpecializationDecl *Spec 125 = dyn_cast<ClassTemplateSpecializationDecl>(RD); 126 if (!Spec) 127 return RD->getName(); 128 129 const TemplateArgument *Args; 130 unsigned NumArgs; 131 std::string Buffer; 132 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) { 133 const TemplateSpecializationType *TST = 134 cast<TemplateSpecializationType>(TAW->getType()); 135 Args = TST->getArgs(); 136 NumArgs = TST->getNumArgs(); 137 } else { 138 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 139 Args = TemplateArgs.getFlatArgumentList(); 140 NumArgs = TemplateArgs.flat_size(); 141 } 142 Buffer = RD->getIdentifier()->getNameStart(); 143 PrintingPolicy Policy(CGM.getLangOptions()); 144 Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args, 145 NumArgs, 146 Policy); 147 148 // Copy this name on the side and use its reference. 149 char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length()); 150 memcpy(StrPtr, Buffer.data(), Buffer.length()); 151 return llvm::StringRef(StrPtr, Buffer.length()); 152} 153 154/// getOrCreateFile - Get the file debug info descriptor for the input location. 155llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 156 if (!Loc.isValid()) 157 // If Location is not valid then use main input file. 158 return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(), 159 TheCU); 160 SourceManager &SM = CGM.getContext().getSourceManager(); 161 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 162 163 // Cache the results. 164 const char *fname = PLoc.getFilename(); 165 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it = 166 DIFileCache.find(fname); 167 168 if (it != DIFileCache.end()) { 169 // Verify that the information still exists. 170 if (&*it->second) 171 return llvm::DIFile(cast<llvm::MDNode>(it->second)); 172 } 173 174 llvm::DIFile F = DebugFactory.CreateFile(PLoc.getFilename(), 175 getCurrentDirname(), TheCU); 176 177 DIFileCache[fname] = F; 178 return F; 179 180} 181 182/// getOrCreateMainFile - Get the file info for main compile unit. 183llvm::DIFile CGDebugInfo::getOrCreateMainFile() { 184 return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(), 185 TheCU); 186} 187 188/// getLineNumber - Get line number for the location. If location is invalid 189/// then use current location. 190unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 191 assert (CurLoc.isValid() && "Invalid current location!"); 192 SourceManager &SM = CGM.getContext().getSourceManager(); 193 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 194 return PLoc.getLine(); 195} 196 197/// getColumnNumber - Get column number for the location. If location is 198/// invalid then use current location. 199unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) { 200 assert (CurLoc.isValid() && "Invalid current location!"); 201 SourceManager &SM = CGM.getContext().getSourceManager(); 202 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 203 return PLoc.getColumn(); 204} 205 206llvm::StringRef CGDebugInfo::getCurrentDirname() { 207 if (!CWDName.empty()) 208 return CWDName; 209 char *CompDirnamePtr = NULL; 210 llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory(); 211 CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size()); 212 memcpy(CompDirnamePtr, CWD.c_str(), CWD.size()); 213 return CWDName = llvm::StringRef(CompDirnamePtr, CWD.size()); 214} 215 216/// CreateCompileUnit - Create new compile unit. 217void CGDebugInfo::CreateCompileUnit() { 218 219 // Get absolute path name. 220 SourceManager &SM = CGM.getContext().getSourceManager(); 221 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 222 if (MainFileName.empty()) 223 MainFileName = "<unknown>"; 224 225 // The main file name provided via the "-main-file-name" option contains just 226 // the file name itself with no path information. This file name may have had 227 // a relative path, so we look into the actual file entry for the main 228 // file to determine the real absolute path for the file. 229 std::string MainFileDir; 230 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 231 MainFileDir = MainFile->getDir()->getName(); 232 if (MainFileDir != ".") 233 MainFileName = MainFileDir + "/" + MainFileName; 234 } 235 236 // Save filename string. 237 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length()); 238 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length()); 239 llvm::StringRef Filename(FilenamePtr, MainFileName.length()); 240 241 unsigned LangTag; 242 const LangOptions &LO = CGM.getLangOptions(); 243 if (LO.CPlusPlus) { 244 if (LO.ObjC1) 245 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 246 else 247 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 248 } else if (LO.ObjC1) { 249 LangTag = llvm::dwarf::DW_LANG_ObjC; 250 } else if (LO.C99) { 251 LangTag = llvm::dwarf::DW_LANG_C99; 252 } else { 253 LangTag = llvm::dwarf::DW_LANG_C89; 254 } 255 256 std::string Producer = getClangFullVersion(); 257 258 // Figure out which version of the ObjC runtime we have. 259 unsigned RuntimeVers = 0; 260 if (LO.ObjC1) 261 RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1; 262 263 // Create new compile unit. 264 TheCU = DebugFactory.CreateCompileUnit( 265 LangTag, Filename, getCurrentDirname(), 266 Producer, true, 267 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers); 268} 269 270/// CreateType - Get the Basic type from the cache or create a new 271/// one if necessary. 272llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) { 273 unsigned Encoding = 0; 274 const char *BTName = NULL; 275 switch (BT->getKind()) { 276 default: 277 case BuiltinType::Void: 278 return llvm::DIType(); 279 case BuiltinType::ObjCClass: 280 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 281 TheCU, "objc_class", 282 getOrCreateMainFile(), 0, 0, 0, 283 0, llvm::DIDescriptor::FlagFwdDecl, 284 llvm::DIType(), llvm::DIArray()); 285 case BuiltinType::ObjCId: { 286 // typedef struct objc_class *Class; 287 // typedef struct objc_object { 288 // Class isa; 289 // } *id; 290 291 llvm::DIType OCTy = 292 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 293 TheCU, "objc_class", 294 getOrCreateMainFile(), 0, 0, 0, 0, 295 llvm::DIDescriptor::FlagFwdDecl, 296 llvm::DIType(), llvm::DIArray()); 297 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 298 299 llvm::DIType ISATy = 300 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 301 TheCU, "", getOrCreateMainFile(), 302 0, Size, 0, 0, 0, OCTy); 303 304 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 305 306 llvm::DIType FieldTy = 307 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, TheCU, 308 "isa", getOrCreateMainFile(), 309 0,Size, 0, 0, 0, ISATy); 310 EltTys.push_back(FieldTy); 311 llvm::DIArray Elements = 312 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 313 314 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 315 TheCU, "objc_object", 316 getOrCreateMainFile(), 317 0, 0, 0, 0, 0, 318 llvm::DIType(), Elements); 319 } 320 case BuiltinType::UChar: 321 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break; 322 case BuiltinType::Char_S: 323 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break; 324 case BuiltinType::UShort: 325 case BuiltinType::UInt: 326 case BuiltinType::ULong: 327 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break; 328 case BuiltinType::Short: 329 case BuiltinType::Int: 330 case BuiltinType::Long: 331 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break; 332 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; 333 case BuiltinType::Float: 334 case BuiltinType::LongDouble: 335 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; 336 } 337 338 switch (BT->getKind()) { 339 case BuiltinType::Long: BTName = "long int"; break; 340 case BuiltinType::LongLong: BTName = "long long int"; break; 341 case BuiltinType::ULong: BTName = "long unsigned int"; break; 342 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break; 343 default: 344 BTName = BT->getName(CGM.getContext().getLangOptions()); 345 break; 346 } 347 // Bit size, align and offset of the type. 348 uint64_t Size = CGM.getContext().getTypeSize(BT); 349 uint64_t Align = CGM.getContext().getTypeAlign(BT); 350 uint64_t Offset = 0; 351 llvm::DIType DbgTy = 352 DebugFactory.CreateBasicType(TheCU, BTName, getOrCreateMainFile(), 353 0, Size, Align, Offset, /*flags*/ 0, Encoding); 354 return DbgTy; 355} 356 357llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty, 358 llvm::DIFile Unit) { 359 // Bit size, align and offset of the type. 360 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float; 361 if (Ty->isComplexIntegerType()) 362 Encoding = llvm::dwarf::DW_ATE_lo_user; 363 364 uint64_t Size = CGM.getContext().getTypeSize(Ty); 365 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 366 uint64_t Offset = 0; 367 368 llvm::DIType DbgTy = 369 DebugFactory.CreateBasicType(TheCU, "complex", getOrCreateMainFile(), 370 0, Size, Align, Offset, /*flags*/ 0, Encoding); 371 return DbgTy; 372} 373 374/// CreateCVRType - Get the qualified type from the cache or create 375/// a new one if necessary. 376llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) { 377 QualifierCollector Qc; 378 const Type *T = Qc.strip(Ty); 379 380 // Ignore these qualifiers for now. 381 Qc.removeObjCGCAttr(); 382 Qc.removeAddressSpace(); 383 384 // We will create one Derived type for one qualifier and recurse to handle any 385 // additional ones. 386 unsigned Tag; 387 if (Qc.hasConst()) { 388 Tag = llvm::dwarf::DW_TAG_const_type; 389 Qc.removeConst(); 390 } else if (Qc.hasVolatile()) { 391 Tag = llvm::dwarf::DW_TAG_volatile_type; 392 Qc.removeVolatile(); 393 } else if (Qc.hasRestrict()) { 394 Tag = llvm::dwarf::DW_TAG_restrict_type; 395 Qc.removeRestrict(); 396 } else { 397 assert(Qc.empty() && "Unknown type qualifier for debug info"); 398 return getOrCreateType(QualType(T, 0), Unit); 399 } 400 401 llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit); 402 403 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 404 // CVR derived types. 405 llvm::DIType DbgTy = 406 DebugFactory.CreateDerivedType(Tag, Unit, "", Unit, 407 0, 0, 0, 0, 0, FromTy); 408 return DbgTy; 409} 410 411llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 412 llvm::DIFile Unit) { 413 llvm::DIType DbgTy = 414 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 415 Ty->getPointeeType(), Unit); 416 return DbgTy; 417} 418 419llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, 420 llvm::DIFile Unit) { 421 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 422 Ty->getPointeeType(), Unit); 423} 424 425/// CreatePointeeType - Create PointTee type. If Pointee is a record 426/// then emit record's fwd if debug info size reduction is enabled. 427llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy, 428 llvm::DIFile Unit) { 429 if (!CGM.getCodeGenOpts().LimitDebugInfo) 430 return getOrCreateType(PointeeTy, Unit); 431 432 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) { 433 RecordDecl *RD = RTy->getDecl(); 434 unsigned RTag; 435 if (RD->isStruct()) 436 RTag = llvm::dwarf::DW_TAG_structure_type; 437 else if (RD->isUnion()) 438 RTag = llvm::dwarf::DW_TAG_union_type; 439 else { 440 assert(RD->isClass() && "Unknown RecordType!"); 441 RTag = llvm::dwarf::DW_TAG_class_type; 442 } 443 444 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 445 unsigned Line = getLineNumber(RD->getLocation()); 446 llvm::DIDescriptor FDContext = 447 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit); 448 449 return 450 DebugFactory.CreateCompositeType(RTag, FDContext, RD->getName(), 451 DefUnit, Line, 0, 0, 0, 452 llvm::DIType::FlagFwdDecl, 453 llvm::DIType(), llvm::DIArray()); 454 } 455 return getOrCreateType(PointeeTy, Unit); 456 457} 458 459llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag, 460 const Type *Ty, 461 QualType PointeeTy, 462 llvm::DIFile Unit) { 463 // Bit size, align and offset of the type. 464 465 // Size is always the size of a pointer. We can't use getTypeSize here 466 // because that does not return the correct value for references. 467 uint64_t Size = 468 CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace()); 469 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 470 471 return DebugFactory.CreateDerivedType(Tag, Unit, "", Unit, 472 0, Size, Align, 0, 0, 473 CreatePointeeType(PointeeTy, Unit)); 474 475} 476 477llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, 478 llvm::DIFile Unit) { 479 if (BlockLiteralGenericSet) 480 return BlockLiteralGeneric; 481 482 unsigned Tag = llvm::dwarf::DW_TAG_structure_type; 483 484 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys; 485 486 llvm::DIType FieldTy; 487 488 QualType FType; 489 uint64_t FieldSize, FieldOffset; 490 unsigned FieldAlign; 491 492 llvm::DIArray Elements; 493 llvm::DIType EltTy, DescTy; 494 495 FieldOffset = 0; 496 FType = CGM.getContext().UnsignedLongTy; 497 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 498 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 499 500 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 501 EltTys.clear(); 502 503 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock; 504 unsigned LineNo = getLineNumber(CurLoc); 505 506 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor", 507 Unit, LineNo, FieldOffset, 0, 0, 508 Flags, llvm::DIType(), Elements); 509 510 // Bit size, align and offset of the type. 511 uint64_t Size = CGM.getContext().getTypeSize(Ty); 512 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 513 514 DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 515 Unit, "", Unit, 516 LineNo, Size, Align, 0, 0, EltTy); 517 518 FieldOffset = 0; 519 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 520 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 521 FType = CGM.getContext().IntTy; 522 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 523 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 524 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 525 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 526 527 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 528 FieldTy = DescTy; 529 FieldSize = CGM.getContext().getTypeSize(Ty); 530 FieldAlign = CGM.getContext().getTypeAlign(Ty); 531 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 532 "__descriptor", Unit, 533 LineNo, FieldSize, FieldAlign, 534 FieldOffset, 0, FieldTy); 535 EltTys.push_back(FieldTy); 536 537 FieldOffset += FieldSize; 538 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 539 540 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic", 541 Unit, LineNo, FieldOffset, 0, 0, 542 Flags, llvm::DIType(), Elements); 543 544 BlockLiteralGenericSet = true; 545 BlockLiteralGeneric 546 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, 547 "", Unit, 548 LineNo, Size, Align, 0, 0, EltTy); 549 return BlockLiteralGeneric; 550} 551 552llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, 553 llvm::DIFile Unit) { 554 // Typedefs are derived from some other type. If we have a typedef of a 555 // typedef, make sure to emit the whole chain. 556 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); 557 558 // We don't set size information, but do specify where the typedef was 559 // declared. 560 unsigned Line = getLineNumber(Ty->getDecl()->getLocation()); 561 562 llvm::DIDescriptor TyContext 563 = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()), 564 Unit); 565 llvm::DIType DbgTy = 566 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, 567 TyContext, 568 Ty->getDecl()->getName(), Unit, 569 Line, 0, 0, 0, 0, Src); 570 return DbgTy; 571} 572 573llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, 574 llvm::DIFile Unit) { 575 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 576 577 // Add the result type at least. 578 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); 579 580 // Set up remainder of arguments if there is a prototype. 581 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! 582 if (isa<FunctionNoProtoType>(Ty)) 583 EltTys.push_back(DebugFactory.CreateUnspecifiedParameter()); 584 else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) { 585 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 586 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit)); 587 } 588 589 llvm::DIArray EltTypeArray = 590 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 591 592 llvm::DIType DbgTy = 593 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, 594 Unit, "", Unit, 595 0, 0, 0, 0, 0, 596 llvm::DIType(), EltTypeArray); 597 return DbgTy; 598} 599 600/// CollectRecordFields - A helper function to collect debug info for 601/// record fields. This is used while creating debug info entry for a Record. 602void CGDebugInfo:: 603CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit, 604 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) { 605 unsigned FieldNo = 0; 606 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 607 for (RecordDecl::field_iterator I = RD->field_begin(), 608 E = RD->field_end(); 609 I != E; ++I, ++FieldNo) { 610 FieldDecl *Field = *I; 611 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 612 llvm::StringRef FieldName = Field->getName(); 613 614 // Ignore unnamed fields. Do not ignore unnamed records. 615 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 616 continue; 617 618 // Get the location for the field. 619 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 620 unsigned FieldLine = getLineNumber(Field->getLocation()); 621 QualType FType = Field->getType(); 622 uint64_t FieldSize = 0; 623 unsigned FieldAlign = 0; 624 if (!FType->isIncompleteArrayType()) { 625 626 // Bit size, align and offset of the type. 627 FieldSize = CGM.getContext().getTypeSize(FType); 628 Expr *BitWidth = Field->getBitWidth(); 629 if (BitWidth) 630 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue(); 631 FieldAlign = CGM.getContext().getTypeAlign(FType); 632 } 633 634 uint64_t FieldOffset = RL.getFieldOffset(FieldNo); 635 636 unsigned Flags = 0; 637 AccessSpecifier Access = I->getAccess(); 638 if (Access == clang::AS_private) 639 Flags |= llvm::DIDescriptor::FlagPrivate; 640 else if (Access == clang::AS_protected) 641 Flags |= llvm::DIDescriptor::FlagProtected; 642 643 // Create a DW_TAG_member node to remember the offset of this field in the 644 // struct. FIXME: This is an absolutely insane way to capture this 645 // information. When we gut debug info, this should be fixed. 646 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 647 FieldName, FieldDefUnit, 648 FieldLine, FieldSize, FieldAlign, 649 FieldOffset, Flags, FieldTy); 650 EltTys.push_back(FieldTy); 651 } 652} 653 654/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 655/// function type is not updated to include implicit "this" pointer. Use this 656/// routine to get a method type which includes "this" pointer. 657llvm::DIType 658CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 659 llvm::DIFile Unit) { 660 llvm::DIType FnTy 661 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(), 662 0), 663 Unit); 664 665 // Add "this" pointer. 666 667 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray(); 668 assert (Args.getNumElements() && "Invalid number of arguments!"); 669 670 llvm::SmallVector<llvm::DIDescriptor, 16> Elts; 671 672 // First element is always return type. For 'void' functions it is NULL. 673 Elts.push_back(Args.getElement(0)); 674 675 if (!Method->isStatic()) 676 { 677 // "this" pointer is always first argument. 678 ASTContext &Context = CGM.getContext(); 679 QualType ThisPtr = 680 Context.getPointerType(Context.getTagDeclType(Method->getParent())); 681 llvm::DIType ThisPtrType = 682 DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit)); 683 684 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 685 Elts.push_back(ThisPtrType); 686 } 687 688 // Copy rest of the arguments. 689 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 690 Elts.push_back(Args.getElement(i)); 691 692 llvm::DIArray EltTypeArray = 693 DebugFactory.GetOrCreateArray(Elts.data(), Elts.size()); 694 695 return 696 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, 697 Unit, "", Unit, 698 0, 0, 0, 0, 0, 699 llvm::DIType(), EltTypeArray); 700} 701 702/// isFunctionLocalClass - Return true if CXXRecordDecl is defined 703/// inside a function. 704static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 705 if (const CXXRecordDecl *NRD = 706 dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 707 return isFunctionLocalClass(NRD); 708 else if (isa<FunctionDecl>(RD->getDeclContext())) 709 return true; 710 return false; 711 712} 713/// CreateCXXMemberFunction - A helper function to create a DISubprogram for 714/// a single member function GlobalDecl. 715llvm::DISubprogram 716CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 717 llvm::DIFile Unit, 718 llvm::DIType RecordTy) { 719 bool IsCtorOrDtor = 720 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 721 722 llvm::StringRef MethodName = getFunctionName(Method); 723 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit); 724 725 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 726 // make sense to give a single ctor/dtor a linkage name. 727 llvm::StringRef MethodLinkageName; 728 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 729 MethodLinkageName = CGM.getMangledName(Method); 730 731 // Get the location for the method. 732 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 733 unsigned MethodLine = getLineNumber(Method->getLocation()); 734 735 // Collect virtual method info. 736 llvm::DIType ContainingType; 737 unsigned Virtuality = 0; 738 unsigned VIndex = 0; 739 740 if (Method->isVirtual()) { 741 if (Method->isPure()) 742 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 743 else 744 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 745 746 // It doesn't make sense to give a virtual destructor a vtable index, 747 // since a single destructor has two entries in the vtable. 748 if (!isa<CXXDestructorDecl>(Method)) 749 VIndex = CGM.getVTables().getMethodVTableIndex(Method); 750 ContainingType = RecordTy; 751 } 752 753 unsigned Flags = 0; 754 if (Method->isImplicit()) 755 Flags |= llvm::DIDescriptor::FlagArtificial; 756 AccessSpecifier Access = Method->getAccess(); 757 if (Access == clang::AS_private) 758 Flags |= llvm::DIDescriptor::FlagPrivate; 759 else if (Access == clang::AS_protected) 760 Flags |= llvm::DIDescriptor::FlagProtected; 761 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 762 if (CXXC->isExplicit()) 763 Flags |= llvm::DIDescriptor::FlagExplicit; 764 } else if (const CXXConversionDecl *CXXC = 765 dyn_cast<CXXConversionDecl>(Method)) { 766 if (CXXC->isExplicit()) 767 Flags |= llvm::DIDescriptor::FlagExplicit; 768 } 769 if (Method->hasPrototype()) 770 Flags |= llvm::DIDescriptor::FlagPrototyped; 771 772 llvm::DISubprogram SP = 773 DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName, 774 MethodLinkageName, 775 MethodDefUnit, MethodLine, 776 MethodTy, /*isLocalToUnit=*/false, 777 /* isDefinition=*/ false, 778 Virtuality, VIndex, ContainingType, 779 Flags, 780 CGM.getLangOptions().Optimize); 781 782 // Don't cache ctors or dtors since we have to emit multiple functions for 783 // a single ctor or dtor. 784 if (!IsCtorOrDtor && Method->isThisDeclarationADefinition()) 785 SPCache[Method] = llvm::WeakVH(SP); 786 787 return SP; 788} 789 790/// CollectCXXMemberFunctions - A helper function to collect debug info for 791/// C++ member functions.This is used while creating debug info entry for 792/// a Record. 793void CGDebugInfo:: 794CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 795 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys, 796 llvm::DIType RecordTy) { 797 for(CXXRecordDecl::method_iterator I = RD->method_begin(), 798 E = RD->method_end(); I != E; ++I) { 799 const CXXMethodDecl *Method = *I; 800 801 if (Method->isImplicit() && !Method->isUsed()) 802 continue; 803 804 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 805 } 806} 807 808/// CollectCXXFriends - A helper function to collect debug info for 809/// C++ base classes. This is used while creating debug info entry for 810/// a Record. 811void CGDebugInfo:: 812CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 813 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys, 814 llvm::DIType RecordTy) { 815 816 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 817 BE = RD->friend_end(); BI != BE; ++BI) { 818 819 TypeSourceInfo *TInfo = (*BI)->getFriendType(); 820 if(TInfo) 821 { 822 llvm::DIType Ty = getOrCreateType(TInfo->getType(), Unit); 823 824 llvm::DIType DTy = 825 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_friend, 826 RecordTy, llvm::StringRef(), 827 Unit, 0, 0, 0, 828 0, 0, Ty); 829 830 EltTys.push_back(DTy); 831 } 832 833 } 834} 835 836/// CollectCXXBases - A helper function to collect debug info for 837/// C++ base classes. This is used while creating debug info entry for 838/// a Record. 839void CGDebugInfo:: 840CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 841 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys, 842 llvm::DIType RecordTy) { 843 844 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 845 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 846 BE = RD->bases_end(); BI != BE; ++BI) { 847 unsigned BFlags = 0; 848 uint64_t BaseOffset; 849 850 const CXXRecordDecl *Base = 851 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 852 853 if (BI->isVirtual()) { 854 // virtual base offset offset is -ve. The code generator emits dwarf 855 // expression where it expects +ve number. 856 BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base); 857 BFlags = llvm::DIDescriptor::FlagVirtual; 858 } else 859 BaseOffset = RL.getBaseClassOffsetInBits(Base); 860 861 AccessSpecifier Access = BI->getAccessSpecifier(); 862 if (Access == clang::AS_private) 863 BFlags |= llvm::DIDescriptor::FlagPrivate; 864 else if (Access == clang::AS_protected) 865 BFlags |= llvm::DIDescriptor::FlagProtected; 866 867 llvm::DIType DTy = 868 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance, 869 RecordTy, llvm::StringRef(), 870 Unit, 0, 0, 0, 871 BaseOffset, BFlags, 872 getOrCreateType(BI->getType(), 873 Unit)); 874 EltTys.push_back(DTy); 875 } 876} 877 878/// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 879llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 880 if (VTablePtrType.isValid()) 881 return VTablePtrType; 882 883 ASTContext &Context = CGM.getContext(); 884 885 /* Function type */ 886 llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit); 887 llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1); 888 llvm::DIType SubTy = 889 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, 890 Unit, "", Unit, 891 0, 0, 0, 0, 0, llvm::DIType(), SElements); 892 893 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 894 llvm::DIType vtbl_ptr_type 895 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 896 Unit, "__vtbl_ptr_type", Unit, 897 0, Size, 0, 0, 0, SubTy); 898 899 VTablePtrType = 900 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 901 Unit, "", Unit, 902 0, Size, 0, 0, 0, vtbl_ptr_type); 903 return VTablePtrType; 904} 905 906/// getVTableName - Get vtable name for the given Class. 907llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 908 // Otherwise construct gdb compatible name name. 909 std::string Name = "_vptr$" + RD->getNameAsString(); 910 911 // Copy this name on the side and use its reference. 912 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 913 memcpy(StrPtr, Name.data(), Name.length()); 914 return llvm::StringRef(StrPtr, Name.length()); 915} 916 917 918/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 919/// debug info entry in EltTys vector. 920void CGDebugInfo:: 921CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 922 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) { 923 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 924 925 // If there is a primary base then it will hold vtable info. 926 if (RL.getPrimaryBase()) 927 return; 928 929 // If this class is not dynamic then there is not any vtable info to collect. 930 if (!RD->isDynamicClass()) 931 return; 932 933 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 934 llvm::DIType VPTR 935 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 936 getVTableName(RD), Unit, 937 0, Size, 0, 0, 0, 938 getOrCreateVTablePtrType(Unit)); 939 EltTys.push_back(VPTR); 940} 941 942/// getOrCreateRecordType - Emit record type's standalone debug info. 943llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 944 SourceLocation Loc) { 945 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 946 DebugFactory.RecordType(T); 947 return T; 948} 949 950/// CreateType - get structure or union type. 951llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, 952 llvm::DIFile Unit) { 953 RecordDecl *RD = Ty->getDecl(); 954 955 unsigned Tag; 956 if (RD->isStruct()) 957 Tag = llvm::dwarf::DW_TAG_structure_type; 958 else if (RD->isUnion()) 959 Tag = llvm::dwarf::DW_TAG_union_type; 960 else { 961 assert(RD->isClass() && "Unknown RecordType!"); 962 Tag = llvm::dwarf::DW_TAG_class_type; 963 } 964 965 // Get overall information about the record type for the debug info. 966 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 967 unsigned Line = getLineNumber(RD->getLocation()); 968 969 // Records and classes and unions can all be recursive. To handle them, we 970 // first generate a debug descriptor for the struct as a forward declaration. 971 // Then (if it is a definition) we go through and get debug info for all of 972 // its members. Finally, we create a descriptor for the complete type (which 973 // may refer to the forward decl if the struct is recursive) and replace all 974 // uses of the forward declaration with the final definition. 975 llvm::DIDescriptor FDContext = 976 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit); 977 978 // If this is just a forward declaration, construct an appropriately 979 // marked node and just return it. 980 if (!RD->getDefinition()) { 981 llvm::DICompositeType FwdDecl = 982 DebugFactory.CreateCompositeType(Tag, FDContext, RD->getName(), 983 DefUnit, Line, 0, 0, 0, 984 llvm::DIDescriptor::FlagFwdDecl, 985 llvm::DIType(), llvm::DIArray()); 986 987 return FwdDecl; 988 } 989 990 llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType(); 991 992 llvm::MDNode *MN = FwdDecl; 993 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 994 // Otherwise, insert it into the TypeCache so that recursive uses will find 995 // it. 996 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 997 // Push the struct on region stack. 998 RegionStack.push_back(FwdDeclNode); 999 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1000 1001 // Convert all the elements. 1002 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 1003 1004 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1005 if (CXXDecl) { 1006 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl); 1007 CollectVTableInfo(CXXDecl, Unit, EltTys); 1008 } 1009 1010 // Collect static variables with initializers. 1011 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 1012 I != E; ++I) 1013 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) { 1014 if (const Expr *Init = V->getInit()) { 1015 Expr::EvalResult Result; 1016 if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) { 1017 llvm::ConstantInt *CI 1018 = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt()); 1019 1020 // Create the descriptor for static variable. 1021 llvm::DIFile VUnit = getOrCreateFile(V->getLocation()); 1022 llvm::StringRef VName = V->getName(); 1023 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit); 1024 // Do not use DIGlobalVariable for enums. 1025 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) { 1026 DebugFactory.CreateGlobalVariable(FwdDecl, VName, VName, VName, VUnit, 1027 getLineNumber(V->getLocation()), 1028 VTy, true, true, CI); 1029 } 1030 } 1031 } 1032 } 1033 1034 CollectRecordFields(RD, Unit, EltTys); 1035 llvm::MDNode *ContainingType = NULL; 1036 if (CXXDecl) { 1037 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl); 1038 CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl); 1039 1040 // A class's primary base or the class itself contains the vtable. 1041 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1042 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 1043 // Seek non virtual primary base root. 1044 while (1) { 1045 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 1046 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 1047 if (PBT && !BRL.getPrimaryBaseWasVirtual()) 1048 PBase = PBT; 1049 else 1050 break; 1051 } 1052 ContainingType = 1053 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit); 1054 } 1055 else if (CXXDecl->isDynamicClass()) 1056 ContainingType = FwdDecl; 1057 } 1058 1059 llvm::DIArray Elements = 1060 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 1061 1062 // Bit size, align and offset of the type. 1063 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1064 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1065 1066 RegionStack.pop_back(); 1067 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1068 RegionMap.find(Ty->getDecl()); 1069 if (RI != RegionMap.end()) 1070 RegionMap.erase(RI); 1071 1072 llvm::DIDescriptor RDContext = 1073 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit); 1074 1075 llvm::StringRef RDName = RD->getName(); 1076 // If this is a class, include the template arguments also. 1077 if (Tag == llvm::dwarf::DW_TAG_class_type) 1078 RDName = getClassName(RD); 1079 1080 llvm::DICompositeType RealDecl = 1081 DebugFactory.CreateCompositeType(Tag, RDContext, 1082 RDName, 1083 DefUnit, Line, Size, Align, 0, 0, 1084 llvm::DIType(), Elements, 1085 0, ContainingType); 1086 1087 // Now that we have a real decl for the struct, replace anything using the 1088 // old decl with the new one. This will recursively update the debug info. 1089 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1090 RegionMap[RD] = llvm::WeakVH(RealDecl); 1091 return RealDecl; 1092} 1093 1094/// CreateType - get objective-c object type. 1095llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1096 llvm::DIFile Unit) { 1097 // Ignore protocols. 1098 return getOrCreateType(Ty->getBaseType(), Unit); 1099} 1100 1101/// CreateType - get objective-c interface type. 1102llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1103 llvm::DIFile Unit) { 1104 ObjCInterfaceDecl *ID = Ty->getDecl(); 1105 unsigned Tag = llvm::dwarf::DW_TAG_structure_type; 1106 1107 // Get overall information about the record type for the debug info. 1108 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1109 unsigned Line = getLineNumber(ID->getLocation()); 1110 unsigned RuntimeLang = TheCU.getLanguage(); 1111 1112 // If this is just a forward declaration, return a special forward-declaration 1113 // debug type. 1114 if (ID->isForwardDecl()) { 1115 llvm::DICompositeType FwdDecl = 1116 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), 1117 DefUnit, Line, 0, 0, 0, 0, 1118 llvm::DIType(), llvm::DIArray(), 1119 RuntimeLang); 1120 return FwdDecl; 1121 } 1122 1123 // To handle recursive interface, we 1124 // first generate a debug descriptor for the struct as a forward declaration. 1125 // Then (if it is a definition) we go through and get debug info for all of 1126 // its members. Finally, we create a descriptor for the complete type (which 1127 // may refer to the forward decl if the struct is recursive) and replace all 1128 // uses of the forward declaration with the final definition. 1129 llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType(); 1130 1131 llvm::MDNode *MN = FwdDecl; 1132 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1133 // Otherwise, insert it into the TypeCache so that recursive uses will find 1134 // it. 1135 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1136 // Push the struct on region stack. 1137 RegionStack.push_back(FwdDeclNode); 1138 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1139 1140 // Convert all the elements. 1141 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 1142 1143 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1144 if (SClass) { 1145 llvm::DIType SClassTy = 1146 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1147 llvm::DIType InhTag = 1148 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance, 1149 Unit, "", Unit, 0, 0, 0, 1150 0 /* offset */, 0, SClassTy); 1151 EltTys.push_back(InhTag); 1152 } 1153 1154 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1155 1156 unsigned FieldNo = 0; 1157 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1158 Field = Field->getNextIvar(), ++FieldNo) { 1159 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1160 1161 llvm::StringRef FieldName = Field->getName(); 1162 1163 // Ignore unnamed fields. 1164 if (FieldName.empty()) 1165 continue; 1166 1167 // Get the location for the field. 1168 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1169 unsigned FieldLine = getLineNumber(Field->getLocation()); 1170 QualType FType = Field->getType(); 1171 uint64_t FieldSize = 0; 1172 unsigned FieldAlign = 0; 1173 1174 if (!FType->isIncompleteArrayType()) { 1175 1176 // Bit size, align and offset of the type. 1177 FieldSize = CGM.getContext().getTypeSize(FType); 1178 Expr *BitWidth = Field->getBitWidth(); 1179 if (BitWidth) 1180 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue(); 1181 1182 FieldAlign = CGM.getContext().getTypeAlign(FType); 1183 } 1184 1185 uint64_t FieldOffset = RL.getFieldOffset(FieldNo); 1186 1187 unsigned Flags = 0; 1188 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1189 Flags = llvm::DIDescriptor::FlagProtected; 1190 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1191 Flags = llvm::DIDescriptor::FlagPrivate; 1192 1193 // Create a DW_TAG_member node to remember the offset of this field in the 1194 // struct. FIXME: This is an absolutely insane way to capture this 1195 // information. When we gut debug info, this should be fixed. 1196 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 1197 FieldName, FieldDefUnit, 1198 FieldLine, FieldSize, FieldAlign, 1199 FieldOffset, Flags, FieldTy); 1200 EltTys.push_back(FieldTy); 1201 } 1202 1203 llvm::DIArray Elements = 1204 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 1205 1206 RegionStack.pop_back(); 1207 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1208 RegionMap.find(Ty->getDecl()); 1209 if (RI != RegionMap.end()) 1210 RegionMap.erase(RI); 1211 1212 // Bit size, align and offset of the type. 1213 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1214 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1215 1216 llvm::DICompositeType RealDecl = 1217 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit, 1218 Line, Size, Align, 0, 0, llvm::DIType(), 1219 Elements, RuntimeLang); 1220 1221 // Now that we have a real decl for the struct, replace anything using the 1222 // old decl with the new one. This will recursively update the debug info. 1223 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1224 RegionMap[ID] = llvm::WeakVH(RealDecl); 1225 1226 return RealDecl; 1227} 1228 1229llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty, 1230 llvm::DIFile Unit) { 1231 return CreateEnumType(Ty->getDecl(), Unit); 1232 1233} 1234 1235llvm::DIType CGDebugInfo::CreateType(const TagType *Ty, 1236 llvm::DIFile Unit) { 1237 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) 1238 return CreateType(RT, Unit); 1239 else if (const EnumType *ET = dyn_cast<EnumType>(Ty)) 1240 return CreateType(ET, Unit); 1241 1242 return llvm::DIType(); 1243} 1244 1245llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, 1246 llvm::DIFile Unit) { 1247 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1248 uint64_t NumElems = Ty->getNumElements(); 1249 if (NumElems > 0) 1250 --NumElems; 1251 1252 llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems); 1253 llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1); 1254 1255 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1256 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1257 1258 return 1259 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type, 1260 Unit, "", Unit, 1261 0, Size, Align, 0, 0, 1262 ElementTy, SubscriptArray); 1263} 1264 1265llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1266 llvm::DIFile Unit) { 1267 uint64_t Size; 1268 uint64_t Align; 1269 1270 1271 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1272 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1273 Size = 0; 1274 Align = 1275 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1276 } else if (Ty->isIncompleteArrayType()) { 1277 Size = 0; 1278 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1279 } else { 1280 // Size and align of the whole array, not the element type. 1281 Size = CGM.getContext().getTypeSize(Ty); 1282 Align = CGM.getContext().getTypeAlign(Ty); 1283 } 1284 1285 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1286 // interior arrays, do we care? Why aren't nested arrays represented the 1287 // obvious/recursive way? 1288 llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts; 1289 QualType EltTy(Ty, 0); 1290 if (Ty->isIncompleteArrayType()) 1291 EltTy = Ty->getElementType(); 1292 else { 1293 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1294 uint64_t Upper = 0; 1295 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1296 if (CAT->getSize().getZExtValue()) 1297 Upper = CAT->getSize().getZExtValue() - 1; 1298 // FIXME: Verify this is right for VLAs. 1299 Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper)); 1300 EltTy = Ty->getElementType(); 1301 } 1302 } 1303 1304 llvm::DIArray SubscriptArray = 1305 DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size()); 1306 1307 llvm::DIType DbgTy = 1308 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type, 1309 Unit, "", Unit, 1310 0, Size, Align, 0, 0, 1311 getOrCreateType(EltTy, Unit), 1312 SubscriptArray); 1313 return DbgTy; 1314} 1315 1316llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1317 llvm::DIFile Unit) { 1318 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1319 Ty, Ty->getPointeeType(), Unit); 1320} 1321 1322llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1323 llvm::DIFile U) { 1324 QualType PointerDiffTy = CGM.getContext().getPointerDiffType(); 1325 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U); 1326 1327 if (!Ty->getPointeeType()->isFunctionType()) { 1328 // We have a data member pointer type. 1329 return PointerDiffDITy; 1330 } 1331 1332 // We have a member function pointer type. Treat it as a struct with two 1333 // ptrdiff_t members. 1334 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty); 1335 1336 uint64_t FieldOffset = 0; 1337 llvm::DIDescriptor ElementTypes[2]; 1338 1339 // FIXME: This should probably be a function type instead. 1340 ElementTypes[0] = 1341 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U, 1342 "ptr", U, 0, 1343 Info.first, Info.second, FieldOffset, 0, 1344 PointerDiffDITy); 1345 FieldOffset += Info.first; 1346 1347 ElementTypes[1] = 1348 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U, 1349 "ptr", U, 0, 1350 Info.first, Info.second, FieldOffset, 0, 1351 PointerDiffDITy); 1352 1353 llvm::DIArray Elements = 1354 DebugFactory.GetOrCreateArray(&ElementTypes[0], 1355 llvm::array_lengthof(ElementTypes)); 1356 1357 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 1358 U, llvm::StringRef("test"), 1359 U, 0, FieldOffset, 1360 0, 0, 0, llvm::DIType(), Elements); 1361} 1362 1363/// CreateEnumType - get enumeration type. 1364llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED, llvm::DIFile Unit){ 1365 llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators; 1366 1367 // Create DIEnumerator elements for each enumerator. 1368 for (EnumDecl::enumerator_iterator 1369 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1370 Enum != EnumEnd; ++Enum) { 1371 Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(), 1372 Enum->getInitVal().getZExtValue())); 1373 } 1374 1375 // Return a CompositeType for the enum itself. 1376 llvm::DIArray EltArray = 1377 DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size()); 1378 1379 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1380 unsigned Line = getLineNumber(ED->getLocation()); 1381 uint64_t Size = 0; 1382 uint64_t Align = 0; 1383 if (!ED->getTypeForDecl()->isIncompleteType()) { 1384 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1385 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1386 } 1387 llvm::DIDescriptor EnumContext = 1388 getContextDescriptor(dyn_cast<Decl>(ED->getDeclContext()), Unit); 1389 llvm::DIType DbgTy = 1390 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type, 1391 EnumContext, ED->getName(), 1392 DefUnit, Line, Size, Align, 0, 0, 1393 llvm::DIType(), EltArray); 1394 return DbgTy; 1395} 1396 1397static QualType UnwrapTypeForDebugInfo(QualType T) { 1398 do { 1399 QualType LastT = T; 1400 switch (T->getTypeClass()) { 1401 default: 1402 return T; 1403 case Type::TemplateSpecialization: 1404 T = cast<TemplateSpecializationType>(T)->desugar(); 1405 break; 1406 case Type::TypeOfExpr: { 1407 TypeOfExprType *Ty = cast<TypeOfExprType>(T); 1408 T = Ty->getUnderlyingExpr()->getType(); 1409 break; 1410 } 1411 case Type::TypeOf: 1412 T = cast<TypeOfType>(T)->getUnderlyingType(); 1413 break; 1414 case Type::Decltype: 1415 T = cast<DecltypeType>(T)->getUnderlyingType(); 1416 break; 1417 case Type::Elaborated: 1418 T = cast<ElaboratedType>(T)->getNamedType(); 1419 break; 1420 case Type::SubstTemplateTypeParm: 1421 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1422 break; 1423 } 1424 1425 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1426 if (T == LastT) 1427 return T; 1428 } while (true); 1429 1430 return T; 1431} 1432 1433/// getOrCreateType - Get the type from the cache or create a new 1434/// one if necessary. 1435llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, 1436 llvm::DIFile Unit) { 1437 if (Ty.isNull()) 1438 return llvm::DIType(); 1439 1440 // Unwrap the type as needed for debug information. 1441 Ty = UnwrapTypeForDebugInfo(Ty); 1442 1443 // Check for existing entry. 1444 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1445 TypeCache.find(Ty.getAsOpaquePtr()); 1446 if (it != TypeCache.end()) { 1447 // Verify that the debug info still exists. 1448 if (&*it->second) 1449 return llvm::DIType(cast<llvm::MDNode>(it->second)); 1450 } 1451 1452 // Otherwise create the type. 1453 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1454 1455 // And update the type cache. 1456 TypeCache[Ty.getAsOpaquePtr()] = Res; 1457 return Res; 1458} 1459 1460/// CreateTypeNode - Create a new debug type node. 1461llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, 1462 llvm::DIFile Unit) { 1463 // Handle qualifiers, which recursively handles what they refer to. 1464 if (Ty.hasLocalQualifiers()) 1465 return CreateQualifiedType(Ty, Unit); 1466 1467 const char *Diag = 0; 1468 1469 // Work out details of type. 1470 switch (Ty->getTypeClass()) { 1471#define TYPE(Class, Base) 1472#define ABSTRACT_TYPE(Class, Base) 1473#define NON_CANONICAL_TYPE(Class, Base) 1474#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1475#include "clang/AST/TypeNodes.def" 1476 assert(false && "Dependent types cannot show up in debug information"); 1477 1478 // FIXME: Handle these. 1479 case Type::ExtVector: 1480 return llvm::DIType(); 1481 1482 case Type::Vector: 1483 return CreateType(cast<VectorType>(Ty), Unit); 1484 case Type::ObjCObjectPointer: 1485 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 1486 case Type::ObjCObject: 1487 return CreateType(cast<ObjCObjectType>(Ty), Unit); 1488 case Type::ObjCInterface: 1489 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 1490 case Type::Builtin: return CreateType(cast<BuiltinType>(Ty)); 1491 case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit); 1492 case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit); 1493 case Type::BlockPointer: 1494 return CreateType(cast<BlockPointerType>(Ty), Unit); 1495 case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit); 1496 case Type::Record: 1497 case Type::Enum: 1498 return CreateType(cast<TagType>(Ty), Unit); 1499 case Type::FunctionProto: 1500 case Type::FunctionNoProto: 1501 return CreateType(cast<FunctionType>(Ty), Unit); 1502 case Type::ConstantArray: 1503 case Type::VariableArray: 1504 case Type::IncompleteArray: 1505 return CreateType(cast<ArrayType>(Ty), Unit); 1506 1507 case Type::LValueReference: 1508 return CreateType(cast<LValueReferenceType>(Ty), Unit); 1509 1510 case Type::MemberPointer: 1511 return CreateType(cast<MemberPointerType>(Ty), Unit); 1512 1513 case Type::TemplateSpecialization: 1514 case Type::Elaborated: 1515 case Type::SubstTemplateTypeParm: 1516 case Type::TypeOfExpr: 1517 case Type::TypeOf: 1518 case Type::Decltype: 1519 llvm_unreachable("type should have been unwrapped!"); 1520 return llvm::DIType(); 1521 1522 case Type::RValueReference: 1523 // FIXME: Implement! 1524 Diag = "rvalue references"; 1525 break; 1526 } 1527 1528 assert(Diag && "Fall through without a diagnostic?"); 1529 unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error, 1530 "debug information for %0 is not yet supported"); 1531 CGM.getDiags().Report(FullSourceLoc(), DiagID) 1532 << Diag; 1533 return llvm::DIType(); 1534} 1535 1536/// CreateMemberType - Create new member and increase Offset by FType's size. 1537llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 1538 llvm::StringRef Name, 1539 uint64_t *Offset) { 1540 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1541 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 1542 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 1543 llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, 1544 Unit, Name, Unit, 0, 1545 FieldSize, FieldAlign, 1546 *Offset, 0, FieldTy); 1547 *Offset += FieldSize; 1548 return Ty; 1549} 1550 1551/// EmitFunctionStart - Constructs the debug code for entering a function - 1552/// "llvm.dbg.func.start.". 1553void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 1554 llvm::Function *Fn, 1555 CGBuilderTy &Builder) { 1556 1557 llvm::StringRef Name; 1558 llvm::StringRef LinkageName; 1559 1560 FnBeginRegionCount.push_back(RegionStack.size()); 1561 1562 const Decl *D = GD.getDecl(); 1563 unsigned Flags = 0; 1564 llvm::DIFile Unit = getOrCreateFile(CurLoc); 1565 llvm::DIDescriptor FDContext(Unit); 1566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1567 // If there is a DISubprogram for this function available then use it. 1568 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 1569 FI = SPCache.find(FD); 1570 if (FI != SPCache.end()) { 1571 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second)); 1572 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 1573 llvm::MDNode *SPN = SP; 1574 RegionStack.push_back(SPN); 1575 RegionMap[D] = llvm::WeakVH(SP); 1576 return; 1577 } 1578 } 1579 Name = getFunctionName(FD); 1580 // Use mangled name as linkage name for c/c++ functions. 1581 LinkageName = CGM.getMangledName(GD); 1582 if (LinkageName == Name) 1583 LinkageName = llvm::StringRef(); 1584 if (FD->hasPrototype()) 1585 Flags |= llvm::DIDescriptor::FlagPrototyped; 1586 if (const NamespaceDecl *NSDecl = 1587 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 1588 FDContext = getOrCreateNameSpace(NSDecl, Unit); 1589 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 1590 Name = getObjCMethodName(OMD); 1591 Flags |= llvm::DIDescriptor::FlagPrototyped; 1592 } else { 1593 // Use llvm function name. 1594 Name = Fn->getName(); 1595 Flags |= llvm::DIDescriptor::FlagPrototyped; 1596 } 1597 if (!Name.empty() && Name[0] == '\01') 1598 Name = Name.substr(1); 1599 1600 // It is expected that CurLoc is set before using EmitFunctionStart. 1601 // Usually, CurLoc points to the left bracket location of compound 1602 // statement representing function body. 1603 unsigned LineNo = getLineNumber(CurLoc); 1604 if (D->isImplicit()) 1605 Flags |= llvm::DIDescriptor::FlagArtificial; 1606 llvm::DISubprogram SP = 1607 DebugFactory.CreateSubprogram(FDContext, Name, Name, LinkageName, Unit, 1608 LineNo, getOrCreateType(FnType, Unit), 1609 Fn->hasInternalLinkage(), true/*definition*/, 1610 0, 0, llvm::DIType(), 1611 Flags, 1612 CGM.getLangOptions().Optimize, Fn); 1613 1614 // Push function on region stack. 1615 llvm::MDNode *SPN = SP; 1616 RegionStack.push_back(SPN); 1617 RegionMap[D] = llvm::WeakVH(SP); 1618 1619 // Clear stack used to keep track of #line directives. 1620 LineDirectiveFiles.clear(); 1621} 1622 1623 1624void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) { 1625 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 1626 1627 // Don't bother if things are the same as last time. 1628 SourceManager &SM = CGM.getContext().getSourceManager(); 1629 if (CurLoc == PrevLoc 1630 || (SM.getInstantiationLineNumber(CurLoc) == 1631 SM.getInstantiationLineNumber(PrevLoc) 1632 && SM.isFromSameFile(CurLoc, PrevLoc))) 1633 // New Builder may not be in sync with CGDebugInfo. 1634 if (!Builder.getCurrentDebugLocation().isUnknown()) 1635 return; 1636 1637 // Update last state. 1638 PrevLoc = CurLoc; 1639 1640 llvm::MDNode *Scope = RegionStack.back(); 1641 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc), 1642 getColumnNumber(CurLoc), 1643 Scope)); 1644} 1645 1646/// UpdateLineDirectiveRegion - Update region stack only if #line directive 1647/// has introduced scope change. 1648void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) { 1649 if (CurLoc.isInvalid() || CurLoc.isMacroID() || 1650 PrevLoc.isInvalid() || PrevLoc.isMacroID()) 1651 return; 1652 SourceManager &SM = CGM.getContext().getSourceManager(); 1653 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 1654 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc); 1655 1656 if (!strcmp(PPLoc.getFilename(), PCLoc.getFilename())) 1657 return; 1658 1659 // If #line directive stack is empty then we are entering a new scope. 1660 if (LineDirectiveFiles.empty()) { 1661 EmitRegionStart(Builder); 1662 LineDirectiveFiles.push_back(PCLoc.getFilename()); 1663 return; 1664 } 1665 1666 assert (RegionStack.size() >= LineDirectiveFiles.size() 1667 && "error handling #line regions!"); 1668 1669 bool SeenThisFile = false; 1670 // Chek if current file is already seen earlier. 1671 for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(), 1672 E = LineDirectiveFiles.end(); I != E; ++I) 1673 if (!strcmp(PCLoc.getFilename(), *I)) { 1674 SeenThisFile = true; 1675 break; 1676 } 1677 1678 // If #line for this file is seen earlier then pop out #line regions. 1679 if (SeenThisFile) { 1680 while (!LineDirectiveFiles.empty()) { 1681 const char *LastFile = LineDirectiveFiles.back(); 1682 RegionStack.pop_back(); 1683 LineDirectiveFiles.pop_back(); 1684 if (!strcmp(PPLoc.getFilename(), LastFile)) 1685 break; 1686 } 1687 return; 1688 } 1689 1690 // .. otherwise insert new #line region. 1691 EmitRegionStart(Builder); 1692 LineDirectiveFiles.push_back(PCLoc.getFilename()); 1693 1694 return; 1695} 1696/// EmitRegionStart- Constructs the debug code for entering a declarative 1697/// region - "llvm.dbg.region.start.". 1698void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) { 1699 llvm::DIDescriptor D = 1700 DebugFactory.CreateLexicalBlock(RegionStack.empty() ? 1701 llvm::DIDescriptor() : 1702 llvm::DIDescriptor(RegionStack.back()), 1703 getOrCreateFile(CurLoc), 1704 getLineNumber(CurLoc), 1705 getColumnNumber(CurLoc)); 1706 llvm::MDNode *DN = D; 1707 RegionStack.push_back(DN); 1708} 1709 1710/// EmitRegionEnd - Constructs the debug code for exiting a declarative 1711/// region - "llvm.dbg.region.end." 1712void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) { 1713 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1714 1715 // Provide an region stop point. 1716 EmitStopPoint(Builder); 1717 1718 RegionStack.pop_back(); 1719} 1720 1721/// EmitFunctionEnd - Constructs the debug code for exiting a function. 1722void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 1723 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1724 unsigned RCount = FnBeginRegionCount.back(); 1725 assert(RCount <= RegionStack.size() && "Region stack mismatch"); 1726 1727 // Pop all regions for this function. 1728 while (RegionStack.size() != RCount) 1729 EmitRegionEnd(Builder); 1730 FnBeginRegionCount.pop_back(); 1731} 1732 1733// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 1734// See BuildByRefType. 1735llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD, 1736 uint64_t *XOffset) { 1737 1738 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys; 1739 1740 QualType FType; 1741 uint64_t FieldSize, FieldOffset; 1742 unsigned FieldAlign; 1743 1744 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1745 QualType Type = VD->getType(); 1746 1747 FieldOffset = 0; 1748 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1749 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 1750 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 1751 FType = CGM.getContext().IntTy; 1752 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 1753 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 1754 1755 bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type); 1756 if (HasCopyAndDispose) { 1757 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1758 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 1759 &FieldOffset)); 1760 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 1761 &FieldOffset)); 1762 } 1763 1764 CharUnits Align = CGM.getContext().getDeclAlign(VD); 1765 if (Align > CharUnits::fromQuantity( 1766 CGM.getContext().Target.getPointerAlign(0) / 8)) { 1767 unsigned AlignedOffsetInBytes 1768 = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity()); 1769 unsigned NumPaddingBytes 1770 = AlignedOffsetInBytes - FieldOffset/8; 1771 1772 if (NumPaddingBytes > 0) { 1773 llvm::APInt pad(32, NumPaddingBytes); 1774 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 1775 pad, ArrayType::Normal, 0); 1776 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 1777 } 1778 } 1779 1780 FType = Type; 1781 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1782 FieldSize = CGM.getContext().getTypeSize(FType); 1783 FieldAlign = Align.getQuantity()*8; 1784 1785 *XOffset = FieldOffset; 1786 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 1787 VD->getName(), Unit, 1788 0, FieldSize, FieldAlign, 1789 FieldOffset, 0, FieldTy); 1790 EltTys.push_back(FieldTy); 1791 FieldOffset += FieldSize; 1792 1793 llvm::DIArray Elements = 1794 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 1795 1796 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 1797 1798 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 1799 Unit, "", Unit, 1800 0, FieldOffset, 0, 0, Flags, 1801 llvm::DIType(), Elements); 1802 1803} 1804/// EmitDeclare - Emit local variable declaration debug info. 1805void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 1806 llvm::Value *Storage, CGBuilderTy &Builder) { 1807 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1808 1809 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1810 llvm::DIType Ty; 1811 uint64_t XOffset = 0; 1812 if (VD->hasAttr<BlocksAttr>()) 1813 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 1814 else 1815 Ty = getOrCreateType(VD->getType(), Unit); 1816 1817 // If there is not any debug info for type then do not emit debug info 1818 // for this variable. 1819 if (!Ty) 1820 return; 1821 1822 // Get location information. 1823 unsigned Line = getLineNumber(VD->getLocation()); 1824 unsigned Column = getColumnNumber(VD->getLocation()); 1825 unsigned Flags = 0; 1826 if (VD->isImplicit()) 1827 Flags |= llvm::DIDescriptor::FlagArtificial; 1828 llvm::MDNode *Scope = RegionStack.back(); 1829 1830 llvm::StringRef Name = VD->getName(); 1831 if (!Name.empty()) { 1832 // Create the descriptor for the variable. 1833 llvm::DIVariable D = 1834 DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(Scope), 1835 Name, Unit, Line, Ty, 1836 CGM.getLangOptions().Optimize, Flags); 1837 1838 // Insert an llvm.dbg.declare into the current block. 1839 llvm::Instruction *Call = 1840 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); 1841 1842 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1843 return; 1844 } 1845 1846 // If VD is an anonymous union then Storage represents value for 1847 // all union fields. 1848 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) 1849 if (const RecordDecl *RD = dyn_cast<RecordDecl>(RT->getDecl())) 1850 if (RD->isUnion()) { 1851 for (RecordDecl::field_iterator I = RD->field_begin(), 1852 E = RD->field_end(); 1853 I != E; ++I) { 1854 FieldDecl *Field = *I; 1855 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1856 llvm::StringRef FieldName = Field->getName(); 1857 1858 // Ignore unnamed fields. Do not ignore unnamed records. 1859 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 1860 continue; 1861 1862 // Use VarDecl's Tag, Scope and Line number. 1863 llvm::DIVariable D = 1864 DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(Scope), 1865 FieldName, Unit, Line, FieldTy, 1866 CGM.getLangOptions().Optimize, Flags); 1867 1868 // Insert an llvm.dbg.declare into the current block. 1869 llvm::Instruction *Call = 1870 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); 1871 1872 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1873 } 1874 } 1875} 1876 1877/// EmitDeclare - Emit local variable declaration debug info. 1878void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag, 1879 llvm::Value *Storage, CGBuilderTy &Builder, 1880 CodeGenFunction *CGF) { 1881 const ValueDecl *VD = BDRE->getDecl(); 1882 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1883 1884 if (Builder.GetInsertBlock() == 0) 1885 return; 1886 1887 uint64_t XOffset = 0; 1888 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1889 llvm::DIType Ty; 1890 if (VD->hasAttr<BlocksAttr>()) 1891 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 1892 else 1893 Ty = getOrCreateType(VD->getType(), Unit); 1894 1895 // Get location information. 1896 unsigned Line = getLineNumber(VD->getLocation()); 1897 unsigned Column = getColumnNumber(VD->getLocation()); 1898 1899 CharUnits offset = CGF->BlockDecls[VD]; 1900 llvm::SmallVector<llvm::Value *, 9> addr; 1901 const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext()); 1902 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref)); 1903 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus)); 1904 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1905 if (BDRE->isByRef()) { 1906 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref)); 1907 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus)); 1908 // offset of __forwarding field 1909 offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8); 1910 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1911 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref)); 1912 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus)); 1913 // offset of x field 1914 offset = CharUnits::fromQuantity(XOffset/8); 1915 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1916 } 1917 1918 // Create the descriptor for the variable. 1919 llvm::DIVariable D = 1920 DebugFactory.CreateComplexVariable(Tag, 1921 llvm::DIDescriptor(RegionStack.back()), 1922 VD->getName(), Unit, Line, Ty, 1923 addr.data(), addr.size()); 1924 // Insert an llvm.dbg.declare into the current block. 1925 llvm::Instruction *Call = 1926 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); 1927 1928 llvm::MDNode *Scope = RegionStack.back(); 1929 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1930} 1931 1932void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 1933 llvm::Value *Storage, 1934 CGBuilderTy &Builder) { 1935 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder); 1936} 1937 1938void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 1939 const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder, 1940 CodeGenFunction *CGF) { 1941 EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF); 1942} 1943 1944/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 1945/// variable declaration. 1946void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 1947 CGBuilderTy &Builder) { 1948 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder); 1949} 1950 1951 1952 1953/// EmitGlobalVariable - Emit information about a global variable. 1954void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 1955 const VarDecl *D) { 1956 1957 // Create global variable debug descriptor. 1958 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 1959 unsigned LineNo = getLineNumber(D->getLocation()); 1960 1961 QualType T = D->getType(); 1962 if (T->isIncompleteArrayType()) { 1963 1964 // CodeGen turns int[] into int[1] so we'll do the same here. 1965 llvm::APSInt ConstVal(32); 1966 1967 ConstVal = 1; 1968 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 1969 1970 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 1971 ArrayType::Normal, 0); 1972 } 1973 llvm::StringRef DeclName = D->getName(); 1974 llvm::StringRef LinkageName; 1975 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())) 1976 LinkageName = Var->getName(); 1977 if (LinkageName == DeclName) 1978 LinkageName = llvm::StringRef(); 1979 llvm::DIDescriptor DContext = 1980 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit); 1981 DebugFactory.CreateGlobalVariable(DContext, DeclName, DeclName, LinkageName, 1982 Unit, LineNo, getOrCreateType(T, Unit), 1983 Var->hasInternalLinkage(), 1984 true/*definition*/, Var); 1985} 1986 1987/// EmitGlobalVariable - Emit information about an objective-c interface. 1988void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 1989 ObjCInterfaceDecl *ID) { 1990 // Create global variable debug descriptor. 1991 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 1992 unsigned LineNo = getLineNumber(ID->getLocation()); 1993 1994 llvm::StringRef Name = ID->getName(); 1995 1996 QualType T = CGM.getContext().getObjCInterfaceType(ID); 1997 if (T->isIncompleteArrayType()) { 1998 1999 // CodeGen turns int[] into int[1] so we'll do the same here. 2000 llvm::APSInt ConstVal(32); 2001 2002 ConstVal = 1; 2003 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2004 2005 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2006 ArrayType::Normal, 0); 2007 } 2008 2009 DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo, 2010 getOrCreateType(T, Unit), 2011 Var->hasInternalLinkage(), 2012 true/*definition*/, Var); 2013} 2014 2015/// EmitGlobalVariable - Emit global variable's debug info. 2016void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 2017 llvm::Constant *Init) { 2018 // Create the descriptor for the variable. 2019 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2020 llvm::StringRef Name = VD->getName(); 2021 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 2022 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 2023 if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) 2024 Ty = CreateEnumType(ED, Unit); 2025 } 2026 // Do not use DIGlobalVariable for enums. 2027 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 2028 return; 2029 DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, 2030 getLineNumber(VD->getLocation()), 2031 Ty, true, true, Init); 2032} 2033 2034/// getOrCreateNamesSpace - Return namespace descriptor for the given 2035/// namespace decl. 2036llvm::DINameSpace 2037CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl, 2038 llvm::DIDescriptor Unit) { 2039 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 2040 NameSpaceCache.find(NSDecl); 2041 if (I != NameSpaceCache.end()) 2042 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 2043 2044 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 2045 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 2046 llvm::DIDescriptor Context = 2047 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit); 2048 llvm::DINameSpace NS = 2049 DebugFactory.CreateNameSpace(Context, NSDecl->getName(), FileD, LineNo); 2050 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 2051 return NS; 2052} 2053