CGDebugInfo.cpp 157 KB

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