CGDebugInfo.cpp 111 KB

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