CGDebugInfo.cpp 94 KB

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