CGDebugInfo.cpp 170 KB

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