CGDebugInfo.cpp 182 KB

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