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 "CGBlocks.h" 16 #include "CGObjCRuntime.h" 17 #include "CodeGenFunction.h" 18 #include "CodeGenModule.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/DeclFriend.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/Basic/FileManager.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/Version.h" 28 #include "clang/Frontend/CodeGenOptions.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/IR/Constants.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/Support/Dwarf.h" 38 #include "llvm/Support/FileSystem.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() || Scope.isSubprogram()) { 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::DIScope 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 llvm::Value *V = I->second; 100 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V)); 101 } 102 103 // Check namespace. 104 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 105 return getOrCreateNameSpace(NSDecl); 106 107 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) 108 if (!RDecl->isDependentType()) 109 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 110 getOrCreateMainFile()); 111 return TheCU; 112 } 113 114 /// getFunctionName - Get function name for the given FunctionDecl. If the 115 /// name is constructred on demand (e.g. C++ destructor) then the name 116 /// is stored on the side. 117 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 118 assert (FD && "Invalid FunctionDecl!"); 119 IdentifierInfo *FII = FD->getIdentifier(); 120 FunctionTemplateSpecializationInfo *Info 121 = FD->getTemplateSpecializationInfo(); 122 if (!Info && FII) 123 return FII->getName(); 124 125 // Otherwise construct human readable name for debug info. 126 SmallString<128> NS; 127 llvm::raw_svector_ostream OS(NS); 128 FD->printName(OS); 129 130 // Add any template specialization args. 131 if (Info) { 132 const TemplateArgumentList *TArgs = Info->TemplateArguments; 133 const TemplateArgument *Args = TArgs->data(); 134 unsigned NumArgs = TArgs->size(); 135 PrintingPolicy Policy(CGM.getLangOpts()); 136 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs, 137 Policy); 138 } 139 140 // Copy this name on the side and use its reference. 141 OS.flush(); 142 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size()); 143 memcpy(StrPtr, NS.data(), NS.size()); 144 return StringRef(StrPtr, NS.size()); 145 } 146 147 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 148 SmallString<256> MethodName; 149 llvm::raw_svector_ostream OS(MethodName); 150 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 151 const DeclContext *DC = OMD->getDeclContext(); 152 if (const ObjCImplementationDecl *OID = 153 dyn_cast<const ObjCImplementationDecl>(DC)) { 154 OS << OID->getName(); 155 } else if (const ObjCInterfaceDecl *OID = 156 dyn_cast<const ObjCInterfaceDecl>(DC)) { 157 OS << OID->getName(); 158 } else if (const ObjCCategoryImplDecl *OCD = 159 dyn_cast<const ObjCCategoryImplDecl>(DC)){ 160 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' << 161 OCD->getIdentifier()->getNameStart() << ')'; 162 } 163 OS << ' ' << OMD->getSelector().getAsString() << ']'; 164 165 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell()); 166 memcpy(StrPtr, MethodName.begin(), OS.tell()); 167 return StringRef(StrPtr, OS.tell()); 168 } 169 170 /// getSelectorName - Return selector name. This is used for debugging 171 /// info. 172 StringRef CGDebugInfo::getSelectorName(Selector S) { 173 const std::string &SName = S.getAsString(); 174 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size()); 175 memcpy(StrPtr, SName.data(), SName.size()); 176 return StringRef(StrPtr, SName.size()); 177 } 178 179 /// getClassName - Get class name including template argument list. 180 StringRef 181 CGDebugInfo::getClassName(const RecordDecl *RD) { 182 const ClassTemplateSpecializationDecl *Spec 183 = dyn_cast<ClassTemplateSpecializationDecl>(RD); 184 if (!Spec) 185 return RD->getName(); 186 187 const TemplateArgument *Args; 188 unsigned NumArgs; 189 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) { 190 const TemplateSpecializationType *TST = 191 cast<TemplateSpecializationType>(TAW->getType()); 192 Args = TST->getArgs(); 193 NumArgs = TST->getNumArgs(); 194 } else { 195 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 196 Args = TemplateArgs.data(); 197 NumArgs = TemplateArgs.size(); 198 } 199 StringRef Name = RD->getIdentifier()->getName(); 200 PrintingPolicy Policy(CGM.getLangOpts()); 201 SmallString<128> TemplateArgList; 202 { 203 llvm::raw_svector_ostream OS(TemplateArgList); 204 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs, 205 Policy); 206 } 207 208 // Copy this name on the side and use its reference. 209 size_t Length = Name.size() + TemplateArgList.size(); 210 char *StrPtr = DebugInfoNames.Allocate<char>(Length); 211 memcpy(StrPtr, Name.data(), Name.size()); 212 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size()); 213 return StringRef(StrPtr, Length); 214 } 215 216 /// getOrCreateFile - Get the file debug info descriptor for the input location. 217 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 218 if (!Loc.isValid()) 219 // If Location is not valid then use main input file. 220 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 221 222 SourceManager &SM = CGM.getContext().getSourceManager(); 223 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 224 225 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty()) 226 // If the location is not valid then use main input file. 227 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 228 229 // Cache the results. 230 const char *fname = PLoc.getFilename(); 231 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it = 232 DIFileCache.find(fname); 233 234 if (it != DIFileCache.end()) { 235 // Verify that the information still exists. 236 if (llvm::Value *V = it->second) 237 return llvm::DIFile(cast<llvm::MDNode>(V)); 238 } 239 240 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname()); 241 242 DIFileCache[fname] = F; 243 return F; 244 } 245 246 /// getOrCreateMainFile - Get the file info for main compile unit. 247 llvm::DIFile CGDebugInfo::getOrCreateMainFile() { 248 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 249 } 250 251 /// getLineNumber - Get line number for the location. If location is invalid 252 /// then use current location. 253 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 254 if (Loc.isInvalid() && CurLoc.isInvalid()) 255 return 0; 256 SourceManager &SM = CGM.getContext().getSourceManager(); 257 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 258 return PLoc.isValid()? PLoc.getLine() : 0; 259 } 260 261 /// getColumnNumber - Get column number for the location. 262 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { 263 // We may not want column information at all. 264 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) 265 return 0; 266 267 // If the location is invalid then use the current column. 268 if (Loc.isInvalid() && CurLoc.isInvalid()) 269 return 0; 270 SourceManager &SM = CGM.getContext().getSourceManager(); 271 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 272 return PLoc.isValid()? PLoc.getColumn() : 0; 273 } 274 275 StringRef CGDebugInfo::getCurrentDirname() { 276 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) 277 return CGM.getCodeGenOpts().DebugCompilationDir; 278 279 if (!CWDName.empty()) 280 return CWDName; 281 SmallString<256> CWD; 282 llvm::sys::fs::current_path(CWD); 283 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size()); 284 memcpy(CompDirnamePtr, CWD.data(), CWD.size()); 285 return CWDName = StringRef(CompDirnamePtr, CWD.size()); 286 } 287 288 /// CreateCompileUnit - Create new compile unit. 289 void CGDebugInfo::CreateCompileUnit() { 290 291 // Get absolute path name. 292 SourceManager &SM = CGM.getContext().getSourceManager(); 293 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 294 if (MainFileName.empty()) 295 MainFileName = "<unknown>"; 296 297 // The main file name provided via the "-main-file-name" option contains just 298 // the file name itself with no path information. This file name may have had 299 // a relative path, so we look into the actual file entry for the main 300 // file to determine the real absolute path for the file. 301 std::string MainFileDir; 302 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 303 MainFileDir = MainFile->getDir()->getName(); 304 if (MainFileDir != ".") 305 MainFileName = MainFileDir + "/" + MainFileName; 306 } 307 308 // Save filename string. 309 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length()); 310 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length()); 311 StringRef Filename(FilenamePtr, MainFileName.length()); 312 313 // Save split dwarf file string. 314 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile; 315 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length()); 316 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length()); 317 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length()); 318 319 unsigned LangTag; 320 const LangOptions &LO = CGM.getLangOpts(); 321 if (LO.CPlusPlus) { 322 if (LO.ObjC1) 323 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 324 else 325 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 326 } else if (LO.ObjC1) { 327 LangTag = llvm::dwarf::DW_LANG_ObjC; 328 } else if (LO.C99) { 329 LangTag = llvm::dwarf::DW_LANG_C99; 330 } else { 331 LangTag = llvm::dwarf::DW_LANG_C89; 332 } 333 334 std::string Producer = getClangFullVersion(); 335 336 // Figure out which version of the ObjC runtime we have. 337 unsigned RuntimeVers = 0; 338 if (LO.ObjC1) 339 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; 340 341 // Create new compile unit. 342 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(), 343 Producer, LO.Optimize, 344 CGM.getCodeGenOpts().DwarfDebugFlags, 345 RuntimeVers, SplitDwarfFilename); 346 // FIXME - Eliminate TheCU. 347 TheCU = llvm::DICompileUnit(DBuilder.getCU()); 348 } 349 350 /// CreateType - Get the Basic type from the cache or create a new 351 /// one if necessary. 352 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) { 353 unsigned Encoding = 0; 354 StringRef BTName; 355 switch (BT->getKind()) { 356 #define BUILTIN_TYPE(Id, SingletonId) 357 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 358 case BuiltinType::Id: 359 #include "clang/AST/BuiltinTypes.def" 360 case BuiltinType::Dependent: 361 llvm_unreachable("Unexpected builtin type"); 362 case BuiltinType::NullPtr: 363 return DBuilder. 364 createNullPtrType(BT->getName(CGM.getLangOpts())); 365 case BuiltinType::Void: 366 return llvm::DIType(); 367 case BuiltinType::ObjCClass: 368 if (ClassTy.Verify()) 369 return ClassTy; 370 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 371 "objc_class", TheCU, 372 getOrCreateMainFile(), 0); 373 return ClassTy; 374 case BuiltinType::ObjCId: { 375 // typedef struct objc_class *Class; 376 // typedef struct objc_object { 377 // Class isa; 378 // } *id; 379 380 if (ObjTy.Verify()) 381 return ObjTy; 382 383 if (!ClassTy.Verify()) 384 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 385 "objc_class", TheCU, 386 getOrCreateMainFile(), 0); 387 388 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 389 390 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size); 391 392 ObjTy = 393 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(), 394 0, 0, 0, 0, llvm::DIType(), llvm::DIArray()); 395 396 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType( 397 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy))); 398 return ObjTy; 399 } 400 case BuiltinType::ObjCSel: { 401 if (SelTy.Verify()) 402 return SelTy; 403 SelTy = 404 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 405 "objc_selector", TheCU, getOrCreateMainFile(), 406 0); 407 return SelTy; 408 } 409 410 case BuiltinType::OCLImage1d: 411 return getOrCreateStructPtrType("opencl_image1d_t", 412 OCLImage1dDITy); 413 case BuiltinType::OCLImage1dArray: 414 return getOrCreateStructPtrType("opencl_image1d_array_t", 415 OCLImage1dArrayDITy); 416 case BuiltinType::OCLImage1dBuffer: 417 return getOrCreateStructPtrType("opencl_image1d_buffer_t", 418 OCLImage1dBufferDITy); 419 case BuiltinType::OCLImage2d: 420 return getOrCreateStructPtrType("opencl_image2d_t", 421 OCLImage2dDITy); 422 case BuiltinType::OCLImage2dArray: 423 return getOrCreateStructPtrType("opencl_image2d_array_t", 424 OCLImage2dArrayDITy); 425 case BuiltinType::OCLImage3d: 426 return getOrCreateStructPtrType("opencl_image3d_t", 427 OCLImage3dDITy); 428 case BuiltinType::OCLSampler: 429 return DBuilder.createBasicType("opencl_sampler_t", 430 CGM.getContext().getTypeSize(BT), 431 CGM.getContext().getTypeAlign(BT), 432 llvm::dwarf::DW_ATE_unsigned); 433 case BuiltinType::OCLEvent: 434 return getOrCreateStructPtrType("opencl_event_t", 435 OCLEventDITy); 436 437 case BuiltinType::UChar: 438 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break; 439 case BuiltinType::Char_S: 440 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break; 441 case BuiltinType::Char16: 442 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break; 443 case BuiltinType::UShort: 444 case BuiltinType::UInt: 445 case BuiltinType::UInt128: 446 case BuiltinType::ULong: 447 case BuiltinType::WChar_U: 448 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break; 449 case BuiltinType::Short: 450 case BuiltinType::Int: 451 case BuiltinType::Int128: 452 case BuiltinType::Long: 453 case BuiltinType::WChar_S: 454 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break; 455 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; 456 case BuiltinType::Half: 457 case BuiltinType::Float: 458 case BuiltinType::LongDouble: 459 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; 460 } 461 462 switch (BT->getKind()) { 463 case BuiltinType::Long: BTName = "long int"; break; 464 case BuiltinType::LongLong: BTName = "long long int"; break; 465 case BuiltinType::ULong: BTName = "long unsigned int"; break; 466 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break; 467 default: 468 BTName = BT->getName(CGM.getLangOpts()); 469 break; 470 } 471 // Bit size, align and offset of the type. 472 uint64_t Size = CGM.getContext().getTypeSize(BT); 473 uint64_t Align = CGM.getContext().getTypeAlign(BT); 474 llvm::DIType DbgTy = 475 DBuilder.createBasicType(BTName, Size, Align, Encoding); 476 return DbgTy; 477 } 478 479 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) { 480 // Bit size, align and offset of the type. 481 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float; 482 if (Ty->isComplexIntegerType()) 483 Encoding = llvm::dwarf::DW_ATE_lo_user; 484 485 uint64_t Size = CGM.getContext().getTypeSize(Ty); 486 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 487 llvm::DIType DbgTy = 488 DBuilder.createBasicType("complex", Size, Align, Encoding); 489 490 return DbgTy; 491 } 492 493 /// CreateCVRType - Get the qualified type from the cache or create 494 /// a new one if necessary. 495 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) { 496 QualifierCollector Qc; 497 const Type *T = Qc.strip(Ty); 498 499 // Ignore these qualifiers for now. 500 Qc.removeObjCGCAttr(); 501 Qc.removeAddressSpace(); 502 Qc.removeObjCLifetime(); 503 504 // We will create one Derived type for one qualifier and recurse to handle any 505 // additional ones. 506 unsigned Tag; 507 if (Qc.hasConst()) { 508 Tag = llvm::dwarf::DW_TAG_const_type; 509 Qc.removeConst(); 510 } else if (Qc.hasVolatile()) { 511 Tag = llvm::dwarf::DW_TAG_volatile_type; 512 Qc.removeVolatile(); 513 } else if (Qc.hasRestrict()) { 514 Tag = llvm::dwarf::DW_TAG_restrict_type; 515 Qc.removeRestrict(); 516 } else { 517 assert(Qc.empty() && "Unknown type qualifier for debug info"); 518 return getOrCreateType(QualType(T, 0), Unit); 519 } 520 521 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit); 522 523 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 524 // CVR derived types. 525 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy); 526 527 return DbgTy; 528 } 529 530 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 531 llvm::DIFile Unit) { 532 533 // The frontend treats 'id' as a typedef to an ObjCObjectType, 534 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the 535 // debug info, we want to emit 'id' in both cases. 536 if (Ty->isObjCQualifiedIdType()) 537 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit); 538 539 llvm::DIType DbgTy = 540 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 541 Ty->getPointeeType(), Unit); 542 return DbgTy; 543 } 544 545 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, 546 llvm::DIFile Unit) { 547 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 548 Ty->getPointeeType(), Unit); 549 } 550 551 // Creates a forward declaration for a RecordDecl in the given context. 552 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD, 553 llvm::DIDescriptor Ctx) { 554 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 555 unsigned Line = getLineNumber(RD->getLocation()); 556 StringRef RDName = getClassName(RD); 557 558 unsigned Tag = 0; 559 if (RD->isStruct() || RD->isInterface()) 560 Tag = llvm::dwarf::DW_TAG_structure_type; 561 else if (RD->isUnion()) 562 Tag = llvm::dwarf::DW_TAG_union_type; 563 else { 564 assert(RD->isClass()); 565 Tag = llvm::dwarf::DW_TAG_class_type; 566 } 567 568 // Create the type. 569 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line); 570 } 571 572 // Walk up the context chain and create forward decls for record decls, 573 // and normal descriptors for namespaces. 574 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) { 575 if (!Context) 576 return TheCU; 577 578 // See if we already have the parent. 579 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 580 I = RegionMap.find(Context); 581 if (I != RegionMap.end()) { 582 llvm::Value *V = I->second; 583 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V)); 584 } 585 586 // Check namespace. 587 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 588 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl)); 589 590 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) { 591 if (!RD->isDependentType()) { 592 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD), 593 getOrCreateMainFile()); 594 return llvm::DIDescriptor(Ty); 595 } 596 } 597 return TheCU; 598 } 599 600 /// CreatePointeeType - Create Pointee type. If Pointee is a record 601 /// then emit record's fwd if debug info size reduction is enabled. 602 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy, 603 llvm::DIFile Unit) { 604 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo) 605 return getOrCreateType(PointeeTy, Unit); 606 607 // Limit debug info for the pointee type. 608 609 // If we have an existing type, use that, it's still smaller than creating 610 // a new type. 611 llvm::DIType Ty = getTypeOrNull(PointeeTy); 612 if (Ty.Verify()) return Ty; 613 614 // Handle qualifiers. 615 if (PointeeTy.hasLocalQualifiers()) 616 return CreateQualifiedType(PointeeTy, Unit); 617 618 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) { 619 RecordDecl *RD = RTy->getDecl(); 620 llvm::DIDescriptor FDContext = 621 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 622 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext); 623 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy; 624 return RetTy; 625 } 626 return getOrCreateType(PointeeTy, Unit); 627 } 628 629 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag, 630 const Type *Ty, 631 QualType PointeeTy, 632 llvm::DIFile Unit) { 633 if (Tag == llvm::dwarf::DW_TAG_reference_type || 634 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) 635 return DBuilder.createReferenceType(Tag, 636 CreatePointeeType(PointeeTy, Unit)); 637 638 // Bit size, align and offset of the type. 639 // Size is always the size of a pointer. We can't use getTypeSize here 640 // because that does not return the correct value for references. 641 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 642 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 643 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 644 645 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), 646 Size, Align); 647 } 648 649 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) { 650 if (Cache.Verify()) 651 return Cache; 652 Cache = 653 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 654 Name, TheCU, getOrCreateMainFile(), 655 0); 656 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 657 Cache = DBuilder.createPointerType(Cache, Size); 658 return Cache; 659 } 660 661 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, 662 llvm::DIFile Unit) { 663 if (BlockLiteralGenericSet) 664 return BlockLiteralGeneric; 665 666 SmallVector<llvm::Value *, 8> EltTys; 667 llvm::DIType FieldTy; 668 QualType FType; 669 uint64_t FieldSize, FieldOffset; 670 unsigned FieldAlign; 671 llvm::DIArray Elements; 672 llvm::DIType EltTy, DescTy; 673 674 FieldOffset = 0; 675 FType = CGM.getContext().UnsignedLongTy; 676 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 677 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 678 679 Elements = DBuilder.getOrCreateArray(EltTys); 680 EltTys.clear(); 681 682 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock; 683 unsigned LineNo = getLineNumber(CurLoc); 684 685 EltTy = DBuilder.createStructType(Unit, "__block_descriptor", 686 Unit, LineNo, FieldOffset, 0, 687 Flags, llvm::DIType(), Elements); 688 689 // Bit size, align and offset of the type. 690 uint64_t Size = CGM.getContext().getTypeSize(Ty); 691 692 DescTy = DBuilder.createPointerType(EltTy, Size); 693 694 FieldOffset = 0; 695 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 696 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 697 FType = CGM.getContext().IntTy; 698 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 699 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 700 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 701 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 702 703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 704 FieldTy = DescTy; 705 FieldSize = CGM.getContext().getTypeSize(Ty); 706 FieldAlign = CGM.getContext().getTypeAlign(Ty); 707 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit, 708 LineNo, FieldSize, FieldAlign, 709 FieldOffset, 0, FieldTy); 710 EltTys.push_back(FieldTy); 711 712 FieldOffset += FieldSize; 713 Elements = DBuilder.getOrCreateArray(EltTys); 714 715 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic", 716 Unit, LineNo, FieldOffset, 0, 717 Flags, llvm::DIType(), Elements); 718 719 BlockLiteralGenericSet = true; 720 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size); 721 return BlockLiteralGeneric; 722 } 723 724 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) { 725 // Typedefs are derived from some other type. If we have a typedef of a 726 // typedef, make sure to emit the whole chain. 727 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); 728 if (!Src.Verify()) 729 return llvm::DIType(); 730 // We don't set size information, but do specify where the typedef was 731 // declared. 732 unsigned Line = getLineNumber(Ty->getDecl()->getLocation()); 733 const TypedefNameDecl *TyDecl = Ty->getDecl(); 734 735 llvm::DIDescriptor TypedefContext = 736 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())); 737 738 return 739 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext); 740 } 741 742 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, 743 llvm::DIFile Unit) { 744 SmallVector<llvm::Value *, 16> EltTys; 745 746 // Add the result type at least. 747 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); 748 749 // Set up remainder of arguments if there is a prototype. 750 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! 751 if (isa<FunctionNoProtoType>(Ty)) 752 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 753 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) { 754 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i) 755 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit)); 756 } 757 758 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys); 759 return DBuilder.createSubroutineType(Unit, EltTypeArray); 760 } 761 762 763 llvm::DIType CGDebugInfo::createFieldType(StringRef name, 764 QualType type, 765 uint64_t sizeInBitsOverride, 766 SourceLocation loc, 767 AccessSpecifier AS, 768 uint64_t offsetInBits, 769 llvm::DIFile tunit, 770 llvm::DIDescriptor scope) { 771 llvm::DIType debugType = getOrCreateType(type, tunit); 772 773 // Get the location for the field. 774 llvm::DIFile file = getOrCreateFile(loc); 775 unsigned line = getLineNumber(loc); 776 777 uint64_t sizeInBits = 0; 778 unsigned alignInBits = 0; 779 if (!type->isIncompleteArrayType()) { 780 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type); 781 782 if (sizeInBitsOverride) 783 sizeInBits = sizeInBitsOverride; 784 } 785 786 unsigned flags = 0; 787 if (AS == clang::AS_private) 788 flags |= llvm::DIDescriptor::FlagPrivate; 789 else if (AS == clang::AS_protected) 790 flags |= llvm::DIDescriptor::FlagProtected; 791 792 return DBuilder.createMemberType(scope, name, file, line, sizeInBits, 793 alignInBits, offsetInBits, flags, debugType); 794 } 795 796 /// CollectRecordLambdaFields - Helper for CollectRecordFields. 797 void CGDebugInfo:: 798 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl, 799 SmallVectorImpl<llvm::Value *> &elements, 800 llvm::DIType RecordTy) { 801 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture 802 // has the name and the location of the variable so we should iterate over 803 // both concurrently. 804 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); 805 RecordDecl::field_iterator Field = CXXDecl->field_begin(); 806 unsigned fieldno = 0; 807 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), 808 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) { 809 const LambdaExpr::Capture C = *I; 810 if (C.capturesVariable()) { 811 VarDecl *V = C.getCapturedVar(); 812 llvm::DIFile VUnit = getOrCreateFile(C.getLocation()); 813 StringRef VName = V->getName(); 814 uint64_t SizeInBitsOverride = 0; 815 if (Field->isBitField()) { 816 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext()); 817 assert(SizeInBitsOverride && "found named 0-width bitfield"); 818 } 819 llvm::DIType fieldType 820 = createFieldType(VName, Field->getType(), SizeInBitsOverride, 821 C.getLocation(), Field->getAccess(), 822 layout.getFieldOffset(fieldno), VUnit, RecordTy); 823 elements.push_back(fieldType); 824 } else { 825 // TODO: Need to handle 'this' in some way by probably renaming the 826 // this of the lambda class and having a field member of 'this' or 827 // by using AT_object_pointer for the function and having that be 828 // used as 'this' for semantic references. 829 assert(C.capturesThis() && "Field that isn't captured and isn't this?"); 830 FieldDecl *f = *Field; 831 llvm::DIFile VUnit = getOrCreateFile(f->getLocation()); 832 QualType type = f->getType(); 833 llvm::DIType fieldType 834 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(), 835 layout.getFieldOffset(fieldno), VUnit, RecordTy); 836 837 elements.push_back(fieldType); 838 } 839 } 840 } 841 842 /// CollectRecordStaticField - Helper for CollectRecordFields. 843 void CGDebugInfo:: 844 CollectRecordStaticField(const VarDecl *Var, 845 SmallVectorImpl<llvm::Value *> &elements, 846 llvm::DIType RecordTy) { 847 // Create the descriptor for the static variable, with or without 848 // constant initializers. 849 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation()); 850 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit); 851 852 // Do not describe enums as static members. 853 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 854 return; 855 856 unsigned LineNumber = getLineNumber(Var->getLocation()); 857 StringRef VName = Var->getName(); 858 llvm::Constant *C = NULL; 859 if (Var->getInit()) { 860 const APValue *Value = Var->evaluateValue(); 861 if (Value) { 862 if (Value->isInt()) 863 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 864 if (Value->isFloat()) 865 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat()); 866 } 867 } 868 869 unsigned Flags = 0; 870 AccessSpecifier Access = Var->getAccess(); 871 if (Access == clang::AS_private) 872 Flags |= llvm::DIDescriptor::FlagPrivate; 873 else if (Access == clang::AS_protected) 874 Flags |= llvm::DIDescriptor::FlagProtected; 875 876 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit, 877 LineNumber, VTy, Flags, C); 878 elements.push_back(GV); 879 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV); 880 } 881 882 /// CollectRecordNormalField - Helper for CollectRecordFields. 883 void CGDebugInfo:: 884 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits, 885 llvm::DIFile tunit, 886 SmallVectorImpl<llvm::Value *> &elements, 887 llvm::DIType RecordTy) { 888 StringRef name = field->getName(); 889 QualType type = field->getType(); 890 891 // Ignore unnamed fields unless they're anonymous structs/unions. 892 if (name.empty() && !type->isRecordType()) 893 return; 894 895 uint64_t SizeInBitsOverride = 0; 896 if (field->isBitField()) { 897 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext()); 898 assert(SizeInBitsOverride && "found named 0-width bitfield"); 899 } 900 901 llvm::DIType fieldType 902 = createFieldType(name, type, SizeInBitsOverride, 903 field->getLocation(), field->getAccess(), 904 OffsetInBits, tunit, RecordTy); 905 906 elements.push_back(fieldType); 907 } 908 909 /// CollectRecordFields - A helper function to collect debug info for 910 /// record fields. This is used while creating debug info entry for a Record. 911 void CGDebugInfo:: 912 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit, 913 SmallVectorImpl<llvm::Value *> &elements, 914 llvm::DIType RecordTy) { 915 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record); 916 917 if (CXXDecl && CXXDecl->isLambda()) 918 CollectRecordLambdaFields(CXXDecl, elements, RecordTy); 919 else { 920 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 921 922 // Field number for non-static fields. 923 unsigned fieldNo = 0; 924 925 // Bookkeeping for an ms struct, which ignores certain fields. 926 bool IsMsStruct = record->isMsStruct(CGM.getContext()); 927 const FieldDecl *LastFD = 0; 928 929 // Static and non-static members should appear in the same order as 930 // the corresponding declarations in the source program. 931 for (RecordDecl::decl_iterator I = record->decls_begin(), 932 E = record->decls_end(); I != E; ++I) 933 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) 934 CollectRecordStaticField(V, elements, RecordTy); 935 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) { 936 if (IsMsStruct) { 937 // Zero-length bitfields following non-bitfield members are 938 // completely ignored; we don't even count them. 939 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) 940 continue; 941 LastFD = field; 942 } 943 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), 944 tunit, elements, RecordTy); 945 946 // Bump field number for next field. 947 ++fieldNo; 948 } 949 } 950 } 951 952 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 953 /// function type is not updated to include implicit "this" pointer. Use this 954 /// routine to get a method type which includes "this" pointer. 955 llvm::DIType 956 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 957 llvm::DIFile Unit) { 958 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 959 if (Method->isStatic()) 960 return getOrCreateType(QualType(Func, 0), Unit); 961 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()), 962 Func, Unit); 963 } 964 965 llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType( 966 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) { 967 // Add "this" pointer. 968 llvm::DIArray Args = llvm::DICompositeType( 969 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray(); 970 assert (Args.getNumElements() && "Invalid number of arguments!"); 971 972 SmallVector<llvm::Value *, 16> Elts; 973 974 // First element is always return type. For 'void' functions it is NULL. 975 Elts.push_back(Args.getElement(0)); 976 977 // "this" pointer is always first argument. 978 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); 979 if (isa<ClassTemplateSpecializationDecl>(RD)) { 980 // Create pointer type directly in this case. 981 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 982 QualType PointeeTy = ThisPtrTy->getPointeeType(); 983 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 984 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 985 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy); 986 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit); 987 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align); 988 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 989 // TODO: This and the artificial type below are misleading, the 990 // types aren't artificial the argument is, but the current 991 // metadata doesn't represent that. 992 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 993 Elts.push_back(ThisPtrType); 994 } else { 995 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit); 996 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 997 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 998 Elts.push_back(ThisPtrType); 999 } 1000 1001 // Copy rest of the arguments. 1002 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 1003 Elts.push_back(Args.getElement(i)); 1004 1005 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 1006 1007 return DBuilder.createSubroutineType(Unit, EltTypeArray); 1008 } 1009 1010 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 1011 /// inside a function. 1012 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 1013 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 1014 return isFunctionLocalClass(NRD); 1015 if (isa<FunctionDecl>(RD->getDeclContext())) 1016 return true; 1017 return false; 1018 } 1019 1020 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for 1021 /// a single member function GlobalDecl. 1022 llvm::DISubprogram 1023 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 1024 llvm::DIFile Unit, 1025 llvm::DIType RecordTy) { 1026 bool IsCtorOrDtor = 1027 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 1028 1029 StringRef MethodName = getFunctionName(Method); 1030 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit); 1031 1032 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 1033 // make sense to give a single ctor/dtor a linkage name. 1034 StringRef MethodLinkageName; 1035 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 1036 MethodLinkageName = CGM.getMangledName(Method); 1037 1038 // Get the location for the method. 1039 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 1040 unsigned MethodLine = getLineNumber(Method->getLocation()); 1041 1042 // Collect virtual method info. 1043 llvm::DIType ContainingType; 1044 unsigned Virtuality = 0; 1045 unsigned VIndex = 0; 1046 1047 if (Method->isVirtual()) { 1048 if (Method->isPure()) 1049 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 1050 else 1051 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 1052 1053 // It doesn't make sense to give a virtual destructor a vtable index, 1054 // since a single destructor has two entries in the vtable. 1055 if (!isa<CXXDestructorDecl>(Method)) 1056 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method); 1057 ContainingType = RecordTy; 1058 } 1059 1060 unsigned Flags = 0; 1061 if (Method->isImplicit()) 1062 Flags |= llvm::DIDescriptor::FlagArtificial; 1063 AccessSpecifier Access = Method->getAccess(); 1064 if (Access == clang::AS_private) 1065 Flags |= llvm::DIDescriptor::FlagPrivate; 1066 else if (Access == clang::AS_protected) 1067 Flags |= llvm::DIDescriptor::FlagProtected; 1068 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 1069 if (CXXC->isExplicit()) 1070 Flags |= llvm::DIDescriptor::FlagExplicit; 1071 } else if (const CXXConversionDecl *CXXC = 1072 dyn_cast<CXXConversionDecl>(Method)) { 1073 if (CXXC->isExplicit()) 1074 Flags |= llvm::DIDescriptor::FlagExplicit; 1075 } 1076 if (Method->hasPrototype()) 1077 Flags |= llvm::DIDescriptor::FlagPrototyped; 1078 1079 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 1080 llvm::DISubprogram SP = 1081 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName, 1082 MethodDefUnit, MethodLine, 1083 MethodTy, /*isLocalToUnit=*/false, 1084 /* isDefinition=*/ false, 1085 Virtuality, VIndex, ContainingType, 1086 Flags, CGM.getLangOpts().Optimize, NULL, 1087 TParamsArray); 1088 1089 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP); 1090 1091 return SP; 1092 } 1093 1094 /// CollectCXXMemberFunctions - A helper function to collect debug info for 1095 /// C++ member functions. This is used while creating debug info entry for 1096 /// a Record. 1097 void CGDebugInfo:: 1098 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 1099 SmallVectorImpl<llvm::Value *> &EltTys, 1100 llvm::DIType RecordTy) { 1101 1102 // Since we want more than just the individual member decls if we 1103 // have templated functions iterate over every declaration to gather 1104 // the functions. 1105 for(DeclContext::decl_iterator I = RD->decls_begin(), 1106 E = RD->decls_end(); I != E; ++I) { 1107 Decl *D = *I; 1108 if (D->isImplicit() && !D->isUsed()) 1109 continue; 1110 1111 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1112 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 1113 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 1114 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(), 1115 SE = FTD->spec_end(); SI != SE; ++SI) 1116 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit, 1117 RecordTy)); 1118 } 1119 } 1120 1121 /// CollectCXXFriends - A helper function to collect debug info for 1122 /// C++ base classes. This is used while creating debug info entry for 1123 /// a Record. 1124 void CGDebugInfo:: 1125 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 1126 SmallVectorImpl<llvm::Value *> &EltTys, 1127 llvm::DIType RecordTy) { 1128 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 1129 BE = RD->friend_end(); BI != BE; ++BI) { 1130 if ((*BI)->isUnsupportedFriend()) 1131 continue; 1132 if (TypeSourceInfo *TInfo = (*BI)->getFriendType()) 1133 EltTys.push_back(DBuilder.createFriend(RecordTy, 1134 getOrCreateType(TInfo->getType(), 1135 Unit))); 1136 } 1137 } 1138 1139 /// CollectCXXBases - A helper function to collect debug info for 1140 /// C++ base classes. This is used while creating debug info entry for 1141 /// a Record. 1142 void CGDebugInfo:: 1143 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 1144 SmallVectorImpl<llvm::Value *> &EltTys, 1145 llvm::DIType RecordTy) { 1146 1147 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1148 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 1149 BE = RD->bases_end(); BI != BE; ++BI) { 1150 unsigned BFlags = 0; 1151 uint64_t BaseOffset; 1152 1153 const CXXRecordDecl *Base = 1154 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 1155 1156 if (BI->isVirtual()) { 1157 // virtual base offset offset is -ve. The code generator emits dwarf 1158 // expression where it expects +ve number. 1159 BaseOffset = 1160 0 - CGM.getVTableContext() 1161 .getVirtualBaseOffsetOffset(RD, Base).getQuantity(); 1162 BFlags = llvm::DIDescriptor::FlagVirtual; 1163 } else 1164 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 1165 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 1166 // BI->isVirtual() and bits when not. 1167 1168 AccessSpecifier Access = BI->getAccessSpecifier(); 1169 if (Access == clang::AS_private) 1170 BFlags |= llvm::DIDescriptor::FlagPrivate; 1171 else if (Access == clang::AS_protected) 1172 BFlags |= llvm::DIDescriptor::FlagProtected; 1173 1174 llvm::DIType DTy = 1175 DBuilder.createInheritance(RecordTy, 1176 getOrCreateType(BI->getType(), Unit), 1177 BaseOffset, BFlags); 1178 EltTys.push_back(DTy); 1179 } 1180 } 1181 1182 /// CollectTemplateParams - A helper function to collect template parameters. 1183 llvm::DIArray CGDebugInfo:: 1184 CollectTemplateParams(const TemplateParameterList *TPList, 1185 const TemplateArgumentList &TAList, 1186 llvm::DIFile Unit) { 1187 SmallVector<llvm::Value *, 16> TemplateParams; 1188 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 1189 const TemplateArgument &TA = TAList[i]; 1190 const NamedDecl *ND = TPList->getParam(i); 1191 if (TA.getKind() == TemplateArgument::Type) { 1192 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 1193 llvm::DITemplateTypeParameter TTP = 1194 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy); 1195 TemplateParams.push_back(TTP); 1196 } else if (TA.getKind() == TemplateArgument::Integral) { 1197 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 1198 llvm::DITemplateValueParameter TVP = 1199 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, 1200 TA.getAsIntegral().getZExtValue()); 1201 TemplateParams.push_back(TVP); 1202 } 1203 } 1204 return DBuilder.getOrCreateArray(TemplateParams); 1205 } 1206 1207 /// CollectFunctionTemplateParams - A helper function to collect debug 1208 /// info for function template parameters. 1209 llvm::DIArray CGDebugInfo:: 1210 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) { 1211 if (FD->getTemplatedKind() == 1212 FunctionDecl::TK_FunctionTemplateSpecialization) { 1213 const TemplateParameterList *TList = 1214 FD->getTemplateSpecializationInfo()->getTemplate() 1215 ->getTemplateParameters(); 1216 return 1217 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit); 1218 } 1219 return llvm::DIArray(); 1220 } 1221 1222 /// CollectCXXTemplateParams - A helper function to collect debug info for 1223 /// template parameters. 1224 llvm::DIArray CGDebugInfo:: 1225 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial, 1226 llvm::DIFile Unit) { 1227 llvm::PointerUnion<ClassTemplateDecl *, 1228 ClassTemplatePartialSpecializationDecl *> 1229 PU = TSpecial->getSpecializedTemplateOrPartial(); 1230 1231 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ? 1232 PU.get<ClassTemplateDecl *>()->getTemplateParameters() : 1233 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters(); 1234 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs(); 1235 return CollectTemplateParams(TPList, TAList, Unit); 1236 } 1237 1238 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 1239 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 1240 if (VTablePtrType.isValid()) 1241 return VTablePtrType; 1242 1243 ASTContext &Context = CGM.getContext(); 1244 1245 /* Function type */ 1246 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 1247 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy); 1248 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 1249 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1250 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0, 1251 "__vtbl_ptr_type"); 1252 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1253 return VTablePtrType; 1254 } 1255 1256 /// getVTableName - Get vtable name for the given Class. 1257 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1258 // Construct gdb compatible name name. 1259 std::string Name = "_vptr$" + RD->getNameAsString(); 1260 1261 // Copy this name on the side and use its reference. 1262 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 1263 memcpy(StrPtr, Name.data(), Name.length()); 1264 return StringRef(StrPtr, Name.length()); 1265 } 1266 1267 1268 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 1269 /// debug info entry in EltTys vector. 1270 void CGDebugInfo:: 1271 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 1272 SmallVectorImpl<llvm::Value *> &EltTys) { 1273 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1274 1275 // If there is a primary base then it will hold vtable info. 1276 if (RL.getPrimaryBase()) 1277 return; 1278 1279 // If this class is not dynamic then there is not any vtable info to collect. 1280 if (!RD->isDynamicClass()) 1281 return; 1282 1283 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1284 llvm::DIType VPTR 1285 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 1286 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial, 1287 getOrCreateVTablePtrType(Unit)); 1288 EltTys.push_back(VPTR); 1289 } 1290 1291 /// getOrCreateRecordType - Emit record type's standalone debug info. 1292 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 1293 SourceLocation Loc) { 1294 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 1295 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1296 return T; 1297 } 1298 1299 /// getOrCreateInterfaceType - Emit an objective c interface type standalone 1300 /// debug info. 1301 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D, 1302 SourceLocation Loc) { 1303 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 1304 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc)); 1305 RetainedTypes.push_back(D.getAsOpaquePtr()); 1306 return T; 1307 } 1308 1309 /// CreateType - get structure or union type. 1310 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 1311 RecordDecl *RD = Ty->getDecl(); 1312 1313 // Get overall information about the record type for the debug info. 1314 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 1315 1316 // Records and classes and unions can all be recursive. To handle them, we 1317 // first generate a debug descriptor for the struct as a forward declaration. 1318 // Then (if it is a definition) we go through and get debug info for all of 1319 // its members. Finally, we create a descriptor for the complete type (which 1320 // may refer to the forward decl if the struct is recursive) and replace all 1321 // uses of the forward declaration with the final definition. 1322 1323 llvm::DICompositeType FwdDecl( 1324 getOrCreateLimitedType(QualType(Ty, 0), DefUnit)); 1325 assert(FwdDecl.Verify() && 1326 "The debug type of a RecordType should be a DICompositeType"); 1327 1328 if (FwdDecl.isForwardDecl()) 1329 return FwdDecl; 1330 1331 // Push the struct on region stack. 1332 LexicalBlockStack.push_back(&*FwdDecl); 1333 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1334 1335 // Add this to the completed-type cache while we're completing it recursively. 1336 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1337 1338 // Convert all the elements. 1339 SmallVector<llvm::Value *, 16> EltTys; 1340 1341 // Note: The split of CXXDecl information here is intentional, the 1342 // gdb tests will depend on a certain ordering at printout. The debug 1343 // information offsets are still correct if we merge them all together 1344 // though. 1345 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1346 if (CXXDecl) { 1347 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 1348 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 1349 } 1350 1351 // Collect data fields (including static variables and any initializers). 1352 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 1353 llvm::DIArray TParamsArray; 1354 if (CXXDecl) { 1355 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 1356 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl); 1357 if (const ClassTemplateSpecializationDecl *TSpecial 1358 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1359 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit); 1360 } 1361 1362 LexicalBlockStack.pop_back(); 1363 RegionMap.erase(Ty->getDecl()); 1364 1365 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1366 FwdDecl.setTypeArray(Elements, TParamsArray); 1367 1368 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1369 return FwdDecl; 1370 } 1371 1372 /// CreateType - get objective-c object type. 1373 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1374 llvm::DIFile Unit) { 1375 // Ignore protocols. 1376 return getOrCreateType(Ty->getBaseType(), Unit); 1377 } 1378 1379 /// CreateType - get objective-c interface type. 1380 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1381 llvm::DIFile Unit) { 1382 ObjCInterfaceDecl *ID = Ty->getDecl(); 1383 if (!ID) 1384 return llvm::DIType(); 1385 1386 // Get overall information about the record type for the debug info. 1387 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1388 unsigned Line = getLineNumber(ID->getLocation()); 1389 unsigned RuntimeLang = TheCU.getLanguage(); 1390 1391 // If this is just a forward declaration return a special forward-declaration 1392 // debug type since we won't be able to lay out the entire type. 1393 ObjCInterfaceDecl *Def = ID->getDefinition(); 1394 if (!Def) { 1395 llvm::DIType FwdDecl = 1396 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1397 ID->getName(), TheCU, DefUnit, Line, 1398 RuntimeLang); 1399 return FwdDecl; 1400 } 1401 1402 ID = Def; 1403 1404 // Bit size, align and offset of the type. 1405 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1406 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1407 1408 unsigned Flags = 0; 1409 if (ID->getImplementation()) 1410 Flags |= llvm::DIDescriptor::FlagObjcClassComplete; 1411 1412 llvm::DICompositeType RealDecl = 1413 DBuilder.createStructType(Unit, ID->getName(), DefUnit, 1414 Line, Size, Align, Flags, 1415 llvm::DIType(), llvm::DIArray(), RuntimeLang); 1416 1417 // Otherwise, insert it into the CompletedTypeCache so that recursive uses 1418 // will find it and we're emitting the complete type. 1419 QualType QualTy = QualType(Ty, 0); 1420 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl; 1421 // Push the struct on region stack. 1422 1423 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl)); 1424 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 1425 1426 // Convert all the elements. 1427 SmallVector<llvm::Value *, 16> EltTys; 1428 1429 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1430 if (SClass) { 1431 llvm::DIType SClassTy = 1432 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1433 if (!SClassTy.isValid()) 1434 return llvm::DIType(); 1435 1436 llvm::DIType InhTag = 1437 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 1438 EltTys.push_back(InhTag); 1439 } 1440 1441 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(), 1442 E = ID->prop_end(); I != E; ++I) { 1443 const ObjCPropertyDecl *PD = *I; 1444 SourceLocation Loc = PD->getLocation(); 1445 llvm::DIFile PUnit = getOrCreateFile(Loc); 1446 unsigned PLine = getLineNumber(Loc); 1447 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1448 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1449 llvm::MDNode *PropertyNode = 1450 DBuilder.createObjCProperty(PD->getName(), 1451 PUnit, PLine, 1452 (Getter && Getter->isImplicit()) ? "" : 1453 getSelectorName(PD->getGetterName()), 1454 (Setter && Setter->isImplicit()) ? "" : 1455 getSelectorName(PD->getSetterName()), 1456 PD->getPropertyAttributes(), 1457 getOrCreateType(PD->getType(), PUnit)); 1458 EltTys.push_back(PropertyNode); 1459 } 1460 1461 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1462 unsigned FieldNo = 0; 1463 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1464 Field = Field->getNextIvar(), ++FieldNo) { 1465 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1466 if (!FieldTy.isValid()) 1467 return llvm::DIType(); 1468 1469 StringRef FieldName = Field->getName(); 1470 1471 // Ignore unnamed fields. 1472 if (FieldName.empty()) 1473 continue; 1474 1475 // Get the location for the field. 1476 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1477 unsigned FieldLine = getLineNumber(Field->getLocation()); 1478 QualType FType = Field->getType(); 1479 uint64_t FieldSize = 0; 1480 unsigned FieldAlign = 0; 1481 1482 if (!FType->isIncompleteArrayType()) { 1483 1484 // Bit size, align and offset of the type. 1485 FieldSize = Field->isBitField() 1486 ? Field->getBitWidthValue(CGM.getContext()) 1487 : CGM.getContext().getTypeSize(FType); 1488 FieldAlign = CGM.getContext().getTypeAlign(FType); 1489 } 1490 1491 uint64_t FieldOffset; 1492 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 1493 // We don't know the runtime offset of an ivar if we're using the 1494 // non-fragile ABI. For bitfields, use the bit offset into the first 1495 // byte of storage of the bitfield. For other fields, use zero. 1496 if (Field->isBitField()) { 1497 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset( 1498 CGM, ID, Field); 1499 FieldOffset %= CGM.getContext().getCharWidth(); 1500 } else { 1501 FieldOffset = 0; 1502 } 1503 } else { 1504 FieldOffset = RL.getFieldOffset(FieldNo); 1505 } 1506 1507 unsigned Flags = 0; 1508 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1509 Flags = llvm::DIDescriptor::FlagProtected; 1510 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1511 Flags = llvm::DIDescriptor::FlagPrivate; 1512 1513 llvm::MDNode *PropertyNode = NULL; 1514 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 1515 if (ObjCPropertyImplDecl *PImpD = 1516 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 1517 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 1518 SourceLocation Loc = PD->getLocation(); 1519 llvm::DIFile PUnit = getOrCreateFile(Loc); 1520 unsigned PLine = getLineNumber(Loc); 1521 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1522 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1523 PropertyNode = 1524 DBuilder.createObjCProperty(PD->getName(), 1525 PUnit, PLine, 1526 (Getter && Getter->isImplicit()) ? "" : 1527 getSelectorName(PD->getGetterName()), 1528 (Setter && Setter->isImplicit()) ? "" : 1529 getSelectorName(PD->getSetterName()), 1530 PD->getPropertyAttributes(), 1531 getOrCreateType(PD->getType(), PUnit)); 1532 } 1533 } 1534 } 1535 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, 1536 FieldLine, FieldSize, FieldAlign, 1537 FieldOffset, Flags, FieldTy, 1538 PropertyNode); 1539 EltTys.push_back(FieldTy); 1540 } 1541 1542 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1543 RealDecl.setTypeArray(Elements); 1544 1545 // If the implementation is not yet set, we do not want to mark it 1546 // as complete. An implementation may declare additional 1547 // private ivars that we would miss otherwise. 1548 if (ID->getImplementation() == 0) 1549 CompletedTypeCache.erase(QualTy.getAsOpaquePtr()); 1550 1551 LexicalBlockStack.pop_back(); 1552 return RealDecl; 1553 } 1554 1555 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) { 1556 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1557 int64_t Count = Ty->getNumElements(); 1558 if (Count == 0) 1559 // If number of elements are not known then this is an unbounded array. 1560 // Use Count == -1 to express such arrays. 1561 Count = -1; 1562 1563 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count); 1564 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1565 1566 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1567 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1568 1569 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1570 } 1571 1572 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1573 llvm::DIFile Unit) { 1574 uint64_t Size; 1575 uint64_t Align; 1576 1577 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1578 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1579 Size = 0; 1580 Align = 1581 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1582 } else if (Ty->isIncompleteArrayType()) { 1583 Size = 0; 1584 if (Ty->getElementType()->isIncompleteType()) 1585 Align = 0; 1586 else 1587 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1588 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) { 1589 Size = 0; 1590 Align = 0; 1591 } else { 1592 // Size and align of the whole array, not the element type. 1593 Size = CGM.getContext().getTypeSize(Ty); 1594 Align = CGM.getContext().getTypeAlign(Ty); 1595 } 1596 1597 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1598 // interior arrays, do we care? Why aren't nested arrays represented the 1599 // obvious/recursive way? 1600 SmallVector<llvm::Value *, 8> Subscripts; 1601 QualType EltTy(Ty, 0); 1602 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1603 // If the number of elements is known, then count is that number. Otherwise, 1604 // it's -1. This allows us to represent a subrange with an array of 0 1605 // elements, like this: 1606 // 1607 // struct foo { 1608 // int x[0]; 1609 // }; 1610 int64_t Count = -1; // Count == -1 is an unbounded array. 1611 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1612 Count = CAT->getSize().getZExtValue(); 1613 1614 // FIXME: Verify this is right for VLAs. 1615 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 1616 EltTy = Ty->getElementType(); 1617 } 1618 1619 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1620 1621 llvm::DIType DbgTy = 1622 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1623 SubscriptArray); 1624 return DbgTy; 1625 } 1626 1627 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1628 llvm::DIFile Unit) { 1629 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1630 Ty, Ty->getPointeeType(), Unit); 1631 } 1632 1633 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1634 llvm::DIFile Unit) { 1635 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 1636 Ty, Ty->getPointeeType(), Unit); 1637 } 1638 1639 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1640 llvm::DIFile U) { 1641 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 1642 if (!Ty->getPointeeType()->isFunctionType()) 1643 return DBuilder.createMemberPointerType( 1644 CreatePointeeType(Ty->getPointeeType(), U), ClassType); 1645 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType( 1646 CGM.getContext().getPointerType( 1647 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())), 1648 Ty->getPointeeType()->getAs<FunctionProtoType>(), U), 1649 ClassType); 1650 } 1651 1652 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, 1653 llvm::DIFile U) { 1654 // Ignore the atomic wrapping 1655 // FIXME: What is the correct representation? 1656 return getOrCreateType(Ty->getValueType(), U); 1657 } 1658 1659 /// CreateEnumType - get enumeration type. 1660 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) { 1661 uint64_t Size = 0; 1662 uint64_t Align = 0; 1663 if (!ED->getTypeForDecl()->isIncompleteType()) { 1664 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1665 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1666 } 1667 1668 // If this is just a forward declaration, construct an appropriately 1669 // marked node and just return it. 1670 if (!ED->getDefinition()) { 1671 llvm::DIDescriptor EDContext; 1672 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1673 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1674 unsigned Line = getLineNumber(ED->getLocation()); 1675 StringRef EDName = ED->getName(); 1676 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type, 1677 EDName, EDContext, DefUnit, Line, 0, 1678 Size, Align); 1679 } 1680 1681 // Create DIEnumerator elements for each enumerator. 1682 SmallVector<llvm::Value *, 16> Enumerators; 1683 ED = ED->getDefinition(); 1684 for (EnumDecl::enumerator_iterator 1685 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1686 Enum != EnumEnd; ++Enum) { 1687 Enumerators.push_back( 1688 DBuilder.createEnumerator(Enum->getName(), 1689 Enum->getInitVal().getZExtValue())); 1690 } 1691 1692 // Return a CompositeType for the enum itself. 1693 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1694 1695 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1696 unsigned Line = getLineNumber(ED->getLocation()); 1697 llvm::DIDescriptor EnumContext = 1698 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1699 llvm::DIType ClassTy = ED->isFixed() ? 1700 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType(); 1701 llvm::DIType DbgTy = 1702 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 1703 Size, Align, EltArray, 1704 ClassTy); 1705 return DbgTy; 1706 } 1707 1708 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 1709 Qualifiers Quals; 1710 do { 1711 Quals += T.getLocalQualifiers(); 1712 QualType LastT = T; 1713 switch (T->getTypeClass()) { 1714 default: 1715 return C.getQualifiedType(T.getTypePtr(), Quals); 1716 case Type::TemplateSpecialization: 1717 T = cast<TemplateSpecializationType>(T)->desugar(); 1718 break; 1719 case Type::TypeOfExpr: 1720 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1721 break; 1722 case Type::TypeOf: 1723 T = cast<TypeOfType>(T)->getUnderlyingType(); 1724 break; 1725 case Type::Decltype: 1726 T = cast<DecltypeType>(T)->getUnderlyingType(); 1727 break; 1728 case Type::UnaryTransform: 1729 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 1730 break; 1731 case Type::Attributed: 1732 T = cast<AttributedType>(T)->getEquivalentType(); 1733 break; 1734 case Type::Elaborated: 1735 T = cast<ElaboratedType>(T)->getNamedType(); 1736 break; 1737 case Type::Paren: 1738 T = cast<ParenType>(T)->getInnerType(); 1739 break; 1740 case Type::SubstTemplateTypeParm: 1741 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1742 break; 1743 case Type::Auto: 1744 T = cast<AutoType>(T)->getDeducedType(); 1745 break; 1746 } 1747 1748 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1749 (void)LastT; 1750 } while (true); 1751 } 1752 1753 /// getType - Get the type from the cache or return null type if it doesn't exist. 1754 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) { 1755 1756 // Unwrap the type as needed for debug information. 1757 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1758 1759 // Check for existing entry. 1760 if (Ty->getTypeClass() == Type::ObjCInterface) { 1761 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty); 1762 if (V) 1763 return llvm::DIType(cast<llvm::MDNode>(V)); 1764 else return llvm::DIType(); 1765 } 1766 1767 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1768 TypeCache.find(Ty.getAsOpaquePtr()); 1769 if (it != TypeCache.end()) { 1770 // Verify that the debug info still exists. 1771 if (llvm::Value *V = it->second) 1772 return llvm::DIType(cast<llvm::MDNode>(V)); 1773 } 1774 1775 return llvm::DIType(); 1776 } 1777 1778 /// getCompletedTypeOrNull - Get the type from the cache or return null if it 1779 /// doesn't exist. 1780 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) { 1781 1782 // Unwrap the type as needed for debug information. 1783 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1784 1785 // Check for existing entry. 1786 llvm::Value *V = 0; 1787 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1788 CompletedTypeCache.find(Ty.getAsOpaquePtr()); 1789 if (it != CompletedTypeCache.end()) 1790 V = it->second; 1791 else { 1792 V = getCachedInterfaceTypeOrNull(Ty); 1793 } 1794 1795 // Verify that any cached debug info still exists. 1796 if (V != 0) 1797 return llvm::DIType(cast<llvm::MDNode>(V)); 1798 1799 return llvm::DIType(); 1800 } 1801 1802 /// getCachedInterfaceTypeOrNull - Get the type from the interface 1803 /// cache, unless it needs to regenerated. Otherwise return null. 1804 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) { 1805 // Is there a cached interface that hasn't changed? 1806 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > > 1807 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr()); 1808 1809 if (it1 != ObjCInterfaceCache.end()) 1810 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) 1811 if (Checksum(Decl) == it1->second.second) 1812 // Return cached forward declaration. 1813 return it1->second.first; 1814 1815 return 0; 1816 } 1817 1818 /// getOrCreateType - Get the type from the cache or create a new 1819 /// one if necessary. 1820 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 1821 if (Ty.isNull()) 1822 return llvm::DIType(); 1823 1824 // Unwrap the type as needed for debug information. 1825 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1826 1827 llvm::DIType T = getCompletedTypeOrNull(Ty); 1828 1829 if (T.Verify()) 1830 return T; 1831 1832 // Otherwise create the type. 1833 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1834 void* TyPtr = Ty.getAsOpaquePtr(); 1835 1836 // And update the type cache. 1837 TypeCache[TyPtr] = Res; 1838 1839 llvm::DIType TC = getTypeOrNull(Ty); 1840 if (TC.Verify() && TC.isForwardDecl()) 1841 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 1842 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) { 1843 // Interface types may have elements added to them by a 1844 // subsequent implementation or extension, so we keep them in 1845 // the ObjCInterfaceCache together with a checksum. Instead of 1846 // the (possibly) incomplete interace type, we return a forward 1847 // declaration that gets RAUW'd in CGDebugInfo::finalize(). 1848 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > > 1849 ::iterator it = ObjCInterfaceCache.find(TyPtr); 1850 if (it != ObjCInterfaceCache.end()) 1851 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first)); 1852 else 1853 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1854 Decl->getName(), TheCU, Unit, 1855 getLineNumber(Decl->getLocation()), 1856 TheCU.getLanguage()); 1857 // Store the forward declaration in the cache. 1858 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl)); 1859 1860 // Register the type for replacement in finalize(). 1861 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 1862 return TC; 1863 } 1864 1865 if (!Res.isForwardDecl()) 1866 CompletedTypeCache[TyPtr] = Res; 1867 1868 return Res; 1869 } 1870 1871 /// Currently the checksum merely consists of the number of ivars. 1872 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl 1873 *InterfaceDecl) { 1874 unsigned IvarNo = 0; 1875 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin(); 1876 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo; 1877 return IvarNo; 1878 } 1879 1880 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 1881 switch (Ty->getTypeClass()) { 1882 case Type::ObjCObjectPointer: 1883 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 1884 case Type::ObjCInterface: 1885 return cast<ObjCInterfaceType>(Ty)->getDecl(); 1886 default: 1887 return 0; 1888 } 1889 } 1890 1891 /// CreateTypeNode - Create a new debug type node. 1892 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) { 1893 // Handle qualifiers, which recursively handles what they refer to. 1894 if (Ty.hasLocalQualifiers()) 1895 return CreateQualifiedType(Ty, Unit); 1896 1897 const char *Diag = 0; 1898 1899 // Work out details of type. 1900 switch (Ty->getTypeClass()) { 1901 #define TYPE(Class, Base) 1902 #define ABSTRACT_TYPE(Class, Base) 1903 #define NON_CANONICAL_TYPE(Class, Base) 1904 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1905 #include "clang/AST/TypeNodes.def" 1906 llvm_unreachable("Dependent types cannot show up in debug information"); 1907 1908 case Type::ExtVector: 1909 case Type::Vector: 1910 return CreateType(cast<VectorType>(Ty), Unit); 1911 case Type::ObjCObjectPointer: 1912 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 1913 case Type::ObjCObject: 1914 return CreateType(cast<ObjCObjectType>(Ty), Unit); 1915 case Type::ObjCInterface: 1916 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 1917 case Type::Builtin: 1918 return CreateType(cast<BuiltinType>(Ty)); 1919 case Type::Complex: 1920 return CreateType(cast<ComplexType>(Ty)); 1921 case Type::Pointer: 1922 return CreateType(cast<PointerType>(Ty), Unit); 1923 case Type::BlockPointer: 1924 return CreateType(cast<BlockPointerType>(Ty), Unit); 1925 case Type::Typedef: 1926 return CreateType(cast<TypedefType>(Ty), Unit); 1927 case Type::Record: 1928 return CreateType(cast<RecordType>(Ty)); 1929 case Type::Enum: 1930 return CreateEnumType(cast<EnumType>(Ty)->getDecl()); 1931 case Type::FunctionProto: 1932 case Type::FunctionNoProto: 1933 return CreateType(cast<FunctionType>(Ty), Unit); 1934 case Type::ConstantArray: 1935 case Type::VariableArray: 1936 case Type::IncompleteArray: 1937 return CreateType(cast<ArrayType>(Ty), Unit); 1938 1939 case Type::LValueReference: 1940 return CreateType(cast<LValueReferenceType>(Ty), Unit); 1941 case Type::RValueReference: 1942 return CreateType(cast<RValueReferenceType>(Ty), Unit); 1943 1944 case Type::MemberPointer: 1945 return CreateType(cast<MemberPointerType>(Ty), Unit); 1946 1947 case Type::Atomic: 1948 return CreateType(cast<AtomicType>(Ty), Unit); 1949 1950 case Type::Attributed: 1951 case Type::TemplateSpecialization: 1952 case Type::Elaborated: 1953 case Type::Paren: 1954 case Type::SubstTemplateTypeParm: 1955 case Type::TypeOfExpr: 1956 case Type::TypeOf: 1957 case Type::Decltype: 1958 case Type::UnaryTransform: 1959 case Type::Auto: 1960 llvm_unreachable("type should have been unwrapped!"); 1961 } 1962 1963 assert(Diag && "Fall through without a diagnostic?"); 1964 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1965 "debug information for %0 is not yet supported"); 1966 CGM.getDiags().Report(DiagID) 1967 << Diag; 1968 return llvm::DIType(); 1969 } 1970 1971 /// getOrCreateLimitedType - Get the type from the cache or create a new 1972 /// limited type if necessary. 1973 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty, 1974 llvm::DIFile Unit) { 1975 if (Ty.isNull()) 1976 return llvm::DIType(); 1977 1978 // Unwrap the type as needed for debug information. 1979 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1980 1981 llvm::DIType T = getTypeOrNull(Ty); 1982 1983 // We may have cached a forward decl when we could have created 1984 // a non-forward decl. Go ahead and create a non-forward decl 1985 // now. 1986 if (T.Verify() && !T.isForwardDecl()) return T; 1987 1988 // Otherwise create the type. 1989 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit); 1990 1991 if (T.Verify() && T.isForwardDecl()) 1992 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), 1993 static_cast<llvm::Value*>(T))); 1994 1995 // And update the type cache. 1996 TypeCache[Ty.getAsOpaquePtr()] = Res; 1997 return Res; 1998 } 1999 2000 // TODO: Currently used for context chains when limiting debug info. 2001 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2002 RecordDecl *RD = Ty->getDecl(); 2003 2004 // Get overall information about the record type for the debug info. 2005 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 2006 unsigned Line = getLineNumber(RD->getLocation()); 2007 StringRef RDName = getClassName(RD); 2008 2009 llvm::DIDescriptor RDContext; 2010 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) 2011 RDContext = createContextChain(cast<Decl>(RD->getDeclContext())); 2012 else 2013 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext())); 2014 2015 // If this is just a forward declaration, construct an appropriately 2016 // marked node and just return it. 2017 if (!RD->getDefinition()) 2018 return createRecordFwdDecl(RD, RDContext); 2019 2020 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2021 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 2022 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2023 llvm::DICompositeType RealDecl; 2024 2025 if (RD->isUnion()) 2026 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, 2027 Size, Align, 0, llvm::DIArray()); 2028 else if (RD->isClass()) { 2029 // FIXME: This could be a struct type giving a default visibility different 2030 // than C++ class type, but needs llvm metadata changes first. 2031 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line, 2032 Size, Align, 0, 0, llvm::DIType(), 2033 llvm::DIArray(), llvm::DIType(), 2034 llvm::DIArray()); 2035 } else 2036 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line, 2037 Size, Align, 0, llvm::DIType(), llvm::DIArray()); 2038 2039 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 2040 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; 2041 2042 if (CXXDecl) { 2043 // A class's primary base or the class itself contains the vtable. 2044 llvm::DICompositeType ContainingType; 2045 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2046 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2047 // Seek non virtual primary base root. 2048 while (1) { 2049 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2050 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2051 if (PBT && !BRL.isPrimaryBaseVirtual()) 2052 PBase = PBT; 2053 else 2054 break; 2055 } 2056 ContainingType = llvm::DICompositeType( 2057 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit)); 2058 } else if (CXXDecl->isDynamicClass()) 2059 ContainingType = RealDecl; 2060 2061 RealDecl.setContainingType(ContainingType); 2062 } 2063 return llvm::DIType(RealDecl); 2064 } 2065 2066 /// CreateLimitedTypeNode - Create a new debug type node, but only forward 2067 /// declare composite types that haven't been processed yet. 2068 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) { 2069 2070 // Work out details of type. 2071 switch (Ty->getTypeClass()) { 2072 #define TYPE(Class, Base) 2073 #define ABSTRACT_TYPE(Class, Base) 2074 #define NON_CANONICAL_TYPE(Class, Base) 2075 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2076 #include "clang/AST/TypeNodes.def" 2077 llvm_unreachable("Dependent types cannot show up in debug information"); 2078 2079 case Type::Record: 2080 return CreateLimitedType(cast<RecordType>(Ty)); 2081 default: 2082 return CreateTypeNode(Ty, Unit); 2083 } 2084 } 2085 2086 /// CreateMemberType - Create new member and increase Offset by FType's size. 2087 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 2088 StringRef Name, 2089 uint64_t *Offset) { 2090 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2091 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2092 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 2093 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, 2094 FieldSize, FieldAlign, 2095 *Offset, 0, FieldTy); 2096 *Offset += FieldSize; 2097 return Ty; 2098 } 2099 2100 /// getFunctionDeclaration - Return debug info descriptor to describe method 2101 /// declaration for the given method definition. 2102 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2103 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2104 if (!FD) return llvm::DISubprogram(); 2105 2106 // Setup context. 2107 getContextDescriptor(cast<Decl>(D->getDeclContext())); 2108 2109 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2110 MI = SPCache.find(FD->getCanonicalDecl()); 2111 if (MI != SPCache.end()) { 2112 llvm::Value *V = MI->second; 2113 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2114 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 2115 return SP; 2116 } 2117 2118 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(), 2119 E = FD->redecls_end(); I != E; ++I) { 2120 const FunctionDecl *NextFD = *I; 2121 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2122 MI = SPCache.find(NextFD->getCanonicalDecl()); 2123 if (MI != SPCache.end()) { 2124 llvm::Value *V = MI->second; 2125 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2126 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 2127 return SP; 2128 } 2129 } 2130 return llvm::DISubprogram(); 2131 } 2132 2133 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include 2134 // implicit parameter "this". 2135 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2136 QualType FnType, 2137 llvm::DIFile F) { 2138 2139 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 2140 return getOrCreateMethodType(Method, F); 2141 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 2142 // Add "self" and "_cmd" 2143 SmallVector<llvm::Value *, 16> Elts; 2144 2145 // First element is always return type. For 'void' functions it is NULL. 2146 Elts.push_back(getOrCreateType(OMethod->getResultType(), F)); 2147 // "self" pointer is always first argument. 2148 QualType SelfDeclTy = OMethod->getSelfDecl()->getType(); 2149 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F); 2150 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy)); 2151 // "_cmd" pointer is always second argument. 2152 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F); 2153 Elts.push_back(DBuilder.createArtificialType(CmdTy)); 2154 // Get rest of the arguments. 2155 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(), 2156 PE = OMethod->param_end(); PI != PE; ++PI) 2157 Elts.push_back(getOrCreateType((*PI)->getType(), F)); 2158 2159 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2160 return DBuilder.createSubroutineType(F, EltTypeArray); 2161 } 2162 return getOrCreateType(FnType, F); 2163 } 2164 2165 /// EmitFunctionStart - Constructs the debug code for entering a function. 2166 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 2167 llvm::Function *Fn, 2168 CGBuilderTy &Builder) { 2169 2170 StringRef Name; 2171 StringRef LinkageName; 2172 2173 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 2174 2175 const Decl *D = GD.getDecl(); 2176 // Function may lack declaration in source code if it is created by Clang 2177 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 2178 bool HasDecl = (D != 0); 2179 // Use the location of the declaration. 2180 SourceLocation Loc; 2181 if (HasDecl) 2182 Loc = D->getLocation(); 2183 2184 unsigned Flags = 0; 2185 llvm::DIFile Unit = getOrCreateFile(Loc); 2186 llvm::DIDescriptor FDContext(Unit); 2187 llvm::DIArray TParamsArray; 2188 if (!HasDecl) { 2189 // Use llvm function name. 2190 Name = Fn->getName(); 2191 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2192 // If there is a DISubprogram for this function available then use it. 2193 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2194 FI = SPCache.find(FD->getCanonicalDecl()); 2195 if (FI != SPCache.end()) { 2196 llvm::Value *V = FI->second; 2197 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V)); 2198 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 2199 llvm::MDNode *SPN = SP; 2200 LexicalBlockStack.push_back(SPN); 2201 RegionMap[D] = llvm::WeakVH(SP); 2202 return; 2203 } 2204 } 2205 Name = getFunctionName(FD); 2206 // Use mangled name as linkage name for C/C++ functions. 2207 if (FD->hasPrototype()) { 2208 LinkageName = CGM.getMangledName(GD); 2209 Flags |= llvm::DIDescriptor::FlagPrototyped; 2210 } 2211 // No need to replicate the linkage name if it isn't different from the 2212 // subprogram name, no need to have it at all unless coverage is enabled or 2213 // debug is set to more than just line tables. 2214 if (LinkageName == Name || 2215 (!CGM.getCodeGenOpts().EmitGcovArcs && 2216 !CGM.getCodeGenOpts().EmitGcovNotes && 2217 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly)) 2218 LinkageName = StringRef(); 2219 2220 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 2221 if (const NamespaceDecl *NSDecl = 2222 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2223 FDContext = getOrCreateNameSpace(NSDecl); 2224 else if (const RecordDecl *RDecl = 2225 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 2226 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext())); 2227 2228 // Collect template parameters. 2229 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2230 } 2231 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2232 Name = getObjCMethodName(OMD); 2233 Flags |= llvm::DIDescriptor::FlagPrototyped; 2234 } else { 2235 // Use llvm function name. 2236 Name = Fn->getName(); 2237 Flags |= llvm::DIDescriptor::FlagPrototyped; 2238 } 2239 if (!Name.empty() && Name[0] == '\01') 2240 Name = Name.substr(1); 2241 2242 unsigned LineNo = getLineNumber(Loc); 2243 if (!HasDecl || D->isImplicit()) 2244 Flags |= llvm::DIDescriptor::FlagArtificial; 2245 2246 llvm::DIType DIFnType; 2247 llvm::DISubprogram SPDecl; 2248 if (HasDecl && 2249 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 2250 DIFnType = getOrCreateFunctionType(D, FnType, Unit); 2251 SPDecl = getFunctionDeclaration(D); 2252 } else { 2253 // Create fake but valid subroutine type. Otherwise 2254 // llvm::DISubprogram::Verify() would return false, and 2255 // subprogram DIE will miss DW_AT_decl_file and 2256 // DW_AT_decl_line fields. 2257 SmallVector<llvm::Value*, 16> Elts; 2258 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2259 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray); 2260 } 2261 llvm::DISubprogram SP; 2262 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit, 2263 LineNo, DIFnType, 2264 Fn->hasInternalLinkage(), true/*definition*/, 2265 getLineNumber(CurLoc), Flags, 2266 CGM.getLangOpts().Optimize, 2267 Fn, TParamsArray, SPDecl); 2268 2269 // Push function on region stack. 2270 llvm::MDNode *SPN = SP; 2271 LexicalBlockStack.push_back(SPN); 2272 if (HasDecl) 2273 RegionMap[D] = llvm::WeakVH(SP); 2274 } 2275 2276 /// EmitLocation - Emit metadata to indicate a change in line/column 2277 /// information in the source file. 2278 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc, 2279 bool ForceColumnInfo) { 2280 2281 // Update our current location 2282 setLocation(Loc); 2283 2284 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 2285 2286 // Don't bother if things are the same as last time. 2287 SourceManager &SM = CGM.getContext().getSourceManager(); 2288 if (CurLoc == PrevLoc || 2289 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc)) 2290 // New Builder may not be in sync with CGDebugInfo. 2291 if (!Builder.getCurrentDebugLocation().isUnknown() && 2292 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) == 2293 LexicalBlockStack.back()) 2294 return; 2295 2296 // Update last state. 2297 PrevLoc = CurLoc; 2298 2299 llvm::MDNode *Scope = LexicalBlockStack.back(); 2300 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get 2301 (getLineNumber(CurLoc), 2302 getColumnNumber(CurLoc, ForceColumnInfo), 2303 Scope)); 2304 } 2305 2306 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on 2307 /// the stack. 2308 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 2309 llvm::DIDescriptor D = 2310 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ? 2311 llvm::DIDescriptor() : 2312 llvm::DIDescriptor(LexicalBlockStack.back()), 2313 getOrCreateFile(CurLoc), 2314 getLineNumber(CurLoc), 2315 getColumnNumber(CurLoc)); 2316 llvm::MDNode *DN = D; 2317 LexicalBlockStack.push_back(DN); 2318 } 2319 2320 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 2321 /// region - beginning of a DW_TAG_lexical_block. 2322 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) { 2323 // Set our current location. 2324 setLocation(Loc); 2325 2326 // Create a new lexical block and push it on the stack. 2327 CreateLexicalBlock(Loc); 2328 2329 // Emit a line table change for the current location inside the new scope. 2330 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc), 2331 getColumnNumber(Loc), 2332 LexicalBlockStack.back())); 2333 } 2334 2335 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 2336 /// region - end of a DW_TAG_lexical_block. 2337 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) { 2338 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2339 2340 // Provide an entry in the line table for the end of the block. 2341 EmitLocation(Builder, Loc); 2342 2343 LexicalBlockStack.pop_back(); 2344 } 2345 2346 /// EmitFunctionEnd - Constructs the debug code for exiting a function. 2347 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 2348 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2349 unsigned RCount = FnBeginRegionCount.back(); 2350 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 2351 2352 // Pop all regions for this function. 2353 while (LexicalBlockStack.size() != RCount) 2354 EmitLexicalBlockEnd(Builder, CurLoc); 2355 FnBeginRegionCount.pop_back(); 2356 } 2357 2358 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 2359 // See BuildByRefType. 2360 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 2361 uint64_t *XOffset) { 2362 2363 SmallVector<llvm::Value *, 5> EltTys; 2364 QualType FType; 2365 uint64_t FieldSize, FieldOffset; 2366 unsigned FieldAlign; 2367 2368 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2369 QualType Type = VD->getType(); 2370 2371 FieldOffset = 0; 2372 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2373 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 2374 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 2375 FType = CGM.getContext().IntTy; 2376 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 2377 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 2378 2379 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 2380 if (HasCopyAndDispose) { 2381 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2382 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 2383 &FieldOffset)); 2384 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 2385 &FieldOffset)); 2386 } 2387 bool HasByrefExtendedLayout; 2388 Qualifiers::ObjCLifetime Lifetime; 2389 if (CGM.getContext().getByrefLifetime(Type, 2390 Lifetime, HasByrefExtendedLayout) 2391 && HasByrefExtendedLayout) 2392 EltTys.push_back(CreateMemberType(Unit, FType, 2393 "__byref_variable_layout", 2394 &FieldOffset)); 2395 2396 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2397 if (Align > CGM.getContext().toCharUnitsFromBits( 2398 CGM.getTarget().getPointerAlign(0))) { 2399 CharUnits FieldOffsetInBytes 2400 = CGM.getContext().toCharUnitsFromBits(FieldOffset); 2401 CharUnits AlignedOffsetInBytes 2402 = FieldOffsetInBytes.RoundUpToAlignment(Align); 2403 CharUnits NumPaddingBytes 2404 = AlignedOffsetInBytes - FieldOffsetInBytes; 2405 2406 if (NumPaddingBytes.isPositive()) { 2407 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2408 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2409 pad, ArrayType::Normal, 0); 2410 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2411 } 2412 } 2413 2414 FType = Type; 2415 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2416 FieldSize = CGM.getContext().getTypeSize(FType); 2417 FieldAlign = CGM.getContext().toBits(Align); 2418 2419 *XOffset = FieldOffset; 2420 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 2421 0, FieldSize, FieldAlign, 2422 FieldOffset, 0, FieldTy); 2423 EltTys.push_back(FieldTy); 2424 FieldOffset += FieldSize; 2425 2426 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 2427 2428 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 2429 2430 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2431 llvm::DIType(), Elements); 2432 } 2433 2434 /// EmitDeclare - Emit local variable declaration debug info. 2435 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 2436 llvm::Value *Storage, 2437 unsigned ArgNo, CGBuilderTy &Builder) { 2438 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2439 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2440 2441 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2442 llvm::DIType Ty; 2443 uint64_t XOffset = 0; 2444 if (VD->hasAttr<BlocksAttr>()) 2445 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2446 else 2447 Ty = getOrCreateType(VD->getType(), Unit); 2448 2449 // If there is no debug info for this type then do not emit debug info 2450 // for this variable. 2451 if (!Ty) 2452 return; 2453 2454 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) { 2455 // If Storage is an aggregate returned as 'sret' then let debugger know 2456 // about this. 2457 if (Arg->hasStructRetAttr()) 2458 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty); 2459 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) { 2460 // If an aggregate variable has non trivial destructor or non trivial copy 2461 // constructor than it is pass indirectly. Let debug info know about this 2462 // by using reference of the aggregate type as a argument type. 2463 if (Record->hasNonTrivialCopyConstructor() || 2464 !Record->hasTrivialDestructor()) 2465 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty); 2466 } 2467 } 2468 2469 // Get location information. 2470 unsigned Line = getLineNumber(VD->getLocation()); 2471 unsigned Column = getColumnNumber(VD->getLocation()); 2472 unsigned Flags = 0; 2473 if (VD->isImplicit()) 2474 Flags |= llvm::DIDescriptor::FlagArtificial; 2475 // If this is the first argument and it is implicit then 2476 // give it an object pointer flag. 2477 // FIXME: There has to be a better way to do this, but for static 2478 // functions there won't be an implicit param at arg1 and 2479 // otherwise it is 'self' or 'this'. 2480 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1) 2481 Flags |= llvm::DIDescriptor::FlagObjectPointer; 2482 2483 llvm::MDNode *Scope = LexicalBlockStack.back(); 2484 2485 StringRef Name = VD->getName(); 2486 if (!Name.empty()) { 2487 if (VD->hasAttr<BlocksAttr>()) { 2488 CharUnits offset = CharUnits::fromQuantity(32); 2489 SmallVector<llvm::Value *, 9> addr; 2490 llvm::Type *Int64Ty = CGM.Int64Ty; 2491 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2492 // offset of __forwarding field 2493 offset = CGM.getContext().toCharUnitsFromBits( 2494 CGM.getTarget().getPointerWidth(0)); 2495 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2496 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2497 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2498 // offset of x field 2499 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2500 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2501 2502 // Create the descriptor for the variable. 2503 llvm::DIVariable D = 2504 DBuilder.createComplexVariable(Tag, 2505 llvm::DIDescriptor(Scope), 2506 VD->getName(), Unit, Line, Ty, 2507 addr, ArgNo); 2508 2509 // Insert an llvm.dbg.declare into the current block. 2510 llvm::Instruction *Call = 2511 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2512 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2513 return; 2514 } else if (isa<VariableArrayType>(VD->getType())) { 2515 // These are "complex" variables in that they need an op_deref. 2516 // Create the descriptor for the variable. 2517 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty, 2518 llvm::DIBuilder::OpDeref); 2519 llvm::DIVariable D = 2520 DBuilder.createComplexVariable(Tag, 2521 llvm::DIDescriptor(Scope), 2522 Name, Unit, Line, Ty, 2523 Addr, ArgNo); 2524 2525 // Insert an llvm.dbg.declare into the current block. 2526 llvm::Instruction *Call = 2527 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2528 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2529 return; 2530 } 2531 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2532 // If VD is an anonymous union then Storage represents value for 2533 // all union fields. 2534 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2535 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 2536 for (RecordDecl::field_iterator I = RD->field_begin(), 2537 E = RD->field_end(); 2538 I != E; ++I) { 2539 FieldDecl *Field = *I; 2540 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 2541 StringRef FieldName = Field->getName(); 2542 2543 // Ignore unnamed fields. Do not ignore unnamed records. 2544 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2545 continue; 2546 2547 // Use VarDecl's Tag, Scope and Line number. 2548 llvm::DIVariable D = 2549 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2550 FieldName, Unit, Line, FieldTy, 2551 CGM.getLangOpts().Optimize, Flags, 2552 ArgNo); 2553 2554 // Insert an llvm.dbg.declare into the current block. 2555 llvm::Instruction *Call = 2556 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2557 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2558 } 2559 return; 2560 } 2561 } 2562 2563 // Create the descriptor for the variable. 2564 llvm::DIVariable D = 2565 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2566 Name, Unit, Line, Ty, 2567 CGM.getLangOpts().Optimize, Flags, ArgNo); 2568 2569 // Insert an llvm.dbg.declare into the current block. 2570 llvm::Instruction *Call = 2571 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2572 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2573 } 2574 2575 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2576 llvm::Value *Storage, 2577 CGBuilderTy &Builder) { 2578 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2579 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 2580 } 2581 2582 /// Look up the completed type for a self pointer in the TypeCache and 2583 /// create a copy of it with the ObjectPointer and Artificial flags 2584 /// set. If the type is not cached, a new one is created. This should 2585 /// never happen though, since creating a type for the implicit self 2586 /// argument implies that we already parsed the interface definition 2587 /// and the ivar declarations in the implementation. 2588 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) { 2589 llvm::DIType CachedTy = getTypeOrNull(QualTy); 2590 if (CachedTy.Verify()) Ty = CachedTy; 2591 else DEBUG(llvm::dbgs() << "No cached type for self."); 2592 return DBuilder.createObjectPointerType(Ty); 2593 } 2594 2595 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD, 2596 llvm::Value *Storage, 2597 CGBuilderTy &Builder, 2598 const CGBlockInfo &blockInfo) { 2599 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2600 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2601 2602 if (Builder.GetInsertBlock() == 0) 2603 return; 2604 2605 bool isByRef = VD->hasAttr<BlocksAttr>(); 2606 2607 uint64_t XOffset = 0; 2608 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2609 llvm::DIType Ty; 2610 if (isByRef) 2611 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2612 else 2613 Ty = getOrCreateType(VD->getType(), Unit); 2614 2615 // Self is passed along as an implicit non-arg variable in a 2616 // block. Mark it as the object pointer. 2617 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 2618 Ty = CreateSelfType(VD->getType(), Ty); 2619 2620 // Get location information. 2621 unsigned Line = getLineNumber(VD->getLocation()); 2622 unsigned Column = getColumnNumber(VD->getLocation()); 2623 2624 const llvm::DataLayout &target = CGM.getDataLayout(); 2625 2626 CharUnits offset = CharUnits::fromQuantity( 2627 target.getStructLayout(blockInfo.StructureType) 2628 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 2629 2630 SmallVector<llvm::Value *, 9> addr; 2631 llvm::Type *Int64Ty = CGM.Int64Ty; 2632 if (isa<llvm::AllocaInst>(Storage)) 2633 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2634 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2635 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2636 if (isByRef) { 2637 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2638 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2639 // offset of __forwarding field 2640 offset = CGM.getContext() 2641 .toCharUnitsFromBits(target.getPointerSizeInBits(0)); 2642 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2643 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2644 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2645 // offset of x field 2646 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2647 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2648 } 2649 2650 // Create the descriptor for the variable. 2651 llvm::DIVariable D = 2652 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable, 2653 llvm::DIDescriptor(LexicalBlockStack.back()), 2654 VD->getName(), Unit, Line, Ty, addr); 2655 2656 // Insert an llvm.dbg.declare into the current block. 2657 llvm::Instruction *Call = 2658 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint()); 2659 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, 2660 LexicalBlockStack.back())); 2661 } 2662 2663 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2664 /// variable declaration. 2665 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2666 unsigned ArgNo, 2667 CGBuilderTy &Builder) { 2668 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2669 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2670 } 2671 2672 namespace { 2673 struct BlockLayoutChunk { 2674 uint64_t OffsetInBits; 2675 const BlockDecl::Capture *Capture; 2676 }; 2677 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2678 return l.OffsetInBits < r.OffsetInBits; 2679 } 2680 } 2681 2682 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2683 llvm::Value *Arg, 2684 llvm::Value *LocalAddr, 2685 CGBuilderTy &Builder) { 2686 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2687 ASTContext &C = CGM.getContext(); 2688 const BlockDecl *blockDecl = block.getBlockDecl(); 2689 2690 // Collect some general information about the block's location. 2691 SourceLocation loc = blockDecl->getCaretLocation(); 2692 llvm::DIFile tunit = getOrCreateFile(loc); 2693 unsigned line = getLineNumber(loc); 2694 unsigned column = getColumnNumber(loc); 2695 2696 // Build the debug-info type for the block literal. 2697 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 2698 2699 const llvm::StructLayout *blockLayout = 2700 CGM.getDataLayout().getStructLayout(block.StructureType); 2701 2702 SmallVector<llvm::Value*, 16> fields; 2703 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 2704 blockLayout->getElementOffsetInBits(0), 2705 tunit, tunit)); 2706 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 2707 blockLayout->getElementOffsetInBits(1), 2708 tunit, tunit)); 2709 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 2710 blockLayout->getElementOffsetInBits(2), 2711 tunit, tunit)); 2712 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public, 2713 blockLayout->getElementOffsetInBits(3), 2714 tunit, tunit)); 2715 fields.push_back(createFieldType("__descriptor", 2716 C.getPointerType(block.NeedsCopyDispose ? 2717 C.getBlockDescriptorExtendedType() : 2718 C.getBlockDescriptorType()), 2719 0, loc, AS_public, 2720 blockLayout->getElementOffsetInBits(4), 2721 tunit, tunit)); 2722 2723 // We want to sort the captures by offset, not because DWARF 2724 // requires this, but because we're paranoid about debuggers. 2725 SmallVector<BlockLayoutChunk, 8> chunks; 2726 2727 // 'this' capture. 2728 if (blockDecl->capturesCXXThis()) { 2729 BlockLayoutChunk chunk; 2730 chunk.OffsetInBits = 2731 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 2732 chunk.Capture = 0; 2733 chunks.push_back(chunk); 2734 } 2735 2736 // Variable captures. 2737 for (BlockDecl::capture_const_iterator 2738 i = blockDecl->capture_begin(), e = blockDecl->capture_end(); 2739 i != e; ++i) { 2740 const BlockDecl::Capture &capture = *i; 2741 const VarDecl *variable = capture.getVariable(); 2742 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 2743 2744 // Ignore constant captures. 2745 if (captureInfo.isConstant()) 2746 continue; 2747 2748 BlockLayoutChunk chunk; 2749 chunk.OffsetInBits = 2750 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 2751 chunk.Capture = &capture; 2752 chunks.push_back(chunk); 2753 } 2754 2755 // Sort by offset. 2756 llvm::array_pod_sort(chunks.begin(), chunks.end()); 2757 2758 for (SmallVectorImpl<BlockLayoutChunk>::iterator 2759 i = chunks.begin(), e = chunks.end(); i != e; ++i) { 2760 uint64_t offsetInBits = i->OffsetInBits; 2761 const BlockDecl::Capture *capture = i->Capture; 2762 2763 // If we have a null capture, this must be the C++ 'this' capture. 2764 if (!capture) { 2765 const CXXMethodDecl *method = 2766 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 2767 QualType type = method->getThisType(C); 2768 2769 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 2770 offsetInBits, tunit, tunit)); 2771 continue; 2772 } 2773 2774 const VarDecl *variable = capture->getVariable(); 2775 StringRef name = variable->getName(); 2776 2777 llvm::DIType fieldType; 2778 if (capture->isByRef()) { 2779 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy); 2780 2781 // FIXME: this creates a second copy of this type! 2782 uint64_t xoffset; 2783 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 2784 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first); 2785 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 2786 ptrInfo.first, ptrInfo.second, 2787 offsetInBits, 0, fieldType); 2788 } else { 2789 fieldType = createFieldType(name, variable->getType(), 0, 2790 loc, AS_public, offsetInBits, tunit, tunit); 2791 } 2792 fields.push_back(fieldType); 2793 } 2794 2795 SmallString<36> typeName; 2796 llvm::raw_svector_ostream(typeName) 2797 << "__block_literal_" << CGM.getUniqueBlockCount(); 2798 2799 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields); 2800 2801 llvm::DIType type = 2802 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 2803 CGM.getContext().toBits(block.BlockSize), 2804 CGM.getContext().toBits(block.BlockAlign), 2805 0, llvm::DIType(), fieldsArray); 2806 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 2807 2808 // Get overall information about the block. 2809 unsigned flags = llvm::DIDescriptor::FlagArtificial; 2810 llvm::MDNode *scope = LexicalBlockStack.back(); 2811 2812 // Create the descriptor for the parameter. 2813 llvm::DIVariable debugVar = 2814 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable, 2815 llvm::DIDescriptor(scope), 2816 Arg->getName(), tunit, line, type, 2817 CGM.getLangOpts().Optimize, flags, 2818 cast<llvm::Argument>(Arg)->getArgNo() + 1); 2819 2820 if (LocalAddr) { 2821 // Insert an llvm.dbg.value into the current block. 2822 llvm::Instruction *DbgVal = 2823 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar, 2824 Builder.GetInsertBlock()); 2825 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2826 } 2827 2828 // Insert an llvm.dbg.declare into the current block. 2829 llvm::Instruction *DbgDecl = 2830 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock()); 2831 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2832 } 2833 2834 /// getStaticDataMemberDeclaration - If D is an out-of-class definition of 2835 /// a static data member of a class, find its corresponding in-class 2836 /// declaration. 2837 llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) { 2838 if (cast<VarDecl>(D)->isStaticDataMember()) { 2839 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 2840 MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 2841 if (MI != StaticDataMemberCache.end()) 2842 // Verify the info still exists. 2843 if (llvm::Value *V = MI->second) 2844 return llvm::DIDerivedType(cast<llvm::MDNode>(V)); 2845 } 2846 return llvm::DIDerivedType(); 2847 } 2848 2849 /// EmitGlobalVariable - Emit information about a global variable. 2850 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2851 const VarDecl *D) { 2852 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2853 // Create global variable debug descriptor. 2854 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 2855 unsigned LineNo = getLineNumber(D->getLocation()); 2856 2857 setLocation(D->getLocation()); 2858 2859 QualType T = D->getType(); 2860 if (T->isIncompleteArrayType()) { 2861 2862 // CodeGen turns int[] into int[1] so we'll do the same here. 2863 llvm::APInt ConstVal(32, 1); 2864 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2865 2866 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2867 ArrayType::Normal, 0); 2868 } 2869 StringRef DeclName = D->getName(); 2870 StringRef LinkageName; 2871 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) 2872 && !isa<ObjCMethodDecl>(D->getDeclContext())) 2873 LinkageName = Var->getName(); 2874 if (LinkageName == DeclName) 2875 LinkageName = StringRef(); 2876 llvm::DIDescriptor DContext = 2877 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext())); 2878 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, 2879 Unit, LineNo, getOrCreateType(T, Unit), 2880 Var->hasInternalLinkage(), Var, 2881 getStaticDataMemberDeclaration(D)); 2882 } 2883 2884 /// EmitGlobalVariable - Emit information about an objective-c interface. 2885 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2886 ObjCInterfaceDecl *ID) { 2887 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2888 // Create global variable debug descriptor. 2889 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 2890 unsigned LineNo = getLineNumber(ID->getLocation()); 2891 2892 StringRef Name = ID->getName(); 2893 2894 QualType T = CGM.getContext().getObjCInterfaceType(ID); 2895 if (T->isIncompleteArrayType()) { 2896 2897 // CodeGen turns int[] into int[1] so we'll do the same here. 2898 llvm::APInt ConstVal(32, 1); 2899 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2900 2901 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2902 ArrayType::Normal, 0); 2903 } 2904 2905 DBuilder.createGlobalVariable(Name, Unit, LineNo, 2906 getOrCreateType(T, Unit), 2907 Var->hasInternalLinkage(), Var); 2908 } 2909 2910 /// EmitGlobalVariable - Emit global variable's debug info. 2911 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 2912 llvm::Constant *Init) { 2913 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo); 2914 // Create the descriptor for the variable. 2915 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2916 StringRef Name = VD->getName(); 2917 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 2918 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 2919 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 2920 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 2921 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 2922 } 2923 // Do not use DIGlobalVariable for enums. 2924 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 2925 return; 2926 DBuilder.createStaticVariable(Unit, Name, Name, Unit, 2927 getLineNumber(VD->getLocation()), 2928 Ty, true, Init, 2929 getStaticDataMemberDeclaration(VD)); 2930 } 2931 2932 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 2933 DBuilder.createImportedModule( 2934 getContextDescriptor(cast<Decl>(UD.getDeclContext())), 2935 getOrCreateNameSpace(UD.getNominatedNamespace()), 2936 getLineNumber(UD.getLocation())); 2937 } 2938 2939 /// getOrCreateNamesSpace - Return namespace descriptor for the given 2940 /// namespace decl. 2941 llvm::DINameSpace 2942 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 2943 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 2944 NameSpaceCache.find(NSDecl); 2945 if (I != NameSpaceCache.end()) 2946 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 2947 2948 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 2949 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 2950 llvm::DIDescriptor Context = 2951 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 2952 llvm::DINameSpace NS = 2953 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 2954 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 2955 return NS; 2956 } 2957 2958 void CGDebugInfo::finalize() { 2959 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI 2960 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) { 2961 llvm::DIType Ty, RepTy; 2962 // Verify that the debug info still exists. 2963 if (llvm::Value *V = VI->second) 2964 Ty = llvm::DIType(cast<llvm::MDNode>(V)); 2965 2966 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2967 TypeCache.find(VI->first); 2968 if (it != TypeCache.end()) { 2969 // Verify that the debug info still exists. 2970 if (llvm::Value *V = it->second) 2971 RepTy = llvm::DIType(cast<llvm::MDNode>(V)); 2972 } 2973 2974 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) 2975 Ty.replaceAllUsesWith(RepTy); 2976 } 2977 2978 // We keep our own list of retained types, because we need to look 2979 // up the final type in the type cache. 2980 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(), 2981 RE = RetainedTypes.end(); RI != RE; ++RI) 2982 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI]))); 2983 2984 DBuilder.finalize(); 2985 } 2986