CGDebugInfo.cpp 171 KB

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