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().getInstantiationLoc(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 llvm::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 99 llvm::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. 123 llvm::StringRef 124 CGDebugInfo::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. 156 llvm::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. 187 llvm::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. 193 unsigned 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. 202 unsigned 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 209 llvm::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. 220 void 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. 277 llvm::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 357 llvm::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. 373 llvm::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 407 llvm::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 415 llvm::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. 423 llvm::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 454 llvm::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 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 466 uint64_t Size = CGM.getContext().Target.getPointerWidth(AS); 467 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 468 469 return 470 DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, Align); 471 } 472 473 llvm::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 536 llvm::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 551 llvm::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 574 llvm::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. 608 void CGDebugInfo:: 609 CollectRecordFields(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. 637 llvm::DIType 638 CGDebugInfo::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 QualType ThisPtr = Method->getThisType(CGM.getContext()); 659 llvm::DIType ThisPtrType = 660 DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit)); 661 662 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 663 Elts.push_back(ThisPtrType); 664 } 665 666 // Copy rest of the arguments. 667 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 668 Elts.push_back(Args.getElement(i)); 669 670 llvm::DIArray EltTypeArray = 671 DBuilder.getOrCreateArray(Elts.data(), Elts.size()); 672 673 return DBuilder.createSubroutineType(Unit, EltTypeArray); 674 } 675 676 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 677 /// inside a function. 678 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 679 if (const CXXRecordDecl *NRD = 680 dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 681 return isFunctionLocalClass(NRD); 682 else if (isa<FunctionDecl>(RD->getDeclContext())) 683 return true; 684 return false; 685 686 } 687 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for 688 /// a single member function GlobalDecl. 689 llvm::DISubprogram 690 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 691 llvm::DIFile Unit, 692 llvm::DIType RecordTy) { 693 bool IsCtorOrDtor = 694 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 695 696 llvm::StringRef MethodName = getFunctionName(Method); 697 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit); 698 699 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 700 // make sense to give a single ctor/dtor a linkage name. 701 llvm::StringRef MethodLinkageName; 702 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 703 MethodLinkageName = CGM.getMangledName(Method); 704 705 // Get the location for the method. 706 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 707 unsigned MethodLine = getLineNumber(Method->getLocation()); 708 709 // Collect virtual method info. 710 llvm::DIType ContainingType; 711 unsigned Virtuality = 0; 712 unsigned VIndex = 0; 713 714 if (Method->isVirtual()) { 715 if (Method->isPure()) 716 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 717 else 718 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 719 720 // It doesn't make sense to give a virtual destructor a vtable index, 721 // since a single destructor has two entries in the vtable. 722 if (!isa<CXXDestructorDecl>(Method)) 723 VIndex = CGM.getVTables().getMethodVTableIndex(Method); 724 ContainingType = RecordTy; 725 } 726 727 unsigned Flags = 0; 728 if (Method->isImplicit()) 729 Flags |= llvm::DIDescriptor::FlagArtificial; 730 AccessSpecifier Access = Method->getAccess(); 731 if (Access == clang::AS_private) 732 Flags |= llvm::DIDescriptor::FlagPrivate; 733 else if (Access == clang::AS_protected) 734 Flags |= llvm::DIDescriptor::FlagProtected; 735 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 736 if (CXXC->isExplicit()) 737 Flags |= llvm::DIDescriptor::FlagExplicit; 738 } else if (const CXXConversionDecl *CXXC = 739 dyn_cast<CXXConversionDecl>(Method)) { 740 if (CXXC->isExplicit()) 741 Flags |= llvm::DIDescriptor::FlagExplicit; 742 } 743 if (Method->hasPrototype()) 744 Flags |= llvm::DIDescriptor::FlagPrototyped; 745 746 llvm::DISubprogram SP = 747 DBuilder.createMethod(RecordTy , MethodName, MethodLinkageName, 748 MethodDefUnit, MethodLine, 749 MethodTy, /*isLocalToUnit=*/false, 750 /* isDefinition=*/ false, 751 Virtuality, VIndex, ContainingType, 752 Flags, CGM.getLangOptions().Optimize); 753 754 // Don't cache ctors or dtors since we have to emit multiple functions for 755 // a single ctor or dtor. 756 if (!IsCtorOrDtor && Method->isThisDeclarationADefinition()) 757 SPCache[Method] = llvm::WeakVH(SP); 758 759 return SP; 760 } 761 762 /// CollectCXXMemberFunctions - A helper function to collect debug info for 763 /// C++ member functions.This is used while creating debug info entry for 764 /// a Record. 765 void CGDebugInfo:: 766 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 767 llvm::SmallVectorImpl<llvm::Value *> &EltTys, 768 llvm::DIType RecordTy) { 769 for(CXXRecordDecl::method_iterator I = RD->method_begin(), 770 E = RD->method_end(); I != E; ++I) { 771 const CXXMethodDecl *Method = *I; 772 773 if (Method->isImplicit() && !Method->isUsed()) 774 continue; 775 776 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 777 } 778 } 779 780 /// CollectCXXFriends - A helper function to collect debug info for 781 /// C++ base classes. This is used while creating debug info entry for 782 /// a Record. 783 void CGDebugInfo:: 784 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 785 llvm::SmallVectorImpl<llvm::Value *> &EltTys, 786 llvm::DIType RecordTy) { 787 788 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 789 BE = RD->friend_end(); BI != BE; ++BI) { 790 if (TypeSourceInfo *TInfo = (*BI)->getFriendType()) 791 EltTys.push_back(DBuilder.createFriend(RecordTy, 792 getOrCreateType(TInfo->getType(), 793 Unit))); 794 } 795 } 796 797 /// CollectCXXBases - A helper function to collect debug info for 798 /// C++ base classes. This is used while creating debug info entry for 799 /// a Record. 800 void CGDebugInfo:: 801 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 802 llvm::SmallVectorImpl<llvm::Value *> &EltTys, 803 llvm::DIType RecordTy) { 804 805 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 806 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 807 BE = RD->bases_end(); BI != BE; ++BI) { 808 unsigned BFlags = 0; 809 uint64_t BaseOffset; 810 811 const CXXRecordDecl *Base = 812 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 813 814 if (BI->isVirtual()) { 815 // virtual base offset offset is -ve. The code generator emits dwarf 816 // expression where it expects +ve number. 817 BaseOffset = 818 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base).getQuantity(); 819 BFlags = llvm::DIDescriptor::FlagVirtual; 820 } else 821 BaseOffset = RL.getBaseClassOffsetInBits(Base); 822 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 823 // BI->isVirtual() and bits when not. 824 825 AccessSpecifier Access = BI->getAccessSpecifier(); 826 if (Access == clang::AS_private) 827 BFlags |= llvm::DIDescriptor::FlagPrivate; 828 else if (Access == clang::AS_protected) 829 BFlags |= llvm::DIDescriptor::FlagProtected; 830 831 llvm::DIType DTy = 832 DBuilder.createInheritance(RecordTy, 833 getOrCreateType(BI->getType(), Unit), 834 BaseOffset, BFlags); 835 EltTys.push_back(DTy); 836 } 837 } 838 839 /// CollectTemplateParams - A helper function to collect template parameters. 840 llvm::DIArray CGDebugInfo:: 841 CollectTemplateParams(const TemplateParameterList *TPList, 842 const TemplateArgumentList &TAList, 843 llvm::DIFile Unit) { 844 llvm::SmallVector<llvm::Value *, 16> TemplateParams; 845 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 846 const TemplateArgument &TA = TAList[i]; 847 const NamedDecl *ND = TPList->getParam(i); 848 if (TA.getKind() == TemplateArgument::Type) { 849 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 850 llvm::DITemplateTypeParameter TTP = 851 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy); 852 TemplateParams.push_back(TTP); 853 } else if (TA.getKind() == TemplateArgument::Integral) { 854 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 855 llvm::DITemplateValueParameter TVP = 856 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, 857 TA.getAsIntegral()->getZExtValue()); 858 TemplateParams.push_back(TVP); 859 } 860 } 861 return DBuilder.getOrCreateArray(TemplateParams.data(), TemplateParams.size()); 862 } 863 864 /// CollectFunctionTemplateParams - A helper function to collect debug 865 /// info for function template parameters. 866 llvm::DIArray CGDebugInfo:: 867 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) { 868 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization){ 869 const TemplateParameterList *TList = 870 FD->getTemplateSpecializationInfo()->getTemplate()->getTemplateParameters(); 871 return 872 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit); 873 } 874 return llvm::DIArray(); 875 } 876 877 /// CollectCXXTemplateParams - A helper function to collect debug info for 878 /// template parameters. 879 llvm::DIArray CGDebugInfo:: 880 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial, 881 llvm::DIFile Unit) { 882 llvm::PointerUnion<ClassTemplateDecl *, 883 ClassTemplatePartialSpecializationDecl *> 884 PU = TSpecial->getSpecializedTemplateOrPartial(); 885 886 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ? 887 PU.get<ClassTemplateDecl *>()->getTemplateParameters() : 888 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters(); 889 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs(); 890 return CollectTemplateParams(TPList, TAList, Unit); 891 } 892 893 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 894 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 895 if (VTablePtrType.isValid()) 896 return VTablePtrType; 897 898 ASTContext &Context = CGM.getContext(); 899 900 /* Function type */ 901 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 902 llvm::DIArray SElements = DBuilder.getOrCreateArray(&STy, 1); 903 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 904 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 905 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0, 906 "__vtbl_ptr_type"); 907 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 908 return VTablePtrType; 909 } 910 911 /// getVTableName - Get vtable name for the given Class. 912 llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 913 // Otherwise construct gdb compatible name name. 914 std::string Name = "_vptr$" + RD->getNameAsString(); 915 916 // Copy this name on the side and use its reference. 917 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 918 memcpy(StrPtr, Name.data(), Name.length()); 919 return llvm::StringRef(StrPtr, Name.length()); 920 } 921 922 923 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 924 /// debug info entry in EltTys vector. 925 void CGDebugInfo:: 926 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 927 llvm::SmallVectorImpl<llvm::Value *> &EltTys) { 928 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 929 930 // If there is a primary base then it will hold vtable info. 931 if (RL.getPrimaryBase()) 932 return; 933 934 // If this class is not dynamic then there is not any vtable info to collect. 935 if (!RD->isDynamicClass()) 936 return; 937 938 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 939 llvm::DIType VPTR 940 = DBuilder.createMemberType(getVTableName(RD), Unit, 941 0, Size, 0, 0, 0, 942 getOrCreateVTablePtrType(Unit)); 943 EltTys.push_back(VPTR); 944 } 945 946 /// getOrCreateRecordType - Emit record type's standalone debug info. 947 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 948 SourceLocation Loc) { 949 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 950 DBuilder.retainType(T); 951 return T; 952 } 953 954 /// CreateType - get structure or union type. 955 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 956 RecordDecl *RD = Ty->getDecl(); 957 llvm::DIFile Unit = getOrCreateFile(RD->getLocation()); 958 959 // Get overall information about the record type for the debug info. 960 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 961 unsigned Line = getLineNumber(RD->getLocation()); 962 963 // Records and classes and unions can all be recursive. To handle them, we 964 // first generate a debug descriptor for the struct as a forward declaration. 965 // Then (if it is a definition) we go through and get debug info for all of 966 // its members. Finally, we create a descriptor for the complete type (which 967 // may refer to the forward decl if the struct is recursive) and replace all 968 // uses of the forward declaration with the final definition. 969 llvm::DIDescriptor FDContext = 970 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 971 972 // If this is just a forward declaration, construct an appropriately 973 // marked node and just return it. 974 if (!RD->getDefinition()) { 975 llvm::DIType FwdDecl = 976 DBuilder.createStructType(FDContext, RD->getName(), 977 DefUnit, Line, 0, 0, 978 llvm::DIDescriptor::FlagFwdDecl, 979 llvm::DIArray()); 980 981 return FwdDecl; 982 } 983 984 llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit); 985 986 llvm::MDNode *MN = FwdDecl; 987 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 988 // Otherwise, insert it into the TypeCache so that recursive uses will find 989 // it. 990 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 991 // Push the struct on region stack. 992 RegionStack.push_back(FwdDeclNode); 993 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 994 995 // Convert all the elements. 996 llvm::SmallVector<llvm::Value *, 16> EltTys; 997 998 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 999 if (CXXDecl) { 1000 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl); 1001 CollectVTableInfo(CXXDecl, Unit, EltTys); 1002 } 1003 1004 // Collect static variables with initializers. 1005 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 1006 I != E; ++I) 1007 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) { 1008 if (const Expr *Init = V->getInit()) { 1009 Expr::EvalResult Result; 1010 if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) { 1011 llvm::ConstantInt *CI 1012 = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt()); 1013 1014 // Create the descriptor for static variable. 1015 llvm::DIFile VUnit = getOrCreateFile(V->getLocation()); 1016 llvm::StringRef VName = V->getName(); 1017 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit); 1018 // Do not use DIGlobalVariable for enums. 1019 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) { 1020 DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit, 1021 getLineNumber(V->getLocation()), 1022 VTy, true, CI); 1023 } 1024 } 1025 } 1026 } 1027 1028 CollectRecordFields(RD, Unit, EltTys); 1029 llvm::DIArray TParamsArray; 1030 if (CXXDecl) { 1031 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl); 1032 CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl); 1033 if (const ClassTemplateSpecializationDecl *TSpecial 1034 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1035 TParamsArray = CollectCXXTemplateParams(TSpecial, Unit); 1036 } 1037 1038 RegionStack.pop_back(); 1039 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1040 RegionMap.find(Ty->getDecl()); 1041 if (RI != RegionMap.end()) 1042 RegionMap.erase(RI); 1043 1044 llvm::DIDescriptor RDContext = 1045 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 1046 llvm::StringRef RDName = RD->getName(); 1047 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1048 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1049 llvm::DIArray Elements = 1050 DBuilder.getOrCreateArray(EltTys.data(), EltTys.size()); 1051 llvm::MDNode *RealDecl = NULL; 1052 1053 if (RD->isUnion()) 1054 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, 1055 Size, Align, 0, Elements); 1056 else if (CXXDecl) { 1057 RDName = getClassName(RD); 1058 // A class's primary base or the class itself contains the vtable. 1059 llvm::MDNode *ContainingType = NULL; 1060 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1061 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 1062 // Seek non virtual primary base root. 1063 while (1) { 1064 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 1065 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 1066 if (PBT && !BRL.isPrimaryBaseVirtual()) 1067 PBase = PBT; 1068 else 1069 break; 1070 } 1071 ContainingType = 1072 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit); 1073 } 1074 else if (CXXDecl->isDynamicClass()) 1075 ContainingType = FwdDecl; 1076 1077 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line, 1078 Size, Align, 0, 0, llvm::DIType(), 1079 Elements, ContainingType, 1080 TParamsArray); 1081 } else 1082 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line, 1083 Size, Align, 0, Elements); 1084 1085 // Now that we have a real decl for the struct, replace anything using the 1086 // old decl with the new one. This will recursively update the debug info. 1087 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1088 RegionMap[RD] = llvm::WeakVH(RealDecl); 1089 return llvm::DIType(RealDecl); 1090 } 1091 1092 /// CreateType - get objective-c object type. 1093 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1094 llvm::DIFile Unit) { 1095 // Ignore protocols. 1096 return getOrCreateType(Ty->getBaseType(), Unit); 1097 } 1098 1099 /// CreateType - get objective-c interface type. 1100 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1101 llvm::DIFile Unit) { 1102 ObjCInterfaceDecl *ID = Ty->getDecl(); 1103 if (!ID) 1104 return llvm::DIType(); 1105 1106 // Get overall information about the record type for the debug info. 1107 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1108 unsigned Line = getLineNumber(ID->getLocation()); 1109 unsigned RuntimeLang = TheCU.getLanguage(); 1110 1111 // If this is just a forward declaration, return a special forward-declaration 1112 // debug type. 1113 if (ID->isForwardDecl()) { 1114 llvm::DIType FwdDecl = 1115 DBuilder.createStructType(Unit, ID->getName(), 1116 DefUnit, Line, 0, 0, 0, 1117 llvm::DIArray(), RuntimeLang); 1118 return FwdDecl; 1119 } 1120 1121 // To handle recursive interface, we 1122 // first generate a debug descriptor for the struct as a forward declaration. 1123 // Then (if it is a definition) we go through and get debug info for all of 1124 // its members. Finally, we create a descriptor for the complete type (which 1125 // may refer to the forward decl if the struct is recursive) and replace all 1126 // uses of the forward declaration with the final definition. 1127 llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit); 1128 1129 llvm::MDNode *MN = FwdDecl; 1130 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1131 // Otherwise, insert it into the TypeCache so that recursive uses will find 1132 // it. 1133 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1134 // Push the struct on region stack. 1135 RegionStack.push_back(FwdDeclNode); 1136 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1137 1138 // Convert all the elements. 1139 llvm::SmallVector<llvm::Value *, 16> EltTys; 1140 1141 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1142 if (SClass) { 1143 llvm::DIType SClassTy = 1144 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1145 if (!SClassTy.isValid()) 1146 return llvm::DIType(); 1147 1148 llvm::DIType InhTag = 1149 DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0); 1150 EltTys.push_back(InhTag); 1151 } 1152 1153 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1154 1155 unsigned FieldNo = 0; 1156 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1157 Field = Field->getNextIvar(), ++FieldNo) { 1158 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1159 if (!FieldTy.isValid()) 1160 return llvm::DIType(); 1161 1162 llvm::StringRef FieldName = Field->getName(); 1163 1164 // Ignore unnamed fields. 1165 if (FieldName.empty()) 1166 continue; 1167 1168 // Get the location for the field. 1169 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1170 unsigned FieldLine = getLineNumber(Field->getLocation()); 1171 QualType FType = Field->getType(); 1172 uint64_t FieldSize = 0; 1173 unsigned FieldAlign = 0; 1174 1175 if (!FType->isIncompleteArrayType()) { 1176 1177 // Bit size, align and offset of the type. 1178 FieldSize = CGM.getContext().getTypeSize(FType); 1179 Expr *BitWidth = Field->getBitWidth(); 1180 if (BitWidth) 1181 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue(); 1182 1183 FieldAlign = CGM.getContext().getTypeAlign(FType); 1184 } 1185 1186 uint64_t FieldOffset = RL.getFieldOffset(FieldNo); 1187 1188 unsigned Flags = 0; 1189 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1190 Flags = llvm::DIDescriptor::FlagProtected; 1191 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1192 Flags = llvm::DIDescriptor::FlagPrivate; 1193 1194 FieldTy = DBuilder.createMemberType(FieldName, FieldDefUnit, 1195 FieldLine, FieldSize, FieldAlign, 1196 FieldOffset, Flags, FieldTy); 1197 EltTys.push_back(FieldTy); 1198 } 1199 1200 llvm::DIArray Elements = 1201 DBuilder.getOrCreateArray(EltTys.data(), EltTys.size()); 1202 1203 RegionStack.pop_back(); 1204 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1205 RegionMap.find(Ty->getDecl()); 1206 if (RI != RegionMap.end()) 1207 RegionMap.erase(RI); 1208 1209 // Bit size, align and offset of the type. 1210 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1211 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1212 1213 llvm::DIType RealDecl = 1214 DBuilder.createStructType(Unit, ID->getName(), DefUnit, 1215 Line, Size, Align, 0, 1216 Elements, RuntimeLang); 1217 1218 // Now that we have a real decl for the struct, replace anything using the 1219 // old decl with the new one. This will recursively update the debug info. 1220 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1221 RegionMap[ID] = llvm::WeakVH(RealDecl); 1222 1223 return RealDecl; 1224 } 1225 1226 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) { 1227 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) 1228 return CreateType(RT); 1229 else if (const EnumType *ET = dyn_cast<EnumType>(Ty)) 1230 return CreateEnumType(ET->getDecl()); 1231 1232 return llvm::DIType(); 1233 } 1234 1235 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, 1236 llvm::DIFile Unit) { 1237 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1238 int64_t NumElems = Ty->getNumElements(); 1239 int64_t LowerBound = 0; 1240 if (NumElems == 0) 1241 // If number of elements are not known then this is an unbounded array. 1242 // Use Low = 1, Hi = 0 to express such arrays. 1243 LowerBound = 1; 1244 else 1245 --NumElems; 1246 1247 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems); 1248 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(&Subscript, 1); 1249 1250 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1251 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1252 1253 return 1254 DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1255 } 1256 1257 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1258 llvm::DIFile Unit) { 1259 uint64_t Size; 1260 uint64_t Align; 1261 1262 1263 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1264 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1265 Size = 0; 1266 Align = 1267 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1268 } else if (Ty->isIncompleteArrayType()) { 1269 Size = 0; 1270 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1271 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) { 1272 Size = 0; 1273 Align = 0; 1274 } else { 1275 // Size and align of the whole array, not the element type. 1276 Size = CGM.getContext().getTypeSize(Ty); 1277 Align = CGM.getContext().getTypeAlign(Ty); 1278 } 1279 1280 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1281 // interior arrays, do we care? Why aren't nested arrays represented the 1282 // obvious/recursive way? 1283 llvm::SmallVector<llvm::Value *, 8> Subscripts; 1284 QualType EltTy(Ty, 0); 1285 if (Ty->isIncompleteArrayType()) 1286 EltTy = Ty->getElementType(); 1287 else { 1288 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1289 int64_t UpperBound = 0; 1290 int64_t LowerBound = 0; 1291 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) { 1292 if (CAT->getSize().getZExtValue()) 1293 UpperBound = CAT->getSize().getZExtValue() - 1; 1294 } else 1295 // This is an unbounded array. Use Low = 1, Hi = 0 to express such 1296 // arrays. 1297 LowerBound = 1; 1298 1299 // FIXME: Verify this is right for VLAs. 1300 Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, UpperBound)); 1301 EltTy = Ty->getElementType(); 1302 } 1303 } 1304 1305 llvm::DIArray SubscriptArray = 1306 DBuilder.getOrCreateArray(Subscripts.data(), Subscripts.size()); 1307 1308 llvm::DIType DbgTy = 1309 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1310 SubscriptArray); 1311 return DbgTy; 1312 } 1313 1314 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1315 llvm::DIFile Unit) { 1316 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1317 Ty, Ty->getPointeeType(), Unit); 1318 } 1319 1320 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1321 llvm::DIFile Unit) { 1322 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 1323 Ty, Ty->getPointeeType(), Unit); 1324 } 1325 1326 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1327 llvm::DIFile U) { 1328 QualType PointerDiffTy = CGM.getContext().getPointerDiffType(); 1329 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U); 1330 1331 if (!Ty->getPointeeType()->isFunctionType()) { 1332 // We have a data member pointer type. 1333 return PointerDiffDITy; 1334 } 1335 1336 // We have a member function pointer type. Treat it as a struct with two 1337 // ptrdiff_t members. 1338 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty); 1339 1340 uint64_t FieldOffset = 0; 1341 llvm::Value *ElementTypes[2]; 1342 1343 // FIXME: This should probably be a function type instead. 1344 ElementTypes[0] = 1345 DBuilder.createMemberType("ptr", U, 0, 1346 Info.first, Info.second, FieldOffset, 0, 1347 PointerDiffDITy); 1348 FieldOffset += Info.first; 1349 1350 ElementTypes[1] = 1351 DBuilder.createMemberType("ptr", U, 0, 1352 Info.first, Info.second, FieldOffset, 0, 1353 PointerDiffDITy); 1354 1355 llvm::DIArray Elements = 1356 DBuilder.getOrCreateArray(&ElementTypes[0], 1357 llvm::array_lengthof(ElementTypes)); 1358 1359 return DBuilder.createStructType(U, llvm::StringRef("test"), 1360 U, 0, FieldOffset, 1361 0, 0, Elements); 1362 } 1363 1364 /// CreateEnumType - get enumeration type. 1365 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) { 1366 llvm::DIFile Unit = getOrCreateFile(ED->getLocation()); 1367 llvm::SmallVector<llvm::Value *, 16> Enumerators; 1368 1369 // Create DIEnumerator elements for each enumerator. 1370 for (EnumDecl::enumerator_iterator 1371 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1372 Enum != EnumEnd; ++Enum) { 1373 Enumerators.push_back( 1374 DBuilder.createEnumerator(Enum->getName(), 1375 Enum->getInitVal().getZExtValue())); 1376 } 1377 1378 // Return a CompositeType for the enum itself. 1379 llvm::DIArray EltArray = 1380 DBuilder.getOrCreateArray(Enumerators.data(), Enumerators.size()); 1381 1382 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1383 unsigned Line = getLineNumber(ED->getLocation()); 1384 uint64_t Size = 0; 1385 uint64_t Align = 0; 1386 if (!ED->getTypeForDecl()->isIncompleteType()) { 1387 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1388 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1389 } 1390 llvm::DIDescriptor EnumContext = 1391 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1392 llvm::DIType DbgTy = 1393 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 1394 Size, Align, EltArray); 1395 return DbgTy; 1396 } 1397 1398 static QualType UnwrapTypeForDebugInfo(QualType T) { 1399 do { 1400 QualType LastT = T; 1401 switch (T->getTypeClass()) { 1402 default: 1403 return T; 1404 case Type::TemplateSpecialization: 1405 T = cast<TemplateSpecializationType>(T)->desugar(); 1406 break; 1407 case Type::TypeOfExpr: 1408 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1409 break; 1410 case Type::TypeOf: 1411 T = cast<TypeOfType>(T)->getUnderlyingType(); 1412 break; 1413 case Type::Decltype: 1414 T = cast<DecltypeType>(T)->getUnderlyingType(); 1415 break; 1416 case Type::Attributed: 1417 T = cast<AttributedType>(T)->getEquivalentType(); 1418 break; 1419 case Type::Elaborated: 1420 T = cast<ElaboratedType>(T)->getNamedType(); 1421 break; 1422 case Type::Paren: 1423 T = cast<ParenType>(T)->getInnerType(); 1424 break; 1425 case Type::SubstTemplateTypeParm: 1426 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1427 break; 1428 case Type::Auto: 1429 T = cast<AutoType>(T)->getDeducedType(); 1430 break; 1431 } 1432 1433 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1434 if (T == LastT) 1435 return T; 1436 } while (true); 1437 1438 return T; 1439 } 1440 1441 /// getOrCreateType - Get the type from the cache or create a new 1442 /// one if necessary. 1443 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, 1444 llvm::DIFile Unit) { 1445 if (Ty.isNull()) 1446 return llvm::DIType(); 1447 1448 // Unwrap the type as needed for debug information. 1449 Ty = UnwrapTypeForDebugInfo(Ty); 1450 1451 // Check for existing entry. 1452 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1453 TypeCache.find(Ty.getAsOpaquePtr()); 1454 if (it != TypeCache.end()) { 1455 // Verify that the debug info still exists. 1456 if (&*it->second) 1457 return llvm::DIType(cast<llvm::MDNode>(it->second)); 1458 } 1459 1460 // Otherwise create the type. 1461 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1462 1463 // And update the type cache. 1464 TypeCache[Ty.getAsOpaquePtr()] = Res; 1465 return Res; 1466 } 1467 1468 /// CreateTypeNode - Create a new debug type node. 1469 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, 1470 llvm::DIFile Unit) { 1471 // Handle qualifiers, which recursively handles what they refer to. 1472 if (Ty.hasLocalQualifiers()) 1473 return CreateQualifiedType(Ty, Unit); 1474 1475 const char *Diag = 0; 1476 1477 // Work out details of type. 1478 switch (Ty->getTypeClass()) { 1479 #define TYPE(Class, Base) 1480 #define ABSTRACT_TYPE(Class, Base) 1481 #define NON_CANONICAL_TYPE(Class, Base) 1482 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1483 #include "clang/AST/TypeNodes.def" 1484 assert(false && "Dependent types cannot show up in debug information"); 1485 1486 // FIXME: Handle these. 1487 case Type::ExtVector: 1488 return llvm::DIType(); 1489 1490 case Type::Vector: 1491 return CreateType(cast<VectorType>(Ty), Unit); 1492 case Type::ObjCObjectPointer: 1493 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 1494 case Type::ObjCObject: 1495 return CreateType(cast<ObjCObjectType>(Ty), Unit); 1496 case Type::ObjCInterface: 1497 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 1498 case Type::Builtin: return CreateType(cast<BuiltinType>(Ty)); 1499 case Type::Complex: return CreateType(cast<ComplexType>(Ty)); 1500 case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit); 1501 case Type::BlockPointer: 1502 return CreateType(cast<BlockPointerType>(Ty), Unit); 1503 case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit); 1504 case Type::Record: 1505 case Type::Enum: 1506 return CreateType(cast<TagType>(Ty)); 1507 case Type::FunctionProto: 1508 case Type::FunctionNoProto: 1509 return CreateType(cast<FunctionType>(Ty), Unit); 1510 case Type::ConstantArray: 1511 case Type::VariableArray: 1512 case Type::IncompleteArray: 1513 return CreateType(cast<ArrayType>(Ty), Unit); 1514 1515 case Type::LValueReference: 1516 return CreateType(cast<LValueReferenceType>(Ty), Unit); 1517 case Type::RValueReference: 1518 return CreateType(cast<RValueReferenceType>(Ty), Unit); 1519 1520 case Type::MemberPointer: 1521 return CreateType(cast<MemberPointerType>(Ty), Unit); 1522 1523 case Type::Attributed: 1524 case Type::TemplateSpecialization: 1525 case Type::Elaborated: 1526 case Type::Paren: 1527 case Type::SubstTemplateTypeParm: 1528 case Type::TypeOfExpr: 1529 case Type::TypeOf: 1530 case Type::Decltype: 1531 case Type::Auto: 1532 llvm_unreachable("type should have been unwrapped!"); 1533 return llvm::DIType(); 1534 } 1535 1536 assert(Diag && "Fall through without a diagnostic?"); 1537 unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error, 1538 "debug information for %0 is not yet supported"); 1539 CGM.getDiags().Report(DiagID) 1540 << Diag; 1541 return llvm::DIType(); 1542 } 1543 1544 /// CreateMemberType - Create new member and increase Offset by FType's size. 1545 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 1546 llvm::StringRef Name, 1547 uint64_t *Offset) { 1548 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1549 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 1550 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 1551 llvm::DIType Ty = DBuilder.createMemberType(Name, Unit, 0, 1552 FieldSize, FieldAlign, 1553 *Offset, 0, FieldTy); 1554 *Offset += FieldSize; 1555 return Ty; 1556 } 1557 1558 /// EmitFunctionStart - Constructs the debug code for entering a function - 1559 /// "llvm.dbg.func.start.". 1560 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 1561 llvm::Function *Fn, 1562 CGBuilderTy &Builder) { 1563 1564 llvm::StringRef Name; 1565 llvm::StringRef LinkageName; 1566 1567 FnBeginRegionCount.push_back(RegionStack.size()); 1568 1569 const Decl *D = GD.getDecl(); 1570 1571 unsigned Flags = 0; 1572 llvm::DIFile Unit = getOrCreateFile(CurLoc); 1573 llvm::DIDescriptor FDContext(Unit); 1574 llvm::DIArray TParamsArray; 1575 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1576 // If there is a DISubprogram for this function available then use it. 1577 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 1578 FI = SPCache.find(FD); 1579 if (FI != SPCache.end()) { 1580 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second)); 1581 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 1582 llvm::MDNode *SPN = SP; 1583 RegionStack.push_back(SPN); 1584 RegionMap[D] = llvm::WeakVH(SP); 1585 return; 1586 } 1587 } 1588 Name = getFunctionName(FD); 1589 // Use mangled name as linkage name for c/c++ functions. 1590 LinkageName = CGM.getMangledName(GD); 1591 if (LinkageName == Name) 1592 LinkageName = llvm::StringRef(); 1593 if (FD->hasPrototype()) 1594 Flags |= llvm::DIDescriptor::FlagPrototyped; 1595 if (const NamespaceDecl *NSDecl = 1596 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 1597 FDContext = getOrCreateNameSpace(NSDecl); 1598 1599 // Collect template parameters. 1600 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 1601 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 1602 Name = getObjCMethodName(OMD); 1603 Flags |= llvm::DIDescriptor::FlagPrototyped; 1604 } else { 1605 // Use llvm function name. 1606 Name = Fn->getName(); 1607 Flags |= llvm::DIDescriptor::FlagPrototyped; 1608 } 1609 if (!Name.empty() && Name[0] == '\01') 1610 Name = Name.substr(1); 1611 1612 // It is expected that CurLoc is set before using EmitFunctionStart. 1613 // Usually, CurLoc points to the left bracket location of compound 1614 // statement representing function body. 1615 unsigned LineNo = getLineNumber(CurLoc); 1616 if (D->isImplicit()) 1617 Flags |= llvm::DIDescriptor::FlagArtificial; 1618 llvm::DISubprogram SP = 1619 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, 1620 LineNo, getOrCreateType(FnType, Unit), 1621 Fn->hasInternalLinkage(), true/*definition*/, 1622 Flags, CGM.getLangOptions().Optimize, Fn, 1623 TParamsArray); 1624 1625 // Push function on region stack. 1626 llvm::MDNode *SPN = SP; 1627 RegionStack.push_back(SPN); 1628 RegionMap[D] = llvm::WeakVH(SP); 1629 1630 // Clear stack used to keep track of #line directives. 1631 LineDirectiveFiles.clear(); 1632 } 1633 1634 1635 void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) { 1636 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 1637 1638 // Don't bother if things are the same as last time. 1639 SourceManager &SM = CGM.getContext().getSourceManager(); 1640 if (CurLoc == PrevLoc 1641 || (SM.getInstantiationLineNumber(CurLoc) == 1642 SM.getInstantiationLineNumber(PrevLoc) 1643 && SM.isFromSameFile(CurLoc, PrevLoc))) 1644 // New Builder may not be in sync with CGDebugInfo. 1645 if (!Builder.getCurrentDebugLocation().isUnknown()) 1646 return; 1647 1648 // Update last state. 1649 PrevLoc = CurLoc; 1650 1651 llvm::MDNode *Scope = RegionStack.back(); 1652 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc), 1653 getColumnNumber(CurLoc), 1654 Scope)); 1655 } 1656 1657 /// UpdateLineDirectiveRegion - Update region stack only if #line directive 1658 /// has introduced scope change. 1659 void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) { 1660 if (CurLoc.isInvalid() || CurLoc.isMacroID() || 1661 PrevLoc.isInvalid() || PrevLoc.isMacroID()) 1662 return; 1663 SourceManager &SM = CGM.getContext().getSourceManager(); 1664 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 1665 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc); 1666 1667 if (PCLoc.isInvalid() || PPLoc.isInvalid() || 1668 !strcmp(PPLoc.getFilename(), PCLoc.getFilename())) 1669 return; 1670 1671 // If #line directive stack is empty then we are entering a new scope. 1672 if (LineDirectiveFiles.empty()) { 1673 EmitRegionStart(Builder); 1674 LineDirectiveFiles.push_back(PCLoc.getFilename()); 1675 return; 1676 } 1677 1678 assert (RegionStack.size() >= LineDirectiveFiles.size() 1679 && "error handling #line regions!"); 1680 1681 bool SeenThisFile = false; 1682 // Chek if current file is already seen earlier. 1683 for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(), 1684 E = LineDirectiveFiles.end(); I != E; ++I) 1685 if (!strcmp(PCLoc.getFilename(), *I)) { 1686 SeenThisFile = true; 1687 break; 1688 } 1689 1690 // If #line for this file is seen earlier then pop out #line regions. 1691 if (SeenThisFile) { 1692 while (!LineDirectiveFiles.empty()) { 1693 const char *LastFile = LineDirectiveFiles.back(); 1694 RegionStack.pop_back(); 1695 LineDirectiveFiles.pop_back(); 1696 if (!strcmp(PPLoc.getFilename(), LastFile)) 1697 break; 1698 } 1699 return; 1700 } 1701 1702 // .. otherwise insert new #line region. 1703 EmitRegionStart(Builder); 1704 LineDirectiveFiles.push_back(PCLoc.getFilename()); 1705 1706 return; 1707 } 1708 /// EmitRegionStart- Constructs the debug code for entering a declarative 1709 /// region - "llvm.dbg.region.start.". 1710 void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) { 1711 llvm::DIDescriptor D = 1712 DBuilder.createLexicalBlock(RegionStack.empty() ? 1713 llvm::DIDescriptor() : 1714 llvm::DIDescriptor(RegionStack.back()), 1715 getOrCreateFile(CurLoc), 1716 getLineNumber(CurLoc), 1717 getColumnNumber(CurLoc)); 1718 llvm::MDNode *DN = D; 1719 RegionStack.push_back(DN); 1720 } 1721 1722 /// EmitRegionEnd - Constructs the debug code for exiting a declarative 1723 /// region - "llvm.dbg.region.end." 1724 void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) { 1725 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1726 1727 // Provide an region stop point. 1728 EmitStopPoint(Builder); 1729 1730 RegionStack.pop_back(); 1731 } 1732 1733 /// EmitFunctionEnd - Constructs the debug code for exiting a function. 1734 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 1735 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1736 unsigned RCount = FnBeginRegionCount.back(); 1737 assert(RCount <= RegionStack.size() && "Region stack mismatch"); 1738 1739 // Pop all regions for this function. 1740 while (RegionStack.size() != RCount) 1741 EmitRegionEnd(Builder); 1742 FnBeginRegionCount.pop_back(); 1743 } 1744 1745 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 1746 // See BuildByRefType. 1747 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD, 1748 uint64_t *XOffset) { 1749 1750 llvm::SmallVector<llvm::Value *, 5> EltTys; 1751 QualType FType; 1752 uint64_t FieldSize, FieldOffset; 1753 unsigned FieldAlign; 1754 1755 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1756 QualType Type = VD->getType(); 1757 1758 FieldOffset = 0; 1759 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1760 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 1761 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 1762 FType = CGM.getContext().IntTy; 1763 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 1764 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 1765 1766 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type); 1767 if (HasCopyAndDispose) { 1768 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1769 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 1770 &FieldOffset)); 1771 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 1772 &FieldOffset)); 1773 } 1774 1775 CharUnits Align = CGM.getContext().getDeclAlign(VD); 1776 if (Align > CharUnits::fromQuantity( 1777 CGM.getContext().Target.getPointerAlign(0) / 8)) { 1778 unsigned AlignedOffsetInBytes 1779 = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity()); 1780 unsigned NumPaddingBytes 1781 = AlignedOffsetInBytes - FieldOffset/8; 1782 1783 if (NumPaddingBytes > 0) { 1784 llvm::APInt pad(32, NumPaddingBytes); 1785 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 1786 pad, ArrayType::Normal, 0); 1787 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 1788 } 1789 } 1790 1791 FType = Type; 1792 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1793 FieldSize = CGM.getContext().getTypeSize(FType); 1794 FieldAlign = Align.getQuantity()*8; 1795 1796 *XOffset = FieldOffset; 1797 FieldTy = DBuilder.createMemberType(VD->getName(), Unit, 1798 0, FieldSize, FieldAlign, 1799 FieldOffset, 0, FieldTy); 1800 EltTys.push_back(FieldTy); 1801 FieldOffset += FieldSize; 1802 1803 llvm::DIArray Elements = 1804 DBuilder.getOrCreateArray(EltTys.data(), EltTys.size()); 1805 1806 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 1807 1808 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 1809 Elements); 1810 } 1811 1812 /// EmitDeclare - Emit local variable declaration debug info. 1813 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 1814 llvm::Value *Storage, 1815 unsigned ArgNo, CGBuilderTy &Builder) { 1816 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1817 1818 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1819 llvm::DIType Ty; 1820 uint64_t XOffset = 0; 1821 if (VD->hasAttr<BlocksAttr>()) 1822 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 1823 else 1824 Ty = getOrCreateType(VD->getType(), Unit); 1825 1826 // If there is not any debug info for type then do not emit debug info 1827 // for this variable. 1828 if (!Ty) 1829 return; 1830 1831 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) { 1832 // If Storage is an aggregate returned as 'sret' then let debugger know 1833 // about this. 1834 if (Arg->hasStructRetAttr()) 1835 Ty = DBuilder.createReferenceType(Ty); 1836 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) { 1837 // If an aggregate variable has non trivial destructor or non trivial copy 1838 // constructor than it is pass indirectly. Let debug info know about this 1839 // by using reference of the aggregate type as a argument type. 1840 if (!Record->hasTrivialCopyConstructor() || !Record->hasTrivialDestructor()) 1841 Ty = DBuilder.createReferenceType(Ty); 1842 } 1843 } 1844 1845 // Get location information. 1846 unsigned Line = getLineNumber(VD->getLocation()); 1847 unsigned Column = getColumnNumber(VD->getLocation()); 1848 unsigned Flags = 0; 1849 if (VD->isImplicit()) 1850 Flags |= llvm::DIDescriptor::FlagArtificial; 1851 llvm::MDNode *Scope = RegionStack.back(); 1852 1853 llvm::StringRef Name = VD->getName(); 1854 if (!Name.empty()) { 1855 if (VD->hasAttr<BlocksAttr>()) { 1856 CharUnits offset = CharUnits::fromQuantity(32); 1857 llvm::SmallVector<llvm::Value *, 9> addr; 1858 const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext()); 1859 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 1860 // offset of __forwarding field 1861 offset = 1862 CharUnits::fromQuantity(CGM.getContext().Target.getPointerWidth(0)/8); 1863 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1864 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 1865 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 1866 // offset of x field 1867 offset = CharUnits::fromQuantity(XOffset/8); 1868 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1869 1870 // Create the descriptor for the variable. 1871 llvm::DIVariable D = 1872 DBuilder.createComplexVariable(Tag, 1873 llvm::DIDescriptor(RegionStack.back()), 1874 VD->getName(), Unit, Line, Ty, 1875 addr.data(), addr.size(), ArgNo); 1876 1877 // Insert an llvm.dbg.declare into the current block. 1878 llvm::Instruction *Call = 1879 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 1880 1881 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1882 return; 1883 } 1884 // Create the descriptor for the variable. 1885 llvm::DIVariable D = 1886 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 1887 Name, Unit, Line, Ty, 1888 CGM.getLangOptions().Optimize, Flags, ArgNo); 1889 1890 // Insert an llvm.dbg.declare into the current block. 1891 llvm::Instruction *Call = 1892 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 1893 1894 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1895 return; 1896 } 1897 1898 // If VD is an anonymous union then Storage represents value for 1899 // all union fields. 1900 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 1901 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1902 if (RD->isUnion()) { 1903 for (RecordDecl::field_iterator I = RD->field_begin(), 1904 E = RD->field_end(); 1905 I != E; ++I) { 1906 FieldDecl *Field = *I; 1907 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1908 llvm::StringRef FieldName = Field->getName(); 1909 1910 // Ignore unnamed fields. Do not ignore unnamed records. 1911 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 1912 continue; 1913 1914 // Use VarDecl's Tag, Scope and Line number. 1915 llvm::DIVariable D = 1916 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 1917 FieldName, Unit, Line, FieldTy, 1918 CGM.getLangOptions().Optimize, Flags, 1919 ArgNo); 1920 1921 // Insert an llvm.dbg.declare into the current block. 1922 llvm::Instruction *Call = 1923 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 1924 1925 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1926 } 1927 } 1928 } 1929 } 1930 1931 /// EmitDeclare - Emit local variable declaration debug info. 1932 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 1933 llvm::Value *Storage, CGBuilderTy &Builder, 1934 const CGBlockInfo &blockInfo) { 1935 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1936 1937 if (Builder.GetInsertBlock() == 0) 1938 return; 1939 1940 bool isByRef = VD->hasAttr<BlocksAttr>(); 1941 1942 uint64_t XOffset = 0; 1943 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1944 llvm::DIType Ty; 1945 if (isByRef) 1946 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 1947 else 1948 Ty = getOrCreateType(VD->getType(), Unit); 1949 1950 // Get location information. 1951 unsigned Line = getLineNumber(VD->getLocation()); 1952 unsigned Column = getColumnNumber(VD->getLocation()); 1953 1954 const llvm::TargetData &target = CGM.getTargetData(); 1955 1956 CharUnits offset = CharUnits::fromQuantity( 1957 target.getStructLayout(blockInfo.StructureType) 1958 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 1959 1960 llvm::SmallVector<llvm::Value *, 9> addr; 1961 const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext()); 1962 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 1963 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1964 if (isByRef) { 1965 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 1966 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 1967 // offset of __forwarding field 1968 offset = CharUnits::fromQuantity(target.getPointerSize()/8); 1969 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1970 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 1971 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 1972 // offset of x field 1973 offset = CharUnits::fromQuantity(XOffset/8); 1974 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1975 } 1976 1977 // Create the descriptor for the variable. 1978 llvm::DIVariable D = 1979 DBuilder.createComplexVariable(Tag, llvm::DIDescriptor(RegionStack.back()), 1980 VD->getName(), Unit, Line, Ty, 1981 addr.data(), addr.size()); 1982 // Insert an llvm.dbg.declare into the current block. 1983 llvm::Instruction *Call = 1984 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 1985 1986 llvm::MDNode *Scope = RegionStack.back(); 1987 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1988 } 1989 1990 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 1991 llvm::Value *Storage, 1992 CGBuilderTy &Builder) { 1993 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 1994 } 1995 1996 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 1997 const VarDecl *variable, llvm::Value *Storage, CGBuilderTy &Builder, 1998 const CGBlockInfo &blockInfo) { 1999 EmitDeclare(variable, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, 2000 blockInfo); 2001 } 2002 2003 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2004 /// variable declaration. 2005 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2006 unsigned ArgNo, 2007 CGBuilderTy &Builder) { 2008 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2009 } 2010 2011 namespace { 2012 struct BlockLayoutChunk { 2013 uint64_t OffsetInBits; 2014 const BlockDecl::Capture *Capture; 2015 }; 2016 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2017 return l.OffsetInBits < r.OffsetInBits; 2018 } 2019 } 2020 2021 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2022 llvm::Value *addr, 2023 CGBuilderTy &Builder) { 2024 ASTContext &C = CGM.getContext(); 2025 const BlockDecl *blockDecl = block.getBlockDecl(); 2026 2027 // Collect some general information about the block's location. 2028 SourceLocation loc = blockDecl->getCaretLocation(); 2029 llvm::DIFile tunit = getOrCreateFile(loc); 2030 unsigned line = getLineNumber(loc); 2031 unsigned column = getColumnNumber(loc); 2032 2033 // Build the debug-info type for the block literal. 2034 llvm::DIDescriptor enclosingContext = 2035 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 2036 2037 const llvm::StructLayout *blockLayout = 2038 CGM.getTargetData().getStructLayout(block.StructureType); 2039 2040 llvm::SmallVector<llvm::Value*, 16> fields; 2041 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 2042 blockLayout->getElementOffsetInBits(0), 2043 tunit)); 2044 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 2045 blockLayout->getElementOffsetInBits(1), 2046 tunit)); 2047 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 2048 blockLayout->getElementOffsetInBits(2), 2049 tunit)); 2050 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public, 2051 blockLayout->getElementOffsetInBits(3), 2052 tunit)); 2053 fields.push_back(createFieldType("__descriptor", 2054 C.getPointerType(block.NeedsCopyDispose ? 2055 C.getBlockDescriptorExtendedType() : 2056 C.getBlockDescriptorType()), 2057 0, loc, AS_public, 2058 blockLayout->getElementOffsetInBits(4), 2059 tunit)); 2060 2061 // We want to sort the captures by offset, not because DWARF 2062 // requires this, but because we're paranoid about debuggers. 2063 llvm::SmallVector<BlockLayoutChunk, 8> chunks; 2064 2065 // 'this' capture. 2066 if (blockDecl->capturesCXXThis()) { 2067 BlockLayoutChunk chunk; 2068 chunk.OffsetInBits = 2069 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 2070 chunk.Capture = 0; 2071 chunks.push_back(chunk); 2072 } 2073 2074 // Variable captures. 2075 for (BlockDecl::capture_const_iterator 2076 i = blockDecl->capture_begin(), e = blockDecl->capture_end(); 2077 i != e; ++i) { 2078 const BlockDecl::Capture &capture = *i; 2079 const VarDecl *variable = capture.getVariable(); 2080 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 2081 2082 // Ignore constant captures. 2083 if (captureInfo.isConstant()) 2084 continue; 2085 2086 BlockLayoutChunk chunk; 2087 chunk.OffsetInBits = 2088 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 2089 chunk.Capture = &capture; 2090 chunks.push_back(chunk); 2091 } 2092 2093 // Sort by offset. 2094 llvm::array_pod_sort(chunks.begin(), chunks.end()); 2095 2096 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator 2097 i = chunks.begin(), e = chunks.end(); i != e; ++i) { 2098 uint64_t offsetInBits = i->OffsetInBits; 2099 const BlockDecl::Capture *capture = i->Capture; 2100 2101 // If we have a null capture, this must be the C++ 'this' capture. 2102 if (!capture) { 2103 const CXXMethodDecl *method = 2104 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 2105 QualType type = method->getThisType(C); 2106 2107 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 2108 offsetInBits, tunit)); 2109 continue; 2110 } 2111 2112 const VarDecl *variable = capture->getVariable(); 2113 llvm::StringRef name = variable->getName(); 2114 2115 llvm::DIType fieldType; 2116 if (capture->isByRef()) { 2117 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy); 2118 2119 // FIXME: this creates a second copy of this type! 2120 uint64_t xoffset; 2121 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 2122 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first); 2123 fieldType = DBuilder.createMemberType(name, tunit, line, 2124 ptrInfo.first, ptrInfo.second, 2125 offsetInBits, 0, fieldType); 2126 } else { 2127 fieldType = createFieldType(name, variable->getType(), 0, 2128 loc, AS_public, offsetInBits, tunit); 2129 } 2130 fields.push_back(fieldType); 2131 } 2132 2133 llvm::SmallString<36> typeName; 2134 llvm::raw_svector_ostream(typeName) 2135 << "__block_literal_" << CGM.getUniqueBlockCount(); 2136 2137 llvm::DIArray fieldsArray = 2138 DBuilder.getOrCreateArray(fields.data(), fields.size()); 2139 2140 llvm::DIType type = 2141 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 2142 CGM.getContext().toBits(block.BlockSize), 2143 CGM.getContext().toBits(block.BlockAlign), 2144 0, fieldsArray); 2145 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 2146 2147 // Get overall information about the block. 2148 unsigned flags = llvm::DIDescriptor::FlagArtificial; 2149 llvm::MDNode *scope = RegionStack.back(); 2150 llvm::StringRef name = ".block_descriptor"; 2151 2152 // Create the descriptor for the parameter. 2153 llvm::DIVariable debugVar = 2154 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable, 2155 llvm::DIDescriptor(scope), 2156 name, tunit, line, type, 2157 CGM.getLangOptions().Optimize, flags, 2158 cast<llvm::Argument>(addr)->getArgNo() + 1); 2159 2160 // Insert an llvm.dbg.value into the current block. 2161 llvm::Instruction *declare = 2162 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar, 2163 Builder.GetInsertBlock()); 2164 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2165 } 2166 2167 /// EmitGlobalVariable - Emit information about a global variable. 2168 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2169 const VarDecl *D) { 2170 2171 // Create global variable debug descriptor. 2172 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 2173 unsigned LineNo = getLineNumber(D->getLocation()); 2174 2175 QualType T = D->getType(); 2176 if (T->isIncompleteArrayType()) { 2177 2178 // CodeGen turns int[] into int[1] so we'll do the same here. 2179 llvm::APSInt ConstVal(32); 2180 2181 ConstVal = 1; 2182 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2183 2184 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2185 ArrayType::Normal, 0); 2186 } 2187 llvm::StringRef DeclName = D->getName(); 2188 llvm::StringRef LinkageName; 2189 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) 2190 && !isa<ObjCMethodDecl>(D->getDeclContext())) 2191 LinkageName = Var->getName(); 2192 if (LinkageName == DeclName) 2193 LinkageName = llvm::StringRef(); 2194 llvm::DIDescriptor DContext = 2195 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext())); 2196 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, 2197 Unit, LineNo, getOrCreateType(T, Unit), 2198 Var->hasInternalLinkage(), Var); 2199 } 2200 2201 /// EmitGlobalVariable - Emit information about an objective-c interface. 2202 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2203 ObjCInterfaceDecl *ID) { 2204 // Create global variable debug descriptor. 2205 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 2206 unsigned LineNo = getLineNumber(ID->getLocation()); 2207 2208 llvm::StringRef Name = ID->getName(); 2209 2210 QualType T = CGM.getContext().getObjCInterfaceType(ID); 2211 if (T->isIncompleteArrayType()) { 2212 2213 // CodeGen turns int[] into int[1] so we'll do the same here. 2214 llvm::APSInt ConstVal(32); 2215 2216 ConstVal = 1; 2217 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2218 2219 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2220 ArrayType::Normal, 0); 2221 } 2222 2223 DBuilder.createGlobalVariable(Name, Unit, LineNo, 2224 getOrCreateType(T, Unit), 2225 Var->hasInternalLinkage(), Var); 2226 } 2227 2228 /// EmitGlobalVariable - Emit global variable's debug info. 2229 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 2230 llvm::Constant *Init) { 2231 // Create the descriptor for the variable. 2232 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2233 llvm::StringRef Name = VD->getName(); 2234 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 2235 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 2236 if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) 2237 Ty = CreateEnumType(ED); 2238 } 2239 // Do not use DIGlobalVariable for enums. 2240 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 2241 return; 2242 DBuilder.createStaticVariable(Unit, Name, Name, Unit, 2243 getLineNumber(VD->getLocation()), 2244 Ty, true, Init); 2245 } 2246 2247 /// getOrCreateNamesSpace - Return namespace descriptor for the given 2248 /// namespace decl. 2249 llvm::DINameSpace 2250 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 2251 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 2252 NameSpaceCache.find(NSDecl); 2253 if (I != NameSpaceCache.end()) 2254 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 2255 2256 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 2257 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 2258 llvm::DIDescriptor Context = 2259 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 2260 llvm::DINameSpace NS = 2261 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 2262 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 2263 return NS; 2264 } 2265 2266 /// UpdateCompletedType - Update type cache because the type is now 2267 /// translated. 2268 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) { 2269 QualType Ty = CGM.getContext().getTagDeclType(TD); 2270 2271 // If the type exist in type cache then remove it from the cache. 2272 // There is no need to prepare debug info for the completed type 2273 // right now. It will be generated on demand lazily. 2274 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2275 TypeCache.find(Ty.getAsOpaquePtr()); 2276 if (it != TypeCache.end()) 2277 TypeCache.erase(it); 2278 } 2279