CGDebugInfo.cpp 221 KB

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