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