clang API Documentation
00001 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This coordinates the debug information generation while generating code. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "CGDebugInfo.h" 00015 #include "CGBlocks.h" 00016 #include "CGCXXABI.h" 00017 #include "CGObjCRuntime.h" 00018 #include "CodeGenFunction.h" 00019 #include "CodeGenModule.h" 00020 #include "clang/AST/ASTContext.h" 00021 #include "clang/AST/DeclFriend.h" 00022 #include "clang/AST/DeclObjC.h" 00023 #include "clang/AST/DeclTemplate.h" 00024 #include "clang/AST/Expr.h" 00025 #include "clang/AST/RecordLayout.h" 00026 #include "clang/Basic/FileManager.h" 00027 #include "clang/Basic/SourceManager.h" 00028 #include "clang/Basic/Version.h" 00029 #include "clang/Frontend/CodeGenOptions.h" 00030 #include "llvm/ADT/SmallVector.h" 00031 #include "llvm/ADT/StringExtras.h" 00032 #include "llvm/IR/Constants.h" 00033 #include "llvm/IR/DataLayout.h" 00034 #include "llvm/IR/DerivedTypes.h" 00035 #include "llvm/IR/Instructions.h" 00036 #include "llvm/IR/Intrinsics.h" 00037 #include "llvm/IR/Module.h" 00038 #include "llvm/Support/Dwarf.h" 00039 #include "llvm/Support/FileSystem.h" 00040 #include "llvm/Support/Path.h" 00041 using namespace clang; 00042 using namespace clang::CodeGen; 00043 00044 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 00045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()), 00046 DBuilder(CGM.getModule()) { 00047 CreateCompileUnit(); 00048 } 00049 00050 CGDebugInfo::~CGDebugInfo() { 00051 assert(LexicalBlockStack.empty() && 00052 "Region stack mismatch, stack not empty!"); 00053 } 00054 00055 SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF, 00056 CGBuilderTy &B) 00057 : DI(CGF.getDebugInfo()), Builder(B) { 00058 if (DI) { 00059 SavedLoc = DI->getLocation(); 00060 DI->CurLoc = SourceLocation(); 00061 } 00062 } 00063 00064 SaveAndRestoreLocation::~SaveAndRestoreLocation() { 00065 if (DI) 00066 DI->EmitLocation(Builder, SavedLoc); 00067 } 00068 00069 NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B) 00070 : SaveAndRestoreLocation(CGF, B) { 00071 if (DI) 00072 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 00073 } 00074 00075 NoLocation::~NoLocation() { 00076 if (DI) 00077 assert(Builder.getCurrentDebugLocation().isUnknown()); 00078 } 00079 00080 ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B) 00081 : SaveAndRestoreLocation(CGF, B) { 00082 if (DI) 00083 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 00084 } 00085 00086 void ArtificialLocation::Emit() { 00087 if (DI) { 00088 // Sync the Builder. 00089 DI->EmitLocation(Builder, SavedLoc); 00090 DI->CurLoc = SourceLocation(); 00091 // Construct a location that has a valid scope, but no line info. 00092 assert(!DI->LexicalBlockStack.empty()); 00093 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back()); 00094 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope)); 00095 } 00096 } 00097 00098 ArtificialLocation::~ArtificialLocation() { 00099 if (DI) 00100 assert(Builder.getCurrentDebugLocation().getLine() == 0); 00101 } 00102 00103 void CGDebugInfo::setLocation(SourceLocation Loc) { 00104 // If the new location isn't valid return. 00105 if (Loc.isInvalid()) 00106 return; 00107 00108 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc); 00109 00110 // If we've changed files in the middle of a lexical scope go ahead 00111 // and create a new lexical scope with file node if it's different 00112 // from the one in the scope. 00113 if (LexicalBlockStack.empty()) 00114 return; 00115 00116 SourceManager &SM = CGM.getContext().getSourceManager(); 00117 llvm::DIScope Scope(LexicalBlockStack.back()); 00118 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 00119 00120 if (PCLoc.isInvalid() || Scope.getFilename() == PCLoc.getFilename()) 00121 return; 00122 00123 if (Scope.isLexicalBlockFile()) { 00124 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(Scope); 00125 llvm::DIDescriptor D = DBuilder.createLexicalBlockFile( 00126 LBF.getScope(), getOrCreateFile(CurLoc)); 00127 llvm::MDNode *N = D; 00128 LexicalBlockStack.pop_back(); 00129 LexicalBlockStack.push_back(N); 00130 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) { 00131 llvm::DIDescriptor D = 00132 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)); 00133 llvm::MDNode *N = D; 00134 LexicalBlockStack.pop_back(); 00135 LexicalBlockStack.push_back(N); 00136 } 00137 } 00138 00139 /// getContextDescriptor - Get context info for the decl. 00140 llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) { 00141 if (!Context) 00142 return TheCU; 00143 00144 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I = 00145 RegionMap.find(Context); 00146 if (I != RegionMap.end()) { 00147 llvm::Value *V = I->second; 00148 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V)); 00149 } 00150 00151 // Check namespace. 00152 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 00153 return getOrCreateNameSpace(NSDecl); 00154 00155 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) 00156 if (!RDecl->isDependentType()) 00157 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 00158 getOrCreateMainFile()); 00159 return TheCU; 00160 } 00161 00162 /// getFunctionName - Get function name for the given FunctionDecl. If the 00163 /// name is constructed on demand (e.g. C++ destructor) then the name 00164 /// is stored on the side. 00165 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 00166 assert(FD && "Invalid FunctionDecl!"); 00167 IdentifierInfo *FII = FD->getIdentifier(); 00168 FunctionTemplateSpecializationInfo *Info = 00169 FD->getTemplateSpecializationInfo(); 00170 if (!Info && FII) 00171 return FII->getName(); 00172 00173 // Otherwise construct human readable name for debug info. 00174 SmallString<128> NS; 00175 llvm::raw_svector_ostream OS(NS); 00176 FD->printName(OS); 00177 00178 // Add any template specialization args. 00179 if (Info) { 00180 const TemplateArgumentList *TArgs = Info->TemplateArguments; 00181 const TemplateArgument *Args = TArgs->data(); 00182 unsigned NumArgs = TArgs->size(); 00183 PrintingPolicy Policy(CGM.getLangOpts()); 00184 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs, 00185 Policy); 00186 } 00187 00188 // Copy this name on the side and use its reference. 00189 return internString(OS.str()); 00190 } 00191 00192 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 00193 SmallString<256> MethodName; 00194 llvm::raw_svector_ostream OS(MethodName); 00195 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 00196 const DeclContext *DC = OMD->getDeclContext(); 00197 if (const ObjCImplementationDecl *OID = 00198 dyn_cast<const ObjCImplementationDecl>(DC)) { 00199 OS << OID->getName(); 00200 } else if (const ObjCInterfaceDecl *OID = 00201 dyn_cast<const ObjCInterfaceDecl>(DC)) { 00202 OS << OID->getName(); 00203 } else if (const ObjCCategoryImplDecl *OCD = 00204 dyn_cast<const ObjCCategoryImplDecl>(DC)) { 00205 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' 00206 << OCD->getIdentifier()->getNameStart() << ')'; 00207 } else if (isa<ObjCProtocolDecl>(DC)) { 00208 // We can extract the type of the class from the self pointer. 00209 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) { 00210 QualType ClassTy = 00211 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType(); 00212 ClassTy.print(OS, PrintingPolicy(LangOptions())); 00213 } 00214 } 00215 OS << ' ' << OMD->getSelector().getAsString() << ']'; 00216 00217 return internString(OS.str()); 00218 } 00219 00220 /// getSelectorName - Return selector name. This is used for debugging 00221 /// info. 00222 StringRef CGDebugInfo::getSelectorName(Selector S) { 00223 return internString(S.getAsString()); 00224 } 00225 00226 /// getClassName - Get class name including template argument list. 00227 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) { 00228 // quick optimization to avoid having to intern strings that are already 00229 // stored reliably elsewhere 00230 if (!isa<ClassTemplateSpecializationDecl>(RD)) 00231 return RD->getName(); 00232 00233 SmallString<128> Name; 00234 { 00235 llvm::raw_svector_ostream OS(Name); 00236 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(), 00237 /*Qualified*/ false); 00238 } 00239 00240 // Copy this name on the side and use its reference. 00241 return internString(Name); 00242 } 00243 00244 /// getOrCreateFile - Get the file debug info descriptor for the input location. 00245 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 00246 if (!Loc.isValid()) 00247 // If Location is not valid then use main input file. 00248 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 00249 00250 SourceManager &SM = CGM.getContext().getSourceManager(); 00251 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 00252 00253 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty()) 00254 // If the location is not valid then use main input file. 00255 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 00256 00257 // Cache the results. 00258 const char *fname = PLoc.getFilename(); 00259 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it = 00260 DIFileCache.find(fname); 00261 00262 if (it != DIFileCache.end()) { 00263 // Verify that the information still exists. 00264 if (llvm::Value *V = it->second) 00265 return llvm::DIFile(cast<llvm::MDNode>(V)); 00266 } 00267 00268 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname()); 00269 00270 DIFileCache[fname] = F; 00271 return F; 00272 } 00273 00274 /// getOrCreateMainFile - Get the file info for main compile unit. 00275 llvm::DIFile CGDebugInfo::getOrCreateMainFile() { 00276 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 00277 } 00278 00279 /// getLineNumber - Get line number for the location. If location is invalid 00280 /// then use current location. 00281 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 00282 if (Loc.isInvalid() && CurLoc.isInvalid()) 00283 return 0; 00284 SourceManager &SM = CGM.getContext().getSourceManager(); 00285 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 00286 return PLoc.isValid() ? PLoc.getLine() : 0; 00287 } 00288 00289 /// getColumnNumber - Get column number for the location. 00290 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { 00291 // We may not want column information at all. 00292 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) 00293 return 0; 00294 00295 // If the location is invalid then use the current column. 00296 if (Loc.isInvalid() && CurLoc.isInvalid()) 00297 return 0; 00298 SourceManager &SM = CGM.getContext().getSourceManager(); 00299 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 00300 return PLoc.isValid() ? PLoc.getColumn() : 0; 00301 } 00302 00303 StringRef CGDebugInfo::getCurrentDirname() { 00304 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) 00305 return CGM.getCodeGenOpts().DebugCompilationDir; 00306 00307 if (!CWDName.empty()) 00308 return CWDName; 00309 SmallString<256> CWD; 00310 llvm::sys::fs::current_path(CWD); 00311 return CWDName = internString(CWD); 00312 } 00313 00314 /// CreateCompileUnit - Create new compile unit. 00315 void CGDebugInfo::CreateCompileUnit() { 00316 00317 // Should we be asking the SourceManager for the main file name, instead of 00318 // accepting it as an argument? This just causes the main file name to 00319 // mismatch with source locations and create extra lexical scopes or 00320 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what 00321 // the driver passed, but functions/other things have DW_AT_file of "<stdin>" 00322 // because that's what the SourceManager says) 00323 00324 // Get absolute path name. 00325 SourceManager &SM = CGM.getContext().getSourceManager(); 00326 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 00327 if (MainFileName.empty()) 00328 MainFileName = "<stdin>"; 00329 00330 // The main file name provided via the "-main-file-name" option contains just 00331 // the file name itself with no path information. This file name may have had 00332 // a relative path, so we look into the actual file entry for the main 00333 // file to determine the real absolute path for the file. 00334 std::string MainFileDir; 00335 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 00336 MainFileDir = MainFile->getDir()->getName(); 00337 if (MainFileDir != ".") { 00338 llvm::SmallString<1024> MainFileDirSS(MainFileDir); 00339 llvm::sys::path::append(MainFileDirSS, MainFileName); 00340 MainFileName = MainFileDirSS.str(); 00341 } 00342 } 00343 00344 // Save filename string. 00345 StringRef Filename = internString(MainFileName); 00346 00347 // Save split dwarf file string. 00348 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile; 00349 StringRef SplitDwarfFilename = internString(SplitDwarfFile); 00350 00351 llvm::dwarf::SourceLanguage LangTag; 00352 const LangOptions &LO = CGM.getLangOpts(); 00353 if (LO.CPlusPlus) { 00354 if (LO.ObjC1) 00355 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 00356 else 00357 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 00358 } else if (LO.ObjC1) { 00359 LangTag = llvm::dwarf::DW_LANG_ObjC; 00360 } else if (LO.C99) { 00361 LangTag = llvm::dwarf::DW_LANG_C99; 00362 } else { 00363 LangTag = llvm::dwarf::DW_LANG_C89; 00364 } 00365 00366 std::string Producer = getClangFullVersion(); 00367 00368 // Figure out which version of the ObjC runtime we have. 00369 unsigned RuntimeVers = 0; 00370 if (LO.ObjC1) 00371 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; 00372 00373 // Create new compile unit. 00374 // FIXME - Eliminate TheCU. 00375 TheCU = DBuilder.createCompileUnit( 00376 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize, 00377 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename, 00378 DebugKind <= CodeGenOptions::DebugLineTablesOnly 00379 ? llvm::DIBuilder::LineTablesOnly 00380 : llvm::DIBuilder::FullDebug, 00381 DebugKind != CodeGenOptions::LocTrackingOnly); 00382 } 00383 00384 /// CreateType - Get the Basic type from the cache or create a new 00385 /// one if necessary. 00386 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) { 00387 llvm::dwarf::TypeKind Encoding; 00388 StringRef BTName; 00389 switch (BT->getKind()) { 00390 #define BUILTIN_TYPE(Id, SingletonId) 00391 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 00392 #include "clang/AST/BuiltinTypes.def" 00393 case BuiltinType::Dependent: 00394 llvm_unreachable("Unexpected builtin type"); 00395 case BuiltinType::NullPtr: 00396 return DBuilder.createNullPtrType(); 00397 case BuiltinType::Void: 00398 return llvm::DIType(); 00399 case BuiltinType::ObjCClass: 00400 if (!ClassTy) 00401 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 00402 "objc_class", TheCU, 00403 getOrCreateMainFile(), 0); 00404 return ClassTy; 00405 case BuiltinType::ObjCId: { 00406 // typedef struct objc_class *Class; 00407 // typedef struct objc_object { 00408 // Class isa; 00409 // } *id; 00410 00411 if (ObjTy) 00412 return ObjTy; 00413 00414 if (!ClassTy) 00415 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 00416 "objc_class", TheCU, 00417 getOrCreateMainFile(), 0); 00418 00419 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 00420 00421 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size); 00422 00423 ObjTy = 00424 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(), 00425 0, 0, 0, 0, llvm::DIType(), llvm::DIArray()); 00426 00427 ObjTy.setArrays(DBuilder.getOrCreateArray( 00428 &*DBuilder.createMemberType(ObjTy, "isa", getOrCreateMainFile(), 0, 00429 Size, 0, 0, 0, ISATy))); 00430 return ObjTy; 00431 } 00432 case BuiltinType::ObjCSel: { 00433 if (!SelTy) 00434 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 00435 "objc_selector", TheCU, 00436 getOrCreateMainFile(), 0); 00437 return SelTy; 00438 } 00439 00440 case BuiltinType::OCLImage1d: 00441 return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy); 00442 case BuiltinType::OCLImage1dArray: 00443 return getOrCreateStructPtrType("opencl_image1d_array_t", 00444 OCLImage1dArrayDITy); 00445 case BuiltinType::OCLImage1dBuffer: 00446 return getOrCreateStructPtrType("opencl_image1d_buffer_t", 00447 OCLImage1dBufferDITy); 00448 case BuiltinType::OCLImage2d: 00449 return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy); 00450 case BuiltinType::OCLImage2dArray: 00451 return getOrCreateStructPtrType("opencl_image2d_array_t", 00452 OCLImage2dArrayDITy); 00453 case BuiltinType::OCLImage3d: 00454 return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy); 00455 case BuiltinType::OCLSampler: 00456 return DBuilder.createBasicType( 00457 "opencl_sampler_t", CGM.getContext().getTypeSize(BT), 00458 CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned); 00459 case BuiltinType::OCLEvent: 00460 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy); 00461 00462 case BuiltinType::UChar: 00463 case BuiltinType::Char_U: 00464 Encoding = llvm::dwarf::DW_ATE_unsigned_char; 00465 break; 00466 case BuiltinType::Char_S: 00467 case BuiltinType::SChar: 00468 Encoding = llvm::dwarf::DW_ATE_signed_char; 00469 break; 00470 case BuiltinType::Char16: 00471 case BuiltinType::Char32: 00472 Encoding = llvm::dwarf::DW_ATE_UTF; 00473 break; 00474 case BuiltinType::UShort: 00475 case BuiltinType::UInt: 00476 case BuiltinType::UInt128: 00477 case BuiltinType::ULong: 00478 case BuiltinType::WChar_U: 00479 case BuiltinType::ULongLong: 00480 Encoding = llvm::dwarf::DW_ATE_unsigned; 00481 break; 00482 case BuiltinType::Short: 00483 case BuiltinType::Int: 00484 case BuiltinType::Int128: 00485 case BuiltinType::Long: 00486 case BuiltinType::WChar_S: 00487 case BuiltinType::LongLong: 00488 Encoding = llvm::dwarf::DW_ATE_signed; 00489 break; 00490 case BuiltinType::Bool: 00491 Encoding = llvm::dwarf::DW_ATE_boolean; 00492 break; 00493 case BuiltinType::Half: 00494 case BuiltinType::Float: 00495 case BuiltinType::LongDouble: 00496 case BuiltinType::Double: 00497 Encoding = llvm::dwarf::DW_ATE_float; 00498 break; 00499 } 00500 00501 switch (BT->getKind()) { 00502 case BuiltinType::Long: 00503 BTName = "long int"; 00504 break; 00505 case BuiltinType::LongLong: 00506 BTName = "long long int"; 00507 break; 00508 case BuiltinType::ULong: 00509 BTName = "long unsigned int"; 00510 break; 00511 case BuiltinType::ULongLong: 00512 BTName = "long long unsigned int"; 00513 break; 00514 default: 00515 BTName = BT->getName(CGM.getLangOpts()); 00516 break; 00517 } 00518 // Bit size, align and offset of the type. 00519 uint64_t Size = CGM.getContext().getTypeSize(BT); 00520 uint64_t Align = CGM.getContext().getTypeAlign(BT); 00521 llvm::DIType DbgTy = DBuilder.createBasicType(BTName, Size, Align, Encoding); 00522 return DbgTy; 00523 } 00524 00525 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) { 00526 // Bit size, align and offset of the type. 00527 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float; 00528 if (Ty->isComplexIntegerType()) 00529 Encoding = llvm::dwarf::DW_ATE_lo_user; 00530 00531 uint64_t Size = CGM.getContext().getTypeSize(Ty); 00532 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 00533 llvm::DIType DbgTy = 00534 DBuilder.createBasicType("complex", Size, Align, Encoding); 00535 00536 return DbgTy; 00537 } 00538 00539 /// CreateCVRType - Get the qualified type from the cache or create 00540 /// a new one if necessary. 00541 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) { 00542 QualifierCollector Qc; 00543 const Type *T = Qc.strip(Ty); 00544 00545 // Ignore these qualifiers for now. 00546 Qc.removeObjCGCAttr(); 00547 Qc.removeAddressSpace(); 00548 Qc.removeObjCLifetime(); 00549 00550 // We will create one Derived type for one qualifier and recurse to handle any 00551 // additional ones. 00552 llvm::dwarf::Tag Tag; 00553 if (Qc.hasConst()) { 00554 Tag = llvm::dwarf::DW_TAG_const_type; 00555 Qc.removeConst(); 00556 } else if (Qc.hasVolatile()) { 00557 Tag = llvm::dwarf::DW_TAG_volatile_type; 00558 Qc.removeVolatile(); 00559 } else if (Qc.hasRestrict()) { 00560 Tag = llvm::dwarf::DW_TAG_restrict_type; 00561 Qc.removeRestrict(); 00562 } else { 00563 assert(Qc.empty() && "Unknown type qualifier for debug info"); 00564 return getOrCreateType(QualType(T, 0), Unit); 00565 } 00566 00567 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit); 00568 00569 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 00570 // CVR derived types. 00571 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy); 00572 00573 return DbgTy; 00574 } 00575 00576 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 00577 llvm::DIFile Unit) { 00578 00579 // The frontend treats 'id' as a typedef to an ObjCObjectType, 00580 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the 00581 // debug info, we want to emit 'id' in both cases. 00582 if (Ty->isObjCQualifiedIdType()) 00583 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit); 00584 00585 llvm::DIType DbgTy = CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, 00586 Ty, Ty->getPointeeType(), Unit); 00587 return DbgTy; 00588 } 00589 00590 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, llvm::DIFile Unit) { 00591 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 00592 Ty->getPointeeType(), Unit); 00593 } 00594 00595 /// In C++ mode, types have linkage, so we can rely on the ODR and 00596 /// on their mangled names, if they're external. 00597 static SmallString<256> getUniqueTagTypeName(const TagType *Ty, 00598 CodeGenModule &CGM, 00599 llvm::DICompileUnit TheCU) { 00600 SmallString<256> FullName; 00601 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++. 00602 // For now, only apply ODR with C++. 00603 const TagDecl *TD = Ty->getDecl(); 00604 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus || 00605 !TD->isExternallyVisible()) 00606 return FullName; 00607 // Microsoft Mangler does not have support for mangleCXXRTTIName yet. 00608 if (CGM.getTarget().getCXXABI().isMicrosoft()) 00609 return FullName; 00610 00611 // TODO: This is using the RTTI name. Is there a better way to get 00612 // a unique string for a type? 00613 llvm::raw_svector_ostream Out(FullName); 00614 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out); 00615 Out.flush(); 00616 return FullName; 00617 } 00618 00619 // Creates a forward declaration for a RecordDecl in the given context. 00620 llvm::DICompositeType 00621 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, 00622 llvm::DIDescriptor Ctx) { 00623 const RecordDecl *RD = Ty->getDecl(); 00624 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD))) 00625 return llvm::DICompositeType(T); 00626 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 00627 unsigned Line = getLineNumber(RD->getLocation()); 00628 StringRef RDName = getClassName(RD); 00629 00630 llvm::dwarf::Tag Tag; 00631 if (RD->isStruct() || RD->isInterface()) 00632 Tag = llvm::dwarf::DW_TAG_structure_type; 00633 else if (RD->isUnion()) 00634 Tag = llvm::dwarf::DW_TAG_union_type; 00635 else { 00636 assert(RD->isClass()); 00637 Tag = llvm::dwarf::DW_TAG_class_type; 00638 } 00639 00640 // Create the type. 00641 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 00642 llvm::DICompositeType RetTy = DBuilder.createReplaceableForwardDecl( 00643 Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0, FullName); 00644 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy))); 00645 return RetTy; 00646 } 00647 00648 llvm::DIType CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag, 00649 const Type *Ty, 00650 QualType PointeeTy, 00651 llvm::DIFile Unit) { 00652 if (Tag == llvm::dwarf::DW_TAG_reference_type || 00653 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) 00654 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit)); 00655 00656 // Bit size, align and offset of the type. 00657 // Size is always the size of a pointer. We can't use getTypeSize here 00658 // because that does not return the correct value for references. 00659 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 00660 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 00661 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 00662 00663 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size, 00664 Align); 00665 } 00666 00667 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, 00668 llvm::DIType &Cache) { 00669 if (Cache) 00670 return Cache; 00671 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, 00672 TheCU, getOrCreateMainFile(), 0); 00673 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 00674 Cache = DBuilder.createPointerType(Cache, Size); 00675 return Cache; 00676 } 00677 00678 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, 00679 llvm::DIFile Unit) { 00680 if (BlockLiteralGeneric) 00681 return BlockLiteralGeneric; 00682 00683 SmallVector<llvm::Value *, 8> EltTys; 00684 llvm::DIType FieldTy; 00685 QualType FType; 00686 uint64_t FieldSize, FieldOffset; 00687 unsigned FieldAlign; 00688 llvm::DIArray Elements; 00689 llvm::DIType EltTy, DescTy; 00690 00691 FieldOffset = 0; 00692 FType = CGM.getContext().UnsignedLongTy; 00693 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 00694 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 00695 00696 Elements = DBuilder.getOrCreateArray(EltTys); 00697 EltTys.clear(); 00698 00699 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock; 00700 unsigned LineNo = getLineNumber(CurLoc); 00701 00702 EltTy = DBuilder.createStructType(Unit, "__block_descriptor", Unit, LineNo, 00703 FieldOffset, 0, Flags, llvm::DIType(), 00704 Elements); 00705 00706 // Bit size, align and offset of the type. 00707 uint64_t Size = CGM.getContext().getTypeSize(Ty); 00708 00709 DescTy = DBuilder.createPointerType(EltTy, Size); 00710 00711 FieldOffset = 0; 00712 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 00713 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 00714 FType = CGM.getContext().IntTy; 00715 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 00716 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 00717 FType = CGM.getContext().getPointerType(Ty->getPointeeType()); 00718 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 00719 00720 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 00721 FieldTy = DescTy; 00722 FieldSize = CGM.getContext().getTypeSize(Ty); 00723 FieldAlign = CGM.getContext().getTypeAlign(Ty); 00724 FieldTy = 00725 DBuilder.createMemberType(Unit, "__descriptor", Unit, LineNo, FieldSize, 00726 FieldAlign, FieldOffset, 0, FieldTy); 00727 EltTys.push_back(FieldTy); 00728 00729 FieldOffset += FieldSize; 00730 Elements = DBuilder.getOrCreateArray(EltTys); 00731 00732 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic", Unit, 00733 LineNo, FieldOffset, 0, Flags, 00734 llvm::DIType(), Elements); 00735 00736 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size); 00737 return BlockLiteralGeneric; 00738 } 00739 00740 llvm::DIType CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, 00741 llvm::DIFile Unit) { 00742 assert(Ty->isTypeAlias()); 00743 llvm::DIType Src = getOrCreateType(Ty->getAliasedType(), Unit); 00744 00745 SmallString<128> NS; 00746 llvm::raw_svector_ostream OS(NS); 00747 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), 00748 /*qualified*/ false); 00749 00750 TemplateSpecializationType::PrintTemplateArgumentList( 00751 OS, Ty->getArgs(), Ty->getNumArgs(), 00752 CGM.getContext().getPrintingPolicy()); 00753 00754 TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>( 00755 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl(); 00756 00757 SourceLocation Loc = AliasDecl->getLocation(); 00758 llvm::DIFile File = getOrCreateFile(Loc); 00759 unsigned Line = getLineNumber(Loc); 00760 00761 llvm::DIDescriptor Ctxt = 00762 getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext())); 00763 00764 return DBuilder.createTypedef(Src, internString(OS.str()), File, Line, Ctxt); 00765 } 00766 00767 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) { 00768 // Typedefs are derived from some other type. If we have a typedef of a 00769 // typedef, make sure to emit the whole chain. 00770 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); 00771 // We don't set size information, but do specify where the typedef was 00772 // declared. 00773 SourceLocation Loc = Ty->getDecl()->getLocation(); 00774 llvm::DIFile File = getOrCreateFile(Loc); 00775 unsigned Line = getLineNumber(Loc); 00776 const TypedefNameDecl *TyDecl = Ty->getDecl(); 00777 00778 llvm::DIDescriptor TypedefContext = 00779 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())); 00780 00781 return DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, 00782 TypedefContext); 00783 } 00784 00785 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, 00786 llvm::DIFile Unit) { 00787 SmallVector<llvm::Value *, 16> EltTys; 00788 00789 // Add the result type at least. 00790 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit)); 00791 00792 // Set up remainder of arguments if there is a prototype. 00793 // otherwise emit it as a variadic function. 00794 if (isa<FunctionNoProtoType>(Ty)) 00795 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 00796 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) { 00797 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i) 00798 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit)); 00799 if (FPT->isVariadic()) 00800 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 00801 } 00802 00803 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 00804 return DBuilder.createSubroutineType(Unit, EltTypeArray); 00805 } 00806 00807 /// Convert an AccessSpecifier into the corresponding DIDescriptor flag. 00808 /// As an optimization, return 0 if the access specifier equals the 00809 /// default for the containing type. 00810 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) { 00811 AccessSpecifier Default = clang::AS_none; 00812 if (RD && RD->isClass()) 00813 Default = clang::AS_private; 00814 else if (RD && (RD->isStruct() || RD->isUnion())) 00815 Default = clang::AS_public; 00816 00817 if (Access == Default) 00818 return 0; 00819 00820 switch (Access) { 00821 case clang::AS_private: 00822 return llvm::DIDescriptor::FlagPrivate; 00823 case clang::AS_protected: 00824 return llvm::DIDescriptor::FlagProtected; 00825 case clang::AS_public: 00826 return llvm::DIDescriptor::FlagPublic; 00827 case clang::AS_none: 00828 return 0; 00829 } 00830 llvm_unreachable("unexpected access enumerator"); 00831 } 00832 00833 llvm::DIType CGDebugInfo::createFieldType( 00834 StringRef name, QualType type, uint64_t sizeInBitsOverride, 00835 SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits, 00836 llvm::DIFile tunit, llvm::DIScope scope, const RecordDecl *RD) { 00837 llvm::DIType debugType = getOrCreateType(type, tunit); 00838 00839 // Get the location for the field. 00840 llvm::DIFile file = getOrCreateFile(loc); 00841 unsigned line = getLineNumber(loc); 00842 00843 uint64_t SizeInBits = 0; 00844 unsigned AlignInBits = 0; 00845 if (!type->isIncompleteArrayType()) { 00846 TypeInfo TI = CGM.getContext().getTypeInfo(type); 00847 SizeInBits = TI.Width; 00848 AlignInBits = TI.Align; 00849 00850 if (sizeInBitsOverride) 00851 SizeInBits = sizeInBitsOverride; 00852 } 00853 00854 unsigned flags = getAccessFlag(AS, RD); 00855 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, 00856 AlignInBits, offsetInBits, flags, debugType); 00857 } 00858 00859 /// CollectRecordLambdaFields - Helper for CollectRecordFields. 00860 void 00861 CGDebugInfo::CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl, 00862 SmallVectorImpl<llvm::Value *> &elements, 00863 llvm::DIType RecordTy) { 00864 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture 00865 // has the name and the location of the variable so we should iterate over 00866 // both concurrently. 00867 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); 00868 RecordDecl::field_iterator Field = CXXDecl->field_begin(); 00869 unsigned fieldno = 0; 00870 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), 00871 E = CXXDecl->captures_end(); 00872 I != E; ++I, ++Field, ++fieldno) { 00873 const LambdaCapture &C = *I; 00874 if (C.capturesVariable()) { 00875 VarDecl *V = C.getCapturedVar(); 00876 llvm::DIFile VUnit = getOrCreateFile(C.getLocation()); 00877 StringRef VName = V->getName(); 00878 uint64_t SizeInBitsOverride = 0; 00879 if (Field->isBitField()) { 00880 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext()); 00881 assert(SizeInBitsOverride && "found named 0-width bitfield"); 00882 } 00883 llvm::DIType fieldType = createFieldType( 00884 VName, Field->getType(), SizeInBitsOverride, C.getLocation(), 00885 Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy, 00886 CXXDecl); 00887 elements.push_back(fieldType); 00888 } else if (C.capturesThis()) { 00889 // TODO: Need to handle 'this' in some way by probably renaming the 00890 // this of the lambda class and having a field member of 'this' or 00891 // by using AT_object_pointer for the function and having that be 00892 // used as 'this' for semantic references. 00893 FieldDecl *f = *Field; 00894 llvm::DIFile VUnit = getOrCreateFile(f->getLocation()); 00895 QualType type = f->getType(); 00896 llvm::DIType fieldType = createFieldType( 00897 "this", type, 0, f->getLocation(), f->getAccess(), 00898 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl); 00899 00900 elements.push_back(fieldType); 00901 } 00902 } 00903 } 00904 00905 /// Helper for CollectRecordFields. 00906 llvm::DIDerivedType CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, 00907 llvm::DIType RecordTy, 00908 const RecordDecl *RD) { 00909 // Create the descriptor for the static variable, with or without 00910 // constant initializers. 00911 Var = Var->getCanonicalDecl(); 00912 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation()); 00913 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit); 00914 00915 unsigned LineNumber = getLineNumber(Var->getLocation()); 00916 StringRef VName = Var->getName(); 00917 llvm::Constant *C = nullptr; 00918 if (Var->getInit()) { 00919 const APValue *Value = Var->evaluateValue(); 00920 if (Value) { 00921 if (Value->isInt()) 00922 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 00923 if (Value->isFloat()) 00924 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat()); 00925 } 00926 } 00927 00928 unsigned Flags = getAccessFlag(Var->getAccess(), RD); 00929 llvm::DIDerivedType GV = DBuilder.createStaticMemberType( 00930 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C); 00931 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV); 00932 return GV; 00933 } 00934 00935 /// CollectRecordNormalField - Helper for CollectRecordFields. 00936 void CGDebugInfo::CollectRecordNormalField( 00937 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile tunit, 00938 SmallVectorImpl<llvm::Value *> &elements, llvm::DIType RecordTy, 00939 const RecordDecl *RD) { 00940 StringRef name = field->getName(); 00941 QualType type = field->getType(); 00942 00943 // Ignore unnamed fields unless they're anonymous structs/unions. 00944 if (name.empty() && !type->isRecordType()) 00945 return; 00946 00947 uint64_t SizeInBitsOverride = 0; 00948 if (field->isBitField()) { 00949 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext()); 00950 assert(SizeInBitsOverride && "found named 0-width bitfield"); 00951 } 00952 00953 llvm::DIType fieldType = 00954 createFieldType(name, type, SizeInBitsOverride, field->getLocation(), 00955 field->getAccess(), OffsetInBits, tunit, RecordTy, RD); 00956 00957 elements.push_back(fieldType); 00958 } 00959 00960 /// CollectRecordFields - A helper function to collect debug info for 00961 /// record fields. This is used while creating debug info entry for a Record. 00962 void CGDebugInfo::CollectRecordFields(const RecordDecl *record, 00963 llvm::DIFile tunit, 00964 SmallVectorImpl<llvm::Value *> &elements, 00965 llvm::DICompositeType RecordTy) { 00966 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record); 00967 00968 if (CXXDecl && CXXDecl->isLambda()) 00969 CollectRecordLambdaFields(CXXDecl, elements, RecordTy); 00970 else { 00971 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 00972 00973 // Field number for non-static fields. 00974 unsigned fieldNo = 0; 00975 00976 // Static and non-static members should appear in the same order as 00977 // the corresponding declarations in the source program. 00978 for (const auto *I : record->decls()) 00979 if (const auto *V = dyn_cast<VarDecl>(I)) { 00980 // Reuse the existing static member declaration if one exists 00981 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI = 00982 StaticDataMemberCache.find(V->getCanonicalDecl()); 00983 if (MI != StaticDataMemberCache.end()) { 00984 assert(MI->second && 00985 "Static data member declaration should still exist"); 00986 elements.push_back( 00987 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second))); 00988 } else { 00989 auto Field = CreateRecordStaticField(V, RecordTy, record); 00990 elements.push_back(Field); 00991 } 00992 } else if (const auto *field = dyn_cast<FieldDecl>(I)) { 00993 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit, 00994 elements, RecordTy, record); 00995 00996 // Bump field number for next field. 00997 ++fieldNo; 00998 } 00999 } 01000 } 01001 01002 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 01003 /// function type is not updated to include implicit "this" pointer. Use this 01004 /// routine to get a method type which includes "this" pointer. 01005 llvm::DICompositeType 01006 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 01007 llvm::DIFile Unit) { 01008 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 01009 if (Method->isStatic()) 01010 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit)); 01011 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()), 01012 Func, Unit); 01013 } 01014 01015 llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType( 01016 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) { 01017 // Add "this" pointer. 01018 llvm::DITypeArray Args = llvm::DISubroutineType( 01019 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray(); 01020 assert(Args.getNumElements() && "Invalid number of arguments!"); 01021 01022 SmallVector<llvm::Value *, 16> Elts; 01023 01024 // First element is always return type. For 'void' functions it is NULL. 01025 Elts.push_back(Args.getElement(0)); 01026 01027 // "this" pointer is always first argument. 01028 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); 01029 if (isa<ClassTemplateSpecializationDecl>(RD)) { 01030 // Create pointer type directly in this case. 01031 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 01032 QualType PointeeTy = ThisPtrTy->getPointeeType(); 01033 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 01034 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 01035 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy); 01036 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit); 01037 llvm::DIType ThisPtrType = 01038 DBuilder.createPointerType(PointeeType, Size, Align); 01039 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 01040 // TODO: This and the artificial type below are misleading, the 01041 // types aren't artificial the argument is, but the current 01042 // metadata doesn't represent that. 01043 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 01044 Elts.push_back(ThisPtrType); 01045 } else { 01046 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit); 01047 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 01048 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 01049 Elts.push_back(ThisPtrType); 01050 } 01051 01052 // Copy rest of the arguments. 01053 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 01054 Elts.push_back(Args.getElement(i)); 01055 01056 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 01057 01058 unsigned Flags = 0; 01059 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue) 01060 Flags |= llvm::DIDescriptor::FlagLValueReference; 01061 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue) 01062 Flags |= llvm::DIDescriptor::FlagRValueReference; 01063 01064 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags); 01065 } 01066 01067 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 01068 /// inside a function. 01069 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 01070 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 01071 return isFunctionLocalClass(NRD); 01072 if (isa<FunctionDecl>(RD->getDeclContext())) 01073 return true; 01074 return false; 01075 } 01076 01077 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for 01078 /// a single member function GlobalDecl. 01079 llvm::DISubprogram 01080 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 01081 llvm::DIFile Unit, llvm::DIType RecordTy) { 01082 bool IsCtorOrDtor = 01083 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 01084 01085 StringRef MethodName = getFunctionName(Method); 01086 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit); 01087 01088 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 01089 // make sense to give a single ctor/dtor a linkage name. 01090 StringRef MethodLinkageName; 01091 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 01092 MethodLinkageName = CGM.getMangledName(Method); 01093 01094 // Get the location for the method. 01095 llvm::DIFile MethodDefUnit; 01096 unsigned MethodLine = 0; 01097 if (!Method->isImplicit()) { 01098 MethodDefUnit = getOrCreateFile(Method->getLocation()); 01099 MethodLine = getLineNumber(Method->getLocation()); 01100 } 01101 01102 // Collect virtual method info. 01103 llvm::DIType ContainingType; 01104 unsigned Virtuality = 0; 01105 unsigned VIndex = 0; 01106 01107 if (Method->isVirtual()) { 01108 if (Method->isPure()) 01109 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 01110 else 01111 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 01112 01113 // It doesn't make sense to give a virtual destructor a vtable index, 01114 // since a single destructor has two entries in the vtable. 01115 // FIXME: Add proper support for debug info for virtual calls in 01116 // the Microsoft ABI, where we may use multiple vptrs to make a vftable 01117 // lookup if we have multiple or virtual inheritance. 01118 if (!isa<CXXDestructorDecl>(Method) && 01119 !CGM.getTarget().getCXXABI().isMicrosoft()) 01120 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method); 01121 ContainingType = RecordTy; 01122 } 01123 01124 unsigned Flags = 0; 01125 if (Method->isImplicit()) 01126 Flags |= llvm::DIDescriptor::FlagArtificial; 01127 Flags |= getAccessFlag(Method->getAccess(), Method->getParent()); 01128 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 01129 if (CXXC->isExplicit()) 01130 Flags |= llvm::DIDescriptor::FlagExplicit; 01131 } else if (const CXXConversionDecl *CXXC = 01132 dyn_cast<CXXConversionDecl>(Method)) { 01133 if (CXXC->isExplicit()) 01134 Flags |= llvm::DIDescriptor::FlagExplicit; 01135 } 01136 if (Method->hasPrototype()) 01137 Flags |= llvm::DIDescriptor::FlagPrototyped; 01138 if (Method->getRefQualifier() == RQ_LValue) 01139 Flags |= llvm::DIDescriptor::FlagLValueReference; 01140 if (Method->getRefQualifier() == RQ_RValue) 01141 Flags |= llvm::DIDescriptor::FlagRValueReference; 01142 01143 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 01144 llvm::DISubprogram SP = DBuilder.createMethod( 01145 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine, 01146 MethodTy, /*isLocalToUnit=*/false, 01147 /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags, 01148 CGM.getLangOpts().Optimize, nullptr, TParamsArray); 01149 01150 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP); 01151 01152 return SP; 01153 } 01154 01155 /// CollectCXXMemberFunctions - A helper function to collect debug info for 01156 /// C++ member functions. This is used while creating debug info entry for 01157 /// a Record. 01158 void CGDebugInfo::CollectCXXMemberFunctions( 01159 const CXXRecordDecl *RD, llvm::DIFile Unit, 01160 SmallVectorImpl<llvm::Value *> &EltTys, llvm::DIType RecordTy) { 01161 01162 // Since we want more than just the individual member decls if we 01163 // have templated functions iterate over every declaration to gather 01164 // the functions. 01165 for (const auto *I : RD->decls()) { 01166 const auto *Method = dyn_cast<CXXMethodDecl>(I); 01167 // If the member is implicit, don't add it to the member list. This avoids 01168 // the member being added to type units by LLVM, while still allowing it 01169 // to be emitted into the type declaration/reference inside the compile 01170 // unit. 01171 // FIXME: Handle Using(Shadow?)Decls here to create 01172 // DW_TAG_imported_declarations inside the class for base decls brought into 01173 // derived classes. GDB doesn't seem to notice/leverage these when I tried 01174 // it, so I'm not rushing to fix this. (GCC seems to produce them, if 01175 // referenced) 01176 if (!Method || Method->isImplicit()) 01177 continue; 01178 01179 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType()) 01180 continue; 01181 01182 // Reuse the existing member function declaration if it exists. 01183 // It may be associated with the declaration of the type & should be 01184 // reused as we're building the definition. 01185 // 01186 // This situation can arise in the vtable-based debug info reduction where 01187 // implicit members are emitted in a non-vtable TU. 01188 auto MI = SPCache.find(Method->getCanonicalDecl()); 01189 EltTys.push_back(MI == SPCache.end() 01190 ? CreateCXXMemberFunction(Method, Unit, RecordTy) 01191 : static_cast<llvm::Value *>(MI->second)); 01192 } 01193 } 01194 01195 /// CollectCXXBases - A helper function to collect debug info for 01196 /// C++ base classes. This is used while creating debug info entry for 01197 /// a Record. 01198 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 01199 SmallVectorImpl<llvm::Value *> &EltTys, 01200 llvm::DIType RecordTy) { 01201 01202 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 01203 for (const auto &BI : RD->bases()) { 01204 unsigned BFlags = 0; 01205 uint64_t BaseOffset; 01206 01207 const CXXRecordDecl *Base = 01208 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl()); 01209 01210 if (BI.isVirtual()) { 01211 if (CGM.getTarget().getCXXABI().isItaniumFamily()) { 01212 // virtual base offset offset is -ve. The code generator emits dwarf 01213 // expression where it expects +ve number. 01214 BaseOffset = 0 - CGM.getItaniumVTableContext() 01215 .getVirtualBaseOffsetOffset(RD, Base) 01216 .getQuantity(); 01217 } else { 01218 // In the MS ABI, store the vbtable offset, which is analogous to the 01219 // vbase offset offset in Itanium. 01220 BaseOffset = 01221 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base); 01222 } 01223 BFlags = llvm::DIDescriptor::FlagVirtual; 01224 } else 01225 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 01226 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 01227 // BI->isVirtual() and bits when not. 01228 01229 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD); 01230 llvm::DIType DTy = DBuilder.createInheritance( 01231 RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags); 01232 EltTys.push_back(DTy); 01233 } 01234 } 01235 01236 /// CollectTemplateParams - A helper function to collect template parameters. 01237 llvm::DIArray 01238 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList, 01239 ArrayRef<TemplateArgument> TAList, 01240 llvm::DIFile Unit) { 01241 SmallVector<llvm::Value *, 16> TemplateParams; 01242 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 01243 const TemplateArgument &TA = TAList[i]; 01244 StringRef Name; 01245 if (TPList) 01246 Name = TPList->getParam(i)->getName(); 01247 switch (TA.getKind()) { 01248 case TemplateArgument::Type: { 01249 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 01250 llvm::DITemplateTypeParameter TTP = 01251 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy); 01252 TemplateParams.push_back(TTP); 01253 } break; 01254 case TemplateArgument::Integral: { 01255 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 01256 llvm::DITemplateValueParameter TVP = 01257 DBuilder.createTemplateValueParameter( 01258 TheCU, Name, TTy, 01259 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())); 01260 TemplateParams.push_back(TVP); 01261 } break; 01262 case TemplateArgument::Declaration: { 01263 const ValueDecl *D = TA.getAsDecl(); 01264 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext()); 01265 llvm::DIType TTy = getOrCreateType(T, Unit); 01266 llvm::Value *V = nullptr; 01267 const CXXMethodDecl *MD; 01268 // Variable pointer template parameters have a value that is the address 01269 // of the variable. 01270 if (const auto *VD = dyn_cast<VarDecl>(D)) 01271 V = CGM.GetAddrOfGlobalVar(VD); 01272 // Member function pointers have special support for building them, though 01273 // this is currently unsupported in LLVM CodeGen. 01274 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance()) 01275 V = CGM.getCXXABI().EmitMemberPointer(MD); 01276 else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 01277 V = CGM.GetAddrOfFunction(FD); 01278 // Member data pointers have special handling too to compute the fixed 01279 // offset within the object. 01280 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) { 01281 // These five lines (& possibly the above member function pointer 01282 // handling) might be able to be refactored to use similar code in 01283 // CodeGenModule::getMemberPointerConstant 01284 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 01285 CharUnits chars = 01286 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset); 01287 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars); 01288 } 01289 llvm::DITemplateValueParameter TVP = 01290 DBuilder.createTemplateValueParameter( 01291 TheCU, Name, TTy, 01292 cast_or_null<llvm::Constant>(V->stripPointerCasts())); 01293 TemplateParams.push_back(TVP); 01294 } break; 01295 case TemplateArgument::NullPtr: { 01296 QualType T = TA.getNullPtrType(); 01297 llvm::DIType TTy = getOrCreateType(T, Unit); 01298 llvm::Value *V = nullptr; 01299 // Special case member data pointer null values since they're actually -1 01300 // instead of zero. 01301 if (const MemberPointerType *MPT = 01302 dyn_cast<MemberPointerType>(T.getTypePtr())) 01303 // But treat member function pointers as simple zero integers because 01304 // it's easier than having a special case in LLVM's CodeGen. If LLVM 01305 // CodeGen grows handling for values of non-null member function 01306 // pointers then perhaps we could remove this special case and rely on 01307 // EmitNullMemberPointer for member function pointers. 01308 if (MPT->isMemberDataPointer()) 01309 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 01310 if (!V) 01311 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 01312 llvm::DITemplateValueParameter TVP = 01313 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, 01314 cast<llvm::Constant>(V)); 01315 TemplateParams.push_back(TVP); 01316 } break; 01317 case TemplateArgument::Template: { 01318 llvm::DITemplateValueParameter 01319 TVP = DBuilder.createTemplateTemplateParameter( 01320 TheCU, Name, llvm::DIType(), 01321 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()); 01322 TemplateParams.push_back(TVP); 01323 } break; 01324 case TemplateArgument::Pack: { 01325 llvm::DITemplateValueParameter TVP = DBuilder.createTemplateParameterPack( 01326 TheCU, Name, llvm::DIType(), 01327 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)); 01328 TemplateParams.push_back(TVP); 01329 } break; 01330 case TemplateArgument::Expression: { 01331 const Expr *E = TA.getAsExpr(); 01332 QualType T = E->getType(); 01333 if (E->isGLValue()) 01334 T = CGM.getContext().getLValueReferenceType(T); 01335 llvm::Value *V = CGM.EmitConstantExpr(E, T); 01336 assert(V && "Expression in template argument isn't constant"); 01337 llvm::DIType TTy = getOrCreateType(T, Unit); 01338 llvm::DITemplateValueParameter TVP = 01339 DBuilder.createTemplateValueParameter( 01340 TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())); 01341 TemplateParams.push_back(TVP); 01342 } break; 01343 // And the following should never occur: 01344 case TemplateArgument::TemplateExpansion: 01345 case TemplateArgument::Null: 01346 llvm_unreachable( 01347 "These argument types shouldn't exist in concrete types"); 01348 } 01349 } 01350 return DBuilder.getOrCreateArray(TemplateParams); 01351 } 01352 01353 /// CollectFunctionTemplateParams - A helper function to collect debug 01354 /// info for function template parameters. 01355 llvm::DIArray CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, 01356 llvm::DIFile Unit) { 01357 if (FD->getTemplatedKind() == 01358 FunctionDecl::TK_FunctionTemplateSpecialization) { 01359 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() 01360 ->getTemplate() 01361 ->getTemplateParameters(); 01362 return CollectTemplateParams( 01363 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit); 01364 } 01365 return llvm::DIArray(); 01366 } 01367 01368 /// CollectCXXTemplateParams - A helper function to collect debug info for 01369 /// template parameters. 01370 llvm::DIArray CGDebugInfo::CollectCXXTemplateParams( 01371 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile Unit) { 01372 // Always get the full list of parameters, not just the ones from 01373 // the specialization. 01374 TemplateParameterList *TPList = 01375 TSpecial->getSpecializedTemplate()->getTemplateParameters(); 01376 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); 01377 return CollectTemplateParams(TPList, TAList.asArray(), Unit); 01378 } 01379 01380 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 01381 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 01382 if (VTablePtrType.isValid()) 01383 return VTablePtrType; 01384 01385 ASTContext &Context = CGM.getContext(); 01386 01387 /* Function type */ 01388 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 01389 llvm::DITypeArray SElements = DBuilder.getOrCreateTypeArray(STy); 01390 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 01391 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 01392 llvm::DIType vtbl_ptr_type = 01393 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type"); 01394 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 01395 return VTablePtrType; 01396 } 01397 01398 /// getVTableName - Get vtable name for the given Class. 01399 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 01400 // Copy the gdb compatible name on the side and use its reference. 01401 return internString("_vptr$", RD->getNameAsString()); 01402 } 01403 01404 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 01405 /// debug info entry in EltTys vector. 01406 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 01407 SmallVectorImpl<llvm::Value *> &EltTys) { 01408 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 01409 01410 // If there is a primary base then it will hold vtable info. 01411 if (RL.getPrimaryBase()) 01412 return; 01413 01414 // If this class is not dynamic then there is not any vtable info to collect. 01415 if (!RD->isDynamicClass()) 01416 return; 01417 01418 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 01419 llvm::DIType VPTR = DBuilder.createMemberType( 01420 Unit, getVTableName(RD), Unit, 0, Size, 0, 0, 01421 llvm::DIDescriptor::FlagArtificial, getOrCreateVTablePtrType(Unit)); 01422 EltTys.push_back(VPTR); 01423 } 01424 01425 /// getOrCreateRecordType - Emit record type's standalone debug info. 01426 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 01427 SourceLocation Loc) { 01428 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 01429 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 01430 return T; 01431 } 01432 01433 /// getOrCreateInterfaceType - Emit an objective c interface type standalone 01434 /// debug info. 01435 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D, 01436 SourceLocation Loc) { 01437 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 01438 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc)); 01439 RetainedTypes.push_back(D.getAsOpaquePtr()); 01440 return T; 01441 } 01442 01443 void CGDebugInfo::completeType(const EnumDecl *ED) { 01444 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 01445 return; 01446 QualType Ty = CGM.getContext().getEnumType(ED); 01447 void *TyPtr = Ty.getAsOpaquePtr(); 01448 auto I = TypeCache.find(TyPtr); 01449 if (I == TypeCache.end() || 01450 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second))) 01451 .isForwardDecl()) 01452 return; 01453 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<EnumType>()); 01454 assert(!Res.isForwardDecl()); 01455 TypeCache[TyPtr] = Res; 01456 } 01457 01458 void CGDebugInfo::completeType(const RecordDecl *RD) { 01459 if (DebugKind > CodeGenOptions::LimitedDebugInfo || 01460 !CGM.getLangOpts().CPlusPlus) 01461 completeRequiredType(RD); 01462 } 01463 01464 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { 01465 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 01466 return; 01467 01468 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 01469 if (CXXDecl->isDynamicClass()) 01470 return; 01471 01472 QualType Ty = CGM.getContext().getRecordType(RD); 01473 llvm::DIType T = getTypeOrNull(Ty); 01474 if (T && T.isForwardDecl()) 01475 completeClassData(RD); 01476 } 01477 01478 void CGDebugInfo::completeClassData(const RecordDecl *RD) { 01479 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 01480 return; 01481 QualType Ty = CGM.getContext().getRecordType(RD); 01482 void *TyPtr = Ty.getAsOpaquePtr(); 01483 auto I = TypeCache.find(TyPtr); 01484 if (I != TypeCache.end() && 01485 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second))) 01486 .isForwardDecl()) 01487 return; 01488 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>()); 01489 assert(!Res.isForwardDecl()); 01490 TypeCache[TyPtr] = Res; 01491 } 01492 01493 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, 01494 CXXRecordDecl::method_iterator End) { 01495 for (; I != End; ++I) 01496 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction()) 01497 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && 01498 !I->getMemberSpecializationInfo()->isExplicitSpecialization()) 01499 return true; 01500 return false; 01501 } 01502 01503 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind, 01504 const RecordDecl *RD, 01505 const LangOptions &LangOpts) { 01506 if (DebugKind > CodeGenOptions::LimitedDebugInfo) 01507 return false; 01508 01509 if (!LangOpts.CPlusPlus) 01510 return false; 01511 01512 if (!RD->isCompleteDefinitionRequired()) 01513 return true; 01514 01515 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 01516 01517 if (!CXXDecl) 01518 return false; 01519 01520 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) 01521 return true; 01522 01523 TemplateSpecializationKind Spec = TSK_Undeclared; 01524 if (const ClassTemplateSpecializationDecl *SD = 01525 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 01526 Spec = SD->getSpecializationKind(); 01527 01528 if (Spec == TSK_ExplicitInstantiationDeclaration && 01529 hasExplicitMemberDefinition(CXXDecl->method_begin(), 01530 CXXDecl->method_end())) 01531 return true; 01532 01533 return false; 01534 } 01535 01536 /// CreateType - get structure or union type. 01537 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 01538 RecordDecl *RD = Ty->getDecl(); 01539 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0))); 01540 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) { 01541 if (!T) 01542 T = getOrCreateRecordFwdDecl( 01543 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext()))); 01544 return T; 01545 } 01546 01547 return CreateTypeDefinition(Ty); 01548 } 01549 01550 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { 01551 RecordDecl *RD = Ty->getDecl(); 01552 01553 // Get overall information about the record type for the debug info. 01554 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 01555 01556 // Records and classes and unions can all be recursive. To handle them, we 01557 // first generate a debug descriptor for the struct as a forward declaration. 01558 // Then (if it is a definition) we go through and get debug info for all of 01559 // its members. Finally, we create a descriptor for the complete type (which 01560 // may refer to the forward decl if the struct is recursive) and replace all 01561 // uses of the forward declaration with the final definition. 01562 01563 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit)); 01564 assert(FwdDecl.isCompositeType() && 01565 "The debug type of a RecordType should be a llvm::DICompositeType"); 01566 01567 if (FwdDecl.isForwardDecl()) 01568 return FwdDecl; 01569 01570 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 01571 CollectContainingType(CXXDecl, FwdDecl); 01572 01573 // Push the struct on region stack. 01574 LexicalBlockStack.push_back(&*FwdDecl); 01575 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 01576 01577 // Convert all the elements. 01578 SmallVector<llvm::Value *, 16> EltTys; 01579 // what about nested types? 01580 01581 // Note: The split of CXXDecl information here is intentional, the 01582 // gdb tests will depend on a certain ordering at printout. The debug 01583 // information offsets are still correct if we merge them all together 01584 // though. 01585 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 01586 if (CXXDecl) { 01587 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 01588 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 01589 } 01590 01591 // Collect data fields (including static variables and any initializers). 01592 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 01593 if (CXXDecl) 01594 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 01595 01596 LexicalBlockStack.pop_back(); 01597 RegionMap.erase(Ty->getDecl()); 01598 01599 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 01600 FwdDecl.setArrays(Elements); 01601 01602 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 01603 return FwdDecl; 01604 } 01605 01606 /// CreateType - get objective-c object type. 01607 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 01608 llvm::DIFile Unit) { 01609 // Ignore protocols. 01610 return getOrCreateType(Ty->getBaseType(), Unit); 01611 } 01612 01613 /// \return true if Getter has the default name for the property PD. 01614 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, 01615 const ObjCMethodDecl *Getter) { 01616 assert(PD); 01617 if (!Getter) 01618 return true; 01619 01620 assert(Getter->getDeclName().isObjCZeroArgSelector()); 01621 return PD->getName() == 01622 Getter->getDeclName().getObjCSelector().getNameForSlot(0); 01623 } 01624 01625 /// \return true if Setter has the default name for the property PD. 01626 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, 01627 const ObjCMethodDecl *Setter) { 01628 assert(PD); 01629 if (!Setter) 01630 return true; 01631 01632 assert(Setter->getDeclName().isObjCOneArgSelector()); 01633 return SelectorTable::constructSetterName(PD->getName()) == 01634 Setter->getDeclName().getObjCSelector().getNameForSlot(0); 01635 } 01636 01637 /// CreateType - get objective-c interface type. 01638 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 01639 llvm::DIFile Unit) { 01640 ObjCInterfaceDecl *ID = Ty->getDecl(); 01641 if (!ID) 01642 return llvm::DIType(); 01643 01644 // Get overall information about the record type for the debug info. 01645 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 01646 unsigned Line = getLineNumber(ID->getLocation()); 01647 llvm::dwarf::SourceLanguage RuntimeLang = TheCU.getLanguage(); 01648 01649 // If this is just a forward declaration return a special forward-declaration 01650 // debug type since we won't be able to lay out the entire type. 01651 ObjCInterfaceDecl *Def = ID->getDefinition(); 01652 if (!Def || !Def->getImplementation()) { 01653 llvm::DIType FwdDecl = DBuilder.createReplaceableForwardDecl( 01654 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line, 01655 RuntimeLang); 01656 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); 01657 return FwdDecl; 01658 } 01659 01660 return CreateTypeDefinition(Ty, Unit); 01661 } 01662 01663 llvm::DIType CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, 01664 llvm::DIFile Unit) { 01665 ObjCInterfaceDecl *ID = Ty->getDecl(); 01666 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 01667 unsigned Line = getLineNumber(ID->getLocation()); 01668 unsigned RuntimeLang = TheCU.getLanguage(); 01669 01670 // Bit size, align and offset of the type. 01671 uint64_t Size = CGM.getContext().getTypeSize(Ty); 01672 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 01673 01674 unsigned Flags = 0; 01675 if (ID->getImplementation()) 01676 Flags |= llvm::DIDescriptor::FlagObjcClassComplete; 01677 01678 llvm::DICompositeType RealDecl = DBuilder.createStructType( 01679 Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, llvm::DIType(), 01680 llvm::DIArray(), RuntimeLang); 01681 01682 QualType QTy(Ty, 0); 01683 TypeCache[QTy.getAsOpaquePtr()] = RealDecl; 01684 01685 // Push the struct on region stack. 01686 LexicalBlockStack.push_back(static_cast<llvm::MDNode *>(RealDecl)); 01687 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 01688 01689 // Convert all the elements. 01690 SmallVector<llvm::Value *, 16> EltTys; 01691 01692 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 01693 if (SClass) { 01694 llvm::DIType SClassTy = 01695 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 01696 if (!SClassTy.isValid()) 01697 return llvm::DIType(); 01698 01699 llvm::DIType InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 01700 EltTys.push_back(InhTag); 01701 } 01702 01703 // Create entries for all of the properties. 01704 for (const auto *PD : ID->properties()) { 01705 SourceLocation Loc = PD->getLocation(); 01706 llvm::DIFile PUnit = getOrCreateFile(Loc); 01707 unsigned PLine = getLineNumber(Loc); 01708 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 01709 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 01710 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( 01711 PD->getName(), PUnit, PLine, 01712 hasDefaultGetterName(PD, Getter) ? "" 01713 : getSelectorName(PD->getGetterName()), 01714 hasDefaultSetterName(PD, Setter) ? "" 01715 : getSelectorName(PD->getSetterName()), 01716 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit)); 01717 EltTys.push_back(PropertyNode); 01718 } 01719 01720 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 01721 unsigned FieldNo = 0; 01722 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 01723 Field = Field->getNextIvar(), ++FieldNo) { 01724 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 01725 if (!FieldTy.isValid()) 01726 return llvm::DIType(); 01727 01728 StringRef FieldName = Field->getName(); 01729 01730 // Ignore unnamed fields. 01731 if (FieldName.empty()) 01732 continue; 01733 01734 // Get the location for the field. 01735 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 01736 unsigned FieldLine = getLineNumber(Field->getLocation()); 01737 QualType FType = Field->getType(); 01738 uint64_t FieldSize = 0; 01739 unsigned FieldAlign = 0; 01740 01741 if (!FType->isIncompleteArrayType()) { 01742 01743 // Bit size, align and offset of the type. 01744 FieldSize = Field->isBitField() 01745 ? Field->getBitWidthValue(CGM.getContext()) 01746 : CGM.getContext().getTypeSize(FType); 01747 FieldAlign = CGM.getContext().getTypeAlign(FType); 01748 } 01749 01750 uint64_t FieldOffset; 01751 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 01752 // We don't know the runtime offset of an ivar if we're using the 01753 // non-fragile ABI. For bitfields, use the bit offset into the first 01754 // byte of storage of the bitfield. For other fields, use zero. 01755 if (Field->isBitField()) { 01756 FieldOffset = 01757 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field); 01758 FieldOffset %= CGM.getContext().getCharWidth(); 01759 } else { 01760 FieldOffset = 0; 01761 } 01762 } else { 01763 FieldOffset = RL.getFieldOffset(FieldNo); 01764 } 01765 01766 unsigned Flags = 0; 01767 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 01768 Flags = llvm::DIDescriptor::FlagProtected; 01769 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 01770 Flags = llvm::DIDescriptor::FlagPrivate; 01771 else if (Field->getAccessControl() == ObjCIvarDecl::Public) 01772 Flags = llvm::DIDescriptor::FlagPublic; 01773 01774 llvm::MDNode *PropertyNode = nullptr; 01775 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 01776 if (ObjCPropertyImplDecl *PImpD = 01777 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 01778 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 01779 SourceLocation Loc = PD->getLocation(); 01780 llvm::DIFile PUnit = getOrCreateFile(Loc); 01781 unsigned PLine = getLineNumber(Loc); 01782 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 01783 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 01784 PropertyNode = DBuilder.createObjCProperty( 01785 PD->getName(), PUnit, PLine, 01786 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName( 01787 PD->getGetterName()), 01788 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName( 01789 PD->getSetterName()), 01790 PD->getPropertyAttributes(), 01791 getOrCreateType(PD->getType(), PUnit)); 01792 } 01793 } 01794 } 01795 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine, 01796 FieldSize, FieldAlign, FieldOffset, Flags, 01797 FieldTy, PropertyNode); 01798 EltTys.push_back(FieldTy); 01799 } 01800 01801 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 01802 RealDecl.setArrays(Elements); 01803 01804 LexicalBlockStack.pop_back(); 01805 return RealDecl; 01806 } 01807 01808 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) { 01809 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 01810 int64_t Count = Ty->getNumElements(); 01811 if (Count == 0) 01812 // If number of elements are not known then this is an unbounded array. 01813 // Use Count == -1 to express such arrays. 01814 Count = -1; 01815 01816 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count); 01817 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 01818 01819 uint64_t Size = CGM.getContext().getTypeSize(Ty); 01820 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 01821 01822 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 01823 } 01824 01825 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile Unit) { 01826 uint64_t Size; 01827 uint64_t Align; 01828 01829 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 01830 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 01831 Size = 0; 01832 Align = 01833 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 01834 } else if (Ty->isIncompleteArrayType()) { 01835 Size = 0; 01836 if (Ty->getElementType()->isIncompleteType()) 01837 Align = 0; 01838 else 01839 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 01840 } else if (Ty->isIncompleteType()) { 01841 Size = 0; 01842 Align = 0; 01843 } else { 01844 // Size and align of the whole array, not the element type. 01845 Size = CGM.getContext().getTypeSize(Ty); 01846 Align = CGM.getContext().getTypeAlign(Ty); 01847 } 01848 01849 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 01850 // interior arrays, do we care? Why aren't nested arrays represented the 01851 // obvious/recursive way? 01852 SmallVector<llvm::Value *, 8> Subscripts; 01853 QualType EltTy(Ty, 0); 01854 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 01855 // If the number of elements is known, then count is that number. Otherwise, 01856 // it's -1. This allows us to represent a subrange with an array of 0 01857 // elements, like this: 01858 // 01859 // struct foo { 01860 // int x[0]; 01861 // }; 01862 int64_t Count = -1; // Count == -1 is an unbounded array. 01863 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 01864 Count = CAT->getSize().getZExtValue(); 01865 01866 // FIXME: Verify this is right for VLAs. 01867 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 01868 EltTy = Ty->getElementType(); 01869 } 01870 01871 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 01872 01873 llvm::DIType DbgTy = DBuilder.createArrayType( 01874 Size, Align, getOrCreateType(EltTy, Unit), SubscriptArray); 01875 return DbgTy; 01876 } 01877 01878 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 01879 llvm::DIFile Unit) { 01880 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty, 01881 Ty->getPointeeType(), Unit); 01882 } 01883 01884 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 01885 llvm::DIFile Unit) { 01886 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty, 01887 Ty->getPointeeType(), Unit); 01888 } 01889 01890 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 01891 llvm::DIFile U) { 01892 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 01893 if (!Ty->getPointeeType()->isFunctionType()) 01894 return DBuilder.createMemberPointerType( 01895 getOrCreateType(Ty->getPointeeType(), U), ClassType); 01896 01897 const FunctionProtoType *FPT = 01898 Ty->getPointeeType()->getAs<FunctionProtoType>(); 01899 return DBuilder.createMemberPointerType( 01900 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType( 01901 Ty->getClass(), FPT->getTypeQuals())), 01902 FPT, U), 01903 ClassType); 01904 } 01905 01906 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile U) { 01907 // Ignore the atomic wrapping 01908 // FIXME: What is the correct representation? 01909 return getOrCreateType(Ty->getValueType(), U); 01910 } 01911 01912 /// CreateEnumType - get enumeration type. 01913 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) { 01914 const EnumDecl *ED = Ty->getDecl(); 01915 uint64_t Size = 0; 01916 uint64_t Align = 0; 01917 if (!ED->getTypeForDecl()->isIncompleteType()) { 01918 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 01919 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 01920 } 01921 01922 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 01923 01924 // If this is just a forward declaration, construct an appropriately 01925 // marked node and just return it. 01926 if (!ED->getDefinition()) { 01927 llvm::DIDescriptor EDContext; 01928 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext())); 01929 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 01930 unsigned Line = getLineNumber(ED->getLocation()); 01931 StringRef EDName = ED->getName(); 01932 llvm::DIType RetTy = DBuilder.createReplaceableForwardDecl( 01933 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line, 01934 0, Size, Align, FullName); 01935 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy))); 01936 return RetTy; 01937 } 01938 01939 return CreateTypeDefinition(Ty); 01940 } 01941 01942 llvm::DIType CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { 01943 const EnumDecl *ED = Ty->getDecl(); 01944 uint64_t Size = 0; 01945 uint64_t Align = 0; 01946 if (!ED->getTypeForDecl()->isIncompleteType()) { 01947 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 01948 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 01949 } 01950 01951 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 01952 01953 // Create DIEnumerator elements for each enumerator. 01954 SmallVector<llvm::Value *, 16> Enumerators; 01955 ED = ED->getDefinition(); 01956 for (const auto *Enum : ED->enumerators()) { 01957 Enumerators.push_back(DBuilder.createEnumerator( 01958 Enum->getName(), Enum->getInitVal().getSExtValue())); 01959 } 01960 01961 // Return a CompositeType for the enum itself. 01962 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators); 01963 01964 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 01965 unsigned Line = getLineNumber(ED->getLocation()); 01966 llvm::DIDescriptor EnumContext = 01967 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 01968 llvm::DIType ClassTy = ED->isFixed() 01969 ? getOrCreateType(ED->getIntegerType(), DefUnit) 01970 : llvm::DIType(); 01971 llvm::DIType DbgTy = 01972 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 01973 Size, Align, EltArray, ClassTy, FullName); 01974 return DbgTy; 01975 } 01976 01977 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 01978 Qualifiers Quals; 01979 do { 01980 Qualifiers InnerQuals = T.getLocalQualifiers(); 01981 // Qualifiers::operator+() doesn't like it if you add a Qualifier 01982 // that is already there. 01983 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 01984 Quals += InnerQuals; 01985 QualType LastT = T; 01986 switch (T->getTypeClass()) { 01987 default: 01988 return C.getQualifiedType(T.getTypePtr(), Quals); 01989 case Type::TemplateSpecialization: { 01990 const auto *Spec = cast<TemplateSpecializationType>(T); 01991 if (Spec->isTypeAlias()) 01992 return C.getQualifiedType(T.getTypePtr(), Quals); 01993 T = Spec->desugar(); 01994 break; 01995 } 01996 case Type::TypeOfExpr: 01997 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 01998 break; 01999 case Type::TypeOf: 02000 T = cast<TypeOfType>(T)->getUnderlyingType(); 02001 break; 02002 case Type::Decltype: 02003 T = cast<DecltypeType>(T)->getUnderlyingType(); 02004 break; 02005 case Type::UnaryTransform: 02006 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 02007 break; 02008 case Type::Attributed: 02009 T = cast<AttributedType>(T)->getEquivalentType(); 02010 break; 02011 case Type::Elaborated: 02012 T = cast<ElaboratedType>(T)->getNamedType(); 02013 break; 02014 case Type::Paren: 02015 T = cast<ParenType>(T)->getInnerType(); 02016 break; 02017 case Type::SubstTemplateTypeParm: 02018 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 02019 break; 02020 case Type::Auto: 02021 QualType DT = cast<AutoType>(T)->getDeducedType(); 02022 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 02023 T = DT; 02024 break; 02025 } 02026 02027 assert(T != LastT && "Type unwrapping failed to unwrap!"); 02028 (void)LastT; 02029 } while (true); 02030 } 02031 02032 /// getType - Get the type from the cache or return null type if it doesn't 02033 /// exist. 02034 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) { 02035 02036 // Unwrap the type as needed for debug information. 02037 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 02038 02039 auto it = TypeCache.find(Ty.getAsOpaquePtr()); 02040 if (it != TypeCache.end()) { 02041 // Verify that the debug info still exists. 02042 if (llvm::Value *V = it->second) 02043 return llvm::DIType(cast<llvm::MDNode>(V)); 02044 } 02045 02046 return llvm::DIType(); 02047 } 02048 02049 void CGDebugInfo::completeTemplateDefinition( 02050 const ClassTemplateSpecializationDecl &SD) { 02051 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 02052 return; 02053 02054 completeClassData(&SD); 02055 // In case this type has no member function definitions being emitted, ensure 02056 // it is retained 02057 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr()); 02058 } 02059 02060 /// getOrCreateType - Get the type from the cache or create a new 02061 /// one if necessary. 02062 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 02063 if (Ty.isNull()) 02064 return llvm::DIType(); 02065 02066 // Unwrap the type as needed for debug information. 02067 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 02068 02069 if (llvm::DIType T = getTypeOrNull(Ty)) 02070 return T; 02071 02072 // Otherwise create the type. 02073 llvm::DIType Res = CreateTypeNode(Ty, Unit); 02074 void *TyPtr = Ty.getAsOpaquePtr(); 02075 02076 // And update the type cache. 02077 TypeCache[TyPtr] = Res; 02078 02079 return Res; 02080 } 02081 02082 /// Currently the checksum of an interface includes the number of 02083 /// ivars and property accessors. 02084 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) { 02085 // The assumption is that the number of ivars can only increase 02086 // monotonically, so it is safe to just use their current number as 02087 // a checksum. 02088 unsigned Sum = 0; 02089 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin(); 02090 Ivar != nullptr; Ivar = Ivar->getNextIvar()) 02091 ++Sum; 02092 02093 return Sum; 02094 } 02095 02096 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 02097 switch (Ty->getTypeClass()) { 02098 case Type::ObjCObjectPointer: 02099 return getObjCInterfaceDecl( 02100 cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 02101 case Type::ObjCInterface: 02102 return cast<ObjCInterfaceType>(Ty)->getDecl(); 02103 default: 02104 return nullptr; 02105 } 02106 } 02107 02108 /// CreateTypeNode - Create a new debug type node. 02109 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) { 02110 // Handle qualifiers, which recursively handles what they refer to. 02111 if (Ty.hasLocalQualifiers()) 02112 return CreateQualifiedType(Ty, Unit); 02113 02114 // Work out details of type. 02115 switch (Ty->getTypeClass()) { 02116 #define TYPE(Class, Base) 02117 #define ABSTRACT_TYPE(Class, Base) 02118 #define NON_CANONICAL_TYPE(Class, Base) 02119 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 02120 #include "clang/AST/TypeNodes.def" 02121 llvm_unreachable("Dependent types cannot show up in debug information"); 02122 02123 case Type::ExtVector: 02124 case Type::Vector: 02125 return CreateType(cast<VectorType>(Ty), Unit); 02126 case Type::ObjCObjectPointer: 02127 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 02128 case Type::ObjCObject: 02129 return CreateType(cast<ObjCObjectType>(Ty), Unit); 02130 case Type::ObjCInterface: 02131 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 02132 case Type::Builtin: 02133 return CreateType(cast<BuiltinType>(Ty)); 02134 case Type::Complex: 02135 return CreateType(cast<ComplexType>(Ty)); 02136 case Type::Pointer: 02137 return CreateType(cast<PointerType>(Ty), Unit); 02138 case Type::Adjusted: 02139 case Type::Decayed: 02140 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 02141 return CreateType( 02142 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit); 02143 case Type::BlockPointer: 02144 return CreateType(cast<BlockPointerType>(Ty), Unit); 02145 case Type::Typedef: 02146 return CreateType(cast<TypedefType>(Ty), Unit); 02147 case Type::Record: 02148 return CreateType(cast<RecordType>(Ty)); 02149 case Type::Enum: 02150 return CreateEnumType(cast<EnumType>(Ty)); 02151 case Type::FunctionProto: 02152 case Type::FunctionNoProto: 02153 return CreateType(cast<FunctionType>(Ty), Unit); 02154 case Type::ConstantArray: 02155 case Type::VariableArray: 02156 case Type::IncompleteArray: 02157 return CreateType(cast<ArrayType>(Ty), Unit); 02158 02159 case Type::LValueReference: 02160 return CreateType(cast<LValueReferenceType>(Ty), Unit); 02161 case Type::RValueReference: 02162 return CreateType(cast<RValueReferenceType>(Ty), Unit); 02163 02164 case Type::MemberPointer: 02165 return CreateType(cast<MemberPointerType>(Ty), Unit); 02166 02167 case Type::Atomic: 02168 return CreateType(cast<AtomicType>(Ty), Unit); 02169 02170 case Type::TemplateSpecialization: 02171 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 02172 02173 case Type::Auto: 02174 case Type::Attributed: 02175 case Type::Elaborated: 02176 case Type::Paren: 02177 case Type::SubstTemplateTypeParm: 02178 case Type::TypeOfExpr: 02179 case Type::TypeOf: 02180 case Type::Decltype: 02181 case Type::UnaryTransform: 02182 case Type::PackExpansion: 02183 break; 02184 } 02185 02186 llvm_unreachable("type should have been unwrapped!"); 02187 } 02188 02189 /// getOrCreateLimitedType - Get the type from the cache or create a new 02190 /// limited type if necessary. 02191 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 02192 llvm::DIFile Unit) { 02193 QualType QTy(Ty, 0); 02194 02195 llvm::DICompositeType T(getTypeOrNull(QTy)); 02196 02197 // We may have cached a forward decl when we could have created 02198 // a non-forward decl. Go ahead and create a non-forward decl 02199 // now. 02200 if (T && !T.isForwardDecl()) 02201 return T; 02202 02203 // Otherwise create the type. 02204 llvm::DICompositeType Res = CreateLimitedType(Ty); 02205 02206 // Propagate members from the declaration to the definition 02207 // CreateType(const RecordType*) will overwrite this with the members in the 02208 // correct order if the full type is needed. 02209 Res.setArrays(T.getElements()); 02210 02211 // And update the type cache. 02212 TypeCache[QTy.getAsOpaquePtr()] = Res; 02213 return Res; 02214 } 02215 02216 // TODO: Currently used for context chains when limiting debug info. 02217 llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 02218 RecordDecl *RD = Ty->getDecl(); 02219 02220 // Get overall information about the record type for the debug info. 02221 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 02222 unsigned Line = getLineNumber(RD->getLocation()); 02223 StringRef RDName = getClassName(RD); 02224 02225 llvm::DIDescriptor RDContext = 02226 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 02227 02228 // If we ended up creating the type during the context chain construction, 02229 // just return that. 02230 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD))); 02231 if (T && (!T.isForwardDecl() || !RD->getDefinition())) 02232 return T; 02233 02234 // If this is just a forward or incomplete declaration, construct an 02235 // appropriately marked node and just return it. 02236 const RecordDecl *D = RD->getDefinition(); 02237 if (!D || !D->isCompleteDefinition()) 02238 return getOrCreateRecordFwdDecl(Ty, RDContext); 02239 02240 uint64_t Size = CGM.getContext().getTypeSize(Ty); 02241 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 02242 llvm::DICompositeType RealDecl; 02243 02244 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 02245 02246 if (RD->isUnion()) 02247 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, Size, 02248 Align, 0, llvm::DIArray(), 0, FullName); 02249 else if (RD->isClass()) { 02250 // FIXME: This could be a struct type giving a default visibility different 02251 // than C++ class type, but needs llvm metadata changes first. 02252 RealDecl = DBuilder.createClassType( 02253 RDContext, RDName, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(), 02254 llvm::DIArray(), llvm::DIType(), llvm::DIArray(), FullName); 02255 } else 02256 RealDecl = DBuilder.createStructType( 02257 RDContext, RDName, DefUnit, Line, Size, Align, 0, llvm::DIType(), 02258 llvm::DIArray(), 0, llvm::DIType(), FullName); 02259 02260 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 02261 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; 02262 02263 if (const ClassTemplateSpecializationDecl *TSpecial = 02264 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 02265 RealDecl.setArrays(llvm::DIArray(), 02266 CollectCXXTemplateParams(TSpecial, DefUnit)); 02267 return RealDecl; 02268 } 02269 02270 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 02271 llvm::DICompositeType RealDecl) { 02272 // A class's primary base or the class itself contains the vtable. 02273 llvm::DICompositeType ContainingType; 02274 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 02275 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 02276 // Seek non-virtual primary base root. 02277 while (1) { 02278 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 02279 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 02280 if (PBT && !BRL.isPrimaryBaseVirtual()) 02281 PBase = PBT; 02282 else 02283 break; 02284 } 02285 ContainingType = llvm::DICompositeType( 02286 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 02287 getOrCreateFile(RD->getLocation()))); 02288 } else if (RD->isDynamicClass()) 02289 ContainingType = RealDecl; 02290 02291 RealDecl.setContainingType(ContainingType); 02292 } 02293 02294 /// CreateMemberType - Create new member and increase Offset by FType's size. 02295 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 02296 StringRef Name, uint64_t *Offset) { 02297 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 02298 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 02299 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 02300 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, 02301 FieldAlign, *Offset, 0, FieldTy); 02302 *Offset += FieldSize; 02303 return Ty; 02304 } 02305 02306 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, 02307 llvm::DIFile Unit, 02308 StringRef &Name, StringRef &LinkageName, 02309 llvm::DIDescriptor &FDContext, 02310 llvm::DIArray &TParamsArray, 02311 unsigned &Flags) { 02312 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 02313 Name = getFunctionName(FD); 02314 // Use mangled name as linkage name for C/C++ functions. 02315 if (FD->hasPrototype()) { 02316 LinkageName = CGM.getMangledName(GD); 02317 Flags |= llvm::DIDescriptor::FlagPrototyped; 02318 } 02319 // No need to replicate the linkage name if it isn't different from the 02320 // subprogram name, no need to have it at all unless coverage is enabled or 02321 // debug is set to more than just line tables. 02322 if (LinkageName == Name || 02323 (!CGM.getCodeGenOpts().EmitGcovArcs && 02324 !CGM.getCodeGenOpts().EmitGcovNotes && 02325 DebugKind <= CodeGenOptions::DebugLineTablesOnly)) 02326 LinkageName = StringRef(); 02327 02328 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) { 02329 if (const NamespaceDecl *NSDecl = 02330 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 02331 FDContext = getOrCreateNameSpace(NSDecl); 02332 else if (const RecordDecl *RDecl = 02333 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 02334 FDContext = getContextDescriptor(cast<Decl>(RDecl)); 02335 // Collect template parameters. 02336 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 02337 } 02338 } 02339 02340 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile &Unit, 02341 unsigned &LineNo, QualType &T, 02342 StringRef &Name, StringRef &LinkageName, 02343 llvm::DIDescriptor &VDContext) { 02344 Unit = getOrCreateFile(VD->getLocation()); 02345 LineNo = getLineNumber(VD->getLocation()); 02346 02347 setLocation(VD->getLocation()); 02348 02349 T = VD->getType(); 02350 if (T->isIncompleteArrayType()) { 02351 // CodeGen turns int[] into int[1] so we'll do the same here. 02352 llvm::APInt ConstVal(32, 1); 02353 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 02354 02355 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 02356 ArrayType::Normal, 0); 02357 } 02358 02359 Name = VD->getName(); 02360 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 02361 !isa<ObjCMethodDecl>(VD->getDeclContext())) 02362 LinkageName = CGM.getMangledName(VD); 02363 if (LinkageName == Name) 02364 LinkageName = StringRef(); 02365 02366 // Since we emit declarations (DW_AT_members) for static members, place the 02367 // definition of those static members in the namespace they were declared in 02368 // in the source code (the lexical decl context). 02369 // FIXME: Generalize this for even non-member global variables where the 02370 // declaration and definition may have different lexical decl contexts, once 02371 // we have support for emitting declarations of (non-member) global variables. 02372 VDContext = getContextDescriptor( 02373 dyn_cast<Decl>(VD->isStaticDataMember() ? VD->getLexicalDeclContext() 02374 : VD->getDeclContext())); 02375 } 02376 02377 llvm::DISubprogram 02378 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) { 02379 llvm::DIArray TParamsArray; 02380 StringRef Name, LinkageName; 02381 unsigned Flags = 0; 02382 SourceLocation Loc = FD->getLocation(); 02383 llvm::DIFile Unit = getOrCreateFile(Loc); 02384 llvm::DIDescriptor DContext(Unit); 02385 unsigned Line = getLineNumber(Loc); 02386 02387 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext, 02388 TParamsArray, Flags); 02389 // Build function type. 02390 SmallVector<QualType, 16> ArgTypes; 02391 for (const ParmVarDecl *Parm: FD->parameters()) 02392 ArgTypes.push_back(Parm->getType()); 02393 QualType FnType = 02394 CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes, 02395 FunctionProtoType::ExtProtoInfo()); 02396 llvm::DISubprogram SP = 02397 DBuilder.createTempFunctionFwdDecl(DContext, Name, LinkageName, Unit, Line, 02398 getOrCreateFunctionType(FD, FnType, Unit), 02399 !FD->isExternallyVisible(), 02400 false /*declaration*/, 0, Flags, 02401 CGM.getLangOpts().Optimize, nullptr, 02402 TParamsArray, getFunctionDeclaration(FD)); 02403 const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl()); 02404 FwdDeclReplaceMap.push_back(std::make_pair(CanonDecl, 02405 static_cast<llvm::Value *>(SP))); 02406 return SP; 02407 } 02408 02409 llvm::DIGlobalVariable 02410 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 02411 QualType T; 02412 StringRef Name, LinkageName; 02413 SourceLocation Loc = VD->getLocation(); 02414 llvm::DIFile Unit = getOrCreateFile(Loc); 02415 llvm::DIDescriptor DContext(Unit); 02416 unsigned Line = getLineNumber(Loc); 02417 02418 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext); 02419 llvm::DIGlobalVariable GV = 02420 DBuilder.createTempGlobalVariableFwdDecl(DContext, Name, LinkageName, Unit, 02421 Line, getOrCreateType(T, Unit), 02422 !VD->isExternallyVisible(), 02423 nullptr, nullptr); 02424 FwdDeclReplaceMap.push_back(std::make_pair(cast<VarDecl>(VD->getCanonicalDecl()), 02425 static_cast<llvm::Value *>(GV))); 02426 return GV; 02427 } 02428 02429 llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 02430 // We only need a declaration (not a definition) of the type - so use whatever 02431 // we would otherwise do to get a type for a pointee. (forward declarations in 02432 // limited debug info, full definitions (if the type definition is available) 02433 // in unlimited debug info) 02434 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) 02435 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 02436 getOrCreateFile(TD->getLocation())); 02437 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I = 02438 DeclCache.find(D->getCanonicalDecl()); 02439 02440 if (I != DeclCache.end()) { 02441 llvm::Value *V = I->second; 02442 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V)); 02443 } 02444 02445 // No definition for now. Emit a forward definition that might be 02446 // merged with a potential upcoming definition. 02447 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 02448 return getFunctionForwardDeclaration(FD); 02449 else if (const auto *VD = dyn_cast<VarDecl>(D)) 02450 return getGlobalVariableForwardDeclaration(VD); 02451 02452 return llvm::DIDescriptor(); 02453 } 02454 02455 /// getFunctionDeclaration - Return debug info descriptor to describe method 02456 /// declaration for the given method definition. 02457 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) { 02458 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly) 02459 return llvm::DISubprogram(); 02460 02461 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 02462 if (!FD) 02463 return llvm::DISubprogram(); 02464 02465 // Setup context. 02466 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext())); 02467 02468 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI = 02469 SPCache.find(FD->getCanonicalDecl()); 02470 if (MI == SPCache.end()) { 02471 if (const CXXMethodDecl *MD = 02472 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 02473 llvm::DICompositeType T(S); 02474 llvm::DISubprogram SP = 02475 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T); 02476 return SP; 02477 } 02478 } 02479 if (MI != SPCache.end()) { 02480 llvm::Value *V = MI->second; 02481 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 02482 if (SP.isSubprogram() && !SP.isDefinition()) 02483 return SP; 02484 } 02485 02486 for (auto NextFD : FD->redecls()) { 02487 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI = 02488 SPCache.find(NextFD->getCanonicalDecl()); 02489 if (MI != SPCache.end()) { 02490 llvm::Value *V = MI->second; 02491 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 02492 if (SP.isSubprogram() && !SP.isDefinition()) 02493 return SP; 02494 } 02495 } 02496 return llvm::DISubprogram(); 02497 } 02498 02499 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include 02500 // implicit parameter "this". 02501 llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D, 02502 QualType FnType, 02503 llvm::DIFile F) { 02504 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly) 02505 // Create fake but valid subroutine type. Otherwise 02506 // llvm::DISubprogram::Verify() would return false, and 02507 // subprogram DIE will miss DW_AT_decl_file and 02508 // DW_AT_decl_line fields. 02509 return DBuilder.createSubroutineType(F, 02510 DBuilder.getOrCreateTypeArray(None)); 02511 02512 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 02513 return getOrCreateMethodType(Method, F); 02514 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 02515 // Add "self" and "_cmd" 02516 SmallVector<llvm::Value *, 16> Elts; 02517 02518 // First element is always return type. For 'void' functions it is NULL. 02519 QualType ResultTy = OMethod->getReturnType(); 02520 02521 // Replace the instancetype keyword with the actual type. 02522 if (ResultTy == CGM.getContext().getObjCInstanceType()) 02523 ResultTy = CGM.getContext().getPointerType( 02524 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 02525 02526 Elts.push_back(getOrCreateType(ResultTy, F)); 02527 // "self" pointer is always first argument. 02528 QualType SelfDeclTy = OMethod->getSelfDecl()->getType(); 02529 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F); 02530 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy)); 02531 // "_cmd" pointer is always second argument. 02532 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F); 02533 Elts.push_back(DBuilder.createArtificialType(CmdTy)); 02534 // Get rest of the arguments. 02535 for (const auto *PI : OMethod->params()) 02536 Elts.push_back(getOrCreateType(PI->getType(), F)); 02537 // Variadic methods need a special marker at the end of the type list. 02538 if (OMethod->isVariadic()) 02539 Elts.push_back(DBuilder.createUnspecifiedParameter()); 02540 02541 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 02542 return DBuilder.createSubroutineType(F, EltTypeArray); 02543 } 02544 02545 // Handle variadic function types; they need an additional 02546 // unspecified parameter. 02547 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 02548 if (FD->isVariadic()) { 02549 SmallVector<llvm::Value *, 16> EltTys; 02550 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 02551 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType)) 02552 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i) 02553 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F)); 02554 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 02555 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 02556 return DBuilder.createSubroutineType(F, EltTypeArray); 02557 } 02558 02559 return llvm::DICompositeType(getOrCreateType(FnType, F)); 02560 } 02561 02562 /// EmitFunctionStart - Constructs the debug code for entering a function. 02563 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, 02564 SourceLocation ScopeLoc, QualType FnType, 02565 llvm::Function *Fn, CGBuilderTy &Builder) { 02566 02567 StringRef Name; 02568 StringRef LinkageName; 02569 02570 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 02571 02572 const Decl *D = GD.getDecl(); 02573 bool HasDecl = (D != nullptr); 02574 02575 unsigned Flags = 0; 02576 llvm::DIFile Unit = getOrCreateFile(Loc); 02577 llvm::DIDescriptor FDContext(Unit); 02578 llvm::DIArray TParamsArray; 02579 if (!HasDecl) { 02580 // Use llvm function name. 02581 LinkageName = Fn->getName(); 02582 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 02583 // If there is a DISubprogram for this function available then use it. 02584 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator FI = 02585 SPCache.find(FD->getCanonicalDecl()); 02586 if (FI != SPCache.end()) { 02587 llvm::Value *V = FI->second; 02588 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V)); 02589 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 02590 llvm::MDNode *SPN = SP; 02591 LexicalBlockStack.push_back(SPN); 02592 RegionMap[D] = llvm::WeakVH(SP); 02593 return; 02594 } 02595 } 02596 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 02597 TParamsArray, Flags); 02598 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 02599 Name = getObjCMethodName(OMD); 02600 Flags |= llvm::DIDescriptor::FlagPrototyped; 02601 } else { 02602 // Use llvm function name. 02603 Name = Fn->getName(); 02604 Flags |= llvm::DIDescriptor::FlagPrototyped; 02605 } 02606 if (!Name.empty() && Name[0] == '\01') 02607 Name = Name.substr(1); 02608 02609 if (!HasDecl || D->isImplicit()) { 02610 Flags |= llvm::DIDescriptor::FlagArtificial; 02611 // Artificial functions without a location should not silently reuse CurLoc. 02612 if (Loc.isInvalid()) 02613 CurLoc = SourceLocation(); 02614 } 02615 unsigned LineNo = getLineNumber(Loc); 02616 unsigned ScopeLine = getLineNumber(ScopeLoc); 02617 02618 // FIXME: The function declaration we're constructing here is mostly reusing 02619 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 02620 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 02621 // all subprograms instead of the actual context since subprogram definitions 02622 // are emitted as CU level entities by the backend. 02623 llvm::DISubprogram SP = DBuilder.createFunction( 02624 FDContext, Name, LinkageName, Unit, LineNo, 02625 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(), 02626 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn, 02627 TParamsArray, getFunctionDeclaration(D)); 02628 // We might get here with a VarDecl in the case we're generating 02629 // code for the initialization of globals. Do not record these decls 02630 // as they will overwrite the actual VarDecl Decl in the cache. 02631 if (HasDecl && isa<FunctionDecl>(D)) 02632 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP))); 02633 02634 // Push the function onto the lexical block stack. 02635 llvm::MDNode *SPN = SP; 02636 LexicalBlockStack.push_back(SPN); 02637 02638 if (HasDecl) 02639 RegionMap[D] = llvm::WeakVH(SP); 02640 } 02641 02642 /// EmitLocation - Emit metadata to indicate a change in line/column 02643 /// information in the source file. If the location is invalid, the 02644 /// previous location will be reused. 02645 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc, 02646 bool ForceColumnInfo) { 02647 // Update our current location 02648 setLocation(Loc); 02649 02650 if (CurLoc.isInvalid() || CurLoc.isMacroID()) 02651 return; 02652 02653 // Don't bother if things are the same as last time. 02654 SourceManager &SM = CGM.getContext().getSourceManager(); 02655 if (CurLoc == PrevLoc || 02656 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc)) 02657 // New Builder may not be in sync with CGDebugInfo. 02658 if (!Builder.getCurrentDebugLocation().isUnknown() && 02659 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) == 02660 LexicalBlockStack.back()) 02661 return; 02662 02663 // Update last state. 02664 PrevLoc = CurLoc; 02665 02666 llvm::MDNode *Scope = LexicalBlockStack.back(); 02667 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 02668 getLineNumber(CurLoc), getColumnNumber(CurLoc, ForceColumnInfo), Scope)); 02669 } 02670 02671 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on 02672 /// the stack. 02673 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 02674 llvm::DIDescriptor D = DBuilder.createLexicalBlock( 02675 llvm::DIDescriptor(LexicalBlockStack.empty() ? nullptr 02676 : LexicalBlockStack.back()), 02677 getOrCreateFile(CurLoc), getLineNumber(CurLoc), getColumnNumber(CurLoc)); 02678 llvm::MDNode *DN = D; 02679 LexicalBlockStack.push_back(DN); 02680 } 02681 02682 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 02683 /// region - beginning of a DW_TAG_lexical_block. 02684 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 02685 SourceLocation Loc) { 02686 // Set our current location. 02687 setLocation(Loc); 02688 02689 // Emit a line table change for the current location inside the new scope. 02690 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 02691 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back())); 02692 02693 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 02694 return; 02695 02696 // Create a new lexical block and push it on the stack. 02697 CreateLexicalBlock(Loc); 02698 } 02699 02700 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 02701 /// region - end of a DW_TAG_lexical_block. 02702 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 02703 SourceLocation Loc) { 02704 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 02705 02706 // Provide an entry in the line table for the end of the block. 02707 EmitLocation(Builder, Loc); 02708 02709 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 02710 return; 02711 02712 LexicalBlockStack.pop_back(); 02713 } 02714 02715 /// EmitFunctionEnd - Constructs the debug code for exiting a function. 02716 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 02717 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 02718 unsigned RCount = FnBeginRegionCount.back(); 02719 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 02720 02721 // Pop all regions for this function. 02722 while (LexicalBlockStack.size() != RCount) { 02723 // Provide an entry in the line table for the end of the block. 02724 EmitLocation(Builder, CurLoc); 02725 LexicalBlockStack.pop_back(); 02726 } 02727 FnBeginRegionCount.pop_back(); 02728 } 02729 02730 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 02731 // See BuildByRefType. 02732 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 02733 uint64_t *XOffset) { 02734 02735 SmallVector<llvm::Value *, 5> EltTys; 02736 QualType FType; 02737 uint64_t FieldSize, FieldOffset; 02738 unsigned FieldAlign; 02739 02740 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 02741 QualType Type = VD->getType(); 02742 02743 FieldOffset = 0; 02744 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 02745 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 02746 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 02747 FType = CGM.getContext().IntTy; 02748 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 02749 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 02750 02751 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 02752 if (HasCopyAndDispose) { 02753 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 02754 EltTys.push_back( 02755 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 02756 EltTys.push_back( 02757 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 02758 } 02759 bool HasByrefExtendedLayout; 02760 Qualifiers::ObjCLifetime Lifetime; 02761 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 02762 HasByrefExtendedLayout) && 02763 HasByrefExtendedLayout) { 02764 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 02765 EltTys.push_back( 02766 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 02767 } 02768 02769 CharUnits Align = CGM.getContext().getDeclAlign(VD); 02770 if (Align > CGM.getContext().toCharUnitsFromBits( 02771 CGM.getTarget().getPointerAlign(0))) { 02772 CharUnits FieldOffsetInBytes = 02773 CGM.getContext().toCharUnitsFromBits(FieldOffset); 02774 CharUnits AlignedOffsetInBytes = 02775 FieldOffsetInBytes.RoundUpToAlignment(Align); 02776 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 02777 02778 if (NumPaddingBytes.isPositive()) { 02779 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 02780 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 02781 pad, ArrayType::Normal, 0); 02782 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 02783 } 02784 } 02785 02786 FType = Type; 02787 llvm::DIType FieldTy = getOrCreateType(FType, Unit); 02788 FieldSize = CGM.getContext().getTypeSize(FType); 02789 FieldAlign = CGM.getContext().toBits(Align); 02790 02791 *XOffset = FieldOffset; 02792 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize, 02793 FieldAlign, FieldOffset, 0, FieldTy); 02794 EltTys.push_back(FieldTy); 02795 FieldOffset += FieldSize; 02796 02797 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 02798 02799 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 02800 02801 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 02802 llvm::DIType(), Elements); 02803 } 02804 02805 /// EmitDeclare - Emit local variable declaration debug info. 02806 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::LLVMConstants Tag, 02807 llvm::Value *Storage, unsigned ArgNo, 02808 CGBuilderTy &Builder) { 02809 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 02810 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 02811 02812 bool Unwritten = 02813 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 02814 cast<Decl>(VD->getDeclContext())->isImplicit()); 02815 llvm::DIFile Unit; 02816 if (!Unwritten) 02817 Unit = getOrCreateFile(VD->getLocation()); 02818 llvm::DIType Ty; 02819 uint64_t XOffset = 0; 02820 if (VD->hasAttr<BlocksAttr>()) 02821 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 02822 else 02823 Ty = getOrCreateType(VD->getType(), Unit); 02824 02825 // If there is no debug info for this type then do not emit debug info 02826 // for this variable. 02827 if (!Ty) 02828 return; 02829 02830 // Get location information. 02831 unsigned Line = 0; 02832 unsigned Column = 0; 02833 if (!Unwritten) { 02834 Line = getLineNumber(VD->getLocation()); 02835 Column = getColumnNumber(VD->getLocation()); 02836 } 02837 unsigned Flags = 0; 02838 if (VD->isImplicit()) 02839 Flags |= llvm::DIDescriptor::FlagArtificial; 02840 // If this is the first argument and it is implicit then 02841 // give it an object pointer flag. 02842 // FIXME: There has to be a better way to do this, but for static 02843 // functions there won't be an implicit param at arg1 and 02844 // otherwise it is 'self' or 'this'. 02845 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1) 02846 Flags |= llvm::DIDescriptor::FlagObjectPointer; 02847 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) 02848 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && 02849 !VD->getType()->isPointerType()) 02850 Flags |= llvm::DIDescriptor::FlagIndirectVariable; 02851 02852 llvm::MDNode *Scope = LexicalBlockStack.back(); 02853 02854 StringRef Name = VD->getName(); 02855 if (!Name.empty()) { 02856 if (VD->hasAttr<BlocksAttr>()) { 02857 CharUnits offset = CharUnits::fromQuantity(32); 02858 SmallVector<int64_t, 9> addr; 02859 addr.push_back(llvm::dwarf::DW_OP_plus); 02860 // offset of __forwarding field 02861 offset = CGM.getContext().toCharUnitsFromBits( 02862 CGM.getTarget().getPointerWidth(0)); 02863 addr.push_back(offset.getQuantity()); 02864 addr.push_back(llvm::dwarf::DW_OP_deref); 02865 addr.push_back(llvm::dwarf::DW_OP_plus); 02866 // offset of x field 02867 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 02868 addr.push_back(offset.getQuantity()); 02869 02870 // Create the descriptor for the variable. 02871 llvm::DIVariable D = DBuilder.createLocalVariable( 02872 Tag, llvm::DIDescriptor(Scope), VD->getName(), Unit, Line, Ty, ArgNo); 02873 02874 // Insert an llvm.dbg.declare into the current block. 02875 llvm::Instruction *Call = 02876 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), 02877 Builder.GetInsertBlock()); 02878 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 02879 return; 02880 } else if (isa<VariableArrayType>(VD->getType())) 02881 Flags |= llvm::DIDescriptor::FlagIndirectVariable; 02882 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 02883 // If VD is an anonymous union then Storage represents value for 02884 // all union fields. 02885 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 02886 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 02887 for (const auto *Field : RD->fields()) { 02888 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 02889 StringRef FieldName = Field->getName(); 02890 02891 // Ignore unnamed fields. Do not ignore unnamed records. 02892 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 02893 continue; 02894 02895 // Use VarDecl's Tag, Scope and Line number. 02896 llvm::DIVariable D = DBuilder.createLocalVariable( 02897 Tag, llvm::DIDescriptor(Scope), FieldName, Unit, Line, FieldTy, 02898 CGM.getLangOpts().Optimize, Flags, ArgNo); 02899 02900 // Insert an llvm.dbg.declare into the current block. 02901 llvm::Instruction *Call = DBuilder.insertDeclare( 02902 Storage, D, DBuilder.createExpression(), Builder.GetInsertBlock()); 02903 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 02904 } 02905 return; 02906 } 02907 } 02908 02909 // Create the descriptor for the variable. 02910 llvm::DIVariable D = DBuilder.createLocalVariable( 02911 Tag, llvm::DIDescriptor(Scope), Name, Unit, Line, Ty, 02912 CGM.getLangOpts().Optimize, Flags, ArgNo); 02913 02914 // Insert an llvm.dbg.declare into the current block. 02915 llvm::Instruction *Call = DBuilder.insertDeclare( 02916 Storage, D, DBuilder.createExpression(), Builder.GetInsertBlock()); 02917 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 02918 } 02919 02920 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 02921 llvm::Value *Storage, 02922 CGBuilderTy &Builder) { 02923 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 02924 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 02925 } 02926 02927 /// Look up the completed type for a self pointer in the TypeCache and 02928 /// create a copy of it with the ObjectPointer and Artificial flags 02929 /// set. If the type is not cached, a new one is created. This should 02930 /// never happen though, since creating a type for the implicit self 02931 /// argument implies that we already parsed the interface definition 02932 /// and the ivar declarations in the implementation. 02933 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, 02934 llvm::DIType Ty) { 02935 llvm::DIType CachedTy = getTypeOrNull(QualTy); 02936 if (CachedTy) 02937 Ty = CachedTy; 02938 return DBuilder.createObjectPointerType(Ty); 02939 } 02940 02941 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 02942 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 02943 const CGBlockInfo &blockInfo) { 02944 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 02945 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 02946 02947 if (Builder.GetInsertBlock() == nullptr) 02948 return; 02949 02950 bool isByRef = VD->hasAttr<BlocksAttr>(); 02951 02952 uint64_t XOffset = 0; 02953 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 02954 llvm::DIType Ty; 02955 if (isByRef) 02956 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 02957 else 02958 Ty = getOrCreateType(VD->getType(), Unit); 02959 02960 // Self is passed along as an implicit non-arg variable in a 02961 // block. Mark it as the object pointer. 02962 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 02963 Ty = CreateSelfType(VD->getType(), Ty); 02964 02965 // Get location information. 02966 unsigned Line = getLineNumber(VD->getLocation()); 02967 unsigned Column = getColumnNumber(VD->getLocation()); 02968 02969 const llvm::DataLayout &target = CGM.getDataLayout(); 02970 02971 CharUnits offset = CharUnits::fromQuantity( 02972 target.getStructLayout(blockInfo.StructureType) 02973 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 02974 02975 SmallVector<int64_t, 9> addr; 02976 if (isa<llvm::AllocaInst>(Storage)) 02977 addr.push_back(llvm::dwarf::DW_OP_deref); 02978 addr.push_back(llvm::dwarf::DW_OP_plus); 02979 addr.push_back(offset.getQuantity()); 02980 if (isByRef) { 02981 addr.push_back(llvm::dwarf::DW_OP_deref); 02982 addr.push_back(llvm::dwarf::DW_OP_plus); 02983 // offset of __forwarding field 02984 offset = 02985 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 02986 addr.push_back(offset.getQuantity()); 02987 addr.push_back(llvm::dwarf::DW_OP_deref); 02988 addr.push_back(llvm::dwarf::DW_OP_plus); 02989 // offset of x field 02990 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 02991 addr.push_back(offset.getQuantity()); 02992 } 02993 02994 // Create the descriptor for the variable. 02995 llvm::DIVariable D = 02996 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_auto_variable, 02997 llvm::DIDescriptor(LexicalBlockStack.back()), 02998 VD->getName(), Unit, Line, Ty); 02999 03000 // Insert an llvm.dbg.declare into the current block. 03001 llvm::Instruction *Call = DBuilder.insertDeclare( 03002 Storage, D, DBuilder.createExpression(addr), Builder.GetInsertPoint()); 03003 Call->setDebugLoc( 03004 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back())); 03005 } 03006 03007 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 03008 /// variable declaration. 03009 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 03010 unsigned ArgNo, 03011 CGBuilderTy &Builder) { 03012 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 03013 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 03014 } 03015 03016 namespace { 03017 struct BlockLayoutChunk { 03018 uint64_t OffsetInBits; 03019 const BlockDecl::Capture *Capture; 03020 }; 03021 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 03022 return l.OffsetInBits < r.OffsetInBits; 03023 } 03024 } 03025 03026 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 03027 llvm::Value *Arg, 03028 unsigned ArgNo, 03029 llvm::Value *LocalAddr, 03030 CGBuilderTy &Builder) { 03031 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 03032 ASTContext &C = CGM.getContext(); 03033 const BlockDecl *blockDecl = block.getBlockDecl(); 03034 03035 // Collect some general information about the block's location. 03036 SourceLocation loc = blockDecl->getCaretLocation(); 03037 llvm::DIFile tunit = getOrCreateFile(loc); 03038 unsigned line = getLineNumber(loc); 03039 unsigned column = getColumnNumber(loc); 03040 03041 // Build the debug-info type for the block literal. 03042 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 03043 03044 const llvm::StructLayout *blockLayout = 03045 CGM.getDataLayout().getStructLayout(block.StructureType); 03046 03047 SmallVector<llvm::Value *, 16> fields; 03048 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 03049 blockLayout->getElementOffsetInBits(0), 03050 tunit, tunit)); 03051 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 03052 blockLayout->getElementOffsetInBits(1), 03053 tunit, tunit)); 03054 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 03055 blockLayout->getElementOffsetInBits(2), 03056 tunit, tunit)); 03057 auto *FnTy = block.getBlockExpr()->getFunctionType(); 03058 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 03059 fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public, 03060 blockLayout->getElementOffsetInBits(3), 03061 tunit, tunit)); 03062 fields.push_back(createFieldType( 03063 "__descriptor", C.getPointerType(block.NeedsCopyDispose 03064 ? C.getBlockDescriptorExtendedType() 03065 : C.getBlockDescriptorType()), 03066 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); 03067 03068 // We want to sort the captures by offset, not because DWARF 03069 // requires this, but because we're paranoid about debuggers. 03070 SmallVector<BlockLayoutChunk, 8> chunks; 03071 03072 // 'this' capture. 03073 if (blockDecl->capturesCXXThis()) { 03074 BlockLayoutChunk chunk; 03075 chunk.OffsetInBits = 03076 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 03077 chunk.Capture = nullptr; 03078 chunks.push_back(chunk); 03079 } 03080 03081 // Variable captures. 03082 for (const auto &capture : blockDecl->captures()) { 03083 const VarDecl *variable = capture.getVariable(); 03084 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 03085 03086 // Ignore constant captures. 03087 if (captureInfo.isConstant()) 03088 continue; 03089 03090 BlockLayoutChunk chunk; 03091 chunk.OffsetInBits = 03092 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 03093 chunk.Capture = &capture; 03094 chunks.push_back(chunk); 03095 } 03096 03097 // Sort by offset. 03098 llvm::array_pod_sort(chunks.begin(), chunks.end()); 03099 03100 for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(), 03101 e = chunks.end(); 03102 i != e; ++i) { 03103 uint64_t offsetInBits = i->OffsetInBits; 03104 const BlockDecl::Capture *capture = i->Capture; 03105 03106 // If we have a null capture, this must be the C++ 'this' capture. 03107 if (!capture) { 03108 const CXXMethodDecl *method = 03109 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 03110 QualType type = method->getThisType(C); 03111 03112 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 03113 offsetInBits, tunit, tunit)); 03114 continue; 03115 } 03116 03117 const VarDecl *variable = capture->getVariable(); 03118 StringRef name = variable->getName(); 03119 03120 llvm::DIType fieldType; 03121 if (capture->isByRef()) { 03122 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 03123 03124 // FIXME: this creates a second copy of this type! 03125 uint64_t xoffset; 03126 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 03127 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 03128 fieldType = 03129 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width, 03130 PtrInfo.Align, offsetInBits, 0, fieldType); 03131 } else { 03132 fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public, 03133 offsetInBits, tunit, tunit); 03134 } 03135 fields.push_back(fieldType); 03136 } 03137 03138 SmallString<36> typeName; 03139 llvm::raw_svector_ostream(typeName) << "__block_literal_" 03140 << CGM.getUniqueBlockCount(); 03141 03142 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields); 03143 03144 llvm::DIType type = 03145 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 03146 CGM.getContext().toBits(block.BlockSize), 03147 CGM.getContext().toBits(block.BlockAlign), 0, 03148 llvm::DIType(), fieldsArray); 03149 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 03150 03151 // Get overall information about the block. 03152 unsigned flags = llvm::DIDescriptor::FlagArtificial; 03153 llvm::MDNode *scope = LexicalBlockStack.back(); 03154 03155 // Create the descriptor for the parameter. 03156 llvm::DIVariable debugVar = DBuilder.createLocalVariable( 03157 llvm::dwarf::DW_TAG_arg_variable, llvm::DIDescriptor(scope), 03158 Arg->getName(), tunit, line, type, CGM.getLangOpts().Optimize, flags, 03159 ArgNo); 03160 03161 if (LocalAddr) { 03162 // Insert an llvm.dbg.value into the current block. 03163 llvm::Instruction *DbgVal = DBuilder.insertDbgValueIntrinsic( 03164 LocalAddr, 0, debugVar, DBuilder.createExpression(), 03165 Builder.GetInsertBlock()); 03166 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 03167 } 03168 03169 // Insert an llvm.dbg.declare into the current block. 03170 llvm::Instruction *DbgDecl = DBuilder.insertDeclare( 03171 Arg, debugVar, DBuilder.createExpression(), Builder.GetInsertBlock()); 03172 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 03173 } 03174 03175 /// If D is an out-of-class definition of a static data member of a class, find 03176 /// its corresponding in-class declaration. 03177 llvm::DIDerivedType 03178 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 03179 if (!D->isStaticDataMember()) 03180 return llvm::DIDerivedType(); 03181 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI = 03182 StaticDataMemberCache.find(D->getCanonicalDecl()); 03183 if (MI != StaticDataMemberCache.end()) { 03184 assert(MI->second && "Static data member declaration should still exist"); 03185 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)); 03186 } 03187 03188 // If the member wasn't found in the cache, lazily construct and add it to the 03189 // type (used when a limited form of the type is emitted). 03190 auto DC = D->getDeclContext(); 03191 llvm::DICompositeType Ctxt(getContextDescriptor(cast<Decl>(DC))); 03192 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 03193 } 03194 03195 /// Recursively collect all of the member fields of a global anonymous decl and 03196 /// create static variables for them. The first time this is called it needs 03197 /// to be on a union and then from there we can have additional unnamed fields. 03198 llvm::DIGlobalVariable 03199 CGDebugInfo::CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit, 03200 unsigned LineNo, StringRef LinkageName, 03201 llvm::GlobalVariable *Var, 03202 llvm::DIDescriptor DContext) { 03203 llvm::DIGlobalVariable GV; 03204 03205 for (const auto *Field : RD->fields()) { 03206 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 03207 StringRef FieldName = Field->getName(); 03208 03209 // Ignore unnamed fields, but recurse into anonymous records. 03210 if (FieldName.empty()) { 03211 const RecordType *RT = dyn_cast<RecordType>(Field->getType()); 03212 if (RT) 03213 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 03214 Var, DContext); 03215 continue; 03216 } 03217 // Use VarDecl's Tag, Scope and Line number. 03218 GV = DBuilder.createGlobalVariable( 03219 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy, 03220 Var->hasInternalLinkage(), Var, llvm::DIDerivedType()); 03221 } 03222 return GV; 03223 } 03224 03225 /// EmitGlobalVariable - Emit information about a global variable. 03226 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 03227 const VarDecl *D) { 03228 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 03229 // Create global variable debug descriptor. 03230 llvm::DIFile Unit; 03231 llvm::DIDescriptor DContext; 03232 unsigned LineNo; 03233 StringRef DeclName, LinkageName; 03234 QualType T; 03235 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext); 03236 03237 // Attempt to store one global variable for the declaration - even if we 03238 // emit a lot of fields. 03239 llvm::DIGlobalVariable GV; 03240 03241 // If this is an anonymous union then we'll want to emit a global 03242 // variable for each member of the anonymous union so that it's possible 03243 // to find the name of any field in the union. 03244 if (T->isUnionType() && DeclName.empty()) { 03245 const RecordDecl *RD = cast<RecordType>(T)->getDecl(); 03246 assert(RD->isAnonymousStructOrUnion() && 03247 "unnamed non-anonymous struct or union?"); 03248 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 03249 } else { 03250 GV = DBuilder.createGlobalVariable( 03251 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 03252 Var->hasInternalLinkage(), Var, 03253 getOrCreateStaticDataMemberDeclarationOrNull(D)); 03254 } 03255 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV))); 03256 } 03257 03258 /// EmitGlobalVariable - Emit global variable's debug info. 03259 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 03260 llvm::Constant *Init) { 03261 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 03262 // Create the descriptor for the variable. 03263 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 03264 StringRef Name = VD->getName(); 03265 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 03266 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 03267 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 03268 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 03269 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 03270 } 03271 // Do not use DIGlobalVariable for enums. 03272 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 03273 return; 03274 // Do not emit separate definitions for function local const/statics. 03275 if (isa<FunctionDecl>(VD->getDeclContext())) 03276 return; 03277 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 03278 auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH())); 03279 if (!pair.second) 03280 return; 03281 llvm::DIDescriptor DContext = 03282 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext())); 03283 llvm::DIGlobalVariable GV = DBuilder.createGlobalVariable( 03284 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 03285 true, Init, 03286 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD))); 03287 pair.first->second = llvm::WeakVH(GV); 03288 } 03289 03290 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 03291 if (!LexicalBlockStack.empty()) 03292 return llvm::DIScope(LexicalBlockStack.back()); 03293 return getContextDescriptor(D); 03294 } 03295 03296 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 03297 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 03298 return; 03299 DBuilder.createImportedModule( 03300 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 03301 getOrCreateNameSpace(UD.getNominatedNamespace()), 03302 getLineNumber(UD.getLocation())); 03303 } 03304 03305 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 03306 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 03307 return; 03308 assert(UD.shadow_size() && 03309 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 03310 // Emitting one decl is sufficient - debuggers can detect that this is an 03311 // overloaded name & provide lookup for all the overloads. 03312 const UsingShadowDecl &USD = **UD.shadow_begin(); 03313 if (llvm::DIDescriptor Target = 03314 getDeclarationOrDefinition(USD.getUnderlyingDecl())) 03315 DBuilder.createImportedDeclaration( 03316 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 03317 getLineNumber(USD.getLocation())); 03318 } 03319 03320 llvm::DIImportedEntity 03321 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 03322 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 03323 return llvm::DIImportedEntity(nullptr); 03324 llvm::WeakVH &VH = NamespaceAliasCache[&NA]; 03325 if (VH) 03326 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH)); 03327 llvm::DIImportedEntity R(nullptr); 03328 if (const NamespaceAliasDecl *Underlying = 03329 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 03330 // This could cache & dedup here rather than relying on metadata deduping. 03331 R = DBuilder.createImportedDeclaration( 03332 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 03333 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()), 03334 NA.getName()); 03335 else 03336 R = DBuilder.createImportedDeclaration( 03337 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 03338 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 03339 getLineNumber(NA.getLocation()), NA.getName()); 03340 VH = R; 03341 return R; 03342 } 03343 03344 /// getOrCreateNamesSpace - Return namespace descriptor for the given 03345 /// namespace decl. 03346 llvm::DINameSpace 03347 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 03348 NSDecl = NSDecl->getCanonicalDecl(); 03349 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 03350 NameSpaceCache.find(NSDecl); 03351 if (I != NameSpaceCache.end()) 03352 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 03353 03354 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 03355 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 03356 llvm::DIDescriptor Context = 03357 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 03358 llvm::DINameSpace NS = 03359 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 03360 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 03361 return NS; 03362 } 03363 03364 void CGDebugInfo::finalize() { 03365 // Creating types might create further types - invalidating the current 03366 // element and the size(), so don't cache/reference them. 03367 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 03368 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 03369 E.Decl.replaceAllUsesWith(CGM.getLLVMContext(), 03370 E.Type->getDecl()->getDefinition() 03371 ? CreateTypeDefinition(E.Type, E.Unit) 03372 : E.Decl); 03373 } 03374 03375 for (auto p : ReplaceMap) { 03376 assert(p.second); 03377 llvm::DIType Ty(cast<llvm::MDNode>(p.second)); 03378 assert(Ty.isForwardDecl()); 03379 03380 auto it = TypeCache.find(p.first); 03381 assert(it != TypeCache.end()); 03382 assert(it->second); 03383 03384 llvm::DIType RepTy(cast<llvm::MDNode>(it->second)); 03385 Ty.replaceAllUsesWith(CGM.getLLVMContext(), RepTy); 03386 } 03387 03388 for (const auto &p : FwdDeclReplaceMap) { 03389 assert(p.second); 03390 llvm::DIDescriptor FwdDecl(cast<llvm::MDNode>(p.second)); 03391 llvm::WeakVH VH; 03392 03393 auto it = DeclCache.find(p.first); 03394 // If there has been no definition for the declaration, call RAUV 03395 // with ourselves, that will destroy the temporary MDNode and 03396 // replace it with a standard one, avoiding leaking memory. 03397 if (it == DeclCache.end()) 03398 VH = p.second; 03399 else 03400 VH = it->second; 03401 FwdDecl.replaceAllUsesWith(CGM.getLLVMContext(), 03402 llvm::DIDescriptor(cast<llvm::MDNode>(VH))); 03403 } 03404 03405 // We keep our own list of retained types, because we need to look 03406 // up the final type in the type cache. 03407 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(), 03408 RE = RetainedTypes.end(); RI != RE; ++RI) 03409 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI]))); 03410 03411 DBuilder.finalize(); 03412 } 03413 03414 void CGDebugInfo::EmitExplicitCastType(QualType Ty) { 03415 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 03416 return; 03417 llvm::DIType DieTy = getOrCreateType(Ty, getOrCreateMainFile()); 03418 // Don't ignore in case of explicit cast where it is referenced indirectly. 03419 DBuilder.retainType(DieTy); 03420 }