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