CGDebugInfo.cpp 136 KB

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