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