CGDebugInfo.cpp 159 KB

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