CGDebugInfo.cpp 183 KB

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