CGDebugInfo.cpp 175 KB

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