CGDebugInfo.cpp 96 KB

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