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