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