CGDebugInfo.cpp 172 KB

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