InstrRefBasedImpl.cpp 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228
  1. //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
  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. /// \file InstrRefBasedImpl.cpp
  9. ///
  10. /// This is a separate implementation of LiveDebugValues, see
  11. /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
  12. ///
  13. /// This pass propagates variable locations between basic blocks, resolving
  14. /// control flow conflicts between them. The problem is SSA construction, where
  15. /// each debug instruction assigns the *value* that a variable has, and every
  16. /// instruction where the variable is in scope uses that variable. The resulting
  17. /// map of instruction-to-value is then translated into a register (or spill)
  18. /// location for each variable over each instruction.
  19. ///
  20. /// The primary difference from normal SSA construction is that we cannot
  21. /// _create_ PHI values that contain variable values. CodeGen has already
  22. /// completed, and we can't alter it just to make debug-info complete. Thus:
  23. /// we can identify function positions where we would like a PHI value for a
  24. /// variable, but must search the MachineFunction to see whether such a PHI is
  25. /// available. If no such PHI exists, the variable location must be dropped.
  26. ///
  27. /// To achieve this, we perform two kinds of analysis. First, we identify
  28. /// every value defined by every instruction (ignoring those that only move
  29. /// another value), then re-compute an SSA-form representation of the
  30. /// MachineFunction, using value propagation to eliminate any un-necessary
  31. /// PHI values. This gives us a map of every value computed in the function,
  32. /// and its location within the register file / stack.
  33. ///
  34. /// Secondly, for each variable we perform the same analysis, where each debug
  35. /// instruction is considered a def, and every instruction where the variable
  36. /// is in lexical scope as a use. Value propagation is used again to eliminate
  37. /// any un-necessary PHIs. This gives us a map of each variable to the value
  38. /// it should have in a block.
  39. ///
  40. /// Once both are complete, we have two maps for each block:
  41. /// * Variables to the values they should have,
  42. /// * Values to the register / spill slot they are located in.
  43. /// After which we can marry-up variable values with a location, and emit
  44. /// DBG_VALUE instructions specifying those locations. Variable locations may
  45. /// be dropped in this process due to the desired variable value not being
  46. /// resident in any machine location, or because there is no PHI value in any
  47. /// location that accurately represents the desired value. The building of
  48. /// location lists for each block is left to DbgEntityHistoryCalculator.
  49. ///
  50. /// This pass is kept efficient because the size of the first SSA problem
  51. /// is proportional to the working-set size of the function, which the compiler
  52. /// tries to keep small. (It's also proportional to the number of blocks).
  53. /// Additionally, we repeatedly perform the second SSA problem analysis with
  54. /// only the variables and blocks in a single lexical scope, exploiting their
  55. /// locality.
  56. ///
  57. /// ### Terminology
  58. ///
  59. /// A machine location is a register or spill slot, a value is something that's
  60. /// defined by an instruction or PHI node, while a variable value is the value
  61. /// assigned to a variable. A variable location is a machine location, that must
  62. /// contain the appropriate variable value. A value that is a PHI node is
  63. /// occasionally called an mphi.
  64. ///
  65. /// The first SSA problem is the "machine value location" problem,
  66. /// because we're determining which machine locations contain which values.
  67. /// The "locations" are constant: what's unknown is what value they contain.
  68. ///
  69. /// The second SSA problem (the one for variables) is the "variable value
  70. /// problem", because it's determining what values a variable has, rather than
  71. /// what location those values are placed in.
  72. ///
  73. /// TODO:
  74. /// Overlapping fragments
  75. /// Entry values
  76. /// Add back DEBUG statements for debugging this
  77. /// Collect statistics
  78. ///
  79. //===----------------------------------------------------------------------===//
  80. #include "llvm/ADT/DenseMap.h"
  81. #include "llvm/ADT/PostOrderIterator.h"
  82. #include "llvm/ADT/STLExtras.h"
  83. #include "llvm/ADT/SmallPtrSet.h"
  84. #include "llvm/ADT/SmallSet.h"
  85. #include "llvm/ADT/SmallVector.h"
  86. #include "llvm/BinaryFormat/Dwarf.h"
  87. #include "llvm/CodeGen/LexicalScopes.h"
  88. #include "llvm/CodeGen/MachineBasicBlock.h"
  89. #include "llvm/CodeGen/MachineDominators.h"
  90. #include "llvm/CodeGen/MachineFrameInfo.h"
  91. #include "llvm/CodeGen/MachineFunction.h"
  92. #include "llvm/CodeGen/MachineInstr.h"
  93. #include "llvm/CodeGen/MachineInstrBuilder.h"
  94. #include "llvm/CodeGen/MachineInstrBundle.h"
  95. #include "llvm/CodeGen/MachineMemOperand.h"
  96. #include "llvm/CodeGen/MachineOperand.h"
  97. #include "llvm/CodeGen/PseudoSourceValue.h"
  98. #include "llvm/CodeGen/TargetFrameLowering.h"
  99. #include "llvm/CodeGen/TargetInstrInfo.h"
  100. #include "llvm/CodeGen/TargetLowering.h"
  101. #include "llvm/CodeGen/TargetPassConfig.h"
  102. #include "llvm/CodeGen/TargetRegisterInfo.h"
  103. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  104. #include "llvm/Config/llvm-config.h"
  105. #include "llvm/IR/DebugInfoMetadata.h"
  106. #include "llvm/IR/DebugLoc.h"
  107. #include "llvm/IR/Function.h"
  108. #include "llvm/MC/MCRegisterInfo.h"
  109. #include "llvm/Support/Casting.h"
  110. #include "llvm/Support/Compiler.h"
  111. #include "llvm/Support/Debug.h"
  112. #include "llvm/Support/GenericIteratedDominanceFrontier.h"
  113. #include "llvm/Support/TypeSize.h"
  114. #include "llvm/Support/raw_ostream.h"
  115. #include "llvm/Target/TargetMachine.h"
  116. #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
  117. #include <algorithm>
  118. #include <cassert>
  119. #include <climits>
  120. #include <cstdint>
  121. #include <functional>
  122. #include <queue>
  123. #include <tuple>
  124. #include <utility>
  125. #include <vector>
  126. #include "InstrRefBasedImpl.h"
  127. #include "LiveDebugValues.h"
  128. #include <optional>
  129. using namespace llvm;
  130. using namespace LiveDebugValues;
  131. // SSAUpdaterImple sets DEBUG_TYPE, change it.
  132. #undef DEBUG_TYPE
  133. #define DEBUG_TYPE "livedebugvalues"
  134. // Act more like the VarLoc implementation, by propagating some locations too
  135. // far and ignoring some transfers.
  136. static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
  137. cl::desc("Act like old LiveDebugValues did"),
  138. cl::init(false));
  139. // Limit for the maximum number of stack slots we should track, past which we
  140. // will ignore any spills. InstrRefBasedLDV gathers detailed information on all
  141. // stack slots which leads to high memory consumption, and in some scenarios
  142. // (such as asan with very many locals) the working set of the function can be
  143. // very large, causing many spills. In these scenarios, it is very unlikely that
  144. // the developer has hundreds of variables live at the same time that they're
  145. // carefully thinking about -- instead, they probably autogenerated the code.
  146. // When this happens, gracefully stop tracking excess spill slots, rather than
  147. // consuming all the developer's memory.
  148. static cl::opt<unsigned>
  149. StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
  150. cl::desc("livedebugvalues-stack-ws-limit"),
  151. cl::init(250));
  152. DbgOpID DbgOpID::UndefID = DbgOpID(0xffffffff);
  153. /// Tracker for converting machine value locations and variable values into
  154. /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
  155. /// specifying block live-in locations and transfers within blocks.
  156. ///
  157. /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
  158. /// and must be initialized with the set of variable values that are live-in to
  159. /// the block. The caller then repeatedly calls process(). TransferTracker picks
  160. /// out variable locations for the live-in variable values (if there _is_ a
  161. /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
  162. /// stepped through, transfers of values between machine locations are
  163. /// identified and if profitable, a DBG_VALUE created.
  164. ///
  165. /// This is where debug use-before-defs would be resolved: a variable with an
  166. /// unavailable value could materialize in the middle of a block, when the
  167. /// value becomes available. Or, we could detect clobbers and re-specify the
  168. /// variable in a backup location. (XXX these are unimplemented).
  169. class TransferTracker {
  170. public:
  171. const TargetInstrInfo *TII;
  172. const TargetLowering *TLI;
  173. /// This machine location tracker is assumed to always contain the up-to-date
  174. /// value mapping for all machine locations. TransferTracker only reads
  175. /// information from it. (XXX make it const?)
  176. MLocTracker *MTracker;
  177. MachineFunction &MF;
  178. bool ShouldEmitDebugEntryValues;
  179. /// Record of all changes in variable locations at a block position. Awkwardly
  180. /// we allow inserting either before or after the point: MBB != nullptr
  181. /// indicates it's before, otherwise after.
  182. struct Transfer {
  183. MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
  184. MachineBasicBlock *MBB; /// non-null if we should insert after.
  185. SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
  186. };
  187. /// Stores the resolved operands (machine locations and constants) and
  188. /// qualifying meta-information needed to construct a concrete DBG_VALUE-like
  189. /// instruction.
  190. struct ResolvedDbgValue {
  191. SmallVector<ResolvedDbgOp> Ops;
  192. DbgValueProperties Properties;
  193. ResolvedDbgValue(SmallVectorImpl<ResolvedDbgOp> &Ops,
  194. DbgValueProperties Properties)
  195. : Ops(Ops.begin(), Ops.end()), Properties(Properties) {}
  196. /// Returns all the LocIdx values used in this struct, in the order in which
  197. /// they appear as operands in the debug value; may contain duplicates.
  198. auto loc_indices() const {
  199. return map_range(
  200. make_filter_range(
  201. Ops, [](const ResolvedDbgOp &Op) { return !Op.IsConst; }),
  202. [](const ResolvedDbgOp &Op) { return Op.Loc; });
  203. }
  204. };
  205. /// Collection of transfers (DBG_VALUEs) to be inserted.
  206. SmallVector<Transfer, 32> Transfers;
  207. /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
  208. /// between TransferTrackers view of variable locations and MLocTrackers. For
  209. /// example, MLocTracker observes all clobbers, but TransferTracker lazily
  210. /// does not.
  211. SmallVector<ValueIDNum, 32> VarLocs;
  212. /// Map from LocIdxes to which DebugVariables are based that location.
  213. /// Mantained while stepping through the block. Not accurate if
  214. /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
  215. DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
  216. /// Map from DebugVariable to it's current location and qualifying meta
  217. /// information. To be used in conjunction with ActiveMLocs to construct
  218. /// enough information for the DBG_VALUEs for a particular LocIdx.
  219. DenseMap<DebugVariable, ResolvedDbgValue> ActiveVLocs;
  220. /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
  221. SmallVector<MachineInstr *, 4> PendingDbgValues;
  222. /// Record of a use-before-def: created when a value that's live-in to the
  223. /// current block isn't available in any machine location, but it will be
  224. /// defined in this block.
  225. struct UseBeforeDef {
  226. /// Value of this variable, def'd in block.
  227. SmallVector<DbgOp> Values;
  228. /// Identity of this variable.
  229. DebugVariable Var;
  230. /// Additional variable properties.
  231. DbgValueProperties Properties;
  232. UseBeforeDef(ArrayRef<DbgOp> Values, const DebugVariable &Var,
  233. const DbgValueProperties &Properties)
  234. : Values(Values.begin(), Values.end()), Var(Var),
  235. Properties(Properties) {}
  236. };
  237. /// Map from instruction index (within the block) to the set of UseBeforeDefs
  238. /// that become defined at that instruction.
  239. DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
  240. /// The set of variables that are in UseBeforeDefs and can become a location
  241. /// once the relevant value is defined. An element being erased from this
  242. /// collection prevents the use-before-def materializing.
  243. DenseSet<DebugVariable> UseBeforeDefVariables;
  244. const TargetRegisterInfo &TRI;
  245. const BitVector &CalleeSavedRegs;
  246. TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
  247. MachineFunction &MF, const TargetRegisterInfo &TRI,
  248. const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
  249. : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
  250. CalleeSavedRegs(CalleeSavedRegs) {
  251. TLI = MF.getSubtarget().getTargetLowering();
  252. auto &TM = TPC.getTM<TargetMachine>();
  253. ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
  254. }
  255. bool isCalleeSaved(LocIdx L) const {
  256. unsigned Reg = MTracker->LocIdxToLocID[L];
  257. if (Reg >= MTracker->NumRegs)
  258. return false;
  259. for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
  260. if (CalleeSavedRegs.test(*RAI))
  261. return true;
  262. return false;
  263. };
  264. // An estimate of the expected lifespan of values at a machine location, with
  265. // a greater value corresponding to a longer expected lifespan, i.e. spill
  266. // slots generally live longer than callee-saved registers which generally
  267. // live longer than non-callee-saved registers. The minimum value of 0
  268. // corresponds to an illegal location that cannot have a "lifespan" at all.
  269. enum class LocationQuality : unsigned char {
  270. Illegal = 0,
  271. Register,
  272. CalleeSavedRegister,
  273. SpillSlot,
  274. Best = SpillSlot
  275. };
  276. class LocationAndQuality {
  277. unsigned Location : 24;
  278. unsigned Quality : 8;
  279. public:
  280. LocationAndQuality() : Location(0), Quality(0) {}
  281. LocationAndQuality(LocIdx L, LocationQuality Q)
  282. : Location(L.asU64()), Quality(static_cast<unsigned>(Q)) {}
  283. LocIdx getLoc() const {
  284. if (!Quality)
  285. return LocIdx::MakeIllegalLoc();
  286. return LocIdx(Location);
  287. }
  288. LocationQuality getQuality() const { return LocationQuality(Quality); }
  289. bool isIllegal() const { return !Quality; }
  290. bool isBest() const { return getQuality() == LocationQuality::Best; }
  291. };
  292. // Returns the LocationQuality for the location L iff the quality of L is
  293. // is strictly greater than the provided minimum quality.
  294. std::optional<LocationQuality>
  295. getLocQualityIfBetter(LocIdx L, LocationQuality Min) const {
  296. if (L.isIllegal())
  297. return std::nullopt;
  298. if (Min >= LocationQuality::SpillSlot)
  299. return std::nullopt;
  300. if (MTracker->isSpill(L))
  301. return LocationQuality::SpillSlot;
  302. if (Min >= LocationQuality::CalleeSavedRegister)
  303. return std::nullopt;
  304. if (isCalleeSaved(L))
  305. return LocationQuality::CalleeSavedRegister;
  306. if (Min >= LocationQuality::Register)
  307. return std::nullopt;
  308. return LocationQuality::Register;
  309. }
  310. /// For a variable \p Var with the live-in value \p Value, attempts to resolve
  311. /// the DbgValue to a concrete DBG_VALUE, emitting that value and loading the
  312. /// tracking information to track Var throughout the block.
  313. /// \p ValueToLoc is a map containing the best known location for every
  314. /// ValueIDNum that Value may use.
  315. /// \p MBB is the basic block that we are loading the live-in value for.
  316. /// \p DbgOpStore is the map containing the DbgOpID->DbgOp mapping needed to
  317. /// determine the values used by Value.
  318. void loadVarInloc(MachineBasicBlock &MBB, DbgOpIDMap &DbgOpStore,
  319. const DenseMap<ValueIDNum, LocationAndQuality> &ValueToLoc,
  320. DebugVariable Var, DbgValue Value) {
  321. SmallVector<DbgOp> DbgOps;
  322. SmallVector<ResolvedDbgOp> ResolvedDbgOps;
  323. bool IsValueValid = true;
  324. unsigned LastUseBeforeDef = 0;
  325. // If every value used by the incoming DbgValue is available at block
  326. // entry, ResolvedDbgOps will contain the machine locations/constants for
  327. // those values and will be used to emit a debug location.
  328. // If one or more values are not yet available, but will all be defined in
  329. // this block, then LastUseBeforeDef will track the instruction index in
  330. // this BB at which the last of those values is defined, DbgOps will
  331. // contain the values that we will emit when we reach that instruction.
  332. // If one or more values are undef or not available throughout this block,
  333. // and we can't recover as an entry value, we set IsValueValid=false and
  334. // skip this variable.
  335. for (DbgOpID ID : Value.getDbgOpIDs()) {
  336. DbgOp Op = DbgOpStore.find(ID);
  337. DbgOps.push_back(Op);
  338. if (ID.isUndef()) {
  339. IsValueValid = false;
  340. break;
  341. }
  342. if (ID.isConst()) {
  343. ResolvedDbgOps.push_back(Op.MO);
  344. continue;
  345. }
  346. // If the value has no location, we can't make a variable location.
  347. const ValueIDNum &Num = Op.ID;
  348. auto ValuesPreferredLoc = ValueToLoc.find(Num);
  349. if (ValuesPreferredLoc->second.isIllegal()) {
  350. // If it's a def that occurs in this block, register it as a
  351. // use-before-def to be resolved as we step through the block.
  352. // Continue processing values so that we add any other UseBeforeDef
  353. // entries needed for later.
  354. if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) {
  355. LastUseBeforeDef = std::max(LastUseBeforeDef,
  356. static_cast<unsigned>(Num.getInst()));
  357. continue;
  358. }
  359. recoverAsEntryValue(Var, Value.Properties, Num);
  360. IsValueValid = false;
  361. break;
  362. }
  363. // Defer modifying ActiveVLocs until after we've confirmed we have a
  364. // live range.
  365. LocIdx M = ValuesPreferredLoc->second.getLoc();
  366. ResolvedDbgOps.push_back(M);
  367. }
  368. // If we cannot produce a valid value for the LiveIn value within this
  369. // block, skip this variable.
  370. if (!IsValueValid)
  371. return;
  372. // Add UseBeforeDef entry for the last value to be defined in this block.
  373. if (LastUseBeforeDef) {
  374. addUseBeforeDef(Var, Value.Properties, DbgOps,
  375. LastUseBeforeDef);
  376. return;
  377. }
  378. // The LiveIn value is available at block entry, begin tracking and record
  379. // the transfer.
  380. for (const ResolvedDbgOp &Op : ResolvedDbgOps)
  381. if (!Op.IsConst)
  382. ActiveMLocs[Op.Loc].insert(Var);
  383. auto NewValue = ResolvedDbgValue{ResolvedDbgOps, Value.Properties};
  384. auto Result = ActiveVLocs.insert(std::make_pair(Var, NewValue));
  385. if (!Result.second)
  386. Result.first->second = NewValue;
  387. PendingDbgValues.push_back(
  388. MTracker->emitLoc(ResolvedDbgOps, Var, Value.Properties));
  389. }
  390. /// Load object with live-in variable values. \p mlocs contains the live-in
  391. /// values in each machine location, while \p vlocs the live-in variable
  392. /// values. This method picks variable locations for the live-in variables,
  393. /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
  394. /// object fields to track variable locations as we step through the block.
  395. /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
  396. void
  397. loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, DbgOpIDMap &DbgOpStore,
  398. const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
  399. unsigned NumLocs) {
  400. ActiveMLocs.clear();
  401. ActiveVLocs.clear();
  402. VarLocs.clear();
  403. VarLocs.reserve(NumLocs);
  404. UseBeforeDefs.clear();
  405. UseBeforeDefVariables.clear();
  406. // Map of the preferred location for each value.
  407. DenseMap<ValueIDNum, LocationAndQuality> ValueToLoc;
  408. // Initialized the preferred-location map with illegal locations, to be
  409. // filled in later.
  410. for (const auto &VLoc : VLocs)
  411. if (VLoc.second.Kind == DbgValue::Def)
  412. for (DbgOpID OpID : VLoc.second.getDbgOpIDs())
  413. if (!OpID.ID.IsConst)
  414. ValueToLoc.insert({DbgOpStore.find(OpID).ID, LocationAndQuality()});
  415. ActiveMLocs.reserve(VLocs.size());
  416. ActiveVLocs.reserve(VLocs.size());
  417. // Produce a map of value numbers to the current machine locs they live
  418. // in. When emulating VarLocBasedImpl, there should only be one
  419. // location; when not, we get to pick.
  420. for (auto Location : MTracker->locations()) {
  421. LocIdx Idx = Location.Idx;
  422. ValueIDNum &VNum = MLocs[Idx.asU64()];
  423. if (VNum == ValueIDNum::EmptyValue)
  424. continue;
  425. VarLocs.push_back(VNum);
  426. // Is there a variable that wants a location for this value? If not, skip.
  427. auto VIt = ValueToLoc.find(VNum);
  428. if (VIt == ValueToLoc.end())
  429. continue;
  430. auto &Previous = VIt->second;
  431. // If this is the first location with that value, pick it. Otherwise,
  432. // consider whether it's a "longer term" location.
  433. std::optional<LocationQuality> ReplacementQuality =
  434. getLocQualityIfBetter(Idx, Previous.getQuality());
  435. if (ReplacementQuality)
  436. Previous = LocationAndQuality(Idx, *ReplacementQuality);
  437. }
  438. // Now map variables to their picked LocIdxes.
  439. for (const auto &Var : VLocs) {
  440. loadVarInloc(MBB, DbgOpStore, ValueToLoc, Var.first, Var.second);
  441. }
  442. flushDbgValues(MBB.begin(), &MBB);
  443. }
  444. /// Record that \p Var has value \p ID, a value that becomes available
  445. /// later in the function.
  446. void addUseBeforeDef(const DebugVariable &Var,
  447. const DbgValueProperties &Properties,
  448. const SmallVectorImpl<DbgOp> &DbgOps, unsigned Inst) {
  449. UseBeforeDefs[Inst].emplace_back(DbgOps, Var, Properties);
  450. UseBeforeDefVariables.insert(Var);
  451. }
  452. /// After the instruction at index \p Inst and position \p pos has been
  453. /// processed, check whether it defines a variable value in a use-before-def.
  454. /// If so, and the variable value hasn't changed since the start of the
  455. /// block, create a DBG_VALUE.
  456. void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
  457. auto MIt = UseBeforeDefs.find(Inst);
  458. if (MIt == UseBeforeDefs.end())
  459. return;
  460. // Map of values to the locations that store them for every value used by
  461. // the variables that may have become available.
  462. SmallDenseMap<ValueIDNum, LocationAndQuality> ValueToLoc;
  463. // Populate ValueToLoc with illegal default mappings for every value used by
  464. // any UseBeforeDef variables for this instruction.
  465. for (auto &Use : MIt->second) {
  466. if (!UseBeforeDefVariables.count(Use.Var))
  467. continue;
  468. for (DbgOp &Op : Use.Values) {
  469. assert(!Op.isUndef() && "UseBeforeDef erroneously created for a "
  470. "DbgValue with undef values.");
  471. if (Op.IsConst)
  472. continue;
  473. ValueToLoc.insert({Op.ID, LocationAndQuality()});
  474. }
  475. }
  476. // Exit early if we have no DbgValues to produce.
  477. if (ValueToLoc.empty())
  478. return;
  479. // Determine the best location for each desired value.
  480. for (auto Location : MTracker->locations()) {
  481. LocIdx Idx = Location.Idx;
  482. ValueIDNum &LocValueID = Location.Value;
  483. // Is there a variable that wants a location for this value? If not, skip.
  484. auto VIt = ValueToLoc.find(LocValueID);
  485. if (VIt == ValueToLoc.end())
  486. continue;
  487. auto &Previous = VIt->second;
  488. // If this is the first location with that value, pick it. Otherwise,
  489. // consider whether it's a "longer term" location.
  490. std::optional<LocationQuality> ReplacementQuality =
  491. getLocQualityIfBetter(Idx, Previous.getQuality());
  492. if (ReplacementQuality)
  493. Previous = LocationAndQuality(Idx, *ReplacementQuality);
  494. }
  495. // Using the map of values to locations, produce a final set of values for
  496. // this variable.
  497. for (auto &Use : MIt->second) {
  498. if (!UseBeforeDefVariables.count(Use.Var))
  499. continue;
  500. SmallVector<ResolvedDbgOp> DbgOps;
  501. for (DbgOp &Op : Use.Values) {
  502. if (Op.IsConst) {
  503. DbgOps.push_back(Op.MO);
  504. continue;
  505. }
  506. LocIdx NewLoc = ValueToLoc.find(Op.ID)->second.getLoc();
  507. if (NewLoc.isIllegal())
  508. break;
  509. DbgOps.push_back(NewLoc);
  510. }
  511. // If at least one value used by this debug value is no longer available,
  512. // i.e. one of the values was killed before we finished defining all of
  513. // the values used by this variable, discard.
  514. if (DbgOps.size() != Use.Values.size())
  515. continue;
  516. // Otherwise, we're good to go.
  517. PendingDbgValues.push_back(
  518. MTracker->emitLoc(DbgOps, Use.Var, Use.Properties));
  519. }
  520. flushDbgValues(pos, nullptr);
  521. }
  522. /// Helper to move created DBG_VALUEs into Transfers collection.
  523. void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
  524. if (PendingDbgValues.size() == 0)
  525. return;
  526. // Pick out the instruction start position.
  527. MachineBasicBlock::instr_iterator BundleStart;
  528. if (MBB && Pos == MBB->begin())
  529. BundleStart = MBB->instr_begin();
  530. else
  531. BundleStart = getBundleStart(Pos->getIterator());
  532. Transfers.push_back({BundleStart, MBB, PendingDbgValues});
  533. PendingDbgValues.clear();
  534. }
  535. bool isEntryValueVariable(const DebugVariable &Var,
  536. const DIExpression *Expr) const {
  537. if (!Var.getVariable()->isParameter())
  538. return false;
  539. if (Var.getInlinedAt())
  540. return false;
  541. if (Expr->getNumElements() > 0)
  542. return false;
  543. return true;
  544. }
  545. bool isEntryValueValue(const ValueIDNum &Val) const {
  546. // Must be in entry block (block number zero), and be a PHI / live-in value.
  547. if (Val.getBlock() || !Val.isPHI())
  548. return false;
  549. // Entry values must enter in a register.
  550. if (MTracker->isSpill(Val.getLoc()))
  551. return false;
  552. Register SP = TLI->getStackPointerRegisterToSaveRestore();
  553. Register FP = TRI.getFrameRegister(MF);
  554. Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
  555. return Reg != SP && Reg != FP;
  556. }
  557. bool recoverAsEntryValue(const DebugVariable &Var,
  558. const DbgValueProperties &Prop,
  559. const ValueIDNum &Num) {
  560. // Is this variable location a candidate to be an entry value. First,
  561. // should we be trying this at all?
  562. if (!ShouldEmitDebugEntryValues)
  563. return false;
  564. const DIExpression *DIExpr = Prop.DIExpr;
  565. // We don't currently emit entry values for DBG_VALUE_LISTs.
  566. if (Prop.IsVariadic) {
  567. // If this debug value can be converted to be non-variadic, then do so;
  568. // otherwise give up.
  569. auto NonVariadicExpression =
  570. DIExpression::convertToNonVariadicExpression(DIExpr);
  571. if (!NonVariadicExpression)
  572. return false;
  573. DIExpr = *NonVariadicExpression;
  574. }
  575. // Is the variable appropriate for entry values (i.e., is a parameter).
  576. if (!isEntryValueVariable(Var, DIExpr))
  577. return false;
  578. // Is the value assigned to this variable still the entry value?
  579. if (!isEntryValueValue(Num))
  580. return false;
  581. // Emit a variable location using an entry value expression.
  582. DIExpression *NewExpr =
  583. DIExpression::prepend(DIExpr, DIExpression::EntryValue);
  584. Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
  585. MachineOperand MO = MachineOperand::CreateReg(Reg, false);
  586. PendingDbgValues.push_back(
  587. emitMOLoc(MO, Var, {NewExpr, Prop.Indirect, false}));
  588. return true;
  589. }
  590. /// Change a variable value after encountering a DBG_VALUE inside a block.
  591. void redefVar(const MachineInstr &MI) {
  592. DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
  593. MI.getDebugLoc()->getInlinedAt());
  594. DbgValueProperties Properties(MI);
  595. // Ignore non-register locations, we don't transfer those.
  596. if (MI.isUndefDebugValue() ||
  597. all_of(MI.debug_operands(),
  598. [](const MachineOperand &MO) { return !MO.isReg(); })) {
  599. auto It = ActiveVLocs.find(Var);
  600. if (It != ActiveVLocs.end()) {
  601. for (LocIdx Loc : It->second.loc_indices())
  602. ActiveMLocs[Loc].erase(Var);
  603. ActiveVLocs.erase(It);
  604. }
  605. // Any use-before-defs no longer apply.
  606. UseBeforeDefVariables.erase(Var);
  607. return;
  608. }
  609. SmallVector<ResolvedDbgOp> NewLocs;
  610. for (const MachineOperand &MO : MI.debug_operands()) {
  611. if (MO.isReg()) {
  612. // Any undef regs have already been filtered out above.
  613. Register Reg = MO.getReg();
  614. LocIdx NewLoc = MTracker->getRegMLoc(Reg);
  615. NewLocs.push_back(NewLoc);
  616. } else {
  617. NewLocs.push_back(MO);
  618. }
  619. }
  620. redefVar(MI, Properties, NewLocs);
  621. }
  622. /// Handle a change in variable location within a block. Terminate the
  623. /// variables current location, and record the value it now refers to, so
  624. /// that we can detect location transfers later on.
  625. void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
  626. SmallVectorImpl<ResolvedDbgOp> &NewLocs) {
  627. DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
  628. MI.getDebugLoc()->getInlinedAt());
  629. // Any use-before-defs no longer apply.
  630. UseBeforeDefVariables.erase(Var);
  631. // Erase any previous location.
  632. auto It = ActiveVLocs.find(Var);
  633. if (It != ActiveVLocs.end()) {
  634. for (LocIdx Loc : It->second.loc_indices())
  635. ActiveMLocs[Loc].erase(Var);
  636. }
  637. // If there _is_ no new location, all we had to do was erase.
  638. if (NewLocs.empty()) {
  639. if (It != ActiveVLocs.end())
  640. ActiveVLocs.erase(It);
  641. return;
  642. }
  643. SmallVector<std::pair<LocIdx, DebugVariable>> LostMLocs;
  644. for (ResolvedDbgOp &Op : NewLocs) {
  645. if (Op.IsConst)
  646. continue;
  647. LocIdx NewLoc = Op.Loc;
  648. // Check whether our local copy of values-by-location in #VarLocs is out
  649. // of date. Wipe old tracking data for the location if it's been clobbered
  650. // in the meantime.
  651. if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
  652. for (const auto &P : ActiveMLocs[NewLoc]) {
  653. auto LostVLocIt = ActiveVLocs.find(P);
  654. if (LostVLocIt != ActiveVLocs.end()) {
  655. for (LocIdx Loc : LostVLocIt->second.loc_indices()) {
  656. // Every active variable mapping for NewLoc will be cleared, no
  657. // need to track individual variables.
  658. if (Loc == NewLoc)
  659. continue;
  660. LostMLocs.emplace_back(Loc, P);
  661. }
  662. }
  663. ActiveVLocs.erase(P);
  664. }
  665. for (const auto &LostMLoc : LostMLocs)
  666. ActiveMLocs[LostMLoc.first].erase(LostMLoc.second);
  667. LostMLocs.clear();
  668. It = ActiveVLocs.find(Var);
  669. ActiveMLocs[NewLoc.asU64()].clear();
  670. VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
  671. }
  672. ActiveMLocs[NewLoc].insert(Var);
  673. }
  674. if (It == ActiveVLocs.end()) {
  675. ActiveVLocs.insert(
  676. std::make_pair(Var, ResolvedDbgValue(NewLocs, Properties)));
  677. } else {
  678. It->second.Ops.assign(NewLocs);
  679. It->second.Properties = Properties;
  680. }
  681. }
  682. /// Account for a location \p mloc being clobbered. Examine the variable
  683. /// locations that will be terminated: and try to recover them by using
  684. /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
  685. /// explicitly terminate a location if it can't be recovered.
  686. void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
  687. bool MakeUndef = true) {
  688. auto ActiveMLocIt = ActiveMLocs.find(MLoc);
  689. if (ActiveMLocIt == ActiveMLocs.end())
  690. return;
  691. // What was the old variable value?
  692. ValueIDNum OldValue = VarLocs[MLoc.asU64()];
  693. clobberMloc(MLoc, OldValue, Pos, MakeUndef);
  694. }
  695. /// Overload that takes an explicit value \p OldValue for when the value in
  696. /// \p MLoc has changed and the TransferTracker's locations have not been
  697. /// updated yet.
  698. void clobberMloc(LocIdx MLoc, ValueIDNum OldValue,
  699. MachineBasicBlock::iterator Pos, bool MakeUndef = true) {
  700. auto ActiveMLocIt = ActiveMLocs.find(MLoc);
  701. if (ActiveMLocIt == ActiveMLocs.end())
  702. return;
  703. VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
  704. // Examine the remaining variable locations: if we can find the same value
  705. // again, we can recover the location.
  706. std::optional<LocIdx> NewLoc;
  707. for (auto Loc : MTracker->locations())
  708. if (Loc.Value == OldValue)
  709. NewLoc = Loc.Idx;
  710. // If there is no location, and we weren't asked to make the variable
  711. // explicitly undef, then stop here.
  712. if (!NewLoc && !MakeUndef) {
  713. // Try and recover a few more locations with entry values.
  714. for (const auto &Var : ActiveMLocIt->second) {
  715. auto &Prop = ActiveVLocs.find(Var)->second.Properties;
  716. recoverAsEntryValue(Var, Prop, OldValue);
  717. }
  718. flushDbgValues(Pos, nullptr);
  719. return;
  720. }
  721. // Examine all the variables based on this location.
  722. DenseSet<DebugVariable> NewMLocs;
  723. // If no new location has been found, every variable that depends on this
  724. // MLoc is dead, so end their existing MLoc->Var mappings as well.
  725. SmallVector<std::pair<LocIdx, DebugVariable>> LostMLocs;
  726. for (const auto &Var : ActiveMLocIt->second) {
  727. auto ActiveVLocIt = ActiveVLocs.find(Var);
  728. // Re-state the variable location: if there's no replacement then NewLoc
  729. // is std::nullopt and a $noreg DBG_VALUE will be created. Otherwise, a
  730. // DBG_VALUE identifying the alternative location will be emitted.
  731. const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
  732. // Produce the new list of debug ops - an empty list if no new location
  733. // was found, or the existing list with the substitution MLoc -> NewLoc
  734. // otherwise.
  735. SmallVector<ResolvedDbgOp> DbgOps;
  736. if (NewLoc) {
  737. ResolvedDbgOp OldOp(MLoc);
  738. ResolvedDbgOp NewOp(*NewLoc);
  739. // Insert illegal ops to overwrite afterwards.
  740. DbgOps.insert(DbgOps.begin(), ActiveVLocIt->second.Ops.size(),
  741. ResolvedDbgOp(LocIdx::MakeIllegalLoc()));
  742. replace_copy(ActiveVLocIt->second.Ops, DbgOps.begin(), OldOp, NewOp);
  743. }
  744. PendingDbgValues.push_back(MTracker->emitLoc(DbgOps, Var, Properties));
  745. // Update machine locations <=> variable locations maps. Defer updating
  746. // ActiveMLocs to avoid invalidating the ActiveMLocIt iterator.
  747. if (!NewLoc) {
  748. for (LocIdx Loc : ActiveVLocIt->second.loc_indices()) {
  749. if (Loc != MLoc)
  750. LostMLocs.emplace_back(Loc, Var);
  751. }
  752. ActiveVLocs.erase(ActiveVLocIt);
  753. } else {
  754. ActiveVLocIt->second.Ops = DbgOps;
  755. NewMLocs.insert(Var);
  756. }
  757. }
  758. // Remove variables from ActiveMLocs if they no longer use any other MLocs
  759. // due to being killed by this clobber.
  760. for (auto &LocVarIt : LostMLocs) {
  761. auto LostMLocIt = ActiveMLocs.find(LocVarIt.first);
  762. assert(LostMLocIt != ActiveMLocs.end() &&
  763. "Variable was using this MLoc, but ActiveMLocs[MLoc] has no "
  764. "entries?");
  765. LostMLocIt->second.erase(LocVarIt.second);
  766. }
  767. // We lazily track what locations have which values; if we've found a new
  768. // location for the clobbered value, remember it.
  769. if (NewLoc)
  770. VarLocs[NewLoc->asU64()] = OldValue;
  771. flushDbgValues(Pos, nullptr);
  772. // Commit ActiveMLoc changes.
  773. ActiveMLocIt->second.clear();
  774. if (!NewMLocs.empty())
  775. for (auto &Var : NewMLocs)
  776. ActiveMLocs[*NewLoc].insert(Var);
  777. }
  778. /// Transfer variables based on \p Src to be based on \p Dst. This handles
  779. /// both register copies as well as spills and restores. Creates DBG_VALUEs
  780. /// describing the movement.
  781. void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
  782. // Does Src still contain the value num we expect? If not, it's been
  783. // clobbered in the meantime, and our variable locations are stale.
  784. if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
  785. return;
  786. // assert(ActiveMLocs[Dst].size() == 0);
  787. //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
  788. // Move set of active variables from one location to another.
  789. auto MovingVars = ActiveMLocs[Src];
  790. ActiveMLocs[Dst].insert(MovingVars.begin(), MovingVars.end());
  791. VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
  792. // For each variable based on Src; create a location at Dst.
  793. ResolvedDbgOp SrcOp(Src);
  794. ResolvedDbgOp DstOp(Dst);
  795. for (const auto &Var : MovingVars) {
  796. auto ActiveVLocIt = ActiveVLocs.find(Var);
  797. assert(ActiveVLocIt != ActiveVLocs.end());
  798. // Update all instances of Src in the variable's tracked values to Dst.
  799. std::replace(ActiveVLocIt->second.Ops.begin(),
  800. ActiveVLocIt->second.Ops.end(), SrcOp, DstOp);
  801. MachineInstr *MI = MTracker->emitLoc(ActiveVLocIt->second.Ops, Var,
  802. ActiveVLocIt->second.Properties);
  803. PendingDbgValues.push_back(MI);
  804. }
  805. ActiveMLocs[Src].clear();
  806. flushDbgValues(Pos, nullptr);
  807. // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
  808. // about the old location.
  809. if (EmulateOldLDV)
  810. VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
  811. }
  812. MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
  813. const DebugVariable &Var,
  814. const DbgValueProperties &Properties) {
  815. DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
  816. Var.getVariable()->getScope(),
  817. const_cast<DILocation *>(Var.getInlinedAt()));
  818. auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
  819. MIB.add(MO);
  820. if (Properties.Indirect)
  821. MIB.addImm(0);
  822. else
  823. MIB.addReg(0);
  824. MIB.addMetadata(Var.getVariable());
  825. MIB.addMetadata(Properties.DIExpr);
  826. return MIB;
  827. }
  828. };
  829. //===----------------------------------------------------------------------===//
  830. // Implementation
  831. //===----------------------------------------------------------------------===//
  832. ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
  833. ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
  834. #ifndef NDEBUG
  835. void ResolvedDbgOp::dump(const MLocTracker *MTrack) const {
  836. if (IsConst) {
  837. dbgs() << MO;
  838. } else {
  839. dbgs() << MTrack->LocIdxToName(Loc);
  840. }
  841. }
  842. void DbgOp::dump(const MLocTracker *MTrack) const {
  843. if (IsConst) {
  844. dbgs() << MO;
  845. } else if (!isUndef()) {
  846. dbgs() << MTrack->IDAsString(ID);
  847. }
  848. }
  849. void DbgOpID::dump(const MLocTracker *MTrack, const DbgOpIDMap *OpStore) const {
  850. if (!OpStore) {
  851. dbgs() << "ID(" << asU32() << ")";
  852. } else {
  853. OpStore->find(*this).dump(MTrack);
  854. }
  855. }
  856. void DbgValue::dump(const MLocTracker *MTrack,
  857. const DbgOpIDMap *OpStore) const {
  858. if (Kind == NoVal) {
  859. dbgs() << "NoVal(" << BlockNo << ")";
  860. } else if (Kind == VPHI || Kind == Def) {
  861. if (Kind == VPHI)
  862. dbgs() << "VPHI(" << BlockNo << ",";
  863. else
  864. dbgs() << "Def(";
  865. for (unsigned Idx = 0; Idx < getDbgOpIDs().size(); ++Idx) {
  866. getDbgOpID(Idx).dump(MTrack, OpStore);
  867. if (Idx != 0)
  868. dbgs() << ",";
  869. }
  870. dbgs() << ")";
  871. }
  872. if (Properties.Indirect)
  873. dbgs() << " indir";
  874. if (Properties.DIExpr)
  875. dbgs() << " " << *Properties.DIExpr;
  876. }
  877. #endif
  878. MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
  879. const TargetRegisterInfo &TRI,
  880. const TargetLowering &TLI)
  881. : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
  882. LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
  883. NumRegs = TRI.getNumRegs();
  884. reset();
  885. LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
  886. assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
  887. // Always track SP. This avoids the implicit clobbering caused by regmasks
  888. // from affectings its values. (LiveDebugValues disbelieves calls and
  889. // regmasks that claim to clobber SP).
  890. Register SP = TLI.getStackPointerRegisterToSaveRestore();
  891. if (SP) {
  892. unsigned ID = getLocID(SP);
  893. (void)lookupOrTrackRegister(ID);
  894. for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
  895. SPAliases.insert(*RAI);
  896. }
  897. // Build some common stack positions -- full registers being spilt to the
  898. // stack.
  899. StackSlotIdxes.insert({{8, 0}, 0});
  900. StackSlotIdxes.insert({{16, 0}, 1});
  901. StackSlotIdxes.insert({{32, 0}, 2});
  902. StackSlotIdxes.insert({{64, 0}, 3});
  903. StackSlotIdxes.insert({{128, 0}, 4});
  904. StackSlotIdxes.insert({{256, 0}, 5});
  905. StackSlotIdxes.insert({{512, 0}, 6});
  906. // Traverse all the subregister idxes, and ensure there's an index for them.
  907. // Duplicates are no problem: we're interested in their position in the
  908. // stack slot, we don't want to type the slot.
  909. for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
  910. unsigned Size = TRI.getSubRegIdxSize(I);
  911. unsigned Offs = TRI.getSubRegIdxOffset(I);
  912. unsigned Idx = StackSlotIdxes.size();
  913. // Some subregs have -1, -2 and so forth fed into their fields, to mean
  914. // special backend things. Ignore those.
  915. if (Size > 60000 || Offs > 60000)
  916. continue;
  917. StackSlotIdxes.insert({{Size, Offs}, Idx});
  918. }
  919. // There may also be strange register class sizes (think x86 fp80s).
  920. for (const TargetRegisterClass *RC : TRI.regclasses()) {
  921. unsigned Size = TRI.getRegSizeInBits(*RC);
  922. // We might see special reserved values as sizes, and classes for other
  923. // stuff the machine tries to model. If it's more than 512 bits, then it
  924. // is very unlikely to be a register than can be spilt.
  925. if (Size > 512)
  926. continue;
  927. unsigned Idx = StackSlotIdxes.size();
  928. StackSlotIdxes.insert({{Size, 0}, Idx});
  929. }
  930. for (auto &Idx : StackSlotIdxes)
  931. StackIdxesToPos[Idx.second] = Idx.first;
  932. NumSlotIdxes = StackSlotIdxes.size();
  933. }
  934. LocIdx MLocTracker::trackRegister(unsigned ID) {
  935. assert(ID != 0);
  936. LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
  937. LocIdxToIDNum.grow(NewIdx);
  938. LocIdxToLocID.grow(NewIdx);
  939. // Default: it's an mphi.
  940. ValueIDNum ValNum = {CurBB, 0, NewIdx};
  941. // Was this reg ever touched by a regmask?
  942. for (const auto &MaskPair : reverse(Masks)) {
  943. if (MaskPair.first->clobbersPhysReg(ID)) {
  944. // There was an earlier def we skipped.
  945. ValNum = {CurBB, MaskPair.second, NewIdx};
  946. break;
  947. }
  948. }
  949. LocIdxToIDNum[NewIdx] = ValNum;
  950. LocIdxToLocID[NewIdx] = ID;
  951. return NewIdx;
  952. }
  953. void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
  954. unsigned InstID) {
  955. // Def any register we track have that isn't preserved. The regmask
  956. // terminates the liveness of a register, meaning its value can't be
  957. // relied upon -- we represent this by giving it a new value.
  958. for (auto Location : locations()) {
  959. unsigned ID = LocIdxToLocID[Location.Idx];
  960. // Don't clobber SP, even if the mask says it's clobbered.
  961. if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
  962. defReg(ID, CurBB, InstID);
  963. }
  964. Masks.push_back(std::make_pair(MO, InstID));
  965. }
  966. std::optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
  967. SpillLocationNo SpillID(SpillLocs.idFor(L));
  968. if (SpillID.id() == 0) {
  969. // If there is no location, and we have reached the limit of how many stack
  970. // slots to track, then don't track this one.
  971. if (SpillLocs.size() >= StackWorkingSetLimit)
  972. return std::nullopt;
  973. // Spill location is untracked: create record for this one, and all
  974. // subregister slots too.
  975. SpillID = SpillLocationNo(SpillLocs.insert(L));
  976. for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
  977. unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
  978. LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
  979. LocIdxToIDNum.grow(Idx);
  980. LocIdxToLocID.grow(Idx);
  981. LocIDToLocIdx.push_back(Idx);
  982. LocIdxToLocID[Idx] = L;
  983. // Initialize to PHI value; corresponds to the location's live-in value
  984. // during transfer function construction.
  985. LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
  986. }
  987. }
  988. return SpillID;
  989. }
  990. std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
  991. unsigned ID = LocIdxToLocID[Idx];
  992. if (ID >= NumRegs) {
  993. StackSlotPos Pos = locIDToSpillIdx(ID);
  994. ID -= NumRegs;
  995. unsigned Slot = ID / NumSlotIdxes;
  996. return Twine("slot ")
  997. .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
  998. .concat(Twine(" offs ").concat(Twine(Pos.second))))))
  999. .str();
  1000. } else {
  1001. return TRI.getRegAsmName(ID).str();
  1002. }
  1003. }
  1004. std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
  1005. std::string DefName = LocIdxToName(Num.getLoc());
  1006. return Num.asString(DefName);
  1007. }
  1008. #ifndef NDEBUG
  1009. LLVM_DUMP_METHOD void MLocTracker::dump() {
  1010. for (auto Location : locations()) {
  1011. std::string MLocName = LocIdxToName(Location.Value.getLoc());
  1012. std::string DefName = Location.Value.asString(MLocName);
  1013. dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
  1014. }
  1015. }
  1016. LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
  1017. for (auto Location : locations()) {
  1018. std::string foo = LocIdxToName(Location.Idx);
  1019. dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
  1020. }
  1021. }
  1022. #endif
  1023. MachineInstrBuilder
  1024. MLocTracker::emitLoc(const SmallVectorImpl<ResolvedDbgOp> &DbgOps,
  1025. const DebugVariable &Var,
  1026. const DbgValueProperties &Properties) {
  1027. DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
  1028. Var.getVariable()->getScope(),
  1029. const_cast<DILocation *>(Var.getInlinedAt()));
  1030. const MCInstrDesc &Desc = Properties.IsVariadic
  1031. ? TII.get(TargetOpcode::DBG_VALUE_LIST)
  1032. : TII.get(TargetOpcode::DBG_VALUE);
  1033. #ifdef EXPENSIVE_CHECKS
  1034. assert(all_of(DbgOps,
  1035. [](const ResolvedDbgOp &Op) {
  1036. return Op.IsConst || !Op.Loc.isIllegal();
  1037. }) &&
  1038. "Did not expect illegal ops in DbgOps.");
  1039. assert((DbgOps.size() == 0 ||
  1040. DbgOps.size() == Properties.getLocationOpCount()) &&
  1041. "Expected to have either one DbgOp per MI LocationOp, or none.");
  1042. #endif
  1043. auto GetRegOp = [](unsigned Reg) -> MachineOperand {
  1044. return MachineOperand::CreateReg(
  1045. /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
  1046. /* isKill */ false, /* isDead */ false,
  1047. /* isUndef */ false, /* isEarlyClobber */ false,
  1048. /* SubReg */ 0, /* isDebug */ true);
  1049. };
  1050. SmallVector<MachineOperand> MOs;
  1051. auto EmitUndef = [&]() {
  1052. MOs.clear();
  1053. MOs.assign(Properties.getLocationOpCount(), GetRegOp(0));
  1054. return BuildMI(MF, DL, Desc, false, MOs, Var.getVariable(),
  1055. Properties.DIExpr);
  1056. };
  1057. // Don't bother passing any real operands to BuildMI if any of them would be
  1058. // $noreg.
  1059. if (DbgOps.empty())
  1060. return EmitUndef();
  1061. bool Indirect = Properties.Indirect;
  1062. const DIExpression *Expr = Properties.DIExpr;
  1063. assert(DbgOps.size() == Properties.getLocationOpCount());
  1064. // If all locations are valid, accumulate them into our list of
  1065. // MachineOperands. For any spilled locations, either update the indirectness
  1066. // register or apply the appropriate transformations in the DIExpression.
  1067. for (size_t Idx = 0; Idx < Properties.getLocationOpCount(); ++Idx) {
  1068. const ResolvedDbgOp &Op = DbgOps[Idx];
  1069. if (Op.IsConst) {
  1070. MOs.push_back(Op.MO);
  1071. continue;
  1072. }
  1073. LocIdx MLoc = Op.Loc;
  1074. unsigned LocID = LocIdxToLocID[MLoc];
  1075. if (LocID >= NumRegs) {
  1076. SpillLocationNo SpillID = locIDToSpill(LocID);
  1077. StackSlotPos StackIdx = locIDToSpillIdx(LocID);
  1078. unsigned short Offset = StackIdx.second;
  1079. // TODO: support variables that are located in spill slots, with non-zero
  1080. // offsets from the start of the spill slot. It would require some more
  1081. // complex DIExpression calculations. This doesn't seem to be produced by
  1082. // LLVM right now, so don't try and support it.
  1083. // Accept no-subregister slots and subregisters where the offset is zero.
  1084. // The consumer should already have type information to work out how large
  1085. // the variable is.
  1086. if (Offset == 0) {
  1087. const SpillLoc &Spill = SpillLocs[SpillID.id()];
  1088. unsigned Base = Spill.SpillBase;
  1089. // There are several ways we can dereference things, and several inputs
  1090. // to consider:
  1091. // * NRVO variables will appear with IsIndirect set, but should have
  1092. // nothing else in their DIExpressions,
  1093. // * Variables with DW_OP_stack_value in their expr already need an
  1094. // explicit dereference of the stack location,
  1095. // * Values that don't match the variable size need DW_OP_deref_size,
  1096. // * Everything else can just become a simple location expression.
  1097. // We need to use deref_size whenever there's a mismatch between the
  1098. // size of value and the size of variable portion being read.
  1099. // Additionally, we should use it whenever dealing with stack_value
  1100. // fragments, to avoid the consumer having to determine the deref size
  1101. // from DW_OP_piece.
  1102. bool UseDerefSize = false;
  1103. unsigned ValueSizeInBits = getLocSizeInBits(MLoc);
  1104. unsigned DerefSizeInBytes = ValueSizeInBits / 8;
  1105. if (auto Fragment = Var.getFragment()) {
  1106. unsigned VariableSizeInBits = Fragment->SizeInBits;
  1107. if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex())
  1108. UseDerefSize = true;
  1109. } else if (auto Size = Var.getVariable()->getSizeInBits()) {
  1110. if (*Size != ValueSizeInBits) {
  1111. UseDerefSize = true;
  1112. }
  1113. }
  1114. SmallVector<uint64_t, 5> OffsetOps;
  1115. TRI.getOffsetOpcodes(Spill.SpillOffset, OffsetOps);
  1116. bool StackValue = false;
  1117. if (Properties.Indirect) {
  1118. // This is something like an NRVO variable, where the pointer has been
  1119. // spilt to the stack. It should end up being a memory location, with
  1120. // the pointer to the variable loaded off the stack with a deref:
  1121. assert(!Expr->isImplicit());
  1122. OffsetOps.push_back(dwarf::DW_OP_deref);
  1123. } else if (UseDerefSize && Expr->isSingleLocationExpression()) {
  1124. // TODO: Figure out how to handle deref size issues for variadic
  1125. // values.
  1126. // We're loading a value off the stack that's not the same size as the
  1127. // variable. Add / subtract stack offset, explicitly deref with a
  1128. // size, and add DW_OP_stack_value if not already present.
  1129. OffsetOps.push_back(dwarf::DW_OP_deref_size);
  1130. OffsetOps.push_back(DerefSizeInBytes);
  1131. StackValue = true;
  1132. } else if (Expr->isComplex() || Properties.IsVariadic) {
  1133. // A variable with no size ambiguity, but with extra elements in it's
  1134. // expression. Manually dereference the stack location.
  1135. OffsetOps.push_back(dwarf::DW_OP_deref);
  1136. } else {
  1137. // A plain value that has been spilt to the stack, with no further
  1138. // context. Request a location expression, marking the DBG_VALUE as
  1139. // IsIndirect.
  1140. Indirect = true;
  1141. }
  1142. Expr = DIExpression::appendOpsToArg(Expr, OffsetOps, Idx, StackValue);
  1143. MOs.push_back(GetRegOp(Base));
  1144. } else {
  1145. // This is a stack location with a weird subregister offset: emit an
  1146. // undef DBG_VALUE instead.
  1147. return EmitUndef();
  1148. }
  1149. } else {
  1150. // Non-empty, non-stack slot, must be a plain register.
  1151. MOs.push_back(GetRegOp(LocID));
  1152. }
  1153. }
  1154. return BuildMI(MF, DL, Desc, Indirect, MOs, Var.getVariable(), Expr);
  1155. }
  1156. /// Default construct and initialize the pass.
  1157. InstrRefBasedLDV::InstrRefBasedLDV() = default;
  1158. bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
  1159. unsigned Reg = MTracker->LocIdxToLocID[L];
  1160. return isCalleeSavedReg(Reg);
  1161. }
  1162. bool InstrRefBasedLDV::isCalleeSavedReg(Register R) const {
  1163. for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI)
  1164. if (CalleeSavedRegs.test(*RAI))
  1165. return true;
  1166. return false;
  1167. }
  1168. //===----------------------------------------------------------------------===//
  1169. // Debug Range Extension Implementation
  1170. //===----------------------------------------------------------------------===//
  1171. #ifndef NDEBUG
  1172. // Something to restore in the future.
  1173. // void InstrRefBasedLDV::printVarLocInMBB(..)
  1174. #endif
  1175. std::optional<SpillLocationNo>
  1176. InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
  1177. assert(MI.hasOneMemOperand() &&
  1178. "Spill instruction does not have exactly one memory operand?");
  1179. auto MMOI = MI.memoperands_begin();
  1180. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  1181. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  1182. "Inconsistent memory operand in spill instruction");
  1183. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  1184. const MachineBasicBlock *MBB = MI.getParent();
  1185. Register Reg;
  1186. StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  1187. return MTracker->getOrTrackSpillLoc({Reg, Offset});
  1188. }
  1189. std::optional<LocIdx>
  1190. InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
  1191. std::optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
  1192. if (!SpillLoc)
  1193. return std::nullopt;
  1194. // Where in the stack slot is this value defined -- i.e., what size of value
  1195. // is this? An important question, because it could be loaded into a register
  1196. // from the stack at some point. Happily the memory operand will tell us
  1197. // the size written to the stack.
  1198. auto *MemOperand = *MI.memoperands_begin();
  1199. unsigned SizeInBits = MemOperand->getSizeInBits();
  1200. // Find that position in the stack indexes we're tracking.
  1201. auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0});
  1202. if (IdxIt == MTracker->StackSlotIdxes.end())
  1203. // That index is not tracked. This is suprising, and unlikely to ever
  1204. // occur, but the safe action is to indicate the variable is optimised out.
  1205. return std::nullopt;
  1206. unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second);
  1207. return MTracker->getSpillMLoc(SpillID);
  1208. }
  1209. /// End all previous ranges related to @MI and start a new range from @MI
  1210. /// if it is a DBG_VALUE instr.
  1211. bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
  1212. if (!MI.isDebugValue())
  1213. return false;
  1214. const DILocalVariable *Var = MI.getDebugVariable();
  1215. const DIExpression *Expr = MI.getDebugExpression();
  1216. const DILocation *DebugLoc = MI.getDebugLoc();
  1217. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  1218. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  1219. "Expected inlined-at fields to agree");
  1220. DebugVariable V(Var, Expr, InlinedAt);
  1221. DbgValueProperties Properties(MI);
  1222. // If there are no instructions in this lexical scope, do no location tracking
  1223. // at all, this variable shouldn't get a legitimate location range.
  1224. auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
  1225. if (Scope == nullptr)
  1226. return true; // handled it; by doing nothing
  1227. // MLocTracker needs to know that this register is read, even if it's only
  1228. // read by a debug inst.
  1229. for (const MachineOperand &MO : MI.debug_operands())
  1230. if (MO.isReg() && MO.getReg() != 0)
  1231. (void)MTracker->readReg(MO.getReg());
  1232. // If we're preparing for the second analysis (variables), the machine value
  1233. // locations are already solved, and we report this DBG_VALUE and the value
  1234. // it refers to to VLocTracker.
  1235. if (VTracker) {
  1236. SmallVector<DbgOpID> DebugOps;
  1237. // Feed defVar the new variable location, or if this is a DBG_VALUE $noreg,
  1238. // feed defVar None.
  1239. if (!MI.isUndefDebugValue()) {
  1240. for (const MachineOperand &MO : MI.debug_operands()) {
  1241. // There should be no undef registers here, as we've screened for undef
  1242. // debug values.
  1243. if (MO.isReg()) {
  1244. DebugOps.push_back(DbgOpStore.insert(MTracker->readReg(MO.getReg())));
  1245. } else if (MO.isImm() || MO.isFPImm() || MO.isCImm()) {
  1246. DebugOps.push_back(DbgOpStore.insert(MO));
  1247. } else {
  1248. llvm_unreachable("Unexpected debug operand type.");
  1249. }
  1250. }
  1251. }
  1252. VTracker->defVar(MI, Properties, DebugOps);
  1253. }
  1254. // If performing final tracking of transfers, report this variable definition
  1255. // to the TransferTracker too.
  1256. if (TTracker)
  1257. TTracker->redefVar(MI);
  1258. return true;
  1259. }
  1260. std::optional<ValueIDNum> InstrRefBasedLDV::getValueForInstrRef(
  1261. unsigned InstNo, unsigned OpNo, MachineInstr &MI,
  1262. const ValueTable *MLiveOuts, const ValueTable *MLiveIns) {
  1263. // Various optimizations may have happened to the value during codegen,
  1264. // recorded in the value substitution table. Apply any substitutions to
  1265. // the instruction / operand number in this DBG_INSTR_REF, and collect
  1266. // any subregister extractions performed during optimization.
  1267. const MachineFunction &MF = *MI.getParent()->getParent();
  1268. // Create dummy substitution with Src set, for lookup.
  1269. auto SoughtSub =
  1270. MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
  1271. SmallVector<unsigned, 4> SeenSubregs;
  1272. auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
  1273. while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
  1274. LowerBoundIt->Src == SoughtSub.Src) {
  1275. std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
  1276. SoughtSub.Src = LowerBoundIt->Dest;
  1277. if (unsigned Subreg = LowerBoundIt->Subreg)
  1278. SeenSubregs.push_back(Subreg);
  1279. LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
  1280. }
  1281. // Default machine value number is <None> -- if no instruction defines
  1282. // the corresponding value, it must have been optimized out.
  1283. std::optional<ValueIDNum> NewID;
  1284. // Try to lookup the instruction number, and find the machine value number
  1285. // that it defines. It could be an instruction, or a PHI.
  1286. auto InstrIt = DebugInstrNumToInstr.find(InstNo);
  1287. auto PHIIt = llvm::lower_bound(DebugPHINumToValue, InstNo);
  1288. if (InstrIt != DebugInstrNumToInstr.end()) {
  1289. const MachineInstr &TargetInstr = *InstrIt->second.first;
  1290. uint64_t BlockNo = TargetInstr.getParent()->getNumber();
  1291. // Pick out the designated operand. It might be a memory reference, if
  1292. // a register def was folded into a stack store.
  1293. if (OpNo == MachineFunction::DebugOperandMemNumber &&
  1294. TargetInstr.hasOneMemOperand()) {
  1295. std::optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
  1296. if (L)
  1297. NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
  1298. } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
  1299. // Permit the debug-info to be completely wrong: identifying a nonexistant
  1300. // operand, or one that is not a register definition, means something
  1301. // unexpected happened during optimisation. Broken debug-info, however,
  1302. // shouldn't crash the compiler -- instead leave the variable value as
  1303. // None, which will make it appear "optimised out".
  1304. if (OpNo < TargetInstr.getNumOperands()) {
  1305. const MachineOperand &MO = TargetInstr.getOperand(OpNo);
  1306. if (MO.isReg() && MO.isDef() && MO.getReg()) {
  1307. unsigned LocID = MTracker->getLocID(MO.getReg());
  1308. LocIdx L = MTracker->LocIDToLocIdx[LocID];
  1309. NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
  1310. }
  1311. }
  1312. if (!NewID) {
  1313. LLVM_DEBUG(
  1314. { dbgs() << "Seen instruction reference to illegal operand\n"; });
  1315. }
  1316. }
  1317. // else: NewID is left as None.
  1318. } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
  1319. // It's actually a PHI value. Which value it is might not be obvious, use
  1320. // the resolver helper to find out.
  1321. NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
  1322. MI, InstNo);
  1323. }
  1324. // Apply any subregister extractions, in reverse. We might have seen code
  1325. // like this:
  1326. // CALL64 @foo, implicit-def $rax
  1327. // %0:gr64 = COPY $rax
  1328. // %1:gr32 = COPY %0.sub_32bit
  1329. // %2:gr16 = COPY %1.sub_16bit
  1330. // %3:gr8 = COPY %2.sub_8bit
  1331. // In which case each copy would have been recorded as a substitution with
  1332. // a subregister qualifier. Apply those qualifiers now.
  1333. if (NewID && !SeenSubregs.empty()) {
  1334. unsigned Offset = 0;
  1335. unsigned Size = 0;
  1336. // Look at each subregister that we passed through, and progressively
  1337. // narrow in, accumulating any offsets that occur. Substitutions should
  1338. // only ever be the same or narrower width than what they read from;
  1339. // iterate in reverse order so that we go from wide to small.
  1340. for (unsigned Subreg : reverse(SeenSubregs)) {
  1341. unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
  1342. unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
  1343. Offset += ThisOffset;
  1344. Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
  1345. }
  1346. // If that worked, look for an appropriate subregister with the register
  1347. // where the define happens. Don't look at values that were defined during
  1348. // a stack write: we can't currently express register locations within
  1349. // spills.
  1350. LocIdx L = NewID->getLoc();
  1351. if (NewID && !MTracker->isSpill(L)) {
  1352. // Find the register class for the register where this def happened.
  1353. // FIXME: no index for this?
  1354. Register Reg = MTracker->LocIdxToLocID[L];
  1355. const TargetRegisterClass *TRC = nullptr;
  1356. for (const auto *TRCI : TRI->regclasses())
  1357. if (TRCI->contains(Reg))
  1358. TRC = TRCI;
  1359. assert(TRC && "Couldn't find target register class?");
  1360. // If the register we have isn't the right size or in the right place,
  1361. // Try to find a subregister inside it.
  1362. unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
  1363. if (Size != MainRegSize || Offset) {
  1364. // Enumerate all subregisters, searching.
  1365. Register NewReg = 0;
  1366. for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
  1367. unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
  1368. unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
  1369. unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
  1370. if (SubregSize == Size && SubregOffset == Offset) {
  1371. NewReg = *SRI;
  1372. break;
  1373. }
  1374. }
  1375. // If we didn't find anything: there's no way to express our value.
  1376. if (!NewReg) {
  1377. NewID = std::nullopt;
  1378. } else {
  1379. // Re-state the value as being defined within the subregister
  1380. // that we found.
  1381. LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
  1382. NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
  1383. }
  1384. }
  1385. } else {
  1386. // If we can't handle subregisters, unset the new value.
  1387. NewID = std::nullopt;
  1388. }
  1389. }
  1390. return NewID;
  1391. }
  1392. bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
  1393. const ValueTable *MLiveOuts,
  1394. const ValueTable *MLiveIns) {
  1395. if (!MI.isDebugRef())
  1396. return false;
  1397. // Only handle this instruction when we are building the variable value
  1398. // transfer function.
  1399. if (!VTracker && !TTracker)
  1400. return false;
  1401. const DILocalVariable *Var = MI.getDebugVariable();
  1402. const DIExpression *Expr = MI.getDebugExpression();
  1403. const DILocation *DebugLoc = MI.getDebugLoc();
  1404. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  1405. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  1406. "Expected inlined-at fields to agree");
  1407. DebugVariable V(Var, Expr, InlinedAt);
  1408. auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
  1409. if (Scope == nullptr)
  1410. return true; // Handled by doing nothing. This variable is never in scope.
  1411. SmallVector<DbgOpID> DbgOpIDs;
  1412. for (const MachineOperand &MO : MI.debug_operands()) {
  1413. if (!MO.isDbgInstrRef()) {
  1414. assert(!MO.isReg() && "DBG_INSTR_REF should not contain registers");
  1415. DbgOpID ConstOpID = DbgOpStore.insert(DbgOp(MO));
  1416. DbgOpIDs.push_back(ConstOpID);
  1417. continue;
  1418. }
  1419. unsigned InstNo = MO.getInstrRefInstrIndex();
  1420. unsigned OpNo = MO.getInstrRefOpIndex();
  1421. // Default machine value number is <None> -- if no instruction defines
  1422. // the corresponding value, it must have been optimized out.
  1423. std::optional<ValueIDNum> NewID =
  1424. getValueForInstrRef(InstNo, OpNo, MI, MLiveOuts, MLiveIns);
  1425. // We have a value number or std::nullopt. If the latter, then kill the
  1426. // entire debug value.
  1427. if (NewID) {
  1428. DbgOpIDs.push_back(DbgOpStore.insert(*NewID));
  1429. } else {
  1430. DbgOpIDs.clear();
  1431. break;
  1432. }
  1433. }
  1434. // We have a DbgOpID for every value or for none. Tell the variable value
  1435. // tracker about it. The rest of this LiveDebugValues implementation acts
  1436. // exactly the same for DBG_INSTR_REFs as DBG_VALUEs (just, the former can
  1437. // refer to values that aren't immediately available).
  1438. DbgValueProperties Properties(Expr, false, true);
  1439. if (VTracker)
  1440. VTracker->defVar(MI, Properties, DbgOpIDs);
  1441. // If we're on the final pass through the function, decompose this INSTR_REF
  1442. // into a plain DBG_VALUE.
  1443. if (!TTracker)
  1444. return true;
  1445. // Fetch the concrete DbgOps now, as we will need them later.
  1446. SmallVector<DbgOp> DbgOps;
  1447. for (DbgOpID OpID : DbgOpIDs) {
  1448. DbgOps.push_back(DbgOpStore.find(OpID));
  1449. }
  1450. // Pick a location for the machine value number, if such a location exists.
  1451. // (This information could be stored in TransferTracker to make it faster).
  1452. SmallDenseMap<ValueIDNum, TransferTracker::LocationAndQuality> FoundLocs;
  1453. SmallVector<ValueIDNum> ValuesToFind;
  1454. // Initialized the preferred-location map with illegal locations, to be
  1455. // filled in later.
  1456. for (const DbgOp &Op : DbgOps) {
  1457. if (!Op.IsConst)
  1458. if (FoundLocs.insert({Op.ID, TransferTracker::LocationAndQuality()})
  1459. .second)
  1460. ValuesToFind.push_back(Op.ID);
  1461. }
  1462. for (auto Location : MTracker->locations()) {
  1463. LocIdx CurL = Location.Idx;
  1464. ValueIDNum ID = MTracker->readMLoc(CurL);
  1465. auto ValueToFindIt = find(ValuesToFind, ID);
  1466. if (ValueToFindIt == ValuesToFind.end())
  1467. continue;
  1468. auto &Previous = FoundLocs.find(ID)->second;
  1469. // If this is the first location with that value, pick it. Otherwise,
  1470. // consider whether it's a "longer term" location.
  1471. std::optional<TransferTracker::LocationQuality> ReplacementQuality =
  1472. TTracker->getLocQualityIfBetter(CurL, Previous.getQuality());
  1473. if (ReplacementQuality) {
  1474. Previous = TransferTracker::LocationAndQuality(CurL, *ReplacementQuality);
  1475. if (Previous.isBest()) {
  1476. ValuesToFind.erase(ValueToFindIt);
  1477. if (ValuesToFind.empty())
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. SmallVector<ResolvedDbgOp> NewLocs;
  1483. for (const DbgOp &DbgOp : DbgOps) {
  1484. if (DbgOp.IsConst) {
  1485. NewLocs.push_back(DbgOp.MO);
  1486. continue;
  1487. }
  1488. LocIdx FoundLoc = FoundLocs.find(DbgOp.ID)->second.getLoc();
  1489. if (FoundLoc.isIllegal()) {
  1490. NewLocs.clear();
  1491. break;
  1492. }
  1493. NewLocs.push_back(FoundLoc);
  1494. }
  1495. // Tell transfer tracker that the variable value has changed.
  1496. TTracker->redefVar(MI, Properties, NewLocs);
  1497. // If there were values with no location, but all such values are defined in
  1498. // later instructions in this block, this is a block-local use-before-def.
  1499. if (!DbgOps.empty() && NewLocs.empty()) {
  1500. bool IsValidUseBeforeDef = true;
  1501. uint64_t LastUseBeforeDef = 0;
  1502. for (auto ValueLoc : FoundLocs) {
  1503. ValueIDNum NewID = ValueLoc.first;
  1504. LocIdx FoundLoc = ValueLoc.second.getLoc();
  1505. if (!FoundLoc.isIllegal())
  1506. continue;
  1507. // If we have an value with no location that is not defined in this block,
  1508. // then it has no location in this block, leaving this value undefined.
  1509. if (NewID.getBlock() != CurBB || NewID.getInst() <= CurInst) {
  1510. IsValidUseBeforeDef = false;
  1511. break;
  1512. }
  1513. LastUseBeforeDef = std::max(LastUseBeforeDef, NewID.getInst());
  1514. }
  1515. if (IsValidUseBeforeDef) {
  1516. TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false, true},
  1517. DbgOps, LastUseBeforeDef);
  1518. }
  1519. }
  1520. // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
  1521. // This DBG_VALUE is potentially a $noreg / undefined location, if
  1522. // FoundLoc is illegal.
  1523. // (XXX -- could morph the DBG_INSTR_REF in the future).
  1524. MachineInstr *DbgMI = MTracker->emitLoc(NewLocs, V, Properties);
  1525. TTracker->PendingDbgValues.push_back(DbgMI);
  1526. TTracker->flushDbgValues(MI.getIterator(), nullptr);
  1527. return true;
  1528. }
  1529. bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
  1530. if (!MI.isDebugPHI())
  1531. return false;
  1532. // Analyse these only when solving the machine value location problem.
  1533. if (VTracker || TTracker)
  1534. return true;
  1535. // First operand is the value location, either a stack slot or register.
  1536. // Second is the debug instruction number of the original PHI.
  1537. const MachineOperand &MO = MI.getOperand(0);
  1538. unsigned InstrNum = MI.getOperand(1).getImm();
  1539. auto EmitBadPHI = [this, &MI, InstrNum]() -> bool {
  1540. // Helper lambda to do any accounting when we fail to find a location for
  1541. // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
  1542. // dead stack slot, for example.
  1543. // Record a DebugPHIRecord with an empty value + location.
  1544. DebugPHINumToValue.push_back(
  1545. {InstrNum, MI.getParent(), std::nullopt, std::nullopt});
  1546. return true;
  1547. };
  1548. if (MO.isReg() && MO.getReg()) {
  1549. // The value is whatever's currently in the register. Read and record it,
  1550. // to be analysed later.
  1551. Register Reg = MO.getReg();
  1552. ValueIDNum Num = MTracker->readReg(Reg);
  1553. auto PHIRec = DebugPHIRecord(
  1554. {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
  1555. DebugPHINumToValue.push_back(PHIRec);
  1556. // Ensure this register is tracked.
  1557. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  1558. MTracker->lookupOrTrackRegister(*RAI);
  1559. } else if (MO.isFI()) {
  1560. // The value is whatever's in this stack slot.
  1561. unsigned FI = MO.getIndex();
  1562. // If the stack slot is dead, then this was optimized away.
  1563. // FIXME: stack slot colouring should account for slots that get merged.
  1564. if (MFI->isDeadObjectIndex(FI))
  1565. return EmitBadPHI();
  1566. // Identify this spill slot, ensure it's tracked.
  1567. Register Base;
  1568. StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
  1569. SpillLoc SL = {Base, Offs};
  1570. std::optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
  1571. // We might be able to find a value, but have chosen not to, to avoid
  1572. // tracking too much stack information.
  1573. if (!SpillNo)
  1574. return EmitBadPHI();
  1575. // Any stack location DBG_PHI should have an associate bit-size.
  1576. assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
  1577. unsigned slotBitSize = MI.getOperand(2).getImm();
  1578. unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0});
  1579. LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
  1580. ValueIDNum Result = MTracker->readMLoc(SpillLoc);
  1581. // Record this DBG_PHI for later analysis.
  1582. auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc});
  1583. DebugPHINumToValue.push_back(DbgPHI);
  1584. } else {
  1585. // Else: if the operand is neither a legal register or a stack slot, then
  1586. // we're being fed illegal debug-info. Record an empty PHI, so that any
  1587. // debug users trying to read this number will be put off trying to
  1588. // interpret the value.
  1589. LLVM_DEBUG(
  1590. { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
  1591. return EmitBadPHI();
  1592. }
  1593. return true;
  1594. }
  1595. void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
  1596. // Meta Instructions do not affect the debug liveness of any register they
  1597. // define.
  1598. if (MI.isImplicitDef()) {
  1599. // Except when there's an implicit def, and the location it's defining has
  1600. // no value number. The whole point of an implicit def is to announce that
  1601. // the register is live, without be specific about it's value. So define
  1602. // a value if there isn't one already.
  1603. ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
  1604. // Has a legitimate value -> ignore the implicit def.
  1605. if (Num.getLoc() != 0)
  1606. return;
  1607. // Otherwise, def it here.
  1608. } else if (MI.isMetaInstruction())
  1609. return;
  1610. // We always ignore SP defines on call instructions, they don't actually
  1611. // change the value of the stack pointer... except for win32's _chkstk. This
  1612. // is rare: filter quickly for the common case (no stack adjustments, not a
  1613. // call, etc). If it is a call that modifies SP, recognise the SP register
  1614. // defs.
  1615. bool CallChangesSP = false;
  1616. if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
  1617. !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
  1618. CallChangesSP = true;
  1619. // Test whether we should ignore a def of this register due to it being part
  1620. // of the stack pointer.
  1621. auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
  1622. if (CallChangesSP)
  1623. return false;
  1624. return MI.isCall() && MTracker->SPAliases.count(R);
  1625. };
  1626. // Find the regs killed by MI, and find regmasks of preserved regs.
  1627. // Max out the number of statically allocated elements in `DeadRegs`, as this
  1628. // prevents fallback to std::set::count() operations.
  1629. SmallSet<uint32_t, 32> DeadRegs;
  1630. SmallVector<const uint32_t *, 4> RegMasks;
  1631. SmallVector<const MachineOperand *, 4> RegMaskPtrs;
  1632. for (const MachineOperand &MO : MI.operands()) {
  1633. // Determine whether the operand is a register def.
  1634. if (MO.isReg() && MO.isDef() && MO.getReg() && MO.getReg().isPhysical() &&
  1635. !IgnoreSPAlias(MO.getReg())) {
  1636. // Remove ranges of all aliased registers.
  1637. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  1638. // FIXME: Can we break out of this loop early if no insertion occurs?
  1639. DeadRegs.insert(*RAI);
  1640. } else if (MO.isRegMask()) {
  1641. RegMasks.push_back(MO.getRegMask());
  1642. RegMaskPtrs.push_back(&MO);
  1643. }
  1644. }
  1645. // Tell MLocTracker about all definitions, of regmasks and otherwise.
  1646. for (uint32_t DeadReg : DeadRegs)
  1647. MTracker->defReg(DeadReg, CurBB, CurInst);
  1648. for (const auto *MO : RegMaskPtrs)
  1649. MTracker->writeRegMask(MO, CurBB, CurInst);
  1650. // If this instruction writes to a spill slot, def that slot.
  1651. if (hasFoldedStackStore(MI)) {
  1652. if (std::optional<SpillLocationNo> SpillNo =
  1653. extractSpillBaseRegAndOffset(MI)) {
  1654. for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
  1655. unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
  1656. LocIdx L = MTracker->getSpillMLoc(SpillID);
  1657. MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
  1658. }
  1659. }
  1660. }
  1661. if (!TTracker)
  1662. return;
  1663. // When committing variable values to locations: tell transfer tracker that
  1664. // we've clobbered things. It may be able to recover the variable from a
  1665. // different location.
  1666. // Inform TTracker about any direct clobbers.
  1667. for (uint32_t DeadReg : DeadRegs) {
  1668. LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
  1669. TTracker->clobberMloc(Loc, MI.getIterator(), false);
  1670. }
  1671. // Look for any clobbers performed by a register mask. Only test locations
  1672. // that are actually being tracked.
  1673. if (!RegMaskPtrs.empty()) {
  1674. for (auto L : MTracker->locations()) {
  1675. // Stack locations can't be clobbered by regmasks.
  1676. if (MTracker->isSpill(L.Idx))
  1677. continue;
  1678. Register Reg = MTracker->LocIdxToLocID[L.Idx];
  1679. if (IgnoreSPAlias(Reg))
  1680. continue;
  1681. for (const auto *MO : RegMaskPtrs)
  1682. if (MO->clobbersPhysReg(Reg))
  1683. TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
  1684. }
  1685. }
  1686. // Tell TTracker about any folded stack store.
  1687. if (hasFoldedStackStore(MI)) {
  1688. if (std::optional<SpillLocationNo> SpillNo =
  1689. extractSpillBaseRegAndOffset(MI)) {
  1690. for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
  1691. unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
  1692. LocIdx L = MTracker->getSpillMLoc(SpillID);
  1693. TTracker->clobberMloc(L, MI.getIterator(), true);
  1694. }
  1695. }
  1696. }
  1697. }
  1698. void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
  1699. // In all circumstances, re-def all aliases. It's definitely a new value now.
  1700. for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
  1701. MTracker->defReg(*RAI, CurBB, CurInst);
  1702. ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
  1703. MTracker->setReg(DstRegNum, SrcValue);
  1704. // Copy subregisters from one location to another.
  1705. for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
  1706. unsigned SrcSubReg = SRI.getSubReg();
  1707. unsigned SubRegIdx = SRI.getSubRegIndex();
  1708. unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
  1709. if (!DstSubReg)
  1710. continue;
  1711. // Do copy. There are two matching subregisters, the source value should
  1712. // have been def'd when the super-reg was, the latter might not be tracked
  1713. // yet.
  1714. // This will force SrcSubReg to be tracked, if it isn't yet. Will read
  1715. // mphi values if it wasn't tracked.
  1716. LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
  1717. LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
  1718. (void)SrcL;
  1719. (void)DstL;
  1720. ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
  1721. MTracker->setReg(DstSubReg, CpyValue);
  1722. }
  1723. }
  1724. std::optional<SpillLocationNo>
  1725. InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
  1726. MachineFunction *MF) {
  1727. // TODO: Handle multiple stores folded into one.
  1728. if (!MI.hasOneMemOperand())
  1729. return std::nullopt;
  1730. // Reject any memory operand that's aliased -- we can't guarantee its value.
  1731. auto MMOI = MI.memoperands_begin();
  1732. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  1733. if (PVal->isAliased(MFI))
  1734. return std::nullopt;
  1735. if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
  1736. return std::nullopt; // This is not a spill instruction, since no valid size
  1737. // was returned from either function.
  1738. return extractSpillBaseRegAndOffset(MI);
  1739. }
  1740. bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
  1741. MachineFunction *MF, unsigned &Reg) {
  1742. if (!isSpillInstruction(MI, MF))
  1743. return false;
  1744. int FI;
  1745. Reg = TII->isStoreToStackSlotPostFE(MI, FI);
  1746. return Reg != 0;
  1747. }
  1748. std::optional<SpillLocationNo>
  1749. InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
  1750. MachineFunction *MF, unsigned &Reg) {
  1751. if (!MI.hasOneMemOperand())
  1752. return std::nullopt;
  1753. // FIXME: Handle folded restore instructions with more than one memory
  1754. // operand.
  1755. if (MI.getRestoreSize(TII)) {
  1756. Reg = MI.getOperand(0).getReg();
  1757. return extractSpillBaseRegAndOffset(MI);
  1758. }
  1759. return std::nullopt;
  1760. }
  1761. bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
  1762. // XXX -- it's too difficult to implement VarLocBasedImpl's stack location
  1763. // limitations under the new model. Therefore, when comparing them, compare
  1764. // versions that don't attempt spills or restores at all.
  1765. if (EmulateOldLDV)
  1766. return false;
  1767. // Strictly limit ourselves to plain loads and stores, not all instructions
  1768. // that can access the stack.
  1769. int DummyFI = -1;
  1770. if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
  1771. !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
  1772. return false;
  1773. MachineFunction *MF = MI.getMF();
  1774. unsigned Reg;
  1775. LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
  1776. // Strictly limit ourselves to plain loads and stores, not all instructions
  1777. // that can access the stack.
  1778. int FIDummy;
  1779. if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
  1780. !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
  1781. return false;
  1782. // First, if there are any DBG_VALUEs pointing at a spill slot that is
  1783. // written to, terminate that variable location. The value in memory
  1784. // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
  1785. if (std::optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
  1786. // Un-set this location and clobber, so that earlier locations don't
  1787. // continue past this store.
  1788. for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
  1789. unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
  1790. std::optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
  1791. if (!MLoc)
  1792. continue;
  1793. // We need to over-write the stack slot with something (here, a def at
  1794. // this instruction) to ensure no values are preserved in this stack slot
  1795. // after the spill. It also prevents TTracker from trying to recover the
  1796. // location and re-installing it in the same place.
  1797. ValueIDNum Def(CurBB, CurInst, *MLoc);
  1798. MTracker->setMLoc(*MLoc, Def);
  1799. if (TTracker)
  1800. TTracker->clobberMloc(*MLoc, MI.getIterator());
  1801. }
  1802. }
  1803. // Try to recognise spill and restore instructions that may transfer a value.
  1804. if (isLocationSpill(MI, MF, Reg)) {
  1805. // isLocationSpill returning true should guarantee we can extract a
  1806. // location.
  1807. SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
  1808. auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
  1809. auto ReadValue = MTracker->readReg(SrcReg);
  1810. LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
  1811. MTracker->setMLoc(DstLoc, ReadValue);
  1812. if (TTracker) {
  1813. LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
  1814. TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
  1815. }
  1816. };
  1817. // Then, transfer subreg bits.
  1818. for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
  1819. // Ensure this reg is tracked,
  1820. (void)MTracker->lookupOrTrackRegister(*SRI);
  1821. unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI);
  1822. unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
  1823. DoTransfer(*SRI, SpillID);
  1824. }
  1825. // Directly lookup size of main source reg, and transfer.
  1826. unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
  1827. unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
  1828. DoTransfer(Reg, SpillID);
  1829. } else {
  1830. std::optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
  1831. if (!Loc)
  1832. return false;
  1833. // Assumption: we're reading from the base of the stack slot, not some
  1834. // offset into it. It seems very unlikely LLVM would ever generate
  1835. // restores where this wasn't true. This then becomes a question of what
  1836. // subregisters in the destination register line up with positions in the
  1837. // stack slot.
  1838. // Def all registers that alias the destination.
  1839. for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
  1840. MTracker->defReg(*RAI, CurBB, CurInst);
  1841. // Now find subregisters within the destination register, and load values
  1842. // from stack slot positions.
  1843. auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
  1844. LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
  1845. auto ReadValue = MTracker->readMLoc(SrcIdx);
  1846. MTracker->setReg(DestReg, ReadValue);
  1847. };
  1848. for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
  1849. unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
  1850. unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
  1851. DoTransfer(*SRI, SpillID);
  1852. }
  1853. // Directly look up this registers slot idx by size, and transfer.
  1854. unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
  1855. unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
  1856. DoTransfer(Reg, SpillID);
  1857. }
  1858. return true;
  1859. }
  1860. bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
  1861. auto DestSrc = TII->isCopyInstr(MI);
  1862. if (!DestSrc)
  1863. return false;
  1864. const MachineOperand *DestRegOp = DestSrc->Destination;
  1865. const MachineOperand *SrcRegOp = DestSrc->Source;
  1866. Register SrcReg = SrcRegOp->getReg();
  1867. Register DestReg = DestRegOp->getReg();
  1868. // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
  1869. if (SrcReg == DestReg)
  1870. return true;
  1871. // For emulating VarLocBasedImpl:
  1872. // We want to recognize instructions where destination register is callee
  1873. // saved register. If register that could be clobbered by the call is
  1874. // included, there would be a great chance that it is going to be clobbered
  1875. // soon. It is more likely that previous register, which is callee saved, is
  1876. // going to stay unclobbered longer, even if it is killed.
  1877. //
  1878. // For InstrRefBasedImpl, we can track multiple locations per value, so
  1879. // ignore this condition.
  1880. if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
  1881. return false;
  1882. // InstrRefBasedImpl only followed killing copies.
  1883. if (EmulateOldLDV && !SrcRegOp->isKill())
  1884. return false;
  1885. // Before we update MTracker, remember which values were present in each of
  1886. // the locations about to be overwritten, so that we can recover any
  1887. // potentially clobbered variables.
  1888. DenseMap<LocIdx, ValueIDNum> ClobberedLocs;
  1889. if (TTracker) {
  1890. for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
  1891. LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
  1892. auto MLocIt = TTracker->ActiveMLocs.find(ClobberedLoc);
  1893. // If ActiveMLocs isn't tracking this location or there are no variables
  1894. // using it, don't bother remembering.
  1895. if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty())
  1896. continue;
  1897. ValueIDNum Value = MTracker->readReg(*RAI);
  1898. ClobberedLocs[ClobberedLoc] = Value;
  1899. }
  1900. }
  1901. // Copy MTracker info, including subregs if available.
  1902. InstrRefBasedLDV::performCopy(SrcReg, DestReg);
  1903. // The copy might have clobbered variables based on the destination register.
  1904. // Tell TTracker about it, passing the old ValueIDNum to search for
  1905. // alternative locations (or else terminating those variables).
  1906. if (TTracker) {
  1907. for (auto LocVal : ClobberedLocs) {
  1908. TTracker->clobberMloc(LocVal.first, LocVal.second, MI.getIterator(), false);
  1909. }
  1910. }
  1911. // Only produce a transfer of DBG_VALUE within a block where old LDV
  1912. // would have. We might make use of the additional value tracking in some
  1913. // other way, later.
  1914. if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
  1915. TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
  1916. MTracker->getRegMLoc(DestReg), MI.getIterator());
  1917. // VarLocBasedImpl would quit tracking the old location after copying.
  1918. if (EmulateOldLDV && SrcReg != DestReg)
  1919. MTracker->defReg(SrcReg, CurBB, CurInst);
  1920. return true;
  1921. }
  1922. /// Accumulate a mapping between each DILocalVariable fragment and other
  1923. /// fragments of that DILocalVariable which overlap. This reduces work during
  1924. /// the data-flow stage from "Find any overlapping fragments" to "Check if the
  1925. /// known-to-overlap fragments are present".
  1926. /// \param MI A previously unprocessed debug instruction to analyze for
  1927. /// fragment usage.
  1928. void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
  1929. assert(MI.isDebugValueLike());
  1930. DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
  1931. MI.getDebugLoc()->getInlinedAt());
  1932. FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
  1933. // If this is the first sighting of this variable, then we are guaranteed
  1934. // there are currently no overlapping fragments either. Initialize the set
  1935. // of seen fragments, record no overlaps for the current one, and return.
  1936. auto SeenIt = SeenFragments.find(MIVar.getVariable());
  1937. if (SeenIt == SeenFragments.end()) {
  1938. SmallSet<FragmentInfo, 4> OneFragment;
  1939. OneFragment.insert(ThisFragment);
  1940. SeenFragments.insert({MIVar.getVariable(), OneFragment});
  1941. OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
  1942. return;
  1943. }
  1944. // If this particular Variable/Fragment pair already exists in the overlap
  1945. // map, it has already been accounted for.
  1946. auto IsInOLapMap =
  1947. OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
  1948. if (!IsInOLapMap.second)
  1949. return;
  1950. auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
  1951. auto &AllSeenFragments = SeenIt->second;
  1952. // Otherwise, examine all other seen fragments for this variable, with "this"
  1953. // fragment being a previously unseen fragment. Record any pair of
  1954. // overlapping fragments.
  1955. for (const auto &ASeenFragment : AllSeenFragments) {
  1956. // Does this previously seen fragment overlap?
  1957. if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
  1958. // Yes: Mark the current fragment as being overlapped.
  1959. ThisFragmentsOverlaps.push_back(ASeenFragment);
  1960. // Mark the previously seen fragment as being overlapped by the current
  1961. // one.
  1962. auto ASeenFragmentsOverlaps =
  1963. OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
  1964. assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
  1965. "Previously seen var fragment has no vector of overlaps");
  1966. ASeenFragmentsOverlaps->second.push_back(ThisFragment);
  1967. }
  1968. }
  1969. AllSeenFragments.insert(ThisFragment);
  1970. }
  1971. void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts,
  1972. const ValueTable *MLiveIns) {
  1973. // Try to interpret an MI as a debug or transfer instruction. Only if it's
  1974. // none of these should we interpret it's register defs as new value
  1975. // definitions.
  1976. if (transferDebugValue(MI))
  1977. return;
  1978. if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
  1979. return;
  1980. if (transferDebugPHI(MI))
  1981. return;
  1982. if (transferRegisterCopy(MI))
  1983. return;
  1984. if (transferSpillOrRestoreInst(MI))
  1985. return;
  1986. transferRegisterDef(MI);
  1987. }
  1988. void InstrRefBasedLDV::produceMLocTransferFunction(
  1989. MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
  1990. unsigned MaxNumBlocks) {
  1991. // Because we try to optimize around register mask operands by ignoring regs
  1992. // that aren't currently tracked, we set up something ugly for later: RegMask
  1993. // operands that are seen earlier than the first use of a register, still need
  1994. // to clobber that register in the transfer function. But this information
  1995. // isn't actively recorded. Instead, we track each RegMask used in each block,
  1996. // and accumulated the clobbered but untracked registers in each block into
  1997. // the following bitvector. Later, if new values are tracked, we can add
  1998. // appropriate clobbers.
  1999. SmallVector<BitVector, 32> BlockMasks;
  2000. BlockMasks.resize(MaxNumBlocks);
  2001. // Reserve one bit per register for the masks described above.
  2002. unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
  2003. for (auto &BV : BlockMasks)
  2004. BV.resize(TRI->getNumRegs(), true);
  2005. // Step through all instructions and inhale the transfer function.
  2006. for (auto &MBB : MF) {
  2007. // Object fields that are read by trackers to know where we are in the
  2008. // function.
  2009. CurBB = MBB.getNumber();
  2010. CurInst = 1;
  2011. // Set all machine locations to a PHI value. For transfer function
  2012. // production only, this signifies the live-in value to the block.
  2013. MTracker->reset();
  2014. MTracker->setMPhis(CurBB);
  2015. // Step through each instruction in this block.
  2016. for (auto &MI : MBB) {
  2017. // Pass in an empty unique_ptr for the value tables when accumulating the
  2018. // machine transfer function.
  2019. process(MI, nullptr, nullptr);
  2020. // Also accumulate fragment map.
  2021. if (MI.isDebugValueLike())
  2022. accumulateFragmentMap(MI);
  2023. // Create a map from the instruction number (if present) to the
  2024. // MachineInstr and its position.
  2025. if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
  2026. auto InstrAndPos = std::make_pair(&MI, CurInst);
  2027. auto InsertResult =
  2028. DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
  2029. // There should never be duplicate instruction numbers.
  2030. assert(InsertResult.second);
  2031. (void)InsertResult;
  2032. }
  2033. ++CurInst;
  2034. }
  2035. // Produce the transfer function, a map of machine location to new value. If
  2036. // any machine location has the live-in phi value from the start of the
  2037. // block, it's live-through and doesn't need recording in the transfer
  2038. // function.
  2039. for (auto Location : MTracker->locations()) {
  2040. LocIdx Idx = Location.Idx;
  2041. ValueIDNum &P = Location.Value;
  2042. if (P.isPHI() && P.getLoc() == Idx.asU64())
  2043. continue;
  2044. // Insert-or-update.
  2045. auto &TransferMap = MLocTransfer[CurBB];
  2046. auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
  2047. if (!Result.second)
  2048. Result.first->second = P;
  2049. }
  2050. // Accumulate any bitmask operands into the clobbered reg mask for this
  2051. // block.
  2052. for (auto &P : MTracker->Masks) {
  2053. BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
  2054. }
  2055. }
  2056. // Compute a bitvector of all the registers that are tracked in this block.
  2057. BitVector UsedRegs(TRI->getNumRegs());
  2058. for (auto Location : MTracker->locations()) {
  2059. unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
  2060. // Ignore stack slots, and aliases of the stack pointer.
  2061. if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
  2062. continue;
  2063. UsedRegs.set(ID);
  2064. }
  2065. // Check that any regmask-clobber of a register that gets tracked, is not
  2066. // live-through in the transfer function. It needs to be clobbered at the
  2067. // very least.
  2068. for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
  2069. BitVector &BV = BlockMasks[I];
  2070. BV.flip();
  2071. BV &= UsedRegs;
  2072. // This produces all the bits that we clobber, but also use. Check that
  2073. // they're all clobbered or at least set in the designated transfer
  2074. // elem.
  2075. for (unsigned Bit : BV.set_bits()) {
  2076. unsigned ID = MTracker->getLocID(Bit);
  2077. LocIdx Idx = MTracker->LocIDToLocIdx[ID];
  2078. auto &TransferMap = MLocTransfer[I];
  2079. // Install a value representing the fact that this location is effectively
  2080. // written to in this block. As there's no reserved value, instead use
  2081. // a value number that is never generated. Pick the value number for the
  2082. // first instruction in the block, def'ing this location, which we know
  2083. // this block never used anyway.
  2084. ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
  2085. auto Result =
  2086. TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
  2087. if (!Result.second) {
  2088. ValueIDNum &ValueID = Result.first->second;
  2089. if (ValueID.getBlock() == I && ValueID.isPHI())
  2090. // It was left as live-through. Set it to clobbered.
  2091. ValueID = NotGeneratedNum;
  2092. }
  2093. }
  2094. }
  2095. }
  2096. bool InstrRefBasedLDV::mlocJoin(
  2097. MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  2098. FuncValueTable &OutLocs, ValueTable &InLocs) {
  2099. LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
  2100. bool Changed = false;
  2101. // Handle value-propagation when control flow merges on entry to a block. For
  2102. // any location without a PHI already placed, the location has the same value
  2103. // as its predecessors. If a PHI is placed, test to see whether it's now a
  2104. // redundant PHI that we can eliminate.
  2105. SmallVector<const MachineBasicBlock *, 8> BlockOrders;
  2106. for (auto *Pred : MBB.predecessors())
  2107. BlockOrders.push_back(Pred);
  2108. // Visit predecessors in RPOT order.
  2109. auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
  2110. return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
  2111. };
  2112. llvm::sort(BlockOrders, Cmp);
  2113. // Skip entry block.
  2114. if (BlockOrders.size() == 0)
  2115. return false;
  2116. // Step through all machine locations, look at each predecessor and test
  2117. // whether we can eliminate redundant PHIs.
  2118. for (auto Location : MTracker->locations()) {
  2119. LocIdx Idx = Location.Idx;
  2120. // Pick out the first predecessors live-out value for this location. It's
  2121. // guaranteed to not be a backedge, as we order by RPO.
  2122. ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
  2123. // If we've already eliminated a PHI here, do no further checking, just
  2124. // propagate the first live-in value into this block.
  2125. if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
  2126. if (InLocs[Idx.asU64()] != FirstVal) {
  2127. InLocs[Idx.asU64()] = FirstVal;
  2128. Changed |= true;
  2129. }
  2130. continue;
  2131. }
  2132. // We're now examining a PHI to see whether it's un-necessary. Loop around
  2133. // the other live-in values and test whether they're all the same.
  2134. bool Disagree = false;
  2135. for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
  2136. const MachineBasicBlock *PredMBB = BlockOrders[I];
  2137. const ValueIDNum &PredLiveOut =
  2138. OutLocs[PredMBB->getNumber()][Idx.asU64()];
  2139. // Incoming values agree, continue trying to eliminate this PHI.
  2140. if (FirstVal == PredLiveOut)
  2141. continue;
  2142. // We can also accept a PHI value that feeds back into itself.
  2143. if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
  2144. continue;
  2145. // Live-out of a predecessor disagrees with the first predecessor.
  2146. Disagree = true;
  2147. }
  2148. // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
  2149. if (!Disagree) {
  2150. InLocs[Idx.asU64()] = FirstVal;
  2151. Changed |= true;
  2152. }
  2153. }
  2154. // TODO: Reimplement NumInserted and NumRemoved.
  2155. return Changed;
  2156. }
  2157. void InstrRefBasedLDV::findStackIndexInterference(
  2158. SmallVectorImpl<unsigned> &Slots) {
  2159. // We could spend a bit of time finding the exact, minimal, set of stack
  2160. // indexes that interfere with each other, much like reg units. Or, we can
  2161. // rely on the fact that:
  2162. // * The smallest / lowest index will interfere with everything at zero
  2163. // offset, which will be the largest set of registers,
  2164. // * Most indexes with non-zero offset will end up being interference units
  2165. // anyway.
  2166. // So just pick those out and return them.
  2167. // We can rely on a single-byte stack index existing already, because we
  2168. // initialize them in MLocTracker.
  2169. auto It = MTracker->StackSlotIdxes.find({8, 0});
  2170. assert(It != MTracker->StackSlotIdxes.end());
  2171. Slots.push_back(It->second);
  2172. // Find anything that has a non-zero offset and add that too.
  2173. for (auto &Pair : MTracker->StackSlotIdxes) {
  2174. // Is offset zero? If so, ignore.
  2175. if (!Pair.first.second)
  2176. continue;
  2177. Slots.push_back(Pair.second);
  2178. }
  2179. }
  2180. void InstrRefBasedLDV::placeMLocPHIs(
  2181. MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
  2182. FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
  2183. SmallVector<unsigned, 4> StackUnits;
  2184. findStackIndexInterference(StackUnits);
  2185. // To avoid repeatedly running the PHI placement algorithm, leverage the
  2186. // fact that a def of register MUST also def its register units. Find the
  2187. // units for registers, place PHIs for them, and then replicate them for
  2188. // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
  2189. // arguments) don't lead to register units being tracked, just place PHIs for
  2190. // those registers directly. Stack slots have their own form of "unit",
  2191. // store them to one side.
  2192. SmallSet<Register, 32> RegUnitsToPHIUp;
  2193. SmallSet<LocIdx, 32> NormalLocsToPHI;
  2194. SmallSet<SpillLocationNo, 32> StackSlots;
  2195. for (auto Location : MTracker->locations()) {
  2196. LocIdx L = Location.Idx;
  2197. if (MTracker->isSpill(L)) {
  2198. StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
  2199. continue;
  2200. }
  2201. Register R = MTracker->LocIdxToLocID[L];
  2202. SmallSet<Register, 8> FoundRegUnits;
  2203. bool AnyIllegal = false;
  2204. for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) {
  2205. for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){
  2206. if (!MTracker->isRegisterTracked(*URoot)) {
  2207. // Not all roots were loaded into the tracking map: this register
  2208. // isn't actually def'd anywhere, we only read from it. Generate PHIs
  2209. // for this reg, but don't iterate units.
  2210. AnyIllegal = true;
  2211. } else {
  2212. FoundRegUnits.insert(*URoot);
  2213. }
  2214. }
  2215. }
  2216. if (AnyIllegal) {
  2217. NormalLocsToPHI.insert(L);
  2218. continue;
  2219. }
  2220. RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
  2221. }
  2222. // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
  2223. // collection.
  2224. SmallVector<MachineBasicBlock *, 32> PHIBlocks;
  2225. auto CollectPHIsForLoc = [&](LocIdx L) {
  2226. // Collect the set of defs.
  2227. SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
  2228. for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
  2229. MachineBasicBlock *MBB = OrderToBB[I];
  2230. const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
  2231. if (TransferFunc.find(L) != TransferFunc.end())
  2232. DefBlocks.insert(MBB);
  2233. }
  2234. // The entry block defs the location too: it's the live-in / argument value.
  2235. // Only insert if there are other defs though; everything is trivially live
  2236. // through otherwise.
  2237. if (!DefBlocks.empty())
  2238. DefBlocks.insert(&*MF.begin());
  2239. // Ask the SSA construction algorithm where we should put PHIs. Clear
  2240. // anything that might have been hanging around from earlier.
  2241. PHIBlocks.clear();
  2242. BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
  2243. };
  2244. auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
  2245. for (const MachineBasicBlock *MBB : PHIBlocks)
  2246. MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
  2247. };
  2248. // For locations with no reg units, just place PHIs.
  2249. for (LocIdx L : NormalLocsToPHI) {
  2250. CollectPHIsForLoc(L);
  2251. // Install those PHI values into the live-in value array.
  2252. InstallPHIsAtLoc(L);
  2253. }
  2254. // For stack slots, calculate PHIs for the equivalent of the units, then
  2255. // install for each index.
  2256. for (SpillLocationNo Slot : StackSlots) {
  2257. for (unsigned Idx : StackUnits) {
  2258. unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
  2259. LocIdx L = MTracker->getSpillMLoc(SpillID);
  2260. CollectPHIsForLoc(L);
  2261. InstallPHIsAtLoc(L);
  2262. // Find anything that aliases this stack index, install PHIs for it too.
  2263. unsigned Size, Offset;
  2264. std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
  2265. for (auto &Pair : MTracker->StackSlotIdxes) {
  2266. unsigned ThisSize, ThisOffset;
  2267. std::tie(ThisSize, ThisOffset) = Pair.first;
  2268. if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
  2269. continue;
  2270. unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
  2271. LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
  2272. InstallPHIsAtLoc(ThisL);
  2273. }
  2274. }
  2275. }
  2276. // For reg units, place PHIs, and then place them for any aliasing registers.
  2277. for (Register R : RegUnitsToPHIUp) {
  2278. LocIdx L = MTracker->lookupOrTrackRegister(R);
  2279. CollectPHIsForLoc(L);
  2280. // Install those PHI values into the live-in value array.
  2281. InstallPHIsAtLoc(L);
  2282. // Now find aliases and install PHIs for those.
  2283. for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
  2284. // Super-registers that are "above" the largest register read/written by
  2285. // the function will alias, but will not be tracked.
  2286. if (!MTracker->isRegisterTracked(*RAI))
  2287. continue;
  2288. LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
  2289. InstallPHIsAtLoc(AliasLoc);
  2290. }
  2291. }
  2292. }
  2293. void InstrRefBasedLDV::buildMLocValueMap(
  2294. MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
  2295. SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
  2296. std::priority_queue<unsigned int, std::vector<unsigned int>,
  2297. std::greater<unsigned int>>
  2298. Worklist, Pending;
  2299. // We track what is on the current and pending worklist to avoid inserting
  2300. // the same thing twice. We could avoid this with a custom priority queue,
  2301. // but this is probably not worth it.
  2302. SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
  2303. // Initialize worklist with every block to be visited. Also produce list of
  2304. // all blocks.
  2305. SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
  2306. for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
  2307. Worklist.push(I);
  2308. OnWorklist.insert(OrderToBB[I]);
  2309. AllBlocks.insert(OrderToBB[I]);
  2310. }
  2311. // Initialize entry block to PHIs. These represent arguments.
  2312. for (auto Location : MTracker->locations())
  2313. MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
  2314. MTracker->reset();
  2315. // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
  2316. // any machine-location that isn't live-through a block to be def'd in that
  2317. // block.
  2318. placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
  2319. // Propagate values to eliminate redundant PHIs. At the same time, this
  2320. // produces the table of Block x Location => Value for the entry to each
  2321. // block.
  2322. // The kind of PHIs we can eliminate are, for example, where one path in a
  2323. // conditional spills and restores a register, and the register still has
  2324. // the same value once control flow joins, unbeknowns to the PHI placement
  2325. // code. Propagating values allows us to identify such un-necessary PHIs and
  2326. // remove them.
  2327. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  2328. while (!Worklist.empty() || !Pending.empty()) {
  2329. // Vector for storing the evaluated block transfer function.
  2330. SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
  2331. while (!Worklist.empty()) {
  2332. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  2333. CurBB = MBB->getNumber();
  2334. Worklist.pop();
  2335. // Join the values in all predecessor blocks.
  2336. bool InLocsChanged;
  2337. InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
  2338. InLocsChanged |= Visited.insert(MBB).second;
  2339. // Don't examine transfer function if we've visited this loc at least
  2340. // once, and inlocs haven't changed.
  2341. if (!InLocsChanged)
  2342. continue;
  2343. // Load the current set of live-ins into MLocTracker.
  2344. MTracker->loadFromArray(MInLocs[CurBB], CurBB);
  2345. // Each element of the transfer function can be a new def, or a read of
  2346. // a live-in value. Evaluate each element, and store to "ToRemap".
  2347. ToRemap.clear();
  2348. for (auto &P : MLocTransfer[CurBB]) {
  2349. if (P.second.getBlock() == CurBB && P.second.isPHI()) {
  2350. // This is a movement of whatever was live in. Read it.
  2351. ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
  2352. ToRemap.push_back(std::make_pair(P.first, NewID));
  2353. } else {
  2354. // It's a def. Just set it.
  2355. assert(P.second.getBlock() == CurBB);
  2356. ToRemap.push_back(std::make_pair(P.first, P.second));
  2357. }
  2358. }
  2359. // Commit the transfer function changes into mloc tracker, which
  2360. // transforms the contents of the MLocTracker into the live-outs.
  2361. for (auto &P : ToRemap)
  2362. MTracker->setMLoc(P.first, P.second);
  2363. // Now copy out-locs from mloc tracker into out-loc vector, checking
  2364. // whether changes have occurred. These changes can have come from both
  2365. // the transfer function, and mlocJoin.
  2366. bool OLChanged = false;
  2367. for (auto Location : MTracker->locations()) {
  2368. OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
  2369. MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
  2370. }
  2371. MTracker->reset();
  2372. // No need to examine successors again if out-locs didn't change.
  2373. if (!OLChanged)
  2374. continue;
  2375. // All successors should be visited: put any back-edges on the pending
  2376. // list for the next pass-through, and any other successors to be
  2377. // visited this pass, if they're not going to be already.
  2378. for (auto *s : MBB->successors()) {
  2379. // Does branching to this successor represent a back-edge?
  2380. if (BBToOrder[s] > BBToOrder[MBB]) {
  2381. // No: visit it during this dataflow iteration.
  2382. if (OnWorklist.insert(s).second)
  2383. Worklist.push(BBToOrder[s]);
  2384. } else {
  2385. // Yes: visit it on the next iteration.
  2386. if (OnPending.insert(s).second)
  2387. Pending.push(BBToOrder[s]);
  2388. }
  2389. }
  2390. }
  2391. Worklist.swap(Pending);
  2392. std::swap(OnPending, OnWorklist);
  2393. OnPending.clear();
  2394. // At this point, pending must be empty, since it was just the empty
  2395. // worklist
  2396. assert(Pending.empty() && "Pending should be empty");
  2397. }
  2398. // Once all the live-ins don't change on mlocJoin(), we've eliminated all
  2399. // redundant PHIs.
  2400. }
  2401. void InstrRefBasedLDV::BlockPHIPlacement(
  2402. const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
  2403. const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
  2404. SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
  2405. // Apply IDF calculator to the designated set of location defs, storing
  2406. // required PHIs into PHIBlocks. Uses the dominator tree stored in the
  2407. // InstrRefBasedLDV object.
  2408. IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
  2409. IDF.setLiveInBlocks(AllBlocks);
  2410. IDF.setDefiningBlocks(DefBlocks);
  2411. IDF.calculate(PHIBlocks);
  2412. }
  2413. bool InstrRefBasedLDV::pickVPHILoc(
  2414. SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
  2415. const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
  2416. const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
  2417. // No predecessors means no PHIs.
  2418. if (BlockOrders.empty())
  2419. return false;
  2420. // All the location operands that do not already agree need to be joined,
  2421. // track the indices of each such location operand here.
  2422. SmallDenseSet<unsigned> LocOpsToJoin;
  2423. auto FirstValueIt = LiveOuts.find(BlockOrders[0]);
  2424. if (FirstValueIt == LiveOuts.end())
  2425. return false;
  2426. const DbgValue &FirstValue = *FirstValueIt->second;
  2427. for (const auto p : BlockOrders) {
  2428. auto OutValIt = LiveOuts.find(p);
  2429. if (OutValIt == LiveOuts.end())
  2430. // If we have a predecessor not in scope, we'll never find a PHI position.
  2431. return false;
  2432. const DbgValue &OutVal = *OutValIt->second;
  2433. // No-values cannot have locations we can join on.
  2434. if (OutVal.Kind == DbgValue::NoVal)
  2435. return false;
  2436. // For unjoined VPHIs where we don't know the location, we definitely
  2437. // can't find a join loc unless the VPHI is a backedge.
  2438. if (OutVal.isUnjoinedPHI() && OutVal.BlockNo != MBB.getNumber())
  2439. return false;
  2440. if (!FirstValue.Properties.isJoinable(OutVal.Properties))
  2441. return false;
  2442. for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
  2443. // An unjoined PHI has no defined locations, and so a shared location must
  2444. // be found for every operand.
  2445. if (OutVal.isUnjoinedPHI()) {
  2446. LocOpsToJoin.insert(Idx);
  2447. continue;
  2448. }
  2449. DbgOpID FirstValOp = FirstValue.getDbgOpID(Idx);
  2450. DbgOpID OutValOp = OutVal.getDbgOpID(Idx);
  2451. if (FirstValOp != OutValOp) {
  2452. // We can never join constant ops - the ops must either both be equal
  2453. // constant ops or non-const ops.
  2454. if (FirstValOp.isConst() || OutValOp.isConst())
  2455. return false;
  2456. else
  2457. LocOpsToJoin.insert(Idx);
  2458. }
  2459. }
  2460. }
  2461. SmallVector<DbgOpID> NewDbgOps;
  2462. for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
  2463. // If this op doesn't need to be joined because the values agree, use that
  2464. // already-agreed value.
  2465. if (!LocOpsToJoin.contains(Idx)) {
  2466. NewDbgOps.push_back(FirstValue.getDbgOpID(Idx));
  2467. continue;
  2468. }
  2469. std::optional<ValueIDNum> JoinedOpLoc =
  2470. pickOperandPHILoc(Idx, MBB, LiveOuts, MOutLocs, BlockOrders);
  2471. if (!JoinedOpLoc)
  2472. return false;
  2473. NewDbgOps.push_back(DbgOpStore.insert(*JoinedOpLoc));
  2474. }
  2475. OutValues.append(NewDbgOps);
  2476. return true;
  2477. }
  2478. std::optional<ValueIDNum> InstrRefBasedLDV::pickOperandPHILoc(
  2479. unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
  2480. FuncValueTable &MOutLocs,
  2481. const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
  2482. // Collect a set of locations from predecessor where its live-out value can
  2483. // be found.
  2484. SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
  2485. unsigned NumLocs = MTracker->getNumLocs();
  2486. for (const auto p : BlockOrders) {
  2487. unsigned ThisBBNum = p->getNumber();
  2488. auto OutValIt = LiveOuts.find(p);
  2489. assert(OutValIt != LiveOuts.end());
  2490. const DbgValue &OutVal = *OutValIt->second;
  2491. DbgOpID OutValOpID = OutVal.getDbgOpID(DbgOpIdx);
  2492. DbgOp OutValOp = DbgOpStore.find(OutValOpID);
  2493. assert(!OutValOp.IsConst);
  2494. // Create new empty vector of locations.
  2495. Locs.resize(Locs.size() + 1);
  2496. // If the live-in value is a def, find the locations where that value is
  2497. // present. Do the same for VPHIs where we know the VPHI value.
  2498. if (OutVal.Kind == DbgValue::Def ||
  2499. (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
  2500. !OutValOp.isUndef())) {
  2501. ValueIDNum ValToLookFor = OutValOp.ID;
  2502. // Search the live-outs of the predecessor for the specified value.
  2503. for (unsigned int I = 0; I < NumLocs; ++I) {
  2504. if (MOutLocs[ThisBBNum][I] == ValToLookFor)
  2505. Locs.back().push_back(LocIdx(I));
  2506. }
  2507. } else {
  2508. assert(OutVal.Kind == DbgValue::VPHI);
  2509. // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
  2510. // a value that's live-through the whole loop. (It has to be a backedge,
  2511. // because a block can't dominate itself). We can accept as a PHI location
  2512. // any location where the other predecessors agree, _and_ the machine
  2513. // locations feed back into themselves. Therefore, add all self-looping
  2514. // machine-value PHI locations.
  2515. for (unsigned int I = 0; I < NumLocs; ++I) {
  2516. ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
  2517. if (MOutLocs[ThisBBNum][I] == MPHI)
  2518. Locs.back().push_back(LocIdx(I));
  2519. }
  2520. }
  2521. }
  2522. // We should have found locations for all predecessors, or returned.
  2523. assert(Locs.size() == BlockOrders.size());
  2524. // Starting with the first set of locations, take the intersection with
  2525. // subsequent sets.
  2526. SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
  2527. for (unsigned int I = 1; I < Locs.size(); ++I) {
  2528. auto &LocVec = Locs[I];
  2529. SmallVector<LocIdx, 4> NewCandidates;
  2530. std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
  2531. LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
  2532. CandidateLocs = NewCandidates;
  2533. }
  2534. if (CandidateLocs.empty())
  2535. return std::nullopt;
  2536. // We now have a set of LocIdxes that contain the right output value in
  2537. // each of the predecessors. Pick the lowest; if there's a register loc,
  2538. // that'll be it.
  2539. LocIdx L = *CandidateLocs.begin();
  2540. // Return a PHI-value-number for the found location.
  2541. ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
  2542. return PHIVal;
  2543. }
  2544. bool InstrRefBasedLDV::vlocJoin(
  2545. MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
  2546. SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
  2547. DbgValue &LiveIn) {
  2548. LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
  2549. bool Changed = false;
  2550. // Order predecessors by RPOT order, for exploring them in that order.
  2551. SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
  2552. auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
  2553. return BBToOrder[A] < BBToOrder[B];
  2554. };
  2555. llvm::sort(BlockOrders, Cmp);
  2556. unsigned CurBlockRPONum = BBToOrder[&MBB];
  2557. // Collect all the incoming DbgValues for this variable, from predecessor
  2558. // live-out values.
  2559. SmallVector<InValueT, 8> Values;
  2560. bool Bail = false;
  2561. int BackEdgesStart = 0;
  2562. for (auto *p : BlockOrders) {
  2563. // If the predecessor isn't in scope / to be explored, we'll never be
  2564. // able to join any locations.
  2565. if (!BlocksToExplore.contains(p)) {
  2566. Bail = true;
  2567. break;
  2568. }
  2569. // All Live-outs will have been initialized.
  2570. DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
  2571. // Keep track of where back-edges begin in the Values vector. Relies on
  2572. // BlockOrders being sorted by RPO.
  2573. unsigned ThisBBRPONum = BBToOrder[p];
  2574. if (ThisBBRPONum < CurBlockRPONum)
  2575. ++BackEdgesStart;
  2576. Values.push_back(std::make_pair(p, &OutLoc));
  2577. }
  2578. // If there were no values, or one of the predecessors couldn't have a
  2579. // value, then give up immediately. It's not safe to produce a live-in
  2580. // value. Leave as whatever it was before.
  2581. if (Bail || Values.size() == 0)
  2582. return false;
  2583. // All (non-entry) blocks have at least one non-backedge predecessor.
  2584. // Pick the variable value from the first of these, to compare against
  2585. // all others.
  2586. const DbgValue &FirstVal = *Values[0].second;
  2587. // If the old live-in value is not a PHI then either a) no PHI is needed
  2588. // here, or b) we eliminated the PHI that was here. If so, we can just
  2589. // propagate in the first parent's incoming value.
  2590. if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
  2591. Changed = LiveIn != FirstVal;
  2592. if (Changed)
  2593. LiveIn = FirstVal;
  2594. return Changed;
  2595. }
  2596. // Scan for variable values that can never be resolved: if they have
  2597. // different DIExpressions, different indirectness, or are mixed constants /
  2598. // non-constants.
  2599. for (const auto &V : Values) {
  2600. if (!V.second->Properties.isJoinable(FirstVal.Properties))
  2601. return false;
  2602. if (V.second->Kind == DbgValue::NoVal)
  2603. return false;
  2604. if (!V.second->hasJoinableLocOps(FirstVal))
  2605. return false;
  2606. }
  2607. // Try to eliminate this PHI. Do the incoming values all agree?
  2608. bool Disagree = false;
  2609. for (auto &V : Values) {
  2610. if (*V.second == FirstVal)
  2611. continue; // No disagreement.
  2612. // If both values are not equal but have equal non-empty IDs then they refer
  2613. // to the same value from different sources (e.g. one is VPHI and the other
  2614. // is Def), which does not cause disagreement.
  2615. if (V.second->hasIdenticalValidLocOps(FirstVal))
  2616. continue;
  2617. // Eliminate if a backedge feeds a VPHI back into itself.
  2618. if (V.second->Kind == DbgValue::VPHI &&
  2619. V.second->BlockNo == MBB.getNumber() &&
  2620. // Is this a backedge?
  2621. std::distance(Values.begin(), &V) >= BackEdgesStart)
  2622. continue;
  2623. Disagree = true;
  2624. }
  2625. // No disagreement -> live-through value.
  2626. if (!Disagree) {
  2627. Changed = LiveIn != FirstVal;
  2628. if (Changed)
  2629. LiveIn = FirstVal;
  2630. return Changed;
  2631. } else {
  2632. // Otherwise use a VPHI.
  2633. DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
  2634. Changed = LiveIn != VPHI;
  2635. if (Changed)
  2636. LiveIn = VPHI;
  2637. return Changed;
  2638. }
  2639. }
  2640. void InstrRefBasedLDV::getBlocksForScope(
  2641. const DILocation *DILoc,
  2642. SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
  2643. const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
  2644. // Get the set of "normal" in-lexical-scope blocks.
  2645. LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
  2646. // VarLoc LiveDebugValues tracks variable locations that are defined in
  2647. // blocks not in scope. This is something we could legitimately ignore, but
  2648. // lets allow it for now for the sake of coverage.
  2649. BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
  2650. // Storage for artificial blocks we intend to add to BlocksToExplore.
  2651. DenseSet<const MachineBasicBlock *> ToAdd;
  2652. // To avoid needlessly dropping large volumes of variable locations, propagate
  2653. // variables through aritifical blocks, i.e. those that don't have any
  2654. // instructions in scope at all. To accurately replicate VarLoc
  2655. // LiveDebugValues, this means exploring all artificial successors too.
  2656. // Perform a depth-first-search to enumerate those blocks.
  2657. for (const auto *MBB : BlocksToExplore) {
  2658. // Depth-first-search state: each node is a block and which successor
  2659. // we're currently exploring.
  2660. SmallVector<std::pair<const MachineBasicBlock *,
  2661. MachineBasicBlock::const_succ_iterator>,
  2662. 8>
  2663. DFS;
  2664. // Find any artificial successors not already tracked.
  2665. for (auto *succ : MBB->successors()) {
  2666. if (BlocksToExplore.count(succ))
  2667. continue;
  2668. if (!ArtificialBlocks.count(succ))
  2669. continue;
  2670. ToAdd.insert(succ);
  2671. DFS.push_back({succ, succ->succ_begin()});
  2672. }
  2673. // Search all those blocks, depth first.
  2674. while (!DFS.empty()) {
  2675. const MachineBasicBlock *CurBB = DFS.back().first;
  2676. MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
  2677. // Walk back if we've explored this blocks successors to the end.
  2678. if (CurSucc == CurBB->succ_end()) {
  2679. DFS.pop_back();
  2680. continue;
  2681. }
  2682. // If the current successor is artificial and unexplored, descend into
  2683. // it.
  2684. if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
  2685. ToAdd.insert(*CurSucc);
  2686. DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
  2687. continue;
  2688. }
  2689. ++CurSucc;
  2690. }
  2691. };
  2692. BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
  2693. }
  2694. void InstrRefBasedLDV::buildVLocValueMap(
  2695. const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
  2696. SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
  2697. FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
  2698. SmallVectorImpl<VLocTracker> &AllTheVLocs) {
  2699. // This method is much like buildMLocValueMap: but focuses on a single
  2700. // LexicalScope at a time. Pick out a set of blocks and variables that are
  2701. // to have their value assignments solved, then run our dataflow algorithm
  2702. // until a fixedpoint is reached.
  2703. std::priority_queue<unsigned int, std::vector<unsigned int>,
  2704. std::greater<unsigned int>>
  2705. Worklist, Pending;
  2706. SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
  2707. // The set of blocks we'll be examining.
  2708. SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
  2709. // The order in which to examine them (RPO).
  2710. SmallVector<MachineBasicBlock *, 8> BlockOrders;
  2711. // RPO ordering function.
  2712. auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
  2713. return BBToOrder[A] < BBToOrder[B];
  2714. };
  2715. getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
  2716. // Single block scope: not interesting! No propagation at all. Note that
  2717. // this could probably go above ArtificialBlocks without damage, but
  2718. // that then produces output differences from original-live-debug-values,
  2719. // which propagates from a single block into many artificial ones.
  2720. if (BlocksToExplore.size() == 1)
  2721. return;
  2722. // Convert a const set to a non-const set. LexicalScopes
  2723. // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
  2724. // (Neither of them mutate anything).
  2725. SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
  2726. for (const auto *MBB : BlocksToExplore)
  2727. MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
  2728. // Picks out relevants blocks RPO order and sort them.
  2729. for (const auto *MBB : BlocksToExplore)
  2730. BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
  2731. llvm::sort(BlockOrders, Cmp);
  2732. unsigned NumBlocks = BlockOrders.size();
  2733. // Allocate some vectors for storing the live ins and live outs. Large.
  2734. SmallVector<DbgValue, 32> LiveIns, LiveOuts;
  2735. LiveIns.reserve(NumBlocks);
  2736. LiveOuts.reserve(NumBlocks);
  2737. // Initialize all values to start as NoVals. This signifies "it's live
  2738. // through, but we don't know what it is".
  2739. DbgValueProperties EmptyProperties(EmptyExpr, false, false);
  2740. for (unsigned int I = 0; I < NumBlocks; ++I) {
  2741. DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
  2742. LiveIns.push_back(EmptyDbgValue);
  2743. LiveOuts.push_back(EmptyDbgValue);
  2744. }
  2745. // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
  2746. // vlocJoin.
  2747. LiveIdxT LiveOutIdx, LiveInIdx;
  2748. LiveOutIdx.reserve(NumBlocks);
  2749. LiveInIdx.reserve(NumBlocks);
  2750. for (unsigned I = 0; I < NumBlocks; ++I) {
  2751. LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
  2752. LiveInIdx[BlockOrders[I]] = &LiveIns[I];
  2753. }
  2754. // Loop over each variable and place PHIs for it, then propagate values
  2755. // between blocks. This keeps the locality of working on one lexical scope at
  2756. // at time, but avoids re-processing variable values because some other
  2757. // variable has been assigned.
  2758. for (const auto &Var : VarsWeCareAbout) {
  2759. // Re-initialize live-ins and live-outs, to clear the remains of previous
  2760. // variables live-ins / live-outs.
  2761. for (unsigned int I = 0; I < NumBlocks; ++I) {
  2762. DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
  2763. LiveIns[I] = EmptyDbgValue;
  2764. LiveOuts[I] = EmptyDbgValue;
  2765. }
  2766. // Place PHIs for variable values, using the LLVM IDF calculator.
  2767. // Collect the set of blocks where variables are def'd.
  2768. SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
  2769. for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
  2770. auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
  2771. if (TransferFunc.find(Var) != TransferFunc.end())
  2772. DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
  2773. }
  2774. SmallVector<MachineBasicBlock *, 32> PHIBlocks;
  2775. // Request the set of PHIs we should insert for this variable. If there's
  2776. // only one value definition, things are very simple.
  2777. if (DefBlocks.size() == 1) {
  2778. placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
  2779. AllTheVLocs, Var, Output);
  2780. continue;
  2781. }
  2782. // Otherwise: we need to place PHIs through SSA and propagate values.
  2783. BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
  2784. // Insert PHIs into the per-block live-in tables for this variable.
  2785. for (MachineBasicBlock *PHIMBB : PHIBlocks) {
  2786. unsigned BlockNo = PHIMBB->getNumber();
  2787. DbgValue *LiveIn = LiveInIdx[PHIMBB];
  2788. *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
  2789. }
  2790. for (auto *MBB : BlockOrders) {
  2791. Worklist.push(BBToOrder[MBB]);
  2792. OnWorklist.insert(MBB);
  2793. }
  2794. // Iterate over all the blocks we selected, propagating the variables value.
  2795. // This loop does two things:
  2796. // * Eliminates un-necessary VPHIs in vlocJoin,
  2797. // * Evaluates the blocks transfer function (i.e. variable assignments) and
  2798. // stores the result to the blocks live-outs.
  2799. // Always evaluate the transfer function on the first iteration, and when
  2800. // the live-ins change thereafter.
  2801. bool FirstTrip = true;
  2802. while (!Worklist.empty() || !Pending.empty()) {
  2803. while (!Worklist.empty()) {
  2804. auto *MBB = OrderToBB[Worklist.top()];
  2805. CurBB = MBB->getNumber();
  2806. Worklist.pop();
  2807. auto LiveInsIt = LiveInIdx.find(MBB);
  2808. assert(LiveInsIt != LiveInIdx.end());
  2809. DbgValue *LiveIn = LiveInsIt->second;
  2810. // Join values from predecessors. Updates LiveInIdx, and writes output
  2811. // into JoinedInLocs.
  2812. bool InLocsChanged =
  2813. vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
  2814. SmallVector<const MachineBasicBlock *, 8> Preds;
  2815. for (const auto *Pred : MBB->predecessors())
  2816. Preds.push_back(Pred);
  2817. // If this block's live-in value is a VPHI, try to pick a machine-value
  2818. // for it. This makes the machine-value available and propagated
  2819. // through all blocks by the time value propagation finishes. We can't
  2820. // do this any earlier as it needs to read the block live-outs.
  2821. if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
  2822. // There's a small possibility that on a preceeding path, a VPHI is
  2823. // eliminated and transitions from VPHI-with-location to
  2824. // live-through-value. As a result, the selected location of any VPHI
  2825. // might change, so we need to re-compute it on each iteration.
  2826. SmallVector<DbgOpID> JoinedOps;
  2827. if (pickVPHILoc(JoinedOps, *MBB, LiveOutIdx, MOutLocs, Preds)) {
  2828. bool NewLocPicked = !equal(LiveIn->getDbgOpIDs(), JoinedOps);
  2829. InLocsChanged |= NewLocPicked;
  2830. if (NewLocPicked)
  2831. LiveIn->setDbgOpIDs(JoinedOps);
  2832. }
  2833. }
  2834. if (!InLocsChanged && !FirstTrip)
  2835. continue;
  2836. DbgValue *LiveOut = LiveOutIdx[MBB];
  2837. bool OLChanged = false;
  2838. // Do transfer function.
  2839. auto &VTracker = AllTheVLocs[MBB->getNumber()];
  2840. auto TransferIt = VTracker.Vars.find(Var);
  2841. if (TransferIt != VTracker.Vars.end()) {
  2842. // Erase on empty transfer (DBG_VALUE $noreg).
  2843. if (TransferIt->second.Kind == DbgValue::Undef) {
  2844. DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
  2845. if (*LiveOut != NewVal) {
  2846. *LiveOut = NewVal;
  2847. OLChanged = true;
  2848. }
  2849. } else {
  2850. // Insert new variable value; or overwrite.
  2851. if (*LiveOut != TransferIt->second) {
  2852. *LiveOut = TransferIt->second;
  2853. OLChanged = true;
  2854. }
  2855. }
  2856. } else {
  2857. // Just copy live-ins to live-outs, for anything not transferred.
  2858. if (*LiveOut != *LiveIn) {
  2859. *LiveOut = *LiveIn;
  2860. OLChanged = true;
  2861. }
  2862. }
  2863. // If no live-out value changed, there's no need to explore further.
  2864. if (!OLChanged)
  2865. continue;
  2866. // We should visit all successors. Ensure we'll visit any non-backedge
  2867. // successors during this dataflow iteration; book backedge successors
  2868. // to be visited next time around.
  2869. for (auto *s : MBB->successors()) {
  2870. // Ignore out of scope / not-to-be-explored successors.
  2871. if (LiveInIdx.find(s) == LiveInIdx.end())
  2872. continue;
  2873. if (BBToOrder[s] > BBToOrder[MBB]) {
  2874. if (OnWorklist.insert(s).second)
  2875. Worklist.push(BBToOrder[s]);
  2876. } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
  2877. Pending.push(BBToOrder[s]);
  2878. }
  2879. }
  2880. }
  2881. Worklist.swap(Pending);
  2882. std::swap(OnWorklist, OnPending);
  2883. OnPending.clear();
  2884. assert(Pending.empty());
  2885. FirstTrip = false;
  2886. }
  2887. // Save live-ins to output vector. Ignore any that are still marked as being
  2888. // VPHIs with no location -- those are variables that we know the value of,
  2889. // but are not actually available in the register file.
  2890. for (auto *MBB : BlockOrders) {
  2891. DbgValue *BlockLiveIn = LiveInIdx[MBB];
  2892. if (BlockLiveIn->Kind == DbgValue::NoVal)
  2893. continue;
  2894. if (BlockLiveIn->isUnjoinedPHI())
  2895. continue;
  2896. if (BlockLiveIn->Kind == DbgValue::VPHI)
  2897. BlockLiveIn->Kind = DbgValue::Def;
  2898. assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
  2899. Var.getFragment() && "Fragment info missing during value prop");
  2900. Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
  2901. }
  2902. } // Per-variable loop.
  2903. BlockOrders.clear();
  2904. BlocksToExplore.clear();
  2905. }
  2906. void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
  2907. const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
  2908. MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
  2909. const DebugVariable &Var, LiveInsT &Output) {
  2910. // If there is a single definition of the variable, then working out it's
  2911. // value everywhere is very simple: it's every block dominated by the
  2912. // definition. At the dominance frontier, the usual algorithm would:
  2913. // * Place PHIs,
  2914. // * Propagate values into them,
  2915. // * Find there's no incoming variable value from the other incoming branches
  2916. // of the dominance frontier,
  2917. // * Specify there's no variable value in blocks past the frontier.
  2918. // This is a common case, hence it's worth special-casing it.
  2919. // Pick out the variables value from the block transfer function.
  2920. VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
  2921. auto ValueIt = VLocs.Vars.find(Var);
  2922. const DbgValue &Value = ValueIt->second;
  2923. // If it's an explicit assignment of "undef", that means there is no location
  2924. // anyway, anywhere.
  2925. if (Value.Kind == DbgValue::Undef)
  2926. return;
  2927. // Assign the variable value to entry to each dominated block that's in scope.
  2928. // Skip the definition block -- it's assigned the variable value in the middle
  2929. // of the block somewhere.
  2930. for (auto *ScopeBlock : InScopeBlocks) {
  2931. if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
  2932. continue;
  2933. Output[ScopeBlock->getNumber()].push_back({Var, Value});
  2934. }
  2935. // All blocks that aren't dominated have no live-in value, thus no variable
  2936. // value will be given to them.
  2937. }
  2938. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2939. void InstrRefBasedLDV::dump_mloc_transfer(
  2940. const MLocTransferMap &mloc_transfer) const {
  2941. for (const auto &P : mloc_transfer) {
  2942. std::string foo = MTracker->LocIdxToName(P.first);
  2943. std::string bar = MTracker->IDAsString(P.second);
  2944. dbgs() << "Loc " << foo << " --> " << bar << "\n";
  2945. }
  2946. }
  2947. #endif
  2948. void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
  2949. // Build some useful data structures.
  2950. LLVMContext &Context = MF.getFunction().getContext();
  2951. EmptyExpr = DIExpression::get(Context, {});
  2952. auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
  2953. if (const DebugLoc &DL = MI.getDebugLoc())
  2954. return DL.getLine() != 0;
  2955. return false;
  2956. };
  2957. // Collect a set of all the artificial blocks.
  2958. for (auto &MBB : MF)
  2959. if (none_of(MBB.instrs(), hasNonArtificialLocation))
  2960. ArtificialBlocks.insert(&MBB);
  2961. // Compute mappings of block <=> RPO order.
  2962. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  2963. unsigned int RPONumber = 0;
  2964. auto processMBB = [&](MachineBasicBlock *MBB) {
  2965. OrderToBB[RPONumber] = MBB;
  2966. BBToOrder[MBB] = RPONumber;
  2967. BBNumToRPO[MBB->getNumber()] = RPONumber;
  2968. ++RPONumber;
  2969. };
  2970. for (MachineBasicBlock *MBB : RPOT)
  2971. processMBB(MBB);
  2972. for (MachineBasicBlock &MBB : MF)
  2973. if (BBToOrder.find(&MBB) == BBToOrder.end())
  2974. processMBB(&MBB);
  2975. // Order value substitutions by their "source" operand pair, for quick lookup.
  2976. llvm::sort(MF.DebugValueSubstitutions);
  2977. #ifdef EXPENSIVE_CHECKS
  2978. // As an expensive check, test whether there are any duplicate substitution
  2979. // sources in the collection.
  2980. if (MF.DebugValueSubstitutions.size() > 2) {
  2981. for (auto It = MF.DebugValueSubstitutions.begin();
  2982. It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
  2983. assert(It->Src != std::next(It)->Src && "Duplicate variable location "
  2984. "substitution seen");
  2985. }
  2986. }
  2987. #endif
  2988. }
  2989. // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
  2990. // lexical scope it's used in. When exploring in DFS order and we pass that
  2991. // scope, the block can be processed and any tracking information freed.
  2992. void InstrRefBasedLDV::makeDepthFirstEjectionMap(
  2993. SmallVectorImpl<unsigned> &EjectionMap,
  2994. const ScopeToDILocT &ScopeToDILocation,
  2995. ScopeToAssignBlocksT &ScopeToAssignBlocks) {
  2996. SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
  2997. SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
  2998. auto *TopScope = LS.getCurrentFunctionScope();
  2999. // Unlike lexical scope explorers, we explore in reverse order, to find the
  3000. // "last" lexical scope used for each block early.
  3001. WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
  3002. while (!WorkStack.empty()) {
  3003. auto &ScopePosition = WorkStack.back();
  3004. LexicalScope *WS = ScopePosition.first;
  3005. ssize_t ChildNum = ScopePosition.second--;
  3006. const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
  3007. if (ChildNum >= 0) {
  3008. // If ChildNum is positive, there are remaining children to explore.
  3009. // Push the child and its children-count onto the stack.
  3010. auto &ChildScope = Children[ChildNum];
  3011. WorkStack.push_back(
  3012. std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
  3013. } else {
  3014. WorkStack.pop_back();
  3015. // We've explored all children and any later blocks: examine all blocks
  3016. // in our scope. If they haven't yet had an ejection number set, then
  3017. // this scope will be the last to use that block.
  3018. auto DILocationIt = ScopeToDILocation.find(WS);
  3019. if (DILocationIt != ScopeToDILocation.end()) {
  3020. getBlocksForScope(DILocationIt->second, BlocksToExplore,
  3021. ScopeToAssignBlocks.find(WS)->second);
  3022. for (const auto *MBB : BlocksToExplore) {
  3023. unsigned BBNum = MBB->getNumber();
  3024. if (EjectionMap[BBNum] == 0)
  3025. EjectionMap[BBNum] = WS->getDFSOut();
  3026. }
  3027. BlocksToExplore.clear();
  3028. }
  3029. }
  3030. }
  3031. }
  3032. bool InstrRefBasedLDV::depthFirstVLocAndEmit(
  3033. unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
  3034. const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
  3035. LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
  3036. SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
  3037. DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
  3038. const TargetPassConfig &TPC) {
  3039. TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
  3040. unsigned NumLocs = MTracker->getNumLocs();
  3041. VTracker = nullptr;
  3042. // No scopes? No variable locations.
  3043. if (!LS.getCurrentFunctionScope())
  3044. return false;
  3045. // Build map from block number to the last scope that uses the block.
  3046. SmallVector<unsigned, 16> EjectionMap;
  3047. EjectionMap.resize(MaxNumBlocks, 0);
  3048. makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
  3049. ScopeToAssignBlocks);
  3050. // Helper lambda for ejecting a block -- if nothing is going to use the block,
  3051. // we can translate the variable location information into DBG_VALUEs and then
  3052. // free all of InstrRefBasedLDV's data structures.
  3053. auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
  3054. unsigned BBNum = MBB.getNumber();
  3055. AllTheVLocs[BBNum].clear();
  3056. // Prime the transfer-tracker, and then step through all the block
  3057. // instructions, installing transfers.
  3058. MTracker->reset();
  3059. MTracker->loadFromArray(MInLocs[BBNum], BBNum);
  3060. TTracker->loadInlocs(MBB, MInLocs[BBNum], DbgOpStore, Output[BBNum],
  3061. NumLocs);
  3062. CurBB = BBNum;
  3063. CurInst = 1;
  3064. for (auto &MI : MBB) {
  3065. process(MI, MOutLocs.get(), MInLocs.get());
  3066. TTracker->checkInstForNewValues(CurInst, MI.getIterator());
  3067. ++CurInst;
  3068. }
  3069. // Free machine-location tables for this block.
  3070. MInLocs[BBNum].reset();
  3071. MOutLocs[BBNum].reset();
  3072. // We don't need live-in variable values for this block either.
  3073. Output[BBNum].clear();
  3074. AllTheVLocs[BBNum].clear();
  3075. };
  3076. SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
  3077. SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
  3078. WorkStack.push_back({LS.getCurrentFunctionScope(), 0});
  3079. unsigned HighestDFSIn = 0;
  3080. // Proceed to explore in depth first order.
  3081. while (!WorkStack.empty()) {
  3082. auto &ScopePosition = WorkStack.back();
  3083. LexicalScope *WS = ScopePosition.first;
  3084. ssize_t ChildNum = ScopePosition.second++;
  3085. // We obesrve scopes with children twice here, once descending in, once
  3086. // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
  3087. // we don't process a scope twice. Additionally, ignore scopes that don't
  3088. // have a DILocation -- by proxy, this means we never tracked any variable
  3089. // assignments in that scope.
  3090. auto DILocIt = ScopeToDILocation.find(WS);
  3091. if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
  3092. const DILocation *DILoc = DILocIt->second;
  3093. auto &VarsWeCareAbout = ScopeToVars.find(WS)->second;
  3094. auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second;
  3095. buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs,
  3096. MInLocs, AllTheVLocs);
  3097. }
  3098. HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn());
  3099. // Descend into any scope nests.
  3100. const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
  3101. if (ChildNum < (ssize_t)Children.size()) {
  3102. // There are children to explore -- push onto stack and continue.
  3103. auto &ChildScope = Children[ChildNum];
  3104. WorkStack.push_back(std::make_pair(ChildScope, 0));
  3105. } else {
  3106. WorkStack.pop_back();
  3107. // We've explored a leaf, or have explored all the children of a scope.
  3108. // Try to eject any blocks where this is the last scope it's relevant to.
  3109. auto DILocationIt = ScopeToDILocation.find(WS);
  3110. if (DILocationIt == ScopeToDILocation.end())
  3111. continue;
  3112. getBlocksForScope(DILocationIt->second, BlocksToExplore,
  3113. ScopeToAssignBlocks.find(WS)->second);
  3114. for (const auto *MBB : BlocksToExplore)
  3115. if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
  3116. EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
  3117. BlocksToExplore.clear();
  3118. }
  3119. }
  3120. // Some artificial blocks may not have been ejected, meaning they're not
  3121. // connected to an actual legitimate scope. This can technically happen
  3122. // with things like the entry block. In theory, we shouldn't need to do
  3123. // anything for such out-of-scope blocks, but for the sake of being similar
  3124. // to VarLocBasedLDV, eject these too.
  3125. for (auto *MBB : ArtificialBlocks)
  3126. if (MOutLocs[MBB->getNumber()])
  3127. EjectBlock(*MBB);
  3128. return emitTransfers(AllVarsNumbering);
  3129. }
  3130. bool InstrRefBasedLDV::emitTransfers(
  3131. DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
  3132. // Go through all the transfers recorded in the TransferTracker -- this is
  3133. // both the live-ins to a block, and any movements of values that happen
  3134. // in the middle.
  3135. for (const auto &P : TTracker->Transfers) {
  3136. // We have to insert DBG_VALUEs in a consistent order, otherwise they
  3137. // appear in DWARF in different orders. Use the order that they appear
  3138. // when walking through each block / each instruction, stored in
  3139. // AllVarsNumbering.
  3140. SmallVector<std::pair<unsigned, MachineInstr *>> Insts;
  3141. for (MachineInstr *MI : P.Insts) {
  3142. DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(),
  3143. MI->getDebugLoc()->getInlinedAt());
  3144. Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI);
  3145. }
  3146. llvm::sort(Insts, llvm::less_first());
  3147. // Insert either before or after the designated point...
  3148. if (P.MBB) {
  3149. MachineBasicBlock &MBB = *P.MBB;
  3150. for (const auto &Pair : Insts)
  3151. MBB.insert(P.Pos, Pair.second);
  3152. } else {
  3153. // Terminators, like tail calls, can clobber things. Don't try and place
  3154. // transfers after them.
  3155. if (P.Pos->isTerminator())
  3156. continue;
  3157. MachineBasicBlock &MBB = *P.Pos->getParent();
  3158. for (const auto &Pair : Insts)
  3159. MBB.insertAfterBundle(P.Pos, Pair.second);
  3160. }
  3161. }
  3162. return TTracker->Transfers.size() != 0;
  3163. }
  3164. /// Calculate the liveness information for the given machine function and
  3165. /// extend ranges across basic blocks.
  3166. bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
  3167. MachineDominatorTree *DomTree,
  3168. TargetPassConfig *TPC,
  3169. unsigned InputBBLimit,
  3170. unsigned InputDbgValLimit) {
  3171. // No subprogram means this function contains no debuginfo.
  3172. if (!MF.getFunction().getSubprogram())
  3173. return false;
  3174. LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
  3175. this->TPC = TPC;
  3176. this->DomTree = DomTree;
  3177. TRI = MF.getSubtarget().getRegisterInfo();
  3178. MRI = &MF.getRegInfo();
  3179. TII = MF.getSubtarget().getInstrInfo();
  3180. TFI = MF.getSubtarget().getFrameLowering();
  3181. TFI->getCalleeSaves(MF, CalleeSavedRegs);
  3182. MFI = &MF.getFrameInfo();
  3183. LS.initialize(MF);
  3184. const auto &STI = MF.getSubtarget();
  3185. AdjustsStackInCalls = MFI->adjustsStack() &&
  3186. STI.getFrameLowering()->stackProbeFunctionModifiesSP();
  3187. if (AdjustsStackInCalls)
  3188. StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
  3189. MTracker =
  3190. new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
  3191. VTracker = nullptr;
  3192. TTracker = nullptr;
  3193. SmallVector<MLocTransferMap, 32> MLocTransfer;
  3194. SmallVector<VLocTracker, 8> vlocs;
  3195. LiveInsT SavedLiveIns;
  3196. int MaxNumBlocks = -1;
  3197. for (auto &MBB : MF)
  3198. MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
  3199. assert(MaxNumBlocks >= 0);
  3200. ++MaxNumBlocks;
  3201. initialSetup(MF);
  3202. MLocTransfer.resize(MaxNumBlocks);
  3203. vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr));
  3204. SavedLiveIns.resize(MaxNumBlocks);
  3205. produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
  3206. // Allocate and initialize two array-of-arrays for the live-in and live-out
  3207. // machine values. The outer dimension is the block number; while the inner
  3208. // dimension is a LocIdx from MLocTracker.
  3209. FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
  3210. FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
  3211. unsigned NumLocs = MTracker->getNumLocs();
  3212. for (int i = 0; i < MaxNumBlocks; ++i) {
  3213. // These all auto-initialize to ValueIDNum::EmptyValue
  3214. MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
  3215. MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
  3216. }
  3217. // Solve the machine value dataflow problem using the MLocTransfer function,
  3218. // storing the computed live-ins / live-outs into the array-of-arrays. We use
  3219. // both live-ins and live-outs for decision making in the variable value
  3220. // dataflow problem.
  3221. buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
  3222. // Patch up debug phi numbers, turning unknown block-live-in values into
  3223. // either live-through machine values, or PHIs.
  3224. for (auto &DBG_PHI : DebugPHINumToValue) {
  3225. // Identify unresolved block-live-ins.
  3226. if (!DBG_PHI.ValueRead)
  3227. continue;
  3228. ValueIDNum &Num = *DBG_PHI.ValueRead;
  3229. if (!Num.isPHI())
  3230. continue;
  3231. unsigned BlockNo = Num.getBlock();
  3232. LocIdx LocNo = Num.getLoc();
  3233. Num = MInLocs[BlockNo][LocNo.asU64()];
  3234. }
  3235. // Later, we'll be looking up ranges of instruction numbers.
  3236. llvm::sort(DebugPHINumToValue);
  3237. // Walk back through each block / instruction, collecting DBG_VALUE
  3238. // instructions and recording what machine value their operands refer to.
  3239. for (auto &OrderPair : OrderToBB) {
  3240. MachineBasicBlock &MBB = *OrderPair.second;
  3241. CurBB = MBB.getNumber();
  3242. VTracker = &vlocs[CurBB];
  3243. VTracker->MBB = &MBB;
  3244. MTracker->loadFromArray(MInLocs[CurBB], CurBB);
  3245. CurInst = 1;
  3246. for (auto &MI : MBB) {
  3247. process(MI, MOutLocs.get(), MInLocs.get());
  3248. ++CurInst;
  3249. }
  3250. MTracker->reset();
  3251. }
  3252. // Number all variables in the order that they appear, to be used as a stable
  3253. // insertion order later.
  3254. DenseMap<DebugVariable, unsigned> AllVarsNumbering;
  3255. // Map from one LexicalScope to all the variables in that scope.
  3256. ScopeToVarsT ScopeToVars;
  3257. // Map from One lexical scope to all blocks where assignments happen for
  3258. // that scope.
  3259. ScopeToAssignBlocksT ScopeToAssignBlocks;
  3260. // Store map of DILocations that describes scopes.
  3261. ScopeToDILocT ScopeToDILocation;
  3262. // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
  3263. // the order is unimportant, it just has to be stable.
  3264. unsigned VarAssignCount = 0;
  3265. for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
  3266. auto *MBB = OrderToBB[I];
  3267. auto *VTracker = &vlocs[MBB->getNumber()];
  3268. // Collect each variable with a DBG_VALUE in this block.
  3269. for (auto &idx : VTracker->Vars) {
  3270. const auto &Var = idx.first;
  3271. const DILocation *ScopeLoc = VTracker->Scopes[Var];
  3272. assert(ScopeLoc != nullptr);
  3273. auto *Scope = LS.findLexicalScope(ScopeLoc);
  3274. // No insts in scope -> shouldn't have been recorded.
  3275. assert(Scope != nullptr);
  3276. AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
  3277. ScopeToVars[Scope].insert(Var);
  3278. ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
  3279. ScopeToDILocation[Scope] = ScopeLoc;
  3280. ++VarAssignCount;
  3281. }
  3282. }
  3283. bool Changed = false;
  3284. // If we have an extremely large number of variable assignments and blocks,
  3285. // bail out at this point. We've burnt some time doing analysis already,
  3286. // however we should cut our losses.
  3287. if ((unsigned)MaxNumBlocks > InputBBLimit &&
  3288. VarAssignCount > InputDbgValLimit) {
  3289. LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
  3290. << " has " << MaxNumBlocks << " basic blocks and "
  3291. << VarAssignCount
  3292. << " variable assignments, exceeding limits.\n");
  3293. } else {
  3294. // Optionally, solve the variable value problem and emit to blocks by using
  3295. // a lexical-scope-depth search. It should be functionally identical to
  3296. // the "else" block of this condition.
  3297. Changed = depthFirstVLocAndEmit(
  3298. MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
  3299. SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC);
  3300. }
  3301. delete MTracker;
  3302. delete TTracker;
  3303. MTracker = nullptr;
  3304. VTracker = nullptr;
  3305. TTracker = nullptr;
  3306. ArtificialBlocks.clear();
  3307. OrderToBB.clear();
  3308. BBToOrder.clear();
  3309. BBNumToRPO.clear();
  3310. DebugInstrNumToInstr.clear();
  3311. DebugPHINumToValue.clear();
  3312. OverlapFragments.clear();
  3313. SeenFragments.clear();
  3314. SeenDbgPHIs.clear();
  3315. DbgOpStore.clear();
  3316. return Changed;
  3317. }
  3318. LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
  3319. return new InstrRefBasedLDV();
  3320. }
  3321. namespace {
  3322. class LDVSSABlock;
  3323. class LDVSSAUpdater;
  3324. // Pick a type to identify incoming block values as we construct SSA. We
  3325. // can't use anything more robust than an integer unfortunately, as SSAUpdater
  3326. // expects to zero-initialize the type.
  3327. typedef uint64_t BlockValueNum;
  3328. /// Represents an SSA PHI node for the SSA updater class. Contains the block
  3329. /// this PHI is in, the value number it would have, and the expected incoming
  3330. /// values from parent blocks.
  3331. class LDVSSAPhi {
  3332. public:
  3333. SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
  3334. LDVSSABlock *ParentBlock;
  3335. BlockValueNum PHIValNum;
  3336. LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
  3337. : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
  3338. LDVSSABlock *getParent() { return ParentBlock; }
  3339. };
  3340. /// Thin wrapper around a block predecessor iterator. Only difference from a
  3341. /// normal block iterator is that it dereferences to an LDVSSABlock.
  3342. class LDVSSABlockIterator {
  3343. public:
  3344. MachineBasicBlock::pred_iterator PredIt;
  3345. LDVSSAUpdater &Updater;
  3346. LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
  3347. LDVSSAUpdater &Updater)
  3348. : PredIt(PredIt), Updater(Updater) {}
  3349. bool operator!=(const LDVSSABlockIterator &OtherIt) const {
  3350. return OtherIt.PredIt != PredIt;
  3351. }
  3352. LDVSSABlockIterator &operator++() {
  3353. ++PredIt;
  3354. return *this;
  3355. }
  3356. LDVSSABlock *operator*();
  3357. };
  3358. /// Thin wrapper around a block for SSA Updater interface. Necessary because
  3359. /// we need to track the PHI value(s) that we may have observed as necessary
  3360. /// in this block.
  3361. class LDVSSABlock {
  3362. public:
  3363. MachineBasicBlock &BB;
  3364. LDVSSAUpdater &Updater;
  3365. using PHIListT = SmallVector<LDVSSAPhi, 1>;
  3366. /// List of PHIs in this block. There should only ever be one.
  3367. PHIListT PHIList;
  3368. LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
  3369. : BB(BB), Updater(Updater) {}
  3370. LDVSSABlockIterator succ_begin() {
  3371. return LDVSSABlockIterator(BB.succ_begin(), Updater);
  3372. }
  3373. LDVSSABlockIterator succ_end() {
  3374. return LDVSSABlockIterator(BB.succ_end(), Updater);
  3375. }
  3376. /// SSAUpdater has requested a PHI: create that within this block record.
  3377. LDVSSAPhi *newPHI(BlockValueNum Value) {
  3378. PHIList.emplace_back(Value, this);
  3379. return &PHIList.back();
  3380. }
  3381. /// SSAUpdater wishes to know what PHIs already exist in this block.
  3382. PHIListT &phis() { return PHIList; }
  3383. };
  3384. /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
  3385. /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
  3386. // SSAUpdaterTraits<LDVSSAUpdater>.
  3387. class LDVSSAUpdater {
  3388. public:
  3389. /// Map of value numbers to PHI records.
  3390. DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
  3391. /// Map of which blocks generate Undef values -- blocks that are not
  3392. /// dominated by any Def.
  3393. DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
  3394. /// Map of machine blocks to our own records of them.
  3395. DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
  3396. /// Machine location where any PHI must occur.
  3397. LocIdx Loc;
  3398. /// Table of live-in machine value numbers for blocks / locations.
  3399. const ValueTable *MLiveIns;
  3400. LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns)
  3401. : Loc(L), MLiveIns(MLiveIns) {}
  3402. void reset() {
  3403. for (auto &Block : BlockMap)
  3404. delete Block.second;
  3405. PHIs.clear();
  3406. UndefMap.clear();
  3407. BlockMap.clear();
  3408. }
  3409. ~LDVSSAUpdater() { reset(); }
  3410. /// For a given MBB, create a wrapper block for it. Stores it in the
  3411. /// LDVSSAUpdater block map.
  3412. LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
  3413. auto it = BlockMap.find(BB);
  3414. if (it == BlockMap.end()) {
  3415. BlockMap[BB] = new LDVSSABlock(*BB, *this);
  3416. it = BlockMap.find(BB);
  3417. }
  3418. return it->second;
  3419. }
  3420. /// Find the live-in value number for the given block. Looks up the value at
  3421. /// the PHI location on entry.
  3422. BlockValueNum getValue(LDVSSABlock *LDVBB) {
  3423. return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
  3424. }
  3425. };
  3426. LDVSSABlock *LDVSSABlockIterator::operator*() {
  3427. return Updater.getSSALDVBlock(*PredIt);
  3428. }
  3429. #ifndef NDEBUG
  3430. raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
  3431. out << "SSALDVPHI " << PHI.PHIValNum;
  3432. return out;
  3433. }
  3434. #endif
  3435. } // namespace
  3436. namespace llvm {
  3437. /// Template specialization to give SSAUpdater access to CFG and value
  3438. /// information. SSAUpdater calls methods in these traits, passing in the
  3439. /// LDVSSAUpdater object, to learn about blocks and the values they define.
  3440. /// It also provides methods to create PHI nodes and track them.
  3441. template <> class SSAUpdaterTraits<LDVSSAUpdater> {
  3442. public:
  3443. using BlkT = LDVSSABlock;
  3444. using ValT = BlockValueNum;
  3445. using PhiT = LDVSSAPhi;
  3446. using BlkSucc_iterator = LDVSSABlockIterator;
  3447. // Methods to access block successors -- dereferencing to our wrapper class.
  3448. static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
  3449. static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
  3450. /// Iterator for PHI operands.
  3451. class PHI_iterator {
  3452. private:
  3453. LDVSSAPhi *PHI;
  3454. unsigned Idx;
  3455. public:
  3456. explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
  3457. : PHI(P), Idx(0) {}
  3458. PHI_iterator(LDVSSAPhi *P, bool) // end iterator
  3459. : PHI(P), Idx(PHI->IncomingValues.size()) {}
  3460. PHI_iterator &operator++() {
  3461. Idx++;
  3462. return *this;
  3463. }
  3464. bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
  3465. bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
  3466. BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
  3467. LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
  3468. };
  3469. static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
  3470. static inline PHI_iterator PHI_end(PhiT *PHI) {
  3471. return PHI_iterator(PHI, true);
  3472. }
  3473. /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
  3474. /// vector.
  3475. static void FindPredecessorBlocks(LDVSSABlock *BB,
  3476. SmallVectorImpl<LDVSSABlock *> *Preds) {
  3477. for (MachineBasicBlock *Pred : BB->BB.predecessors())
  3478. Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
  3479. }
  3480. /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
  3481. /// register. For LiveDebugValues, represents a block identified as not having
  3482. /// any DBG_PHI predecessors.
  3483. static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
  3484. // Create a value number for this block -- it needs to be unique and in the
  3485. // "undef" collection, so that we know it's not real. Use a number
  3486. // representing a PHI into this block.
  3487. BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
  3488. Updater->UndefMap[&BB->BB] = Num;
  3489. return Num;
  3490. }
  3491. /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
  3492. /// SSAUpdater will populate it with information about incoming values. The
  3493. /// value number of this PHI is whatever the machine value number problem
  3494. /// solution determined it to be. This includes non-phi values if SSAUpdater
  3495. /// tries to create a PHI where the incoming values are identical.
  3496. static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
  3497. LDVSSAUpdater *Updater) {
  3498. BlockValueNum PHIValNum = Updater->getValue(BB);
  3499. LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
  3500. Updater->PHIs[PHIValNum] = PHI;
  3501. return PHIValNum;
  3502. }
  3503. /// AddPHIOperand - Add the specified value as an operand of the PHI for
  3504. /// the specified predecessor block.
  3505. static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
  3506. PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
  3507. }
  3508. /// ValueIsPHI - Check if the instruction that defines the specified value
  3509. /// is a PHI instruction.
  3510. static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
  3511. auto PHIIt = Updater->PHIs.find(Val);
  3512. if (PHIIt == Updater->PHIs.end())
  3513. return nullptr;
  3514. return PHIIt->second;
  3515. }
  3516. /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
  3517. /// operands, i.e., it was just added.
  3518. static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
  3519. LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
  3520. if (PHI && PHI->IncomingValues.size() == 0)
  3521. return PHI;
  3522. return nullptr;
  3523. }
  3524. /// GetPHIValue - For the specified PHI instruction, return the value
  3525. /// that it defines.
  3526. static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
  3527. };
  3528. } // end namespace llvm
  3529. std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
  3530. MachineFunction &MF, const ValueTable *MLiveOuts,
  3531. const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
  3532. assert(MLiveOuts && MLiveIns &&
  3533. "Tried to resolve DBG_PHI before location "
  3534. "tables allocated?");
  3535. // This function will be called twice per DBG_INSTR_REF, and might end up
  3536. // computing lots of SSA information: memoize it.
  3537. auto SeenDbgPHIIt = SeenDbgPHIs.find(std::make_pair(&Here, InstrNum));
  3538. if (SeenDbgPHIIt != SeenDbgPHIs.end())
  3539. return SeenDbgPHIIt->second;
  3540. std::optional<ValueIDNum> Result =
  3541. resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
  3542. SeenDbgPHIs.insert({std::make_pair(&Here, InstrNum), Result});
  3543. return Result;
  3544. }
  3545. std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
  3546. MachineFunction &MF, const ValueTable *MLiveOuts,
  3547. const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
  3548. // Pick out records of DBG_PHI instructions that have been observed. If there
  3549. // are none, then we cannot compute a value number.
  3550. auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
  3551. DebugPHINumToValue.end(), InstrNum);
  3552. auto LowerIt = RangePair.first;
  3553. auto UpperIt = RangePair.second;
  3554. // No DBG_PHI means there can be no location.
  3555. if (LowerIt == UpperIt)
  3556. return std::nullopt;
  3557. // If any DBG_PHIs referred to a location we didn't understand, don't try to
  3558. // compute a value. There might be scenarios where we could recover a value
  3559. // for some range of DBG_INSTR_REFs, but at this point we can have high
  3560. // confidence that we've seen a bug.
  3561. auto DBGPHIRange = make_range(LowerIt, UpperIt);
  3562. for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
  3563. if (!DBG_PHI.ValueRead)
  3564. return std::nullopt;
  3565. // If there's only one DBG_PHI, then that is our value number.
  3566. if (std::distance(LowerIt, UpperIt) == 1)
  3567. return *LowerIt->ValueRead;
  3568. // Pick out the location (physreg, slot) where any PHIs must occur. It's
  3569. // technically possible for us to merge values in different registers in each
  3570. // block, but highly unlikely that LLVM will generate such code after register
  3571. // allocation.
  3572. LocIdx Loc = *LowerIt->ReadLoc;
  3573. // We have several DBG_PHIs, and a use position (the Here inst). All each
  3574. // DBG_PHI does is identify a value at a program position. We can treat each
  3575. // DBG_PHI like it's a Def of a value, and the use position is a Use of a
  3576. // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
  3577. // determine which Def is used at the Use, and any PHIs that happen along
  3578. // the way.
  3579. // Adapted LLVM SSA Updater:
  3580. LDVSSAUpdater Updater(Loc, MLiveIns);
  3581. // Map of which Def or PHI is the current value in each block.
  3582. DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
  3583. // Set of PHIs that we have created along the way.
  3584. SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
  3585. // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
  3586. // for the SSAUpdater.
  3587. for (const auto &DBG_PHI : DBGPHIRange) {
  3588. LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
  3589. const ValueIDNum &Num = *DBG_PHI.ValueRead;
  3590. AvailableValues.insert(std::make_pair(Block, Num.asU64()));
  3591. }
  3592. LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
  3593. const auto &AvailIt = AvailableValues.find(HereBlock);
  3594. if (AvailIt != AvailableValues.end()) {
  3595. // Actually, we already know what the value is -- the Use is in the same
  3596. // block as the Def.
  3597. return ValueIDNum::fromU64(AvailIt->second);
  3598. }
  3599. // Otherwise, we must use the SSA Updater. It will identify the value number
  3600. // that we are to use, and the PHIs that must happen along the way.
  3601. SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
  3602. BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
  3603. ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
  3604. // We have the number for a PHI, or possibly live-through value, to be used
  3605. // at this Use. There are a number of things we have to check about it though:
  3606. // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
  3607. // Use was not completely dominated by DBG_PHIs and we should abort.
  3608. // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
  3609. // we've left SSA form. Validate that the inputs to each PHI are the
  3610. // expected values.
  3611. // * Is a PHI we've created actually a merging of values, or are all the
  3612. // predecessor values the same, leading to a non-PHI machine value number?
  3613. // (SSAUpdater doesn't know that either). Remap validated PHIs into the
  3614. // the ValidatedValues collection below to sort this out.
  3615. DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
  3616. // Define all the input DBG_PHI values in ValidatedValues.
  3617. for (const auto &DBG_PHI : DBGPHIRange) {
  3618. LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
  3619. const ValueIDNum &Num = *DBG_PHI.ValueRead;
  3620. ValidatedValues.insert(std::make_pair(Block, Num));
  3621. }
  3622. // Sort PHIs to validate into RPO-order.
  3623. SmallVector<LDVSSAPhi *, 8> SortedPHIs;
  3624. for (auto &PHI : CreatedPHIs)
  3625. SortedPHIs.push_back(PHI);
  3626. llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) {
  3627. return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
  3628. });
  3629. for (auto &PHI : SortedPHIs) {
  3630. ValueIDNum ThisBlockValueNum =
  3631. MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
  3632. // Are all these things actually defined?
  3633. for (auto &PHIIt : PHI->IncomingValues) {
  3634. // Any undef input means DBG_PHIs didn't dominate the use point.
  3635. if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
  3636. return std::nullopt;
  3637. ValueIDNum ValueToCheck;
  3638. const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
  3639. auto VVal = ValidatedValues.find(PHIIt.first);
  3640. if (VVal == ValidatedValues.end()) {
  3641. // We cross a loop, and this is a backedge. LLVMs tail duplication
  3642. // happens so late that DBG_PHI instructions should not be able to
  3643. // migrate into loops -- meaning we can only be live-through this
  3644. // loop.
  3645. ValueToCheck = ThisBlockValueNum;
  3646. } else {
  3647. // Does the block have as a live-out, in the location we're examining,
  3648. // the value that we expect? If not, it's been moved or clobbered.
  3649. ValueToCheck = VVal->second;
  3650. }
  3651. if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
  3652. return std::nullopt;
  3653. }
  3654. // Record this value as validated.
  3655. ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
  3656. }
  3657. // All the PHIs are valid: we can return what the SSAUpdater said our value
  3658. // number was.
  3659. return Result;
  3660. }