NewGVN.cpp 171 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281
  1. //===- NewGVN.cpp - Global Value Numbering Pass ---------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file
  10. /// This file implements the new LLVM's Global Value Numbering pass.
  11. /// GVN partitions values computed by a function into congruence classes.
  12. /// Values ending up in the same congruence class are guaranteed to be the same
  13. /// for every execution of the program. In that respect, congruency is a
  14. /// compile-time approximation of equivalence of values at runtime.
  15. /// The algorithm implemented here uses a sparse formulation and it's based
  16. /// on the ideas described in the paper:
  17. /// "A Sparse Algorithm for Predicated Global Value Numbering" from
  18. /// Karthik Gargi.
  19. ///
  20. /// A brief overview of the algorithm: The algorithm is essentially the same as
  21. /// the standard RPO value numbering algorithm (a good reference is the paper
  22. /// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
  23. /// The RPO algorithm proceeds, on every iteration, to process every reachable
  24. /// block and every instruction in that block. This is because the standard RPO
  25. /// algorithm does not track what things have the same value number, it only
  26. /// tracks what the value number of a given operation is (the mapping is
  27. /// operation -> value number). Thus, when a value number of an operation
  28. /// changes, it must reprocess everything to ensure all uses of a value number
  29. /// get updated properly. In constrast, the sparse algorithm we use *also*
  30. /// tracks what operations have a given value number (IE it also tracks the
  31. /// reverse mapping from value number -> operations with that value number), so
  32. /// that it only needs to reprocess the instructions that are affected when
  33. /// something's value number changes. The vast majority of complexity and code
  34. /// in this file is devoted to tracking what value numbers could change for what
  35. /// instructions when various things happen. The rest of the algorithm is
  36. /// devoted to performing symbolic evaluation, forward propagation, and
  37. /// simplification of operations based on the value numbers deduced so far
  38. ///
  39. /// In order to make the GVN mostly-complete, we use a technique derived from
  40. /// "Detection of Redundant Expressions: A Complete and Polynomial-time
  41. /// Algorithm in SSA" by R.R. Pai. The source of incompleteness in most SSA
  42. /// based GVN algorithms is related to their inability to detect equivalence
  43. /// between phi of ops (IE phi(a+b, c+d)) and op of phis (phi(a,c) + phi(b, d)).
  44. /// We resolve this issue by generating the equivalent "phi of ops" form for
  45. /// each op of phis we see, in a way that only takes polynomial time to resolve.
  46. ///
  47. /// We also do not perform elimination by using any published algorithm. All
  48. /// published algorithms are O(Instructions). Instead, we use a technique that
  49. /// is O(number of operations with the same value number), enabling us to skip
  50. /// trying to eliminate things that have unique value numbers.
  51. //
  52. //===----------------------------------------------------------------------===//
  53. #include "llvm/Transforms/Scalar/NewGVN.h"
  54. #include "llvm/ADT/ArrayRef.h"
  55. #include "llvm/ADT/BitVector.h"
  56. #include "llvm/ADT/DenseMap.h"
  57. #include "llvm/ADT/DenseMapInfo.h"
  58. #include "llvm/ADT/DenseSet.h"
  59. #include "llvm/ADT/DepthFirstIterator.h"
  60. #include "llvm/ADT/GraphTraits.h"
  61. #include "llvm/ADT/Hashing.h"
  62. #include "llvm/ADT/PointerIntPair.h"
  63. #include "llvm/ADT/PostOrderIterator.h"
  64. #include "llvm/ADT/SetOperations.h"
  65. #include "llvm/ADT/SmallPtrSet.h"
  66. #include "llvm/ADT/SmallVector.h"
  67. #include "llvm/ADT/SparseBitVector.h"
  68. #include "llvm/ADT/Statistic.h"
  69. #include "llvm/ADT/iterator_range.h"
  70. #include "llvm/Analysis/AliasAnalysis.h"
  71. #include "llvm/Analysis/AssumptionCache.h"
  72. #include "llvm/Analysis/CFGPrinter.h"
  73. #include "llvm/Analysis/ConstantFolding.h"
  74. #include "llvm/Analysis/GlobalsModRef.h"
  75. #include "llvm/Analysis/InstructionSimplify.h"
  76. #include "llvm/Analysis/MemoryBuiltins.h"
  77. #include "llvm/Analysis/MemorySSA.h"
  78. #include "llvm/Analysis/TargetLibraryInfo.h"
  79. #include "llvm/Analysis/ValueTracking.h"
  80. #include "llvm/IR/Argument.h"
  81. #include "llvm/IR/BasicBlock.h"
  82. #include "llvm/IR/Constant.h"
  83. #include "llvm/IR/Constants.h"
  84. #include "llvm/IR/Dominators.h"
  85. #include "llvm/IR/Function.h"
  86. #include "llvm/IR/InstrTypes.h"
  87. #include "llvm/IR/Instruction.h"
  88. #include "llvm/IR/Instructions.h"
  89. #include "llvm/IR/IntrinsicInst.h"
  90. #include "llvm/IR/Intrinsics.h"
  91. #include "llvm/IR/LLVMContext.h"
  92. #include "llvm/IR/PatternMatch.h"
  93. #include "llvm/IR/Type.h"
  94. #include "llvm/IR/Use.h"
  95. #include "llvm/IR/User.h"
  96. #include "llvm/IR/Value.h"
  97. #include "llvm/InitializePasses.h"
  98. #include "llvm/Pass.h"
  99. #include "llvm/Support/Allocator.h"
  100. #include "llvm/Support/ArrayRecycler.h"
  101. #include "llvm/Support/Casting.h"
  102. #include "llvm/Support/CommandLine.h"
  103. #include "llvm/Support/Debug.h"
  104. #include "llvm/Support/DebugCounter.h"
  105. #include "llvm/Support/ErrorHandling.h"
  106. #include "llvm/Support/PointerLikeTypeTraits.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include "llvm/Transforms/Scalar.h"
  109. #include "llvm/Transforms/Scalar/GVNExpression.h"
  110. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  111. #include "llvm/Transforms/Utils/Local.h"
  112. #include "llvm/Transforms/Utils/PredicateInfo.h"
  113. #include "llvm/Transforms/Utils/VNCoercion.h"
  114. #include <algorithm>
  115. #include <cassert>
  116. #include <cstdint>
  117. #include <iterator>
  118. #include <map>
  119. #include <memory>
  120. #include <set>
  121. #include <string>
  122. #include <tuple>
  123. #include <utility>
  124. #include <vector>
  125. using namespace llvm;
  126. using namespace llvm::GVNExpression;
  127. using namespace llvm::VNCoercion;
  128. using namespace llvm::PatternMatch;
  129. #define DEBUG_TYPE "newgvn"
  130. STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
  131. STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
  132. STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
  133. STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
  134. STATISTIC(NumGVNMaxIterations,
  135. "Maximum Number of iterations it took to converge GVN");
  136. STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
  137. STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
  138. STATISTIC(NumGVNAvoidedSortedLeaderChanges,
  139. "Number of avoided sorted leader changes");
  140. STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
  141. STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
  142. STATISTIC(NumGVNPHIOfOpsEliminations,
  143. "Number of things eliminated using PHI of ops");
  144. DEBUG_COUNTER(VNCounter, "newgvn-vn",
  145. "Controls which instructions are value numbered");
  146. DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
  147. "Controls which instructions we create phi of ops for");
  148. // Currently store defining access refinement is too slow due to basicaa being
  149. // egregiously slow. This flag lets us keep it working while we work on this
  150. // issue.
  151. static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
  152. cl::init(false), cl::Hidden);
  153. /// Currently, the generation "phi of ops" can result in correctness issues.
  154. static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(true),
  155. cl::Hidden);
  156. //===----------------------------------------------------------------------===//
  157. // GVN Pass
  158. //===----------------------------------------------------------------------===//
  159. // Anchor methods.
  160. namespace llvm {
  161. namespace GVNExpression {
  162. Expression::~Expression() = default;
  163. BasicExpression::~BasicExpression() = default;
  164. CallExpression::~CallExpression() = default;
  165. LoadExpression::~LoadExpression() = default;
  166. StoreExpression::~StoreExpression() = default;
  167. AggregateValueExpression::~AggregateValueExpression() = default;
  168. PHIExpression::~PHIExpression() = default;
  169. } // end namespace GVNExpression
  170. } // end namespace llvm
  171. namespace {
  172. // Tarjan's SCC finding algorithm with Nuutila's improvements
  173. // SCCIterator is actually fairly complex for the simple thing we want.
  174. // It also wants to hand us SCC's that are unrelated to the phi node we ask
  175. // about, and have us process them there or risk redoing work.
  176. // Graph traits over a filter iterator also doesn't work that well here.
  177. // This SCC finder is specialized to walk use-def chains, and only follows
  178. // instructions,
  179. // not generic values (arguments, etc).
  180. struct TarjanSCC {
  181. TarjanSCC() : Components(1) {}
  182. void Start(const Instruction *Start) {
  183. if (Root.lookup(Start) == 0)
  184. FindSCC(Start);
  185. }
  186. const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
  187. unsigned ComponentID = ValueToComponent.lookup(V);
  188. assert(ComponentID > 0 &&
  189. "Asking for a component for a value we never processed");
  190. return Components[ComponentID];
  191. }
  192. private:
  193. void FindSCC(const Instruction *I) {
  194. Root[I] = ++DFSNum;
  195. // Store the DFS Number we had before it possibly gets incremented.
  196. unsigned int OurDFS = DFSNum;
  197. for (auto &Op : I->operands()) {
  198. if (auto *InstOp = dyn_cast<Instruction>(Op)) {
  199. if (Root.lookup(Op) == 0)
  200. FindSCC(InstOp);
  201. if (!InComponent.count(Op))
  202. Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
  203. }
  204. }
  205. // See if we really were the root of a component, by seeing if we still have
  206. // our DFSNumber. If we do, we are the root of the component, and we have
  207. // completed a component. If we do not, we are not the root of a component,
  208. // and belong on the component stack.
  209. if (Root.lookup(I) == OurDFS) {
  210. unsigned ComponentID = Components.size();
  211. Components.resize(Components.size() + 1);
  212. auto &Component = Components.back();
  213. Component.insert(I);
  214. LLVM_DEBUG(dbgs() << "Component root is " << *I << "\n");
  215. InComponent.insert(I);
  216. ValueToComponent[I] = ComponentID;
  217. // Pop a component off the stack and label it.
  218. while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
  219. auto *Member = Stack.back();
  220. LLVM_DEBUG(dbgs() << "Component member is " << *Member << "\n");
  221. Component.insert(Member);
  222. InComponent.insert(Member);
  223. ValueToComponent[Member] = ComponentID;
  224. Stack.pop_back();
  225. }
  226. } else {
  227. // Part of a component, push to stack
  228. Stack.push_back(I);
  229. }
  230. }
  231. unsigned int DFSNum = 1;
  232. SmallPtrSet<const Value *, 8> InComponent;
  233. DenseMap<const Value *, unsigned int> Root;
  234. SmallVector<const Value *, 8> Stack;
  235. // Store the components as vector of ptr sets, because we need the topo order
  236. // of SCC's, but not individual member order
  237. SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
  238. DenseMap<const Value *, unsigned> ValueToComponent;
  239. };
  240. // Congruence classes represent the set of expressions/instructions
  241. // that are all the same *during some scope in the function*.
  242. // That is, because of the way we perform equality propagation, and
  243. // because of memory value numbering, it is not correct to assume
  244. // you can willy-nilly replace any member with any other at any
  245. // point in the function.
  246. //
  247. // For any Value in the Member set, it is valid to replace any dominated member
  248. // with that Value.
  249. //
  250. // Every congruence class has a leader, and the leader is used to symbolize
  251. // instructions in a canonical way (IE every operand of an instruction that is a
  252. // member of the same congruence class will always be replaced with leader
  253. // during symbolization). To simplify symbolization, we keep the leader as a
  254. // constant if class can be proved to be a constant value. Otherwise, the
  255. // leader is the member of the value set with the smallest DFS number. Each
  256. // congruence class also has a defining expression, though the expression may be
  257. // null. If it exists, it can be used for forward propagation and reassociation
  258. // of values.
  259. // For memory, we also track a representative MemoryAccess, and a set of memory
  260. // members for MemoryPhis (which have no real instructions). Note that for
  261. // memory, it seems tempting to try to split the memory members into a
  262. // MemoryCongruenceClass or something. Unfortunately, this does not work
  263. // easily. The value numbering of a given memory expression depends on the
  264. // leader of the memory congruence class, and the leader of memory congruence
  265. // class depends on the value numbering of a given memory expression. This
  266. // leads to wasted propagation, and in some cases, missed optimization. For
  267. // example: If we had value numbered two stores together before, but now do not,
  268. // we move them to a new value congruence class. This in turn will move at one
  269. // of the memorydefs to a new memory congruence class. Which in turn, affects
  270. // the value numbering of the stores we just value numbered (because the memory
  271. // congruence class is part of the value number). So while theoretically
  272. // possible to split them up, it turns out to be *incredibly* complicated to get
  273. // it to work right, because of the interdependency. While structurally
  274. // slightly messier, it is algorithmically much simpler and faster to do what we
  275. // do here, and track them both at once in the same class.
  276. // Note: The default iterators for this class iterate over values
  277. class CongruenceClass {
  278. public:
  279. using MemberType = Value;
  280. using MemberSet = SmallPtrSet<MemberType *, 4>;
  281. using MemoryMemberType = MemoryPhi;
  282. using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
  283. explicit CongruenceClass(unsigned ID) : ID(ID) {}
  284. CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
  285. : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
  286. unsigned getID() const { return ID; }
  287. // True if this class has no members left. This is mainly used for assertion
  288. // purposes, and for skipping empty classes.
  289. bool isDead() const {
  290. // If it's both dead from a value perspective, and dead from a memory
  291. // perspective, it's really dead.
  292. return empty() && memory_empty();
  293. }
  294. // Leader functions
  295. Value *getLeader() const { return RepLeader; }
  296. void setLeader(Value *Leader) { RepLeader = Leader; }
  297. const std::pair<Value *, unsigned int> &getNextLeader() const {
  298. return NextLeader;
  299. }
  300. void resetNextLeader() { NextLeader = {nullptr, ~0}; }
  301. void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
  302. if (LeaderPair.second < NextLeader.second)
  303. NextLeader = LeaderPair;
  304. }
  305. Value *getStoredValue() const { return RepStoredValue; }
  306. void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
  307. const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
  308. void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
  309. // Forward propagation info
  310. const Expression *getDefiningExpr() const { return DefiningExpr; }
  311. // Value member set
  312. bool empty() const { return Members.empty(); }
  313. unsigned size() const { return Members.size(); }
  314. MemberSet::const_iterator begin() const { return Members.begin(); }
  315. MemberSet::const_iterator end() const { return Members.end(); }
  316. void insert(MemberType *M) { Members.insert(M); }
  317. void erase(MemberType *M) { Members.erase(M); }
  318. void swap(MemberSet &Other) { Members.swap(Other); }
  319. // Memory member set
  320. bool memory_empty() const { return MemoryMembers.empty(); }
  321. unsigned memory_size() const { return MemoryMembers.size(); }
  322. MemoryMemberSet::const_iterator memory_begin() const {
  323. return MemoryMembers.begin();
  324. }
  325. MemoryMemberSet::const_iterator memory_end() const {
  326. return MemoryMembers.end();
  327. }
  328. iterator_range<MemoryMemberSet::const_iterator> memory() const {
  329. return make_range(memory_begin(), memory_end());
  330. }
  331. void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
  332. void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
  333. // Store count
  334. unsigned getStoreCount() const { return StoreCount; }
  335. void incStoreCount() { ++StoreCount; }
  336. void decStoreCount() {
  337. assert(StoreCount != 0 && "Store count went negative");
  338. --StoreCount;
  339. }
  340. // True if this class has no memory members.
  341. bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
  342. // Return true if two congruence classes are equivalent to each other. This
  343. // means that every field but the ID number and the dead field are equivalent.
  344. bool isEquivalentTo(const CongruenceClass *Other) const {
  345. if (!Other)
  346. return false;
  347. if (this == Other)
  348. return true;
  349. if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
  350. std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
  351. Other->RepMemoryAccess))
  352. return false;
  353. if (DefiningExpr != Other->DefiningExpr)
  354. if (!DefiningExpr || !Other->DefiningExpr ||
  355. *DefiningExpr != *Other->DefiningExpr)
  356. return false;
  357. if (Members.size() != Other->Members.size())
  358. return false;
  359. return llvm::set_is_subset(Members, Other->Members);
  360. }
  361. private:
  362. unsigned ID;
  363. // Representative leader.
  364. Value *RepLeader = nullptr;
  365. // The most dominating leader after our current leader, because the member set
  366. // is not sorted and is expensive to keep sorted all the time.
  367. std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
  368. // If this is represented by a store, the value of the store.
  369. Value *RepStoredValue = nullptr;
  370. // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
  371. // access.
  372. const MemoryAccess *RepMemoryAccess = nullptr;
  373. // Defining Expression.
  374. const Expression *DefiningExpr = nullptr;
  375. // Actual members of this class.
  376. MemberSet Members;
  377. // This is the set of MemoryPhis that exist in the class. MemoryDefs and
  378. // MemoryUses have real instructions representing them, so we only need to
  379. // track MemoryPhis here.
  380. MemoryMemberSet MemoryMembers;
  381. // Number of stores in this congruence class.
  382. // This is used so we can detect store equivalence changes properly.
  383. int StoreCount = 0;
  384. };
  385. } // end anonymous namespace
  386. namespace llvm {
  387. struct ExactEqualsExpression {
  388. const Expression &E;
  389. explicit ExactEqualsExpression(const Expression &E) : E(E) {}
  390. hash_code getComputedHash() const { return E.getComputedHash(); }
  391. bool operator==(const Expression &Other) const {
  392. return E.exactlyEquals(Other);
  393. }
  394. };
  395. template <> struct DenseMapInfo<const Expression *> {
  396. static const Expression *getEmptyKey() {
  397. auto Val = static_cast<uintptr_t>(-1);
  398. Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
  399. return reinterpret_cast<const Expression *>(Val);
  400. }
  401. static const Expression *getTombstoneKey() {
  402. auto Val = static_cast<uintptr_t>(~1U);
  403. Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
  404. return reinterpret_cast<const Expression *>(Val);
  405. }
  406. static unsigned getHashValue(const Expression *E) {
  407. return E->getComputedHash();
  408. }
  409. static unsigned getHashValue(const ExactEqualsExpression &E) {
  410. return E.getComputedHash();
  411. }
  412. static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
  413. if (RHS == getTombstoneKey() || RHS == getEmptyKey())
  414. return false;
  415. return LHS == *RHS;
  416. }
  417. static bool isEqual(const Expression *LHS, const Expression *RHS) {
  418. if (LHS == RHS)
  419. return true;
  420. if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
  421. LHS == getEmptyKey() || RHS == getEmptyKey())
  422. return false;
  423. // Compare hashes before equality. This is *not* what the hashtable does,
  424. // since it is computing it modulo the number of buckets, whereas we are
  425. // using the full hash keyspace. Since the hashes are precomputed, this
  426. // check is *much* faster than equality.
  427. if (LHS->getComputedHash() != RHS->getComputedHash())
  428. return false;
  429. return *LHS == *RHS;
  430. }
  431. };
  432. } // end namespace llvm
  433. namespace {
  434. class NewGVN {
  435. Function &F;
  436. DominatorTree *DT = nullptr;
  437. const TargetLibraryInfo *TLI = nullptr;
  438. AliasAnalysis *AA = nullptr;
  439. MemorySSA *MSSA = nullptr;
  440. MemorySSAWalker *MSSAWalker = nullptr;
  441. AssumptionCache *AC = nullptr;
  442. const DataLayout &DL;
  443. std::unique_ptr<PredicateInfo> PredInfo;
  444. // These are the only two things the create* functions should have
  445. // side-effects on due to allocating memory.
  446. mutable BumpPtrAllocator ExpressionAllocator;
  447. mutable ArrayRecycler<Value *> ArgRecycler;
  448. mutable TarjanSCC SCCFinder;
  449. const SimplifyQuery SQ;
  450. // Number of function arguments, used by ranking
  451. unsigned int NumFuncArgs = 0;
  452. // RPOOrdering of basic blocks
  453. DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
  454. // Congruence class info.
  455. // This class is called INITIAL in the paper. It is the class everything
  456. // startsout in, and represents any value. Being an optimistic analysis,
  457. // anything in the TOP class has the value TOP, which is indeterminate and
  458. // equivalent to everything.
  459. CongruenceClass *TOPClass = nullptr;
  460. std::vector<CongruenceClass *> CongruenceClasses;
  461. unsigned NextCongruenceNum = 0;
  462. // Value Mappings.
  463. DenseMap<Value *, CongruenceClass *> ValueToClass;
  464. DenseMap<Value *, const Expression *> ValueToExpression;
  465. // Value PHI handling, used to make equivalence between phi(op, op) and
  466. // op(phi, phi).
  467. // These mappings just store various data that would normally be part of the
  468. // IR.
  469. SmallPtrSet<const Instruction *, 8> PHINodeUses;
  470. DenseMap<const Value *, bool> OpSafeForPHIOfOps;
  471. // Map a temporary instruction we created to a parent block.
  472. DenseMap<const Value *, BasicBlock *> TempToBlock;
  473. // Map between the already in-program instructions and the temporary phis we
  474. // created that they are known equivalent to.
  475. DenseMap<const Value *, PHINode *> RealToTemp;
  476. // In order to know when we should re-process instructions that have
  477. // phi-of-ops, we track the set of expressions that they needed as
  478. // leaders. When we discover new leaders for those expressions, we process the
  479. // associated phi-of-op instructions again in case they have changed. The
  480. // other way they may change is if they had leaders, and those leaders
  481. // disappear. However, at the point they have leaders, there are uses of the
  482. // relevant operands in the created phi node, and so they will get reprocessed
  483. // through the normal user marking we perform.
  484. mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
  485. DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
  486. ExpressionToPhiOfOps;
  487. // Map from temporary operation to MemoryAccess.
  488. DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
  489. // Set of all temporary instructions we created.
  490. // Note: This will include instructions that were just created during value
  491. // numbering. The way to test if something is using them is to check
  492. // RealToTemp.
  493. DenseSet<Instruction *> AllTempInstructions;
  494. // This is the set of instructions to revisit on a reachability change. At
  495. // the end of the main iteration loop it will contain at least all the phi of
  496. // ops instructions that will be changed to phis, as well as regular phis.
  497. // During the iteration loop, it may contain other things, such as phi of ops
  498. // instructions that used edge reachability to reach a result, and so need to
  499. // be revisited when the edge changes, independent of whether the phi they
  500. // depended on changes.
  501. DenseMap<BasicBlock *, SparseBitVector<>> RevisitOnReachabilityChange;
  502. // Mapping from predicate info we used to the instructions we used it with.
  503. // In order to correctly ensure propagation, we must keep track of what
  504. // comparisons we used, so that when the values of the comparisons change, we
  505. // propagate the information to the places we used the comparison.
  506. mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
  507. PredicateToUsers;
  508. // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
  509. // stores, we no longer can rely solely on the def-use chains of MemorySSA.
  510. mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
  511. MemoryToUsers;
  512. // A table storing which memorydefs/phis represent a memory state provably
  513. // equivalent to another memory state.
  514. // We could use the congruence class machinery, but the MemoryAccess's are
  515. // abstract memory states, so they can only ever be equivalent to each other,
  516. // and not to constants, etc.
  517. DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
  518. // We could, if we wanted, build MemoryPhiExpressions and
  519. // MemoryVariableExpressions, etc, and value number them the same way we value
  520. // number phi expressions. For the moment, this seems like overkill. They
  521. // can only exist in one of three states: they can be TOP (equal to
  522. // everything), Equivalent to something else, or unique. Because we do not
  523. // create expressions for them, we need to simulate leader change not just
  524. // when they change class, but when they change state. Note: We can do the
  525. // same thing for phis, and avoid having phi expressions if we wanted, We
  526. // should eventually unify in one direction or the other, so this is a little
  527. // bit of an experiment in which turns out easier to maintain.
  528. enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
  529. DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
  530. enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
  531. mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
  532. // Expression to class mapping.
  533. using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
  534. ExpressionClassMap ExpressionToClass;
  535. // We have a single expression that represents currently DeadExpressions.
  536. // For dead expressions we can prove will stay dead, we mark them with
  537. // DFS number zero. However, it's possible in the case of phi nodes
  538. // for us to assume/prove all arguments are dead during fixpointing.
  539. // We use DeadExpression for that case.
  540. DeadExpression *SingletonDeadExpression = nullptr;
  541. // Which values have changed as a result of leader changes.
  542. SmallPtrSet<Value *, 8> LeaderChanges;
  543. // Reachability info.
  544. using BlockEdge = BasicBlockEdge;
  545. DenseSet<BlockEdge> ReachableEdges;
  546. SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
  547. // This is a bitvector because, on larger functions, we may have
  548. // thousands of touched instructions at once (entire blocks,
  549. // instructions with hundreds of uses, etc). Even with optimization
  550. // for when we mark whole blocks as touched, when this was a
  551. // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
  552. // the time in GVN just managing this list. The bitvector, on the
  553. // other hand, efficiently supports test/set/clear of both
  554. // individual and ranges, as well as "find next element" This
  555. // enables us to use it as a worklist with essentially 0 cost.
  556. BitVector TouchedInstructions;
  557. DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
  558. mutable DenseMap<const IntrinsicInst *, const Value *> IntrinsicInstPred;
  559. #ifndef NDEBUG
  560. // Debugging for how many times each block and instruction got processed.
  561. DenseMap<const Value *, unsigned> ProcessedCount;
  562. #endif
  563. // DFS info.
  564. // This contains a mapping from Instructions to DFS numbers.
  565. // The numbering starts at 1. An instruction with DFS number zero
  566. // means that the instruction is dead.
  567. DenseMap<const Value *, unsigned> InstrDFS;
  568. // This contains the mapping DFS numbers to instructions.
  569. SmallVector<Value *, 32> DFSToInstr;
  570. // Deletion info.
  571. SmallPtrSet<Instruction *, 8> InstructionsToErase;
  572. public:
  573. NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
  574. TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
  575. const DataLayout &DL)
  576. : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), AC(AC), DL(DL),
  577. PredInfo(std::make_unique<PredicateInfo>(F, *DT, *AC)),
  578. SQ(DL, TLI, DT, AC, /*CtxI=*/nullptr, /*UseInstrInfo=*/false,
  579. /*CanUseUndef=*/false) {}
  580. bool runGVN();
  581. private:
  582. /// Helper struct return a Expression with an optional extra dependency.
  583. struct ExprResult {
  584. const Expression *Expr;
  585. Value *ExtraDep;
  586. const PredicateBase *PredDep;
  587. ExprResult(const Expression *Expr, Value *ExtraDep = nullptr,
  588. const PredicateBase *PredDep = nullptr)
  589. : Expr(Expr), ExtraDep(ExtraDep), PredDep(PredDep) {}
  590. ExprResult(const ExprResult &) = delete;
  591. ExprResult(ExprResult &&Other)
  592. : Expr(Other.Expr), ExtraDep(Other.ExtraDep), PredDep(Other.PredDep) {
  593. Other.Expr = nullptr;
  594. Other.ExtraDep = nullptr;
  595. Other.PredDep = nullptr;
  596. }
  597. ExprResult &operator=(const ExprResult &Other) = delete;
  598. ExprResult &operator=(ExprResult &&Other) = delete;
  599. ~ExprResult() { assert(!ExtraDep && "unhandled ExtraDep"); }
  600. operator bool() const { return Expr; }
  601. static ExprResult none() { return {nullptr, nullptr, nullptr}; }
  602. static ExprResult some(const Expression *Expr, Value *ExtraDep = nullptr) {
  603. return {Expr, ExtraDep, nullptr};
  604. }
  605. static ExprResult some(const Expression *Expr,
  606. const PredicateBase *PredDep) {
  607. return {Expr, nullptr, PredDep};
  608. }
  609. static ExprResult some(const Expression *Expr, Value *ExtraDep,
  610. const PredicateBase *PredDep) {
  611. return {Expr, ExtraDep, PredDep};
  612. }
  613. };
  614. // Expression handling.
  615. ExprResult createExpression(Instruction *) const;
  616. const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
  617. Instruction *) const;
  618. // Our canonical form for phi arguments is a pair of incoming value, incoming
  619. // basic block.
  620. using ValPair = std::pair<Value *, BasicBlock *>;
  621. PHIExpression *createPHIExpression(ArrayRef<ValPair>, const Instruction *,
  622. BasicBlock *, bool &HasBackEdge,
  623. bool &OriginalOpsConstant) const;
  624. const DeadExpression *createDeadExpression() const;
  625. const VariableExpression *createVariableExpression(Value *) const;
  626. const ConstantExpression *createConstantExpression(Constant *) const;
  627. const Expression *createVariableOrConstant(Value *V) const;
  628. const UnknownExpression *createUnknownExpression(Instruction *) const;
  629. const StoreExpression *createStoreExpression(StoreInst *,
  630. const MemoryAccess *) const;
  631. LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
  632. const MemoryAccess *) const;
  633. const CallExpression *createCallExpression(CallInst *,
  634. const MemoryAccess *) const;
  635. const AggregateValueExpression *
  636. createAggregateValueExpression(Instruction *) const;
  637. bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
  638. // Congruence class handling.
  639. CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
  640. auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
  641. CongruenceClasses.emplace_back(result);
  642. return result;
  643. }
  644. CongruenceClass *createMemoryClass(MemoryAccess *MA) {
  645. auto *CC = createCongruenceClass(nullptr, nullptr);
  646. CC->setMemoryLeader(MA);
  647. return CC;
  648. }
  649. CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
  650. auto *CC = getMemoryClass(MA);
  651. if (CC->getMemoryLeader() != MA)
  652. CC = createMemoryClass(MA);
  653. return CC;
  654. }
  655. CongruenceClass *createSingletonCongruenceClass(Value *Member) {
  656. CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
  657. CClass->insert(Member);
  658. ValueToClass[Member] = CClass;
  659. return CClass;
  660. }
  661. void initializeCongruenceClasses(Function &F);
  662. const Expression *makePossiblePHIOfOps(Instruction *,
  663. SmallPtrSetImpl<Value *> &);
  664. Value *findLeaderForInst(Instruction *ValueOp,
  665. SmallPtrSetImpl<Value *> &Visited,
  666. MemoryAccess *MemAccess, Instruction *OrigInst,
  667. BasicBlock *PredBB);
  668. bool OpIsSafeForPHIOfOpsHelper(Value *V, const BasicBlock *PHIBlock,
  669. SmallPtrSetImpl<const Value *> &Visited,
  670. SmallVectorImpl<Instruction *> &Worklist);
  671. bool OpIsSafeForPHIOfOps(Value *Op, const BasicBlock *PHIBlock,
  672. SmallPtrSetImpl<const Value *> &);
  673. void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
  674. void removePhiOfOps(Instruction *I, PHINode *PHITemp);
  675. // Value number an Instruction or MemoryPhi.
  676. void valueNumberMemoryPhi(MemoryPhi *);
  677. void valueNumberInstruction(Instruction *);
  678. // Symbolic evaluation.
  679. ExprResult checkExprResults(Expression *, Instruction *, Value *) const;
  680. ExprResult performSymbolicEvaluation(Value *,
  681. SmallPtrSetImpl<Value *> &) const;
  682. const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
  683. Instruction *,
  684. MemoryAccess *) const;
  685. const Expression *performSymbolicLoadEvaluation(Instruction *) const;
  686. const Expression *performSymbolicStoreEvaluation(Instruction *) const;
  687. ExprResult performSymbolicCallEvaluation(Instruction *) const;
  688. void sortPHIOps(MutableArrayRef<ValPair> Ops) const;
  689. const Expression *performSymbolicPHIEvaluation(ArrayRef<ValPair>,
  690. Instruction *I,
  691. BasicBlock *PHIBlock) const;
  692. const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
  693. ExprResult performSymbolicCmpEvaluation(Instruction *) const;
  694. ExprResult performSymbolicPredicateInfoEvaluation(IntrinsicInst *) const;
  695. // Congruence finding.
  696. bool someEquivalentDominates(const Instruction *, const Instruction *) const;
  697. Value *lookupOperandLeader(Value *) const;
  698. CongruenceClass *getClassForExpression(const Expression *E) const;
  699. void performCongruenceFinding(Instruction *, const Expression *);
  700. void moveValueToNewCongruenceClass(Instruction *, const Expression *,
  701. CongruenceClass *, CongruenceClass *);
  702. void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
  703. CongruenceClass *, CongruenceClass *);
  704. Value *getNextValueLeader(CongruenceClass *) const;
  705. const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
  706. bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
  707. CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
  708. const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
  709. bool isMemoryAccessTOP(const MemoryAccess *) const;
  710. // Ranking
  711. unsigned int getRank(const Value *) const;
  712. bool shouldSwapOperands(const Value *, const Value *) const;
  713. bool shouldSwapOperandsForIntrinsic(const Value *, const Value *,
  714. const IntrinsicInst *I) const;
  715. // Reachability handling.
  716. void updateReachableEdge(BasicBlock *, BasicBlock *);
  717. void processOutgoingEdges(Instruction *, BasicBlock *);
  718. Value *findConditionEquivalence(Value *) const;
  719. // Elimination.
  720. struct ValueDFS;
  721. void convertClassToDFSOrdered(const CongruenceClass &,
  722. SmallVectorImpl<ValueDFS> &,
  723. DenseMap<const Value *, unsigned int> &,
  724. SmallPtrSetImpl<Instruction *> &) const;
  725. void convertClassToLoadsAndStores(const CongruenceClass &,
  726. SmallVectorImpl<ValueDFS> &) const;
  727. bool eliminateInstructions(Function &);
  728. void replaceInstruction(Instruction *, Value *);
  729. void markInstructionForDeletion(Instruction *);
  730. void deleteInstructionsInBlock(BasicBlock *);
  731. Value *findPHIOfOpsLeader(const Expression *, const Instruction *,
  732. const BasicBlock *) const;
  733. // Various instruction touch utilities
  734. template <typename Map, typename KeyType>
  735. void touchAndErase(Map &, const KeyType &);
  736. void markUsersTouched(Value *);
  737. void markMemoryUsersTouched(const MemoryAccess *);
  738. void markMemoryDefTouched(const MemoryAccess *);
  739. void markPredicateUsersTouched(Instruction *);
  740. void markValueLeaderChangeTouched(CongruenceClass *CC);
  741. void markMemoryLeaderChangeTouched(CongruenceClass *CC);
  742. void markPhiOfOpsChanged(const Expression *E);
  743. void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
  744. void addAdditionalUsers(Value *To, Value *User) const;
  745. void addAdditionalUsers(ExprResult &Res, Instruction *User) const;
  746. // Main loop of value numbering
  747. void iterateTouchedInstructions();
  748. // Utilities.
  749. void cleanupTables();
  750. std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
  751. void updateProcessedCount(const Value *V);
  752. void verifyMemoryCongruency() const;
  753. void verifyIterationSettled(Function &F);
  754. void verifyStoreExpressions() const;
  755. bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
  756. const MemoryAccess *, const MemoryAccess *) const;
  757. BasicBlock *getBlockForValue(Value *V) const;
  758. void deleteExpression(const Expression *E) const;
  759. MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
  760. MemoryPhi *getMemoryAccess(const BasicBlock *) const;
  761. template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
  762. unsigned InstrToDFSNum(const Value *V) const {
  763. assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
  764. return InstrDFS.lookup(V);
  765. }
  766. unsigned InstrToDFSNum(const MemoryAccess *MA) const {
  767. return MemoryToDFSNum(MA);
  768. }
  769. Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
  770. // Given a MemoryAccess, return the relevant instruction DFS number. Note:
  771. // This deliberately takes a value so it can be used with Use's, which will
  772. // auto-convert to Value's but not to MemoryAccess's.
  773. unsigned MemoryToDFSNum(const Value *MA) const {
  774. assert(isa<MemoryAccess>(MA) &&
  775. "This should not be used with instructions");
  776. return isa<MemoryUseOrDef>(MA)
  777. ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
  778. : InstrDFS.lookup(MA);
  779. }
  780. bool isCycleFree(const Instruction *) const;
  781. bool isBackedge(BasicBlock *From, BasicBlock *To) const;
  782. // Debug counter info. When verifying, we have to reset the value numbering
  783. // debug counter to the same state it started in to get the same results.
  784. int64_t StartingVNCounter = 0;
  785. };
  786. } // end anonymous namespace
  787. template <typename T>
  788. static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
  789. if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
  790. return false;
  791. return LHS.MemoryExpression::equals(RHS);
  792. }
  793. bool LoadExpression::equals(const Expression &Other) const {
  794. return equalsLoadStoreHelper(*this, Other);
  795. }
  796. bool StoreExpression::equals(const Expression &Other) const {
  797. if (!equalsLoadStoreHelper(*this, Other))
  798. return false;
  799. // Make sure that store vs store includes the value operand.
  800. if (const auto *S = dyn_cast<StoreExpression>(&Other))
  801. if (getStoredValue() != S->getStoredValue())
  802. return false;
  803. return true;
  804. }
  805. // Determine if the edge From->To is a backedge
  806. bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
  807. return From == To ||
  808. RPOOrdering.lookup(DT->getNode(From)) >=
  809. RPOOrdering.lookup(DT->getNode(To));
  810. }
  811. #ifndef NDEBUG
  812. static std::string getBlockName(const BasicBlock *B) {
  813. return DOTGraphTraits<DOTFuncInfo *>::getSimpleNodeLabel(B, nullptr);
  814. }
  815. #endif
  816. // Get a MemoryAccess for an instruction, fake or real.
  817. MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
  818. auto *Result = MSSA->getMemoryAccess(I);
  819. return Result ? Result : TempToMemory.lookup(I);
  820. }
  821. // Get a MemoryPhi for a basic block. These are all real.
  822. MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
  823. return MSSA->getMemoryAccess(BB);
  824. }
  825. // Get the basic block from an instruction/memory value.
  826. BasicBlock *NewGVN::getBlockForValue(Value *V) const {
  827. if (auto *I = dyn_cast<Instruction>(V)) {
  828. auto *Parent = I->getParent();
  829. if (Parent)
  830. return Parent;
  831. Parent = TempToBlock.lookup(V);
  832. assert(Parent && "Every fake instruction should have a block");
  833. return Parent;
  834. }
  835. auto *MP = dyn_cast<MemoryPhi>(V);
  836. assert(MP && "Should have been an instruction or a MemoryPhi");
  837. return MP->getBlock();
  838. }
  839. // Delete a definitely dead expression, so it can be reused by the expression
  840. // allocator. Some of these are not in creation functions, so we have to accept
  841. // const versions.
  842. void NewGVN::deleteExpression(const Expression *E) const {
  843. assert(isa<BasicExpression>(E));
  844. auto *BE = cast<BasicExpression>(E);
  845. const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
  846. ExpressionAllocator.Deallocate(E);
  847. }
  848. // If V is a predicateinfo copy, get the thing it is a copy of.
  849. static Value *getCopyOf(const Value *V) {
  850. if (auto *II = dyn_cast<IntrinsicInst>(V))
  851. if (II->getIntrinsicID() == Intrinsic::ssa_copy)
  852. return II->getOperand(0);
  853. return nullptr;
  854. }
  855. // Return true if V is really PN, even accounting for predicateinfo copies.
  856. static bool isCopyOfPHI(const Value *V, const PHINode *PN) {
  857. return V == PN || getCopyOf(V) == PN;
  858. }
  859. static bool isCopyOfAPHI(const Value *V) {
  860. auto *CO = getCopyOf(V);
  861. return CO && isa<PHINode>(CO);
  862. }
  863. // Sort PHI Operands into a canonical order. What we use here is an RPO
  864. // order. The BlockInstRange numbers are generated in an RPO walk of the basic
  865. // blocks.
  866. void NewGVN::sortPHIOps(MutableArrayRef<ValPair> Ops) const {
  867. llvm::sort(Ops, [&](const ValPair &P1, const ValPair &P2) {
  868. return BlockInstRange.lookup(P1.second).first <
  869. BlockInstRange.lookup(P2.second).first;
  870. });
  871. }
  872. // Return true if V is a value that will always be available (IE can
  873. // be placed anywhere) in the function. We don't do globals here
  874. // because they are often worse to put in place.
  875. static bool alwaysAvailable(Value *V) {
  876. return isa<Constant>(V) || isa<Argument>(V);
  877. }
  878. // Create a PHIExpression from an array of {incoming edge, value} pairs. I is
  879. // the original instruction we are creating a PHIExpression for (but may not be
  880. // a phi node). We require, as an invariant, that all the PHIOperands in the
  881. // same block are sorted the same way. sortPHIOps will sort them into a
  882. // canonical order.
  883. PHIExpression *NewGVN::createPHIExpression(ArrayRef<ValPair> PHIOperands,
  884. const Instruction *I,
  885. BasicBlock *PHIBlock,
  886. bool &HasBackedge,
  887. bool &OriginalOpsConstant) const {
  888. unsigned NumOps = PHIOperands.size();
  889. auto *E = new (ExpressionAllocator) PHIExpression(NumOps, PHIBlock);
  890. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  891. E->setType(PHIOperands.begin()->first->getType());
  892. E->setOpcode(Instruction::PHI);
  893. // Filter out unreachable phi operands.
  894. auto Filtered = make_filter_range(PHIOperands, [&](const ValPair &P) {
  895. auto *BB = P.second;
  896. if (auto *PHIOp = dyn_cast<PHINode>(I))
  897. if (isCopyOfPHI(P.first, PHIOp))
  898. return false;
  899. if (!ReachableEdges.count({BB, PHIBlock}))
  900. return false;
  901. // Things in TOPClass are equivalent to everything.
  902. if (ValueToClass.lookup(P.first) == TOPClass)
  903. return false;
  904. OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(P.first);
  905. HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
  906. return lookupOperandLeader(P.first) != I;
  907. });
  908. std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
  909. [&](const ValPair &P) -> Value * {
  910. return lookupOperandLeader(P.first);
  911. });
  912. return E;
  913. }
  914. // Set basic expression info (Arguments, type, opcode) for Expression
  915. // E from Instruction I in block B.
  916. bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
  917. bool AllConstant = true;
  918. if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
  919. E->setType(GEP->getSourceElementType());
  920. else
  921. E->setType(I->getType());
  922. E->setOpcode(I->getOpcode());
  923. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  924. // Transform the operand array into an operand leader array, and keep track of
  925. // whether all members are constant.
  926. std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
  927. auto Operand = lookupOperandLeader(O);
  928. AllConstant = AllConstant && isa<Constant>(Operand);
  929. return Operand;
  930. });
  931. return AllConstant;
  932. }
  933. const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
  934. Value *Arg1, Value *Arg2,
  935. Instruction *I) const {
  936. auto *E = new (ExpressionAllocator) BasicExpression(2);
  937. E->setType(T);
  938. E->setOpcode(Opcode);
  939. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  940. if (Instruction::isCommutative(Opcode)) {
  941. // Ensure that commutative instructions that only differ by a permutation
  942. // of their operands get the same value number by sorting the operand value
  943. // numbers. Since all commutative instructions have two operands it is more
  944. // efficient to sort by hand rather than using, say, std::sort.
  945. if (shouldSwapOperands(Arg1, Arg2))
  946. std::swap(Arg1, Arg2);
  947. }
  948. E->op_push_back(lookupOperandLeader(Arg1));
  949. E->op_push_back(lookupOperandLeader(Arg2));
  950. Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
  951. if (auto Simplified = checkExprResults(E, I, V)) {
  952. addAdditionalUsers(Simplified, I);
  953. return Simplified.Expr;
  954. }
  955. return E;
  956. }
  957. // Take a Value returned by simplification of Expression E/Instruction
  958. // I, and see if it resulted in a simpler expression. If so, return
  959. // that expression.
  960. NewGVN::ExprResult NewGVN::checkExprResults(Expression *E, Instruction *I,
  961. Value *V) const {
  962. if (!V)
  963. return ExprResult::none();
  964. if (auto *C = dyn_cast<Constant>(V)) {
  965. if (I)
  966. LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
  967. << " constant " << *C << "\n");
  968. NumGVNOpsSimplified++;
  969. assert(isa<BasicExpression>(E) &&
  970. "We should always have had a basic expression here");
  971. deleteExpression(E);
  972. return ExprResult::some(createConstantExpression(C));
  973. } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
  974. if (I)
  975. LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
  976. << " variable " << *V << "\n");
  977. deleteExpression(E);
  978. return ExprResult::some(createVariableExpression(V));
  979. }
  980. CongruenceClass *CC = ValueToClass.lookup(V);
  981. if (CC) {
  982. if (CC->getLeader() && CC->getLeader() != I) {
  983. return ExprResult::some(createVariableOrConstant(CC->getLeader()), V);
  984. }
  985. if (CC->getDefiningExpr()) {
  986. if (I)
  987. LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
  988. << " expression " << *CC->getDefiningExpr() << "\n");
  989. NumGVNOpsSimplified++;
  990. deleteExpression(E);
  991. return ExprResult::some(CC->getDefiningExpr(), V);
  992. }
  993. }
  994. return ExprResult::none();
  995. }
  996. // Create a value expression from the instruction I, replacing operands with
  997. // their leaders.
  998. NewGVN::ExprResult NewGVN::createExpression(Instruction *I) const {
  999. auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
  1000. bool AllConstant = setBasicExpressionInfo(I, E);
  1001. if (I->isCommutative()) {
  1002. // Ensure that commutative instructions that only differ by a permutation
  1003. // of their operands get the same value number by sorting the operand value
  1004. // numbers. Since all commutative instructions have two operands it is more
  1005. // efficient to sort by hand rather than using, say, std::sort.
  1006. assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
  1007. if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
  1008. E->swapOperands(0, 1);
  1009. }
  1010. // Perform simplification.
  1011. if (auto *CI = dyn_cast<CmpInst>(I)) {
  1012. // Sort the operand value numbers so x<y and y>x get the same value
  1013. // number.
  1014. CmpInst::Predicate Predicate = CI->getPredicate();
  1015. if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
  1016. E->swapOperands(0, 1);
  1017. Predicate = CmpInst::getSwappedPredicate(Predicate);
  1018. }
  1019. E->setOpcode((CI->getOpcode() << 8) | Predicate);
  1020. // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
  1021. assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
  1022. "Wrong types on cmp instruction");
  1023. assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
  1024. E->getOperand(1)->getType() == I->getOperand(1)->getType()));
  1025. Value *V =
  1026. SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
  1027. if (auto Simplified = checkExprResults(E, I, V))
  1028. return Simplified;
  1029. } else if (isa<SelectInst>(I)) {
  1030. if (isa<Constant>(E->getOperand(0)) ||
  1031. E->getOperand(1) == E->getOperand(2)) {
  1032. assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
  1033. E->getOperand(2)->getType() == I->getOperand(2)->getType());
  1034. Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
  1035. E->getOperand(2), SQ);
  1036. if (auto Simplified = checkExprResults(E, I, V))
  1037. return Simplified;
  1038. }
  1039. } else if (I->isBinaryOp()) {
  1040. Value *V =
  1041. SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
  1042. if (auto Simplified = checkExprResults(E, I, V))
  1043. return Simplified;
  1044. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  1045. Value *V =
  1046. SimplifyCastInst(CI->getOpcode(), E->getOperand(0), CI->getType(), SQ);
  1047. if (auto Simplified = checkExprResults(E, I, V))
  1048. return Simplified;
  1049. } else if (auto *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  1050. Value *V =
  1051. SimplifyGEPInst(GEPI->getSourceElementType(), *E->op_begin(),
  1052. makeArrayRef(std::next(E->op_begin()), E->op_end()),
  1053. GEPI->isInBounds(), SQ);
  1054. if (auto Simplified = checkExprResults(E, I, V))
  1055. return Simplified;
  1056. } else if (AllConstant) {
  1057. // We don't bother trying to simplify unless all of the operands
  1058. // were constant.
  1059. // TODO: There are a lot of Simplify*'s we could call here, if we
  1060. // wanted to. The original motivating case for this code was a
  1061. // zext i1 false to i8, which we don't have an interface to
  1062. // simplify (IE there is no SimplifyZExt).
  1063. SmallVector<Constant *, 8> C;
  1064. for (Value *Arg : E->operands())
  1065. C.emplace_back(cast<Constant>(Arg));
  1066. if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
  1067. if (auto Simplified = checkExprResults(E, I, V))
  1068. return Simplified;
  1069. }
  1070. return ExprResult::some(E);
  1071. }
  1072. const AggregateValueExpression *
  1073. NewGVN::createAggregateValueExpression(Instruction *I) const {
  1074. if (auto *II = dyn_cast<InsertValueInst>(I)) {
  1075. auto *E = new (ExpressionAllocator)
  1076. AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
  1077. setBasicExpressionInfo(I, E);
  1078. E->allocateIntOperands(ExpressionAllocator);
  1079. std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
  1080. return E;
  1081. } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
  1082. auto *E = new (ExpressionAllocator)
  1083. AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
  1084. setBasicExpressionInfo(EI, E);
  1085. E->allocateIntOperands(ExpressionAllocator);
  1086. std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
  1087. return E;
  1088. }
  1089. llvm_unreachable("Unhandled type of aggregate value operation");
  1090. }
  1091. const DeadExpression *NewGVN::createDeadExpression() const {
  1092. // DeadExpression has no arguments and all DeadExpression's are the same,
  1093. // so we only need one of them.
  1094. return SingletonDeadExpression;
  1095. }
  1096. const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
  1097. auto *E = new (ExpressionAllocator) VariableExpression(V);
  1098. E->setOpcode(V->getValueID());
  1099. return E;
  1100. }
  1101. const Expression *NewGVN::createVariableOrConstant(Value *V) const {
  1102. if (auto *C = dyn_cast<Constant>(V))
  1103. return createConstantExpression(C);
  1104. return createVariableExpression(V);
  1105. }
  1106. const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
  1107. auto *E = new (ExpressionAllocator) ConstantExpression(C);
  1108. E->setOpcode(C->getValueID());
  1109. return E;
  1110. }
  1111. const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
  1112. auto *E = new (ExpressionAllocator) UnknownExpression(I);
  1113. E->setOpcode(I->getOpcode());
  1114. return E;
  1115. }
  1116. const CallExpression *
  1117. NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
  1118. // FIXME: Add operand bundles for calls.
  1119. // FIXME: Allow commutative matching for intrinsics.
  1120. auto *E =
  1121. new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
  1122. setBasicExpressionInfo(CI, E);
  1123. return E;
  1124. }
  1125. // Return true if some equivalent of instruction Inst dominates instruction U.
  1126. bool NewGVN::someEquivalentDominates(const Instruction *Inst,
  1127. const Instruction *U) const {
  1128. auto *CC = ValueToClass.lookup(Inst);
  1129. // This must be an instruction because we are only called from phi nodes
  1130. // in the case that the value it needs to check against is an instruction.
  1131. // The most likely candidates for dominance are the leader and the next leader.
  1132. // The leader or nextleader will dominate in all cases where there is an
  1133. // equivalent that is higher up in the dom tree.
  1134. // We can't *only* check them, however, because the
  1135. // dominator tree could have an infinite number of non-dominating siblings
  1136. // with instructions that are in the right congruence class.
  1137. // A
  1138. // B C D E F G
  1139. // |
  1140. // H
  1141. // Instruction U could be in H, with equivalents in every other sibling.
  1142. // Depending on the rpo order picked, the leader could be the equivalent in
  1143. // any of these siblings.
  1144. if (!CC)
  1145. return false;
  1146. if (alwaysAvailable(CC->getLeader()))
  1147. return true;
  1148. if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
  1149. return true;
  1150. if (CC->getNextLeader().first &&
  1151. DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
  1152. return true;
  1153. return llvm::any_of(*CC, [&](const Value *Member) {
  1154. return Member != CC->getLeader() &&
  1155. DT->dominates(cast<Instruction>(Member), U);
  1156. });
  1157. }
  1158. // See if we have a congruence class and leader for this operand, and if so,
  1159. // return it. Otherwise, return the operand itself.
  1160. Value *NewGVN::lookupOperandLeader(Value *V) const {
  1161. CongruenceClass *CC = ValueToClass.lookup(V);
  1162. if (CC) {
  1163. // Everything in TOP is represented by poison, as it can be any value.
  1164. // We do have to make sure we get the type right though, so we can't set the
  1165. // RepLeader to poison.
  1166. if (CC == TOPClass)
  1167. return PoisonValue::get(V->getType());
  1168. return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
  1169. }
  1170. return V;
  1171. }
  1172. const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
  1173. auto *CC = getMemoryClass(MA);
  1174. assert(CC->getMemoryLeader() &&
  1175. "Every MemoryAccess should be mapped to a congruence class with a "
  1176. "representative memory access");
  1177. return CC->getMemoryLeader();
  1178. }
  1179. // Return true if the MemoryAccess is really equivalent to everything. This is
  1180. // equivalent to the lattice value "TOP" in most lattices. This is the initial
  1181. // state of all MemoryAccesses.
  1182. bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
  1183. return getMemoryClass(MA) == TOPClass;
  1184. }
  1185. LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
  1186. LoadInst *LI,
  1187. const MemoryAccess *MA) const {
  1188. auto *E =
  1189. new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
  1190. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  1191. E->setType(LoadType);
  1192. // Give store and loads same opcode so they value number together.
  1193. E->setOpcode(0);
  1194. E->op_push_back(PointerOp);
  1195. // TODO: Value number heap versions. We may be able to discover
  1196. // things alias analysis can't on it's own (IE that a store and a
  1197. // load have the same value, and thus, it isn't clobbering the load).
  1198. return E;
  1199. }
  1200. const StoreExpression *
  1201. NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
  1202. auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
  1203. auto *E = new (ExpressionAllocator)
  1204. StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
  1205. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  1206. E->setType(SI->getValueOperand()->getType());
  1207. // Give store and loads same opcode so they value number together.
  1208. E->setOpcode(0);
  1209. E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
  1210. // TODO: Value number heap versions. We may be able to discover
  1211. // things alias analysis can't on it's own (IE that a store and a
  1212. // load have the same value, and thus, it isn't clobbering the load).
  1213. return E;
  1214. }
  1215. const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
  1216. // Unlike loads, we never try to eliminate stores, so we do not check if they
  1217. // are simple and avoid value numbering them.
  1218. auto *SI = cast<StoreInst>(I);
  1219. auto *StoreAccess = getMemoryAccess(SI);
  1220. // Get the expression, if any, for the RHS of the MemoryDef.
  1221. const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
  1222. if (EnableStoreRefinement)
  1223. StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
  1224. // If we bypassed the use-def chains, make sure we add a use.
  1225. StoreRHS = lookupMemoryLeader(StoreRHS);
  1226. if (StoreRHS != StoreAccess->getDefiningAccess())
  1227. addMemoryUsers(StoreRHS, StoreAccess);
  1228. // If we are defined by ourselves, use the live on entry def.
  1229. if (StoreRHS == StoreAccess)
  1230. StoreRHS = MSSA->getLiveOnEntryDef();
  1231. if (SI->isSimple()) {
  1232. // See if we are defined by a previous store expression, it already has a
  1233. // value, and it's the same value as our current store. FIXME: Right now, we
  1234. // only do this for simple stores, we should expand to cover memcpys, etc.
  1235. const auto *LastStore = createStoreExpression(SI, StoreRHS);
  1236. const auto *LastCC = ExpressionToClass.lookup(LastStore);
  1237. // We really want to check whether the expression we matched was a store. No
  1238. // easy way to do that. However, we can check that the class we found has a
  1239. // store, which, assuming the value numbering state is not corrupt, is
  1240. // sufficient, because we must also be equivalent to that store's expression
  1241. // for it to be in the same class as the load.
  1242. if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
  1243. return LastStore;
  1244. // Also check if our value operand is defined by a load of the same memory
  1245. // location, and the memory state is the same as it was then (otherwise, it
  1246. // could have been overwritten later. See test32 in
  1247. // transforms/DeadStoreElimination/simple.ll).
  1248. if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
  1249. if ((lookupOperandLeader(LI->getPointerOperand()) ==
  1250. LastStore->getOperand(0)) &&
  1251. (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
  1252. StoreRHS))
  1253. return LastStore;
  1254. deleteExpression(LastStore);
  1255. }
  1256. // If the store is not equivalent to anything, value number it as a store that
  1257. // produces a unique memory state (instead of using it's MemoryUse, we use
  1258. // it's MemoryDef).
  1259. return createStoreExpression(SI, StoreAccess);
  1260. }
  1261. // See if we can extract the value of a loaded pointer from a load, a store, or
  1262. // a memory instruction.
  1263. const Expression *
  1264. NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
  1265. LoadInst *LI, Instruction *DepInst,
  1266. MemoryAccess *DefiningAccess) const {
  1267. assert((!LI || LI->isSimple()) && "Not a simple load");
  1268. if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
  1269. // Can't forward from non-atomic to atomic without violating memory model.
  1270. // Also don't need to coerce if they are the same type, we will just
  1271. // propagate.
  1272. if (LI->isAtomic() > DepSI->isAtomic() ||
  1273. LoadType == DepSI->getValueOperand()->getType())
  1274. return nullptr;
  1275. int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
  1276. if (Offset >= 0) {
  1277. if (auto *C = dyn_cast<Constant>(
  1278. lookupOperandLeader(DepSI->getValueOperand()))) {
  1279. LLVM_DEBUG(dbgs() << "Coercing load from store " << *DepSI
  1280. << " to constant " << *C << "\n");
  1281. return createConstantExpression(
  1282. getConstantStoreValueForLoad(C, Offset, LoadType, DL));
  1283. }
  1284. }
  1285. } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
  1286. // Can't forward from non-atomic to atomic without violating memory model.
  1287. if (LI->isAtomic() > DepLI->isAtomic())
  1288. return nullptr;
  1289. int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
  1290. if (Offset >= 0) {
  1291. // We can coerce a constant load into a load.
  1292. if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
  1293. if (auto *PossibleConstant =
  1294. getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
  1295. LLVM_DEBUG(dbgs() << "Coercing load from load " << *LI
  1296. << " to constant " << *PossibleConstant << "\n");
  1297. return createConstantExpression(PossibleConstant);
  1298. }
  1299. }
  1300. } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
  1301. int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
  1302. if (Offset >= 0) {
  1303. if (auto *PossibleConstant =
  1304. getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
  1305. LLVM_DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
  1306. << " to constant " << *PossibleConstant << "\n");
  1307. return createConstantExpression(PossibleConstant);
  1308. }
  1309. }
  1310. }
  1311. // All of the below are only true if the loaded pointer is produced
  1312. // by the dependent instruction.
  1313. if (LoadPtr != lookupOperandLeader(DepInst) &&
  1314. !AA->isMustAlias(LoadPtr, DepInst))
  1315. return nullptr;
  1316. // If this load really doesn't depend on anything, then we must be loading an
  1317. // undef value. This can happen when loading for a fresh allocation with no
  1318. // intervening stores, for example. Note that this is only true in the case
  1319. // that the result of the allocation is pointer equal to the load ptr.
  1320. if (isa<AllocaInst>(DepInst)) {
  1321. return createConstantExpression(UndefValue::get(LoadType));
  1322. }
  1323. // If this load occurs either right after a lifetime begin,
  1324. // then the loaded value is undefined.
  1325. else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
  1326. if (II->getIntrinsicID() == Intrinsic::lifetime_start)
  1327. return createConstantExpression(UndefValue::get(LoadType));
  1328. } else if (isAllocationFn(DepInst, TLI))
  1329. if (auto *InitVal = getInitialValueOfAllocation(cast<CallBase>(DepInst),
  1330. TLI, LoadType))
  1331. return createConstantExpression(InitVal);
  1332. return nullptr;
  1333. }
  1334. const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
  1335. auto *LI = cast<LoadInst>(I);
  1336. // We can eliminate in favor of non-simple loads, but we won't be able to
  1337. // eliminate the loads themselves.
  1338. if (!LI->isSimple())
  1339. return nullptr;
  1340. Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
  1341. // Load of undef is UB.
  1342. if (isa<UndefValue>(LoadAddressLeader))
  1343. return createConstantExpression(PoisonValue::get(LI->getType()));
  1344. MemoryAccess *OriginalAccess = getMemoryAccess(I);
  1345. MemoryAccess *DefiningAccess =
  1346. MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
  1347. if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
  1348. if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
  1349. Instruction *DefiningInst = MD->getMemoryInst();
  1350. // If the defining instruction is not reachable, replace with poison.
  1351. if (!ReachableBlocks.count(DefiningInst->getParent()))
  1352. return createConstantExpression(PoisonValue::get(LI->getType()));
  1353. // This will handle stores and memory insts. We only do if it the
  1354. // defining access has a different type, or it is a pointer produced by
  1355. // certain memory operations that cause the memory to have a fixed value
  1356. // (IE things like calloc).
  1357. if (const auto *CoercionResult =
  1358. performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
  1359. DefiningInst, DefiningAccess))
  1360. return CoercionResult;
  1361. }
  1362. }
  1363. const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader, LI,
  1364. DefiningAccess);
  1365. // If our MemoryLeader is not our defining access, add a use to the
  1366. // MemoryLeader, so that we get reprocessed when it changes.
  1367. if (LE->getMemoryLeader() != DefiningAccess)
  1368. addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
  1369. return LE;
  1370. }
  1371. NewGVN::ExprResult
  1372. NewGVN::performSymbolicPredicateInfoEvaluation(IntrinsicInst *I) const {
  1373. auto *PI = PredInfo->getPredicateInfoFor(I);
  1374. if (!PI)
  1375. return ExprResult::none();
  1376. LLVM_DEBUG(dbgs() << "Found predicate info from instruction !\n");
  1377. const Optional<PredicateConstraint> &Constraint = PI->getConstraint();
  1378. if (!Constraint)
  1379. return ExprResult::none();
  1380. CmpInst::Predicate Predicate = Constraint->Predicate;
  1381. Value *CmpOp0 = I->getOperand(0);
  1382. Value *CmpOp1 = Constraint->OtherOp;
  1383. Value *FirstOp = lookupOperandLeader(CmpOp0);
  1384. Value *SecondOp = lookupOperandLeader(CmpOp1);
  1385. Value *AdditionallyUsedValue = CmpOp0;
  1386. // Sort the ops.
  1387. if (shouldSwapOperandsForIntrinsic(FirstOp, SecondOp, I)) {
  1388. std::swap(FirstOp, SecondOp);
  1389. Predicate = CmpInst::getSwappedPredicate(Predicate);
  1390. AdditionallyUsedValue = CmpOp1;
  1391. }
  1392. if (Predicate == CmpInst::ICMP_EQ)
  1393. return ExprResult::some(createVariableOrConstant(FirstOp),
  1394. AdditionallyUsedValue, PI);
  1395. // Handle the special case of floating point.
  1396. if (Predicate == CmpInst::FCMP_OEQ && isa<ConstantFP>(FirstOp) &&
  1397. !cast<ConstantFP>(FirstOp)->isZero())
  1398. return ExprResult::some(createConstantExpression(cast<Constant>(FirstOp)),
  1399. AdditionallyUsedValue, PI);
  1400. return ExprResult::none();
  1401. }
  1402. // Evaluate read only and pure calls, and create an expression result.
  1403. NewGVN::ExprResult NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
  1404. auto *CI = cast<CallInst>(I);
  1405. if (auto *II = dyn_cast<IntrinsicInst>(I)) {
  1406. // Intrinsics with the returned attribute are copies of arguments.
  1407. if (auto *ReturnedValue = II->getReturnedArgOperand()) {
  1408. if (II->getIntrinsicID() == Intrinsic::ssa_copy)
  1409. if (auto Res = performSymbolicPredicateInfoEvaluation(II))
  1410. return Res;
  1411. return ExprResult::some(createVariableOrConstant(ReturnedValue));
  1412. }
  1413. }
  1414. if (AA->doesNotAccessMemory(CI)) {
  1415. return ExprResult::some(
  1416. createCallExpression(CI, TOPClass->getMemoryLeader()));
  1417. } else if (AA->onlyReadsMemory(CI)) {
  1418. if (auto *MA = MSSA->getMemoryAccess(CI)) {
  1419. auto *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(MA);
  1420. return ExprResult::some(createCallExpression(CI, DefiningAccess));
  1421. } else // MSSA determined that CI does not access memory.
  1422. return ExprResult::some(
  1423. createCallExpression(CI, TOPClass->getMemoryLeader()));
  1424. }
  1425. return ExprResult::none();
  1426. }
  1427. // Retrieve the memory class for a given MemoryAccess.
  1428. CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
  1429. auto *Result = MemoryAccessToClass.lookup(MA);
  1430. assert(Result && "Should have found memory class");
  1431. return Result;
  1432. }
  1433. // Update the MemoryAccess equivalence table to say that From is equal to To,
  1434. // and return true if this is different from what already existed in the table.
  1435. bool NewGVN::setMemoryClass(const MemoryAccess *From,
  1436. CongruenceClass *NewClass) {
  1437. assert(NewClass &&
  1438. "Every MemoryAccess should be getting mapped to a non-null class");
  1439. LLVM_DEBUG(dbgs() << "Setting " << *From);
  1440. LLVM_DEBUG(dbgs() << " equivalent to congruence class ");
  1441. LLVM_DEBUG(dbgs() << NewClass->getID()
  1442. << " with current MemoryAccess leader ");
  1443. LLVM_DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
  1444. auto LookupResult = MemoryAccessToClass.find(From);
  1445. bool Changed = false;
  1446. // If it's already in the table, see if the value changed.
  1447. if (LookupResult != MemoryAccessToClass.end()) {
  1448. auto *OldClass = LookupResult->second;
  1449. if (OldClass != NewClass) {
  1450. // If this is a phi, we have to handle memory member updates.
  1451. if (auto *MP = dyn_cast<MemoryPhi>(From)) {
  1452. OldClass->memory_erase(MP);
  1453. NewClass->memory_insert(MP);
  1454. // This may have killed the class if it had no non-memory members
  1455. if (OldClass->getMemoryLeader() == From) {
  1456. if (OldClass->definesNoMemory()) {
  1457. OldClass->setMemoryLeader(nullptr);
  1458. } else {
  1459. OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
  1460. LLVM_DEBUG(dbgs() << "Memory class leader change for class "
  1461. << OldClass->getID() << " to "
  1462. << *OldClass->getMemoryLeader()
  1463. << " due to removal of a memory member " << *From
  1464. << "\n");
  1465. markMemoryLeaderChangeTouched(OldClass);
  1466. }
  1467. }
  1468. }
  1469. // It wasn't equivalent before, and now it is.
  1470. LookupResult->second = NewClass;
  1471. Changed = true;
  1472. }
  1473. }
  1474. return Changed;
  1475. }
  1476. // Determine if a instruction is cycle-free. That means the values in the
  1477. // instruction don't depend on any expressions that can change value as a result
  1478. // of the instruction. For example, a non-cycle free instruction would be v =
  1479. // phi(0, v+1).
  1480. bool NewGVN::isCycleFree(const Instruction *I) const {
  1481. // In order to compute cycle-freeness, we do SCC finding on the instruction,
  1482. // and see what kind of SCC it ends up in. If it is a singleton, it is
  1483. // cycle-free. If it is not in a singleton, it is only cycle free if the
  1484. // other members are all phi nodes (as they do not compute anything, they are
  1485. // copies).
  1486. auto ICS = InstCycleState.lookup(I);
  1487. if (ICS == ICS_Unknown) {
  1488. SCCFinder.Start(I);
  1489. auto &SCC = SCCFinder.getComponentFor(I);
  1490. // It's cycle free if it's size 1 or the SCC is *only* phi nodes.
  1491. if (SCC.size() == 1)
  1492. InstCycleState.insert({I, ICS_CycleFree});
  1493. else {
  1494. bool AllPhis = llvm::all_of(SCC, [](const Value *V) {
  1495. return isa<PHINode>(V) || isCopyOfAPHI(V);
  1496. });
  1497. ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
  1498. for (auto *Member : SCC)
  1499. if (auto *MemberPhi = dyn_cast<PHINode>(Member))
  1500. InstCycleState.insert({MemberPhi, ICS});
  1501. }
  1502. }
  1503. if (ICS == ICS_Cycle)
  1504. return false;
  1505. return true;
  1506. }
  1507. // Evaluate PHI nodes symbolically and create an expression result.
  1508. const Expression *
  1509. NewGVN::performSymbolicPHIEvaluation(ArrayRef<ValPair> PHIOps,
  1510. Instruction *I,
  1511. BasicBlock *PHIBlock) const {
  1512. // True if one of the incoming phi edges is a backedge.
  1513. bool HasBackedge = false;
  1514. // All constant tracks the state of whether all the *original* phi operands
  1515. // This is really shorthand for "this phi cannot cycle due to forward
  1516. // change in value of the phi is guaranteed not to later change the value of
  1517. // the phi. IE it can't be v = phi(undef, v+1)
  1518. bool OriginalOpsConstant = true;
  1519. auto *E = cast<PHIExpression>(createPHIExpression(
  1520. PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
  1521. // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
  1522. // See if all arguments are the same.
  1523. // We track if any were undef because they need special handling.
  1524. bool HasUndef = false, HasPoison = false;
  1525. auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
  1526. if (isa<PoisonValue>(Arg)) {
  1527. HasPoison = true;
  1528. return false;
  1529. }
  1530. if (isa<UndefValue>(Arg)) {
  1531. HasUndef = true;
  1532. return false;
  1533. }
  1534. return true;
  1535. });
  1536. // If we are left with no operands, it's dead.
  1537. if (Filtered.empty()) {
  1538. // If it has undef or poison at this point, it means there are no-non-undef
  1539. // arguments, and thus, the value of the phi node must be undef.
  1540. if (HasUndef) {
  1541. LLVM_DEBUG(
  1542. dbgs() << "PHI Node " << *I
  1543. << " has no non-undef arguments, valuing it as undef\n");
  1544. return createConstantExpression(UndefValue::get(I->getType()));
  1545. }
  1546. if (HasPoison) {
  1547. LLVM_DEBUG(
  1548. dbgs() << "PHI Node " << *I
  1549. << " has no non-poison arguments, valuing it as poison\n");
  1550. return createConstantExpression(PoisonValue::get(I->getType()));
  1551. }
  1552. LLVM_DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
  1553. deleteExpression(E);
  1554. return createDeadExpression();
  1555. }
  1556. Value *AllSameValue = *(Filtered.begin());
  1557. ++Filtered.begin();
  1558. // Can't use std::equal here, sadly, because filter.begin moves.
  1559. if (llvm::all_of(Filtered, [&](Value *Arg) { return Arg == AllSameValue; })) {
  1560. // Can't fold phi(undef, X) -> X unless X can't be poison (thus X is undef
  1561. // in the worst case).
  1562. if (HasUndef && !isGuaranteedNotToBePoison(AllSameValue, AC, nullptr, DT))
  1563. return E;
  1564. // In LLVM's non-standard representation of phi nodes, it's possible to have
  1565. // phi nodes with cycles (IE dependent on other phis that are .... dependent
  1566. // on the original phi node), especially in weird CFG's where some arguments
  1567. // are unreachable, or uninitialized along certain paths. This can cause
  1568. // infinite loops during evaluation. We work around this by not trying to
  1569. // really evaluate them independently, but instead using a variable
  1570. // expression to say if one is equivalent to the other.
  1571. // We also special case undef/poison, so that if we have an undef, we can't
  1572. // use the common value unless it dominates the phi block.
  1573. if (HasPoison || HasUndef) {
  1574. // If we have undef and at least one other value, this is really a
  1575. // multivalued phi, and we need to know if it's cycle free in order to
  1576. // evaluate whether we can ignore the undef. The other parts of this are
  1577. // just shortcuts. If there is no backedge, or all operands are
  1578. // constants, it also must be cycle free.
  1579. if (HasBackedge && !OriginalOpsConstant &&
  1580. !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
  1581. return E;
  1582. // Only have to check for instructions
  1583. if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
  1584. if (!someEquivalentDominates(AllSameInst, I))
  1585. return E;
  1586. }
  1587. // Can't simplify to something that comes later in the iteration.
  1588. // Otherwise, when and if it changes congruence class, we will never catch
  1589. // up. We will always be a class behind it.
  1590. if (isa<Instruction>(AllSameValue) &&
  1591. InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
  1592. return E;
  1593. NumGVNPhisAllSame++;
  1594. LLVM_DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
  1595. << "\n");
  1596. deleteExpression(E);
  1597. return createVariableOrConstant(AllSameValue);
  1598. }
  1599. return E;
  1600. }
  1601. const Expression *
  1602. NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
  1603. if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
  1604. auto *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
  1605. if (WO && EI->getNumIndices() == 1 && *EI->idx_begin() == 0)
  1606. // EI is an extract from one of our with.overflow intrinsics. Synthesize
  1607. // a semantically equivalent expression instead of an extract value
  1608. // expression.
  1609. return createBinaryExpression(WO->getBinaryOp(), EI->getType(),
  1610. WO->getLHS(), WO->getRHS(), I);
  1611. }
  1612. return createAggregateValueExpression(I);
  1613. }
  1614. NewGVN::ExprResult NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
  1615. assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
  1616. auto *CI = cast<CmpInst>(I);
  1617. // See if our operands are equal to those of a previous predicate, and if so,
  1618. // if it implies true or false.
  1619. auto Op0 = lookupOperandLeader(CI->getOperand(0));
  1620. auto Op1 = lookupOperandLeader(CI->getOperand(1));
  1621. auto OurPredicate = CI->getPredicate();
  1622. if (shouldSwapOperands(Op0, Op1)) {
  1623. std::swap(Op0, Op1);
  1624. OurPredicate = CI->getSwappedPredicate();
  1625. }
  1626. // Avoid processing the same info twice.
  1627. const PredicateBase *LastPredInfo = nullptr;
  1628. // See if we know something about the comparison itself, like it is the target
  1629. // of an assume.
  1630. auto *CmpPI = PredInfo->getPredicateInfoFor(I);
  1631. if (isa_and_nonnull<PredicateAssume>(CmpPI))
  1632. return ExprResult::some(
  1633. createConstantExpression(ConstantInt::getTrue(CI->getType())));
  1634. if (Op0 == Op1) {
  1635. // This condition does not depend on predicates, no need to add users
  1636. if (CI->isTrueWhenEqual())
  1637. return ExprResult::some(
  1638. createConstantExpression(ConstantInt::getTrue(CI->getType())));
  1639. else if (CI->isFalseWhenEqual())
  1640. return ExprResult::some(
  1641. createConstantExpression(ConstantInt::getFalse(CI->getType())));
  1642. }
  1643. // NOTE: Because we are comparing both operands here and below, and using
  1644. // previous comparisons, we rely on fact that predicateinfo knows to mark
  1645. // comparisons that use renamed operands as users of the earlier comparisons.
  1646. // It is *not* enough to just mark predicateinfo renamed operands as users of
  1647. // the earlier comparisons, because the *other* operand may have changed in a
  1648. // previous iteration.
  1649. // Example:
  1650. // icmp slt %a, %b
  1651. // %b.0 = ssa.copy(%b)
  1652. // false branch:
  1653. // icmp slt %c, %b.0
  1654. // %c and %a may start out equal, and thus, the code below will say the second
  1655. // %icmp is false. c may become equal to something else, and in that case the
  1656. // %second icmp *must* be reexamined, but would not if only the renamed
  1657. // %operands are considered users of the icmp.
  1658. // *Currently* we only check one level of comparisons back, and only mark one
  1659. // level back as touched when changes happen. If you modify this code to look
  1660. // back farther through comparisons, you *must* mark the appropriate
  1661. // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
  1662. // we know something just from the operands themselves
  1663. // See if our operands have predicate info, so that we may be able to derive
  1664. // something from a previous comparison.
  1665. for (const auto &Op : CI->operands()) {
  1666. auto *PI = PredInfo->getPredicateInfoFor(Op);
  1667. if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
  1668. if (PI == LastPredInfo)
  1669. continue;
  1670. LastPredInfo = PI;
  1671. // In phi of ops cases, we may have predicate info that we are evaluating
  1672. // in a different context.
  1673. if (!DT->dominates(PBranch->To, getBlockForValue(I)))
  1674. continue;
  1675. // TODO: Along the false edge, we may know more things too, like
  1676. // icmp of
  1677. // same operands is false.
  1678. // TODO: We only handle actual comparison conditions below, not
  1679. // and/or.
  1680. auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
  1681. if (!BranchCond)
  1682. continue;
  1683. auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
  1684. auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
  1685. auto BranchPredicate = BranchCond->getPredicate();
  1686. if (shouldSwapOperands(BranchOp0, BranchOp1)) {
  1687. std::swap(BranchOp0, BranchOp1);
  1688. BranchPredicate = BranchCond->getSwappedPredicate();
  1689. }
  1690. if (BranchOp0 == Op0 && BranchOp1 == Op1) {
  1691. if (PBranch->TrueEdge) {
  1692. // If we know the previous predicate is true and we are in the true
  1693. // edge then we may be implied true or false.
  1694. if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
  1695. OurPredicate)) {
  1696. return ExprResult::some(
  1697. createConstantExpression(ConstantInt::getTrue(CI->getType())),
  1698. PI);
  1699. }
  1700. if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
  1701. OurPredicate)) {
  1702. return ExprResult::some(
  1703. createConstantExpression(ConstantInt::getFalse(CI->getType())),
  1704. PI);
  1705. }
  1706. } else {
  1707. // Just handle the ne and eq cases, where if we have the same
  1708. // operands, we may know something.
  1709. if (BranchPredicate == OurPredicate) {
  1710. // Same predicate, same ops,we know it was false, so this is false.
  1711. return ExprResult::some(
  1712. createConstantExpression(ConstantInt::getFalse(CI->getType())),
  1713. PI);
  1714. } else if (BranchPredicate ==
  1715. CmpInst::getInversePredicate(OurPredicate)) {
  1716. // Inverse predicate, we know the other was false, so this is true.
  1717. return ExprResult::some(
  1718. createConstantExpression(ConstantInt::getTrue(CI->getType())),
  1719. PI);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. }
  1725. // Create expression will take care of simplifyCmpInst
  1726. return createExpression(I);
  1727. }
  1728. // Substitute and symbolize the value before value numbering.
  1729. NewGVN::ExprResult
  1730. NewGVN::performSymbolicEvaluation(Value *V,
  1731. SmallPtrSetImpl<Value *> &Visited) const {
  1732. const Expression *E = nullptr;
  1733. if (auto *C = dyn_cast<Constant>(V))
  1734. E = createConstantExpression(C);
  1735. else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
  1736. E = createVariableExpression(V);
  1737. } else {
  1738. // TODO: memory intrinsics.
  1739. // TODO: Some day, we should do the forward propagation and reassociation
  1740. // parts of the algorithm.
  1741. auto *I = cast<Instruction>(V);
  1742. switch (I->getOpcode()) {
  1743. case Instruction::ExtractValue:
  1744. case Instruction::InsertValue:
  1745. E = performSymbolicAggrValueEvaluation(I);
  1746. break;
  1747. case Instruction::PHI: {
  1748. SmallVector<ValPair, 3> Ops;
  1749. auto *PN = cast<PHINode>(I);
  1750. for (unsigned i = 0; i < PN->getNumOperands(); ++i)
  1751. Ops.push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
  1752. // Sort to ensure the invariant createPHIExpression requires is met.
  1753. sortPHIOps(Ops);
  1754. E = performSymbolicPHIEvaluation(Ops, I, getBlockForValue(I));
  1755. } break;
  1756. case Instruction::Call:
  1757. return performSymbolicCallEvaluation(I);
  1758. break;
  1759. case Instruction::Store:
  1760. E = performSymbolicStoreEvaluation(I);
  1761. break;
  1762. case Instruction::Load:
  1763. E = performSymbolicLoadEvaluation(I);
  1764. break;
  1765. case Instruction::BitCast:
  1766. case Instruction::AddrSpaceCast:
  1767. return createExpression(I);
  1768. break;
  1769. case Instruction::ICmp:
  1770. case Instruction::FCmp:
  1771. return performSymbolicCmpEvaluation(I);
  1772. break;
  1773. case Instruction::FNeg:
  1774. case Instruction::Add:
  1775. case Instruction::FAdd:
  1776. case Instruction::Sub:
  1777. case Instruction::FSub:
  1778. case Instruction::Mul:
  1779. case Instruction::FMul:
  1780. case Instruction::UDiv:
  1781. case Instruction::SDiv:
  1782. case Instruction::FDiv:
  1783. case Instruction::URem:
  1784. case Instruction::SRem:
  1785. case Instruction::FRem:
  1786. case Instruction::Shl:
  1787. case Instruction::LShr:
  1788. case Instruction::AShr:
  1789. case Instruction::And:
  1790. case Instruction::Or:
  1791. case Instruction::Xor:
  1792. case Instruction::Trunc:
  1793. case Instruction::ZExt:
  1794. case Instruction::SExt:
  1795. case Instruction::FPToUI:
  1796. case Instruction::FPToSI:
  1797. case Instruction::UIToFP:
  1798. case Instruction::SIToFP:
  1799. case Instruction::FPTrunc:
  1800. case Instruction::FPExt:
  1801. case Instruction::PtrToInt:
  1802. case Instruction::IntToPtr:
  1803. case Instruction::Select:
  1804. case Instruction::ExtractElement:
  1805. case Instruction::InsertElement:
  1806. case Instruction::GetElementPtr:
  1807. return createExpression(I);
  1808. break;
  1809. case Instruction::ShuffleVector:
  1810. // FIXME: Add support for shufflevector to createExpression.
  1811. return ExprResult::none();
  1812. default:
  1813. return ExprResult::none();
  1814. }
  1815. }
  1816. return ExprResult::some(E);
  1817. }
  1818. // Look up a container of values/instructions in a map, and touch all the
  1819. // instructions in the container. Then erase value from the map.
  1820. template <typename Map, typename KeyType>
  1821. void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
  1822. const auto Result = M.find_as(Key);
  1823. if (Result != M.end()) {
  1824. for (const typename Map::mapped_type::value_type Mapped : Result->second)
  1825. TouchedInstructions.set(InstrToDFSNum(Mapped));
  1826. M.erase(Result);
  1827. }
  1828. }
  1829. void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
  1830. assert(User && To != User);
  1831. if (isa<Instruction>(To))
  1832. AdditionalUsers[To].insert(User);
  1833. }
  1834. void NewGVN::addAdditionalUsers(ExprResult &Res, Instruction *User) const {
  1835. if (Res.ExtraDep && Res.ExtraDep != User)
  1836. addAdditionalUsers(Res.ExtraDep, User);
  1837. Res.ExtraDep = nullptr;
  1838. if (Res.PredDep) {
  1839. if (const auto *PBranch = dyn_cast<PredicateBranch>(Res.PredDep))
  1840. PredicateToUsers[PBranch->Condition].insert(User);
  1841. else if (const auto *PAssume = dyn_cast<PredicateAssume>(Res.PredDep))
  1842. PredicateToUsers[PAssume->Condition].insert(User);
  1843. }
  1844. Res.PredDep = nullptr;
  1845. }
  1846. void NewGVN::markUsersTouched(Value *V) {
  1847. // Now mark the users as touched.
  1848. for (auto *User : V->users()) {
  1849. assert(isa<Instruction>(User) && "Use of value not within an instruction?");
  1850. TouchedInstructions.set(InstrToDFSNum(User));
  1851. }
  1852. touchAndErase(AdditionalUsers, V);
  1853. }
  1854. void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
  1855. LLVM_DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
  1856. MemoryToUsers[To].insert(U);
  1857. }
  1858. void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
  1859. TouchedInstructions.set(MemoryToDFSNum(MA));
  1860. }
  1861. void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
  1862. if (isa<MemoryUse>(MA))
  1863. return;
  1864. for (auto U : MA->users())
  1865. TouchedInstructions.set(MemoryToDFSNum(U));
  1866. touchAndErase(MemoryToUsers, MA);
  1867. }
  1868. // Touch all the predicates that depend on this instruction.
  1869. void NewGVN::markPredicateUsersTouched(Instruction *I) {
  1870. touchAndErase(PredicateToUsers, I);
  1871. }
  1872. // Mark users affected by a memory leader change.
  1873. void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
  1874. for (auto M : CC->memory())
  1875. markMemoryDefTouched(M);
  1876. }
  1877. // Touch the instructions that need to be updated after a congruence class has a
  1878. // leader change, and mark changed values.
  1879. void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
  1880. for (auto M : *CC) {
  1881. if (auto *I = dyn_cast<Instruction>(M))
  1882. TouchedInstructions.set(InstrToDFSNum(I));
  1883. LeaderChanges.insert(M);
  1884. }
  1885. }
  1886. // Give a range of things that have instruction DFS numbers, this will return
  1887. // the member of the range with the smallest dfs number.
  1888. template <class T, class Range>
  1889. T *NewGVN::getMinDFSOfRange(const Range &R) const {
  1890. std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
  1891. for (const auto X : R) {
  1892. auto DFSNum = InstrToDFSNum(X);
  1893. if (DFSNum < MinDFS.second)
  1894. MinDFS = {X, DFSNum};
  1895. }
  1896. return MinDFS.first;
  1897. }
  1898. // This function returns the MemoryAccess that should be the next leader of
  1899. // congruence class CC, under the assumption that the current leader is going to
  1900. // disappear.
  1901. const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
  1902. // TODO: If this ends up to slow, we can maintain a next memory leader like we
  1903. // do for regular leaders.
  1904. // Make sure there will be a leader to find.
  1905. assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
  1906. if (CC->getStoreCount() > 0) {
  1907. if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
  1908. return getMemoryAccess(NL);
  1909. // Find the store with the minimum DFS number.
  1910. auto *V = getMinDFSOfRange<Value>(make_filter_range(
  1911. *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
  1912. return getMemoryAccess(cast<StoreInst>(V));
  1913. }
  1914. assert(CC->getStoreCount() == 0);
  1915. // Given our assertion, hitting this part must mean
  1916. // !OldClass->memory_empty()
  1917. if (CC->memory_size() == 1)
  1918. return *CC->memory_begin();
  1919. return getMinDFSOfRange<const MemoryPhi>(CC->memory());
  1920. }
  1921. // This function returns the next value leader of a congruence class, under the
  1922. // assumption that the current leader is going away. This should end up being
  1923. // the next most dominating member.
  1924. Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
  1925. // We don't need to sort members if there is only 1, and we don't care about
  1926. // sorting the TOP class because everything either gets out of it or is
  1927. // unreachable.
  1928. if (CC->size() == 1 || CC == TOPClass) {
  1929. return *(CC->begin());
  1930. } else if (CC->getNextLeader().first) {
  1931. ++NumGVNAvoidedSortedLeaderChanges;
  1932. return CC->getNextLeader().first;
  1933. } else {
  1934. ++NumGVNSortedLeaderChanges;
  1935. // NOTE: If this ends up to slow, we can maintain a dual structure for
  1936. // member testing/insertion, or keep things mostly sorted, and sort only
  1937. // here, or use SparseBitVector or ....
  1938. return getMinDFSOfRange<Value>(*CC);
  1939. }
  1940. }
  1941. // Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
  1942. // the memory members, etc for the move.
  1943. //
  1944. // The invariants of this function are:
  1945. //
  1946. // - I must be moving to NewClass from OldClass
  1947. // - The StoreCount of OldClass and NewClass is expected to have been updated
  1948. // for I already if it is a store.
  1949. // - The OldClass memory leader has not been updated yet if I was the leader.
  1950. void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
  1951. MemoryAccess *InstMA,
  1952. CongruenceClass *OldClass,
  1953. CongruenceClass *NewClass) {
  1954. // If the leader is I, and we had a representative MemoryAccess, it should
  1955. // be the MemoryAccess of OldClass.
  1956. assert((!InstMA || !OldClass->getMemoryLeader() ||
  1957. OldClass->getLeader() != I ||
  1958. MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
  1959. MemoryAccessToClass.lookup(InstMA)) &&
  1960. "Representative MemoryAccess mismatch");
  1961. // First, see what happens to the new class
  1962. if (!NewClass->getMemoryLeader()) {
  1963. // Should be a new class, or a store becoming a leader of a new class.
  1964. assert(NewClass->size() == 1 ||
  1965. (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
  1966. NewClass->setMemoryLeader(InstMA);
  1967. // Mark it touched if we didn't just create a singleton
  1968. LLVM_DEBUG(dbgs() << "Memory class leader change for class "
  1969. << NewClass->getID()
  1970. << " due to new memory instruction becoming leader\n");
  1971. markMemoryLeaderChangeTouched(NewClass);
  1972. }
  1973. setMemoryClass(InstMA, NewClass);
  1974. // Now, fixup the old class if necessary
  1975. if (OldClass->getMemoryLeader() == InstMA) {
  1976. if (!OldClass->definesNoMemory()) {
  1977. OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
  1978. LLVM_DEBUG(dbgs() << "Memory class leader change for class "
  1979. << OldClass->getID() << " to "
  1980. << *OldClass->getMemoryLeader()
  1981. << " due to removal of old leader " << *InstMA << "\n");
  1982. markMemoryLeaderChangeTouched(OldClass);
  1983. } else
  1984. OldClass->setMemoryLeader(nullptr);
  1985. }
  1986. }
  1987. // Move a value, currently in OldClass, to be part of NewClass
  1988. // Update OldClass and NewClass for the move (including changing leaders, etc).
  1989. void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
  1990. CongruenceClass *OldClass,
  1991. CongruenceClass *NewClass) {
  1992. if (I == OldClass->getNextLeader().first)
  1993. OldClass->resetNextLeader();
  1994. OldClass->erase(I);
  1995. NewClass->insert(I);
  1996. if (NewClass->getLeader() != I)
  1997. NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
  1998. // Handle our special casing of stores.
  1999. if (auto *SI = dyn_cast<StoreInst>(I)) {
  2000. OldClass->decStoreCount();
  2001. // Okay, so when do we want to make a store a leader of a class?
  2002. // If we have a store defined by an earlier load, we want the earlier load
  2003. // to lead the class.
  2004. // If we have a store defined by something else, we want the store to lead
  2005. // the class so everything else gets the "something else" as a value.
  2006. // If we have a store as the single member of the class, we want the store
  2007. // as the leader
  2008. if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
  2009. // If it's a store expression we are using, it means we are not equivalent
  2010. // to something earlier.
  2011. if (auto *SE = dyn_cast<StoreExpression>(E)) {
  2012. NewClass->setStoredValue(SE->getStoredValue());
  2013. markValueLeaderChangeTouched(NewClass);
  2014. // Shift the new class leader to be the store
  2015. LLVM_DEBUG(dbgs() << "Changing leader of congruence class "
  2016. << NewClass->getID() << " from "
  2017. << *NewClass->getLeader() << " to " << *SI
  2018. << " because store joined class\n");
  2019. // If we changed the leader, we have to mark it changed because we don't
  2020. // know what it will do to symbolic evaluation.
  2021. NewClass->setLeader(SI);
  2022. }
  2023. // We rely on the code below handling the MemoryAccess change.
  2024. }
  2025. NewClass->incStoreCount();
  2026. }
  2027. // True if there is no memory instructions left in a class that had memory
  2028. // instructions before.
  2029. // If it's not a memory use, set the MemoryAccess equivalence
  2030. auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
  2031. if (InstMA)
  2032. moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
  2033. ValueToClass[I] = NewClass;
  2034. // See if we destroyed the class or need to swap leaders.
  2035. if (OldClass->empty() && OldClass != TOPClass) {
  2036. if (OldClass->getDefiningExpr()) {
  2037. LLVM_DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
  2038. << " from table\n");
  2039. // We erase it as an exact expression to make sure we don't just erase an
  2040. // equivalent one.
  2041. auto Iter = ExpressionToClass.find_as(
  2042. ExactEqualsExpression(*OldClass->getDefiningExpr()));
  2043. if (Iter != ExpressionToClass.end())
  2044. ExpressionToClass.erase(Iter);
  2045. #ifdef EXPENSIVE_CHECKS
  2046. assert(
  2047. (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
  2048. "We erased the expression we just inserted, which should not happen");
  2049. #endif
  2050. }
  2051. } else if (OldClass->getLeader() == I) {
  2052. // When the leader changes, the value numbering of
  2053. // everything may change due to symbolization changes, so we need to
  2054. // reprocess.
  2055. LLVM_DEBUG(dbgs() << "Value class leader change for class "
  2056. << OldClass->getID() << "\n");
  2057. ++NumGVNLeaderChanges;
  2058. // Destroy the stored value if there are no more stores to represent it.
  2059. // Note that this is basically clean up for the expression removal that
  2060. // happens below. If we remove stores from a class, we may leave it as a
  2061. // class of equivalent memory phis.
  2062. if (OldClass->getStoreCount() == 0) {
  2063. if (OldClass->getStoredValue())
  2064. OldClass->setStoredValue(nullptr);
  2065. }
  2066. OldClass->setLeader(getNextValueLeader(OldClass));
  2067. OldClass->resetNextLeader();
  2068. markValueLeaderChangeTouched(OldClass);
  2069. }
  2070. }
  2071. // For a given expression, mark the phi of ops instructions that could have
  2072. // changed as a result.
  2073. void NewGVN::markPhiOfOpsChanged(const Expression *E) {
  2074. touchAndErase(ExpressionToPhiOfOps, E);
  2075. }
  2076. // Perform congruence finding on a given value numbering expression.
  2077. void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
  2078. // This is guaranteed to return something, since it will at least find
  2079. // TOP.
  2080. CongruenceClass *IClass = ValueToClass.lookup(I);
  2081. assert(IClass && "Should have found a IClass");
  2082. // Dead classes should have been eliminated from the mapping.
  2083. assert(!IClass->isDead() && "Found a dead class");
  2084. CongruenceClass *EClass = nullptr;
  2085. if (const auto *VE = dyn_cast<VariableExpression>(E)) {
  2086. EClass = ValueToClass.lookup(VE->getVariableValue());
  2087. } else if (isa<DeadExpression>(E)) {
  2088. EClass = TOPClass;
  2089. }
  2090. if (!EClass) {
  2091. auto lookupResult = ExpressionToClass.insert({E, nullptr});
  2092. // If it's not in the value table, create a new congruence class.
  2093. if (lookupResult.second) {
  2094. CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
  2095. auto place = lookupResult.first;
  2096. place->second = NewClass;
  2097. // Constants and variables should always be made the leader.
  2098. if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
  2099. NewClass->setLeader(CE->getConstantValue());
  2100. } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
  2101. StoreInst *SI = SE->getStoreInst();
  2102. NewClass->setLeader(SI);
  2103. NewClass->setStoredValue(SE->getStoredValue());
  2104. // The RepMemoryAccess field will be filled in properly by the
  2105. // moveValueToNewCongruenceClass call.
  2106. } else {
  2107. NewClass->setLeader(I);
  2108. }
  2109. assert(!isa<VariableExpression>(E) &&
  2110. "VariableExpression should have been handled already");
  2111. EClass = NewClass;
  2112. LLVM_DEBUG(dbgs() << "Created new congruence class for " << *I
  2113. << " using expression " << *E << " at "
  2114. << NewClass->getID() << " and leader "
  2115. << *(NewClass->getLeader()));
  2116. if (NewClass->getStoredValue())
  2117. LLVM_DEBUG(dbgs() << " and stored value "
  2118. << *(NewClass->getStoredValue()));
  2119. LLVM_DEBUG(dbgs() << "\n");
  2120. } else {
  2121. EClass = lookupResult.first->second;
  2122. if (isa<ConstantExpression>(E))
  2123. assert((isa<Constant>(EClass->getLeader()) ||
  2124. (EClass->getStoredValue() &&
  2125. isa<Constant>(EClass->getStoredValue()))) &&
  2126. "Any class with a constant expression should have a "
  2127. "constant leader");
  2128. assert(EClass && "Somehow don't have an eclass");
  2129. assert(!EClass->isDead() && "We accidentally looked up a dead class");
  2130. }
  2131. }
  2132. bool ClassChanged = IClass != EClass;
  2133. bool LeaderChanged = LeaderChanges.erase(I);
  2134. if (ClassChanged || LeaderChanged) {
  2135. LLVM_DEBUG(dbgs() << "New class " << EClass->getID() << " for expression "
  2136. << *E << "\n");
  2137. if (ClassChanged) {
  2138. moveValueToNewCongruenceClass(I, E, IClass, EClass);
  2139. markPhiOfOpsChanged(E);
  2140. }
  2141. markUsersTouched(I);
  2142. if (MemoryAccess *MA = getMemoryAccess(I))
  2143. markMemoryUsersTouched(MA);
  2144. if (auto *CI = dyn_cast<CmpInst>(I))
  2145. markPredicateUsersTouched(CI);
  2146. }
  2147. // If we changed the class of the store, we want to ensure nothing finds the
  2148. // old store expression. In particular, loads do not compare against stored
  2149. // value, so they will find old store expressions (and associated class
  2150. // mappings) if we leave them in the table.
  2151. if (ClassChanged && isa<StoreInst>(I)) {
  2152. auto *OldE = ValueToExpression.lookup(I);
  2153. // It could just be that the old class died. We don't want to erase it if we
  2154. // just moved classes.
  2155. if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
  2156. // Erase this as an exact expression to ensure we don't erase expressions
  2157. // equivalent to it.
  2158. auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
  2159. if (Iter != ExpressionToClass.end())
  2160. ExpressionToClass.erase(Iter);
  2161. }
  2162. }
  2163. ValueToExpression[I] = E;
  2164. }
  2165. // Process the fact that Edge (from, to) is reachable, including marking
  2166. // any newly reachable blocks and instructions for processing.
  2167. void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
  2168. // Check if the Edge was reachable before.
  2169. if (ReachableEdges.insert({From, To}).second) {
  2170. // If this block wasn't reachable before, all instructions are touched.
  2171. if (ReachableBlocks.insert(To).second) {
  2172. LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
  2173. << " marked reachable\n");
  2174. const auto &InstRange = BlockInstRange.lookup(To);
  2175. TouchedInstructions.set(InstRange.first, InstRange.second);
  2176. } else {
  2177. LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
  2178. << " was reachable, but new edge {"
  2179. << getBlockName(From) << "," << getBlockName(To)
  2180. << "} to it found\n");
  2181. // We've made an edge reachable to an existing block, which may
  2182. // impact predicates. Otherwise, only mark the phi nodes as touched, as
  2183. // they are the only thing that depend on new edges. Anything using their
  2184. // values will get propagated to if necessary.
  2185. if (MemoryAccess *MemPhi = getMemoryAccess(To))
  2186. TouchedInstructions.set(InstrToDFSNum(MemPhi));
  2187. // FIXME: We should just add a union op on a Bitvector and
  2188. // SparseBitVector. We can do it word by word faster than we are doing it
  2189. // here.
  2190. for (auto InstNum : RevisitOnReachabilityChange[To])
  2191. TouchedInstructions.set(InstNum);
  2192. }
  2193. }
  2194. }
  2195. // Given a predicate condition (from a switch, cmp, or whatever) and a block,
  2196. // see if we know some constant value for it already.
  2197. Value *NewGVN::findConditionEquivalence(Value *Cond) const {
  2198. auto Result = lookupOperandLeader(Cond);
  2199. return isa<Constant>(Result) ? Result : nullptr;
  2200. }
  2201. // Process the outgoing edges of a block for reachability.
  2202. void NewGVN::processOutgoingEdges(Instruction *TI, BasicBlock *B) {
  2203. // Evaluate reachability of terminator instruction.
  2204. Value *Cond;
  2205. BasicBlock *TrueSucc, *FalseSucc;
  2206. if (match(TI, m_Br(m_Value(Cond), TrueSucc, FalseSucc))) {
  2207. Value *CondEvaluated = findConditionEquivalence(Cond);
  2208. if (!CondEvaluated) {
  2209. if (auto *I = dyn_cast<Instruction>(Cond)) {
  2210. SmallPtrSet<Value *, 4> Visited;
  2211. auto Res = performSymbolicEvaluation(I, Visited);
  2212. if (const auto *CE = dyn_cast_or_null<ConstantExpression>(Res.Expr)) {
  2213. CondEvaluated = CE->getConstantValue();
  2214. addAdditionalUsers(Res, I);
  2215. } else {
  2216. // Did not use simplification result, no need to add the extra
  2217. // dependency.
  2218. Res.ExtraDep = nullptr;
  2219. }
  2220. } else if (isa<ConstantInt>(Cond)) {
  2221. CondEvaluated = Cond;
  2222. }
  2223. }
  2224. ConstantInt *CI;
  2225. if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
  2226. if (CI->isOne()) {
  2227. LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
  2228. << " evaluated to true\n");
  2229. updateReachableEdge(B, TrueSucc);
  2230. } else if (CI->isZero()) {
  2231. LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
  2232. << " evaluated to false\n");
  2233. updateReachableEdge(B, FalseSucc);
  2234. }
  2235. } else {
  2236. updateReachableEdge(B, TrueSucc);
  2237. updateReachableEdge(B, FalseSucc);
  2238. }
  2239. } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
  2240. // For switches, propagate the case values into the case
  2241. // destinations.
  2242. Value *SwitchCond = SI->getCondition();
  2243. Value *CondEvaluated = findConditionEquivalence(SwitchCond);
  2244. // See if we were able to turn this switch statement into a constant.
  2245. if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
  2246. auto *CondVal = cast<ConstantInt>(CondEvaluated);
  2247. // We should be able to get case value for this.
  2248. auto Case = *SI->findCaseValue(CondVal);
  2249. if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
  2250. // We proved the value is outside of the range of the case.
  2251. // We can't do anything other than mark the default dest as reachable,
  2252. // and go home.
  2253. updateReachableEdge(B, SI->getDefaultDest());
  2254. return;
  2255. }
  2256. // Now get where it goes and mark it reachable.
  2257. BasicBlock *TargetBlock = Case.getCaseSuccessor();
  2258. updateReachableEdge(B, TargetBlock);
  2259. } else {
  2260. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  2261. BasicBlock *TargetBlock = SI->getSuccessor(i);
  2262. updateReachableEdge(B, TargetBlock);
  2263. }
  2264. }
  2265. } else {
  2266. // Otherwise this is either unconditional, or a type we have no
  2267. // idea about. Just mark successors as reachable.
  2268. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
  2269. BasicBlock *TargetBlock = TI->getSuccessor(i);
  2270. updateReachableEdge(B, TargetBlock);
  2271. }
  2272. // This also may be a memory defining terminator, in which case, set it
  2273. // equivalent only to itself.
  2274. //
  2275. auto *MA = getMemoryAccess(TI);
  2276. if (MA && !isa<MemoryUse>(MA)) {
  2277. auto *CC = ensureLeaderOfMemoryClass(MA);
  2278. if (setMemoryClass(MA, CC))
  2279. markMemoryUsersTouched(MA);
  2280. }
  2281. }
  2282. }
  2283. // Remove the PHI of Ops PHI for I
  2284. void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
  2285. InstrDFS.erase(PHITemp);
  2286. // It's still a temp instruction. We keep it in the array so it gets erased.
  2287. // However, it's no longer used by I, or in the block
  2288. TempToBlock.erase(PHITemp);
  2289. RealToTemp.erase(I);
  2290. // We don't remove the users from the phi node uses. This wastes a little
  2291. // time, but such is life. We could use two sets to track which were there
  2292. // are the start of NewGVN, and which were added, but right nowt he cost of
  2293. // tracking is more than the cost of checking for more phi of ops.
  2294. }
  2295. // Add PHI Op in BB as a PHI of operations version of ExistingValue.
  2296. void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
  2297. Instruction *ExistingValue) {
  2298. InstrDFS[Op] = InstrToDFSNum(ExistingValue);
  2299. AllTempInstructions.insert(Op);
  2300. TempToBlock[Op] = BB;
  2301. RealToTemp[ExistingValue] = Op;
  2302. // Add all users to phi node use, as they are now uses of the phi of ops phis
  2303. // and may themselves be phi of ops.
  2304. for (auto *U : ExistingValue->users())
  2305. if (auto *UI = dyn_cast<Instruction>(U))
  2306. PHINodeUses.insert(UI);
  2307. }
  2308. static bool okayForPHIOfOps(const Instruction *I) {
  2309. if (!EnablePhiOfOps)
  2310. return false;
  2311. return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
  2312. isa<LoadInst>(I);
  2313. }
  2314. bool NewGVN::OpIsSafeForPHIOfOpsHelper(
  2315. Value *V, const BasicBlock *PHIBlock,
  2316. SmallPtrSetImpl<const Value *> &Visited,
  2317. SmallVectorImpl<Instruction *> &Worklist) {
  2318. if (!isa<Instruction>(V))
  2319. return true;
  2320. auto OISIt = OpSafeForPHIOfOps.find(V);
  2321. if (OISIt != OpSafeForPHIOfOps.end())
  2322. return OISIt->second;
  2323. // Keep walking until we either dominate the phi block, or hit a phi, or run
  2324. // out of things to check.
  2325. if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
  2326. OpSafeForPHIOfOps.insert({V, true});
  2327. return true;
  2328. }
  2329. // PHI in the same block.
  2330. if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
  2331. OpSafeForPHIOfOps.insert({V, false});
  2332. return false;
  2333. }
  2334. auto *OrigI = cast<Instruction>(V);
  2335. // When we hit an instruction that reads memory (load, call, etc), we must
  2336. // consider any store that may happen in the loop. For now, we assume the
  2337. // worst: there is a store in the loop that alias with this read.
  2338. // The case where the load is outside the loop is already covered by the
  2339. // dominator check above.
  2340. // TODO: relax this condition
  2341. if (OrigI->mayReadFromMemory())
  2342. return false;
  2343. for (auto *Op : OrigI->operand_values()) {
  2344. if (!isa<Instruction>(Op))
  2345. continue;
  2346. // Stop now if we find an unsafe operand.
  2347. auto OISIt = OpSafeForPHIOfOps.find(OrigI);
  2348. if (OISIt != OpSafeForPHIOfOps.end()) {
  2349. if (!OISIt->second) {
  2350. OpSafeForPHIOfOps.insert({V, false});
  2351. return false;
  2352. }
  2353. continue;
  2354. }
  2355. if (!Visited.insert(Op).second)
  2356. continue;
  2357. Worklist.push_back(cast<Instruction>(Op));
  2358. }
  2359. return true;
  2360. }
  2361. // Return true if this operand will be safe to use for phi of ops.
  2362. //
  2363. // The reason some operands are unsafe is that we are not trying to recursively
  2364. // translate everything back through phi nodes. We actually expect some lookups
  2365. // of expressions to fail. In particular, a lookup where the expression cannot
  2366. // exist in the predecessor. This is true even if the expression, as shown, can
  2367. // be determined to be constant.
  2368. bool NewGVN::OpIsSafeForPHIOfOps(Value *V, const BasicBlock *PHIBlock,
  2369. SmallPtrSetImpl<const Value *> &Visited) {
  2370. SmallVector<Instruction *, 4> Worklist;
  2371. if (!OpIsSafeForPHIOfOpsHelper(V, PHIBlock, Visited, Worklist))
  2372. return false;
  2373. while (!Worklist.empty()) {
  2374. auto *I = Worklist.pop_back_val();
  2375. if (!OpIsSafeForPHIOfOpsHelper(I, PHIBlock, Visited, Worklist))
  2376. return false;
  2377. }
  2378. OpSafeForPHIOfOps.insert({V, true});
  2379. return true;
  2380. }
  2381. // Try to find a leader for instruction TransInst, which is a phi translated
  2382. // version of something in our original program. Visited is used to ensure we
  2383. // don't infinite loop during translations of cycles. OrigInst is the
  2384. // instruction in the original program, and PredBB is the predecessor we
  2385. // translated it through.
  2386. Value *NewGVN::findLeaderForInst(Instruction *TransInst,
  2387. SmallPtrSetImpl<Value *> &Visited,
  2388. MemoryAccess *MemAccess, Instruction *OrigInst,
  2389. BasicBlock *PredBB) {
  2390. unsigned IDFSNum = InstrToDFSNum(OrigInst);
  2391. // Make sure it's marked as a temporary instruction.
  2392. AllTempInstructions.insert(TransInst);
  2393. // and make sure anything that tries to add it's DFS number is
  2394. // redirected to the instruction we are making a phi of ops
  2395. // for.
  2396. TempToBlock.insert({TransInst, PredBB});
  2397. InstrDFS.insert({TransInst, IDFSNum});
  2398. auto Res = performSymbolicEvaluation(TransInst, Visited);
  2399. const Expression *E = Res.Expr;
  2400. addAdditionalUsers(Res, OrigInst);
  2401. InstrDFS.erase(TransInst);
  2402. AllTempInstructions.erase(TransInst);
  2403. TempToBlock.erase(TransInst);
  2404. if (MemAccess)
  2405. TempToMemory.erase(TransInst);
  2406. if (!E)
  2407. return nullptr;
  2408. auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
  2409. if (!FoundVal) {
  2410. ExpressionToPhiOfOps[E].insert(OrigInst);
  2411. LLVM_DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
  2412. << " in block " << getBlockName(PredBB) << "\n");
  2413. return nullptr;
  2414. }
  2415. if (auto *SI = dyn_cast<StoreInst>(FoundVal))
  2416. FoundVal = SI->getValueOperand();
  2417. return FoundVal;
  2418. }
  2419. // When we see an instruction that is an op of phis, generate the equivalent phi
  2420. // of ops form.
  2421. const Expression *
  2422. NewGVN::makePossiblePHIOfOps(Instruction *I,
  2423. SmallPtrSetImpl<Value *> &Visited) {
  2424. if (!okayForPHIOfOps(I))
  2425. return nullptr;
  2426. if (!Visited.insert(I).second)
  2427. return nullptr;
  2428. // For now, we require the instruction be cycle free because we don't
  2429. // *always* create a phi of ops for instructions that could be done as phi
  2430. // of ops, we only do it if we think it is useful. If we did do it all the
  2431. // time, we could remove the cycle free check.
  2432. if (!isCycleFree(I))
  2433. return nullptr;
  2434. SmallPtrSet<const Value *, 8> ProcessedPHIs;
  2435. // TODO: We don't do phi translation on memory accesses because it's
  2436. // complicated. For a load, we'd need to be able to simulate a new memoryuse,
  2437. // which we don't have a good way of doing ATM.
  2438. auto *MemAccess = getMemoryAccess(I);
  2439. // If the memory operation is defined by a memory operation this block that
  2440. // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
  2441. // can't help, as it would still be killed by that memory operation.
  2442. if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
  2443. MemAccess->getDefiningAccess()->getBlock() == I->getParent())
  2444. return nullptr;
  2445. // Convert op of phis to phi of ops
  2446. SmallPtrSet<const Value *, 10> VisitedOps;
  2447. SmallVector<Value *, 4> Ops(I->operand_values());
  2448. BasicBlock *SamePHIBlock = nullptr;
  2449. PHINode *OpPHI = nullptr;
  2450. if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
  2451. return nullptr;
  2452. for (auto *Op : Ops) {
  2453. if (!isa<PHINode>(Op)) {
  2454. auto *ValuePHI = RealToTemp.lookup(Op);
  2455. if (!ValuePHI)
  2456. continue;
  2457. LLVM_DEBUG(dbgs() << "Found possible dependent phi of ops\n");
  2458. Op = ValuePHI;
  2459. }
  2460. OpPHI = cast<PHINode>(Op);
  2461. if (!SamePHIBlock) {
  2462. SamePHIBlock = getBlockForValue(OpPHI);
  2463. } else if (SamePHIBlock != getBlockForValue(OpPHI)) {
  2464. LLVM_DEBUG(
  2465. dbgs()
  2466. << "PHIs for operands are not all in the same block, aborting\n");
  2467. return nullptr;
  2468. }
  2469. // No point in doing this for one-operand phis.
  2470. if (OpPHI->getNumOperands() == 1) {
  2471. OpPHI = nullptr;
  2472. continue;
  2473. }
  2474. }
  2475. if (!OpPHI)
  2476. return nullptr;
  2477. SmallVector<ValPair, 4> PHIOps;
  2478. SmallPtrSet<Value *, 4> Deps;
  2479. auto *PHIBlock = getBlockForValue(OpPHI);
  2480. RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(I));
  2481. for (unsigned PredNum = 0; PredNum < OpPHI->getNumOperands(); ++PredNum) {
  2482. auto *PredBB = OpPHI->getIncomingBlock(PredNum);
  2483. Value *FoundVal = nullptr;
  2484. SmallPtrSet<Value *, 4> CurrentDeps;
  2485. // We could just skip unreachable edges entirely but it's tricky to do
  2486. // with rewriting existing phi nodes.
  2487. if (ReachableEdges.count({PredBB, PHIBlock})) {
  2488. // Clone the instruction, create an expression from it that is
  2489. // translated back into the predecessor, and see if we have a leader.
  2490. Instruction *ValueOp = I->clone();
  2491. if (MemAccess)
  2492. TempToMemory.insert({ValueOp, MemAccess});
  2493. bool SafeForPHIOfOps = true;
  2494. VisitedOps.clear();
  2495. for (auto &Op : ValueOp->operands()) {
  2496. auto *OrigOp = &*Op;
  2497. // When these operand changes, it could change whether there is a
  2498. // leader for us or not, so we have to add additional users.
  2499. if (isa<PHINode>(Op)) {
  2500. Op = Op->DoPHITranslation(PHIBlock, PredBB);
  2501. if (Op != OrigOp && Op != I)
  2502. CurrentDeps.insert(Op);
  2503. } else if (auto *ValuePHI = RealToTemp.lookup(Op)) {
  2504. if (getBlockForValue(ValuePHI) == PHIBlock)
  2505. Op = ValuePHI->getIncomingValueForBlock(PredBB);
  2506. }
  2507. // If we phi-translated the op, it must be safe.
  2508. SafeForPHIOfOps =
  2509. SafeForPHIOfOps &&
  2510. (Op != OrigOp || OpIsSafeForPHIOfOps(Op, PHIBlock, VisitedOps));
  2511. }
  2512. // FIXME: For those things that are not safe we could generate
  2513. // expressions all the way down, and see if this comes out to a
  2514. // constant. For anything where that is true, and unsafe, we should
  2515. // have made a phi-of-ops (or value numbered it equivalent to something)
  2516. // for the pieces already.
  2517. FoundVal = !SafeForPHIOfOps ? nullptr
  2518. : findLeaderForInst(ValueOp, Visited,
  2519. MemAccess, I, PredBB);
  2520. ValueOp->deleteValue();
  2521. if (!FoundVal) {
  2522. // We failed to find a leader for the current ValueOp, but this might
  2523. // change in case of the translated operands change.
  2524. if (SafeForPHIOfOps)
  2525. for (auto Dep : CurrentDeps)
  2526. addAdditionalUsers(Dep, I);
  2527. return nullptr;
  2528. }
  2529. Deps.insert(CurrentDeps.begin(), CurrentDeps.end());
  2530. } else {
  2531. LLVM_DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
  2532. << getBlockName(PredBB)
  2533. << " because the block is unreachable\n");
  2534. FoundVal = PoisonValue::get(I->getType());
  2535. RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
  2536. }
  2537. PHIOps.push_back({FoundVal, PredBB});
  2538. LLVM_DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
  2539. << getBlockName(PredBB) << "\n");
  2540. }
  2541. for (auto Dep : Deps)
  2542. addAdditionalUsers(Dep, I);
  2543. sortPHIOps(PHIOps);
  2544. auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
  2545. if (isa<ConstantExpression>(E) || isa<VariableExpression>(E)) {
  2546. LLVM_DEBUG(
  2547. dbgs()
  2548. << "Not creating real PHI of ops because it simplified to existing "
  2549. "value or constant\n");
  2550. // We have leaders for all operands, but do not create a real PHI node with
  2551. // those leaders as operands, so the link between the operands and the
  2552. // PHI-of-ops is not materialized in the IR. If any of those leaders
  2553. // changes, the PHI-of-op may change also, so we need to add the operands as
  2554. // additional users.
  2555. for (auto &O : PHIOps)
  2556. addAdditionalUsers(O.first, I);
  2557. return E;
  2558. }
  2559. auto *ValuePHI = RealToTemp.lookup(I);
  2560. bool NewPHI = false;
  2561. if (!ValuePHI) {
  2562. ValuePHI =
  2563. PHINode::Create(I->getType(), OpPHI->getNumOperands(), "phiofops");
  2564. addPhiOfOps(ValuePHI, PHIBlock, I);
  2565. NewPHI = true;
  2566. NumGVNPHIOfOpsCreated++;
  2567. }
  2568. if (NewPHI) {
  2569. for (auto PHIOp : PHIOps)
  2570. ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
  2571. } else {
  2572. TempToBlock[ValuePHI] = PHIBlock;
  2573. unsigned int i = 0;
  2574. for (auto PHIOp : PHIOps) {
  2575. ValuePHI->setIncomingValue(i, PHIOp.first);
  2576. ValuePHI->setIncomingBlock(i, PHIOp.second);
  2577. ++i;
  2578. }
  2579. }
  2580. RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
  2581. LLVM_DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
  2582. << "\n");
  2583. return E;
  2584. }
  2585. // The algorithm initially places the values of the routine in the TOP
  2586. // congruence class. The leader of TOP is the undetermined value `poison`.
  2587. // When the algorithm has finished, values still in TOP are unreachable.
  2588. void NewGVN::initializeCongruenceClasses(Function &F) {
  2589. NextCongruenceNum = 0;
  2590. // Note that even though we use the live on entry def as a representative
  2591. // MemoryAccess, it is *not* the same as the actual live on entry def. We
  2592. // have no real equivalent to poison for MemoryAccesses, and so we really
  2593. // should be checking whether the MemoryAccess is top if we want to know if it
  2594. // is equivalent to everything. Otherwise, what this really signifies is that
  2595. // the access "it reaches all the way back to the beginning of the function"
  2596. // Initialize all other instructions to be in TOP class.
  2597. TOPClass = createCongruenceClass(nullptr, nullptr);
  2598. TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
  2599. // The live on entry def gets put into it's own class
  2600. MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
  2601. createMemoryClass(MSSA->getLiveOnEntryDef());
  2602. for (auto DTN : nodes(DT)) {
  2603. BasicBlock *BB = DTN->getBlock();
  2604. // All MemoryAccesses are equivalent to live on entry to start. They must
  2605. // be initialized to something so that initial changes are noticed. For
  2606. // the maximal answer, we initialize them all to be the same as
  2607. // liveOnEntry.
  2608. auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
  2609. if (MemoryBlockDefs)
  2610. for (const auto &Def : *MemoryBlockDefs) {
  2611. MemoryAccessToClass[&Def] = TOPClass;
  2612. auto *MD = dyn_cast<MemoryDef>(&Def);
  2613. // Insert the memory phis into the member list.
  2614. if (!MD) {
  2615. const MemoryPhi *MP = cast<MemoryPhi>(&Def);
  2616. TOPClass->memory_insert(MP);
  2617. MemoryPhiState.insert({MP, MPS_TOP});
  2618. }
  2619. if (MD && isa<StoreInst>(MD->getMemoryInst()))
  2620. TOPClass->incStoreCount();
  2621. }
  2622. // FIXME: This is trying to discover which instructions are uses of phi
  2623. // nodes. We should move this into one of the myriad of places that walk
  2624. // all the operands already.
  2625. for (auto &I : *BB) {
  2626. if (isa<PHINode>(&I))
  2627. for (auto *U : I.users())
  2628. if (auto *UInst = dyn_cast<Instruction>(U))
  2629. if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
  2630. PHINodeUses.insert(UInst);
  2631. // Don't insert void terminators into the class. We don't value number
  2632. // them, and they just end up sitting in TOP.
  2633. if (I.isTerminator() && I.getType()->isVoidTy())
  2634. continue;
  2635. TOPClass->insert(&I);
  2636. ValueToClass[&I] = TOPClass;
  2637. }
  2638. }
  2639. // Initialize arguments to be in their own unique congruence classes
  2640. for (auto &FA : F.args())
  2641. createSingletonCongruenceClass(&FA);
  2642. }
  2643. void NewGVN::cleanupTables() {
  2644. for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
  2645. LLVM_DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
  2646. << " has " << CongruenceClasses[i]->size()
  2647. << " members\n");
  2648. // Make sure we delete the congruence class (probably worth switching to
  2649. // a unique_ptr at some point.
  2650. delete CongruenceClasses[i];
  2651. CongruenceClasses[i] = nullptr;
  2652. }
  2653. // Destroy the value expressions
  2654. SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
  2655. AllTempInstructions.end());
  2656. AllTempInstructions.clear();
  2657. // We have to drop all references for everything first, so there are no uses
  2658. // left as we delete them.
  2659. for (auto *I : TempInst) {
  2660. I->dropAllReferences();
  2661. }
  2662. while (!TempInst.empty()) {
  2663. auto *I = TempInst.pop_back_val();
  2664. I->deleteValue();
  2665. }
  2666. ValueToClass.clear();
  2667. ArgRecycler.clear(ExpressionAllocator);
  2668. ExpressionAllocator.Reset();
  2669. CongruenceClasses.clear();
  2670. ExpressionToClass.clear();
  2671. ValueToExpression.clear();
  2672. RealToTemp.clear();
  2673. AdditionalUsers.clear();
  2674. ExpressionToPhiOfOps.clear();
  2675. TempToBlock.clear();
  2676. TempToMemory.clear();
  2677. PHINodeUses.clear();
  2678. OpSafeForPHIOfOps.clear();
  2679. ReachableBlocks.clear();
  2680. ReachableEdges.clear();
  2681. #ifndef NDEBUG
  2682. ProcessedCount.clear();
  2683. #endif
  2684. InstrDFS.clear();
  2685. InstructionsToErase.clear();
  2686. DFSToInstr.clear();
  2687. BlockInstRange.clear();
  2688. TouchedInstructions.clear();
  2689. MemoryAccessToClass.clear();
  2690. PredicateToUsers.clear();
  2691. MemoryToUsers.clear();
  2692. RevisitOnReachabilityChange.clear();
  2693. IntrinsicInstPred.clear();
  2694. }
  2695. // Assign local DFS number mapping to instructions, and leave space for Value
  2696. // PHI's.
  2697. std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
  2698. unsigned Start) {
  2699. unsigned End = Start;
  2700. if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
  2701. InstrDFS[MemPhi] = End++;
  2702. DFSToInstr.emplace_back(MemPhi);
  2703. }
  2704. // Then the real block goes next.
  2705. for (auto &I : *B) {
  2706. // There's no need to call isInstructionTriviallyDead more than once on
  2707. // an instruction. Therefore, once we know that an instruction is dead
  2708. // we change its DFS number so that it doesn't get value numbered.
  2709. if (isInstructionTriviallyDead(&I, TLI)) {
  2710. InstrDFS[&I] = 0;
  2711. LLVM_DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
  2712. markInstructionForDeletion(&I);
  2713. continue;
  2714. }
  2715. if (isa<PHINode>(&I))
  2716. RevisitOnReachabilityChange[B].set(End);
  2717. InstrDFS[&I] = End++;
  2718. DFSToInstr.emplace_back(&I);
  2719. }
  2720. // All of the range functions taken half-open ranges (open on the end side).
  2721. // So we do not subtract one from count, because at this point it is one
  2722. // greater than the last instruction.
  2723. return std::make_pair(Start, End);
  2724. }
  2725. void NewGVN::updateProcessedCount(const Value *V) {
  2726. #ifndef NDEBUG
  2727. if (ProcessedCount.count(V) == 0) {
  2728. ProcessedCount.insert({V, 1});
  2729. } else {
  2730. ++ProcessedCount[V];
  2731. assert(ProcessedCount[V] < 100 &&
  2732. "Seem to have processed the same Value a lot");
  2733. }
  2734. #endif
  2735. }
  2736. // Evaluate MemoryPhi nodes symbolically, just like PHI nodes
  2737. void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
  2738. // If all the arguments are the same, the MemoryPhi has the same value as the
  2739. // argument. Filter out unreachable blocks and self phis from our operands.
  2740. // TODO: We could do cycle-checking on the memory phis to allow valueizing for
  2741. // self-phi checking.
  2742. const BasicBlock *PHIBlock = MP->getBlock();
  2743. auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
  2744. return cast<MemoryAccess>(U) != MP &&
  2745. !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
  2746. ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
  2747. });
  2748. // If all that is left is nothing, our memoryphi is poison. We keep it as
  2749. // InitialClass. Note: The only case this should happen is if we have at
  2750. // least one self-argument.
  2751. if (Filtered.begin() == Filtered.end()) {
  2752. if (setMemoryClass(MP, TOPClass))
  2753. markMemoryUsersTouched(MP);
  2754. return;
  2755. }
  2756. // Transform the remaining operands into operand leaders.
  2757. // FIXME: mapped_iterator should have a range version.
  2758. auto LookupFunc = [&](const Use &U) {
  2759. return lookupMemoryLeader(cast<MemoryAccess>(U));
  2760. };
  2761. auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
  2762. auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
  2763. // and now check if all the elements are equal.
  2764. // Sadly, we can't use std::equals since these are random access iterators.
  2765. const auto *AllSameValue = *MappedBegin;
  2766. ++MappedBegin;
  2767. bool AllEqual = std::all_of(
  2768. MappedBegin, MappedEnd,
  2769. [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
  2770. if (AllEqual)
  2771. LLVM_DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue
  2772. << "\n");
  2773. else
  2774. LLVM_DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
  2775. // If it's equal to something, it's in that class. Otherwise, it has to be in
  2776. // a class where it is the leader (other things may be equivalent to it, but
  2777. // it needs to start off in its own class, which means it must have been the
  2778. // leader, and it can't have stopped being the leader because it was never
  2779. // removed).
  2780. CongruenceClass *CC =
  2781. AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
  2782. auto OldState = MemoryPhiState.lookup(MP);
  2783. assert(OldState != MPS_Invalid && "Invalid memory phi state");
  2784. auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
  2785. MemoryPhiState[MP] = NewState;
  2786. if (setMemoryClass(MP, CC) || OldState != NewState)
  2787. markMemoryUsersTouched(MP);
  2788. }
  2789. // Value number a single instruction, symbolically evaluating, performing
  2790. // congruence finding, and updating mappings.
  2791. void NewGVN::valueNumberInstruction(Instruction *I) {
  2792. LLVM_DEBUG(dbgs() << "Processing instruction " << *I << "\n");
  2793. if (!I->isTerminator()) {
  2794. const Expression *Symbolized = nullptr;
  2795. SmallPtrSet<Value *, 2> Visited;
  2796. if (DebugCounter::shouldExecute(VNCounter)) {
  2797. auto Res = performSymbolicEvaluation(I, Visited);
  2798. Symbolized = Res.Expr;
  2799. addAdditionalUsers(Res, I);
  2800. // Make a phi of ops if necessary
  2801. if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
  2802. !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
  2803. auto *PHIE = makePossiblePHIOfOps(I, Visited);
  2804. // If we created a phi of ops, use it.
  2805. // If we couldn't create one, make sure we don't leave one lying around
  2806. if (PHIE) {
  2807. Symbolized = PHIE;
  2808. } else if (auto *Op = RealToTemp.lookup(I)) {
  2809. removePhiOfOps(I, Op);
  2810. }
  2811. }
  2812. } else {
  2813. // Mark the instruction as unused so we don't value number it again.
  2814. InstrDFS[I] = 0;
  2815. }
  2816. // If we couldn't come up with a symbolic expression, use the unknown
  2817. // expression
  2818. if (Symbolized == nullptr)
  2819. Symbolized = createUnknownExpression(I);
  2820. performCongruenceFinding(I, Symbolized);
  2821. } else {
  2822. // Handle terminators that return values. All of them produce values we
  2823. // don't currently understand. We don't place non-value producing
  2824. // terminators in a class.
  2825. if (!I->getType()->isVoidTy()) {
  2826. auto *Symbolized = createUnknownExpression(I);
  2827. performCongruenceFinding(I, Symbolized);
  2828. }
  2829. processOutgoingEdges(I, I->getParent());
  2830. }
  2831. }
  2832. // Check if there is a path, using single or equal argument phi nodes, from
  2833. // First to Second.
  2834. bool NewGVN::singleReachablePHIPath(
  2835. SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
  2836. const MemoryAccess *Second) const {
  2837. if (First == Second)
  2838. return true;
  2839. if (MSSA->isLiveOnEntryDef(First))
  2840. return false;
  2841. // This is not perfect, but as we're just verifying here, we can live with
  2842. // the loss of precision. The real solution would be that of doing strongly
  2843. // connected component finding in this routine, and it's probably not worth
  2844. // the complexity for the time being. So, we just keep a set of visited
  2845. // MemoryAccess and return true when we hit a cycle.
  2846. if (Visited.count(First))
  2847. return true;
  2848. Visited.insert(First);
  2849. const auto *EndDef = First;
  2850. for (auto *ChainDef : optimized_def_chain(First)) {
  2851. if (ChainDef == Second)
  2852. return true;
  2853. if (MSSA->isLiveOnEntryDef(ChainDef))
  2854. return false;
  2855. EndDef = ChainDef;
  2856. }
  2857. auto *MP = cast<MemoryPhi>(EndDef);
  2858. auto ReachableOperandPred = [&](const Use &U) {
  2859. return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
  2860. };
  2861. auto FilteredPhiArgs =
  2862. make_filter_range(MP->operands(), ReachableOperandPred);
  2863. SmallVector<const Value *, 32> OperandList;
  2864. llvm::copy(FilteredPhiArgs, std::back_inserter(OperandList));
  2865. bool Okay = is_splat(OperandList);
  2866. if (Okay)
  2867. return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
  2868. Second);
  2869. return false;
  2870. }
  2871. // Verify the that the memory equivalence table makes sense relative to the
  2872. // congruence classes. Note that this checking is not perfect, and is currently
  2873. // subject to very rare false negatives. It is only useful for
  2874. // testing/debugging.
  2875. void NewGVN::verifyMemoryCongruency() const {
  2876. #ifndef NDEBUG
  2877. // Verify that the memory table equivalence and memory member set match
  2878. for (const auto *CC : CongruenceClasses) {
  2879. if (CC == TOPClass || CC->isDead())
  2880. continue;
  2881. if (CC->getStoreCount() != 0) {
  2882. assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
  2883. "Any class with a store as a leader should have a "
  2884. "representative stored value");
  2885. assert(CC->getMemoryLeader() &&
  2886. "Any congruence class with a store should have a "
  2887. "representative access");
  2888. }
  2889. if (CC->getMemoryLeader())
  2890. assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
  2891. "Representative MemoryAccess does not appear to be reverse "
  2892. "mapped properly");
  2893. for (auto M : CC->memory())
  2894. assert(MemoryAccessToClass.lookup(M) == CC &&
  2895. "Memory member does not appear to be reverse mapped properly");
  2896. }
  2897. // Anything equivalent in the MemoryAccess table should be in the same
  2898. // congruence class.
  2899. // Filter out the unreachable and trivially dead entries, because they may
  2900. // never have been updated if the instructions were not processed.
  2901. auto ReachableAccessPred =
  2902. [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
  2903. bool Result = ReachableBlocks.count(Pair.first->getBlock());
  2904. if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
  2905. MemoryToDFSNum(Pair.first) == 0)
  2906. return false;
  2907. if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
  2908. return !isInstructionTriviallyDead(MemDef->getMemoryInst());
  2909. // We could have phi nodes which operands are all trivially dead,
  2910. // so we don't process them.
  2911. if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
  2912. for (auto &U : MemPHI->incoming_values()) {
  2913. if (auto *I = dyn_cast<Instruction>(&*U)) {
  2914. if (!isInstructionTriviallyDead(I))
  2915. return true;
  2916. }
  2917. }
  2918. return false;
  2919. }
  2920. return true;
  2921. };
  2922. auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
  2923. for (auto KV : Filtered) {
  2924. if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
  2925. auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
  2926. if (FirstMUD && SecondMUD) {
  2927. SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
  2928. assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
  2929. ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
  2930. ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
  2931. "The instructions for these memory operations should have "
  2932. "been in the same congruence class or reachable through"
  2933. "a single argument phi");
  2934. }
  2935. } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
  2936. // We can only sanely verify that MemoryDefs in the operand list all have
  2937. // the same class.
  2938. auto ReachableOperandPred = [&](const Use &U) {
  2939. return ReachableEdges.count(
  2940. {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
  2941. isa<MemoryDef>(U);
  2942. };
  2943. // All arguments should in the same class, ignoring unreachable arguments
  2944. auto FilteredPhiArgs =
  2945. make_filter_range(FirstMP->operands(), ReachableOperandPred);
  2946. SmallVector<const CongruenceClass *, 16> PhiOpClasses;
  2947. std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
  2948. std::back_inserter(PhiOpClasses), [&](const Use &U) {
  2949. const MemoryDef *MD = cast<MemoryDef>(U);
  2950. return ValueToClass.lookup(MD->getMemoryInst());
  2951. });
  2952. assert(is_splat(PhiOpClasses) &&
  2953. "All MemoryPhi arguments should be in the same class");
  2954. }
  2955. }
  2956. #endif
  2957. }
  2958. // Verify that the sparse propagation we did actually found the maximal fixpoint
  2959. // We do this by storing the value to class mapping, touching all instructions,
  2960. // and redoing the iteration to see if anything changed.
  2961. void NewGVN::verifyIterationSettled(Function &F) {
  2962. #ifndef NDEBUG
  2963. LLVM_DEBUG(dbgs() << "Beginning iteration verification\n");
  2964. if (DebugCounter::isCounterSet(VNCounter))
  2965. DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
  2966. // Note that we have to store the actual classes, as we may change existing
  2967. // classes during iteration. This is because our memory iteration propagation
  2968. // is not perfect, and so may waste a little work. But it should generate
  2969. // exactly the same congruence classes we have now, with different IDs.
  2970. std::map<const Value *, CongruenceClass> BeforeIteration;
  2971. for (auto &KV : ValueToClass) {
  2972. if (auto *I = dyn_cast<Instruction>(KV.first))
  2973. // Skip unused/dead instructions.
  2974. if (InstrToDFSNum(I) == 0)
  2975. continue;
  2976. BeforeIteration.insert({KV.first, *KV.second});
  2977. }
  2978. TouchedInstructions.set();
  2979. TouchedInstructions.reset(0);
  2980. iterateTouchedInstructions();
  2981. DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
  2982. EqualClasses;
  2983. for (const auto &KV : ValueToClass) {
  2984. if (auto *I = dyn_cast<Instruction>(KV.first))
  2985. // Skip unused/dead instructions.
  2986. if (InstrToDFSNum(I) == 0)
  2987. continue;
  2988. // We could sink these uses, but i think this adds a bit of clarity here as
  2989. // to what we are comparing.
  2990. auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
  2991. auto *AfterCC = KV.second;
  2992. // Note that the classes can't change at this point, so we memoize the set
  2993. // that are equal.
  2994. if (!EqualClasses.count({BeforeCC, AfterCC})) {
  2995. assert(BeforeCC->isEquivalentTo(AfterCC) &&
  2996. "Value number changed after main loop completed!");
  2997. EqualClasses.insert({BeforeCC, AfterCC});
  2998. }
  2999. }
  3000. #endif
  3001. }
  3002. // Verify that for each store expression in the expression to class mapping,
  3003. // only the latest appears, and multiple ones do not appear.
  3004. // Because loads do not use the stored value when doing equality with stores,
  3005. // if we don't erase the old store expressions from the table, a load can find
  3006. // a no-longer valid StoreExpression.
  3007. void NewGVN::verifyStoreExpressions() const {
  3008. #ifndef NDEBUG
  3009. // This is the only use of this, and it's not worth defining a complicated
  3010. // densemapinfo hash/equality function for it.
  3011. std::set<
  3012. std::pair<const Value *,
  3013. std::tuple<const Value *, const CongruenceClass *, Value *>>>
  3014. StoreExpressionSet;
  3015. for (const auto &KV : ExpressionToClass) {
  3016. if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
  3017. // Make sure a version that will conflict with loads is not already there
  3018. auto Res = StoreExpressionSet.insert(
  3019. {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
  3020. SE->getStoredValue())});
  3021. bool Okay = Res.second;
  3022. // It's okay to have the same expression already in there if it is
  3023. // identical in nature.
  3024. // This can happen when the leader of the stored value changes over time.
  3025. if (!Okay)
  3026. Okay = (std::get<1>(Res.first->second) == KV.second) &&
  3027. (lookupOperandLeader(std::get<2>(Res.first->second)) ==
  3028. lookupOperandLeader(SE->getStoredValue()));
  3029. assert(Okay && "Stored expression conflict exists in expression table");
  3030. auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
  3031. assert(ValueExpr && ValueExpr->equals(*SE) &&
  3032. "StoreExpression in ExpressionToClass is not latest "
  3033. "StoreExpression for value");
  3034. }
  3035. }
  3036. #endif
  3037. }
  3038. // This is the main value numbering loop, it iterates over the initial touched
  3039. // instruction set, propagating value numbers, marking things touched, etc,
  3040. // until the set of touched instructions is completely empty.
  3041. void NewGVN::iterateTouchedInstructions() {
  3042. unsigned int Iterations = 0;
  3043. // Figure out where touchedinstructions starts
  3044. int FirstInstr = TouchedInstructions.find_first();
  3045. // Nothing set, nothing to iterate, just return.
  3046. if (FirstInstr == -1)
  3047. return;
  3048. const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
  3049. while (TouchedInstructions.any()) {
  3050. ++Iterations;
  3051. // Walk through all the instructions in all the blocks in RPO.
  3052. // TODO: As we hit a new block, we should push and pop equalities into a
  3053. // table lookupOperandLeader can use, to catch things PredicateInfo
  3054. // might miss, like edge-only equivalences.
  3055. for (unsigned InstrNum : TouchedInstructions.set_bits()) {
  3056. // This instruction was found to be dead. We don't bother looking
  3057. // at it again.
  3058. if (InstrNum == 0) {
  3059. TouchedInstructions.reset(InstrNum);
  3060. continue;
  3061. }
  3062. Value *V = InstrFromDFSNum(InstrNum);
  3063. const BasicBlock *CurrBlock = getBlockForValue(V);
  3064. // If we hit a new block, do reachability processing.
  3065. if (CurrBlock != LastBlock) {
  3066. LastBlock = CurrBlock;
  3067. bool BlockReachable = ReachableBlocks.count(CurrBlock);
  3068. const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
  3069. // If it's not reachable, erase any touched instructions and move on.
  3070. if (!BlockReachable) {
  3071. TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
  3072. LLVM_DEBUG(dbgs() << "Skipping instructions in block "
  3073. << getBlockName(CurrBlock)
  3074. << " because it is unreachable\n");
  3075. continue;
  3076. }
  3077. updateProcessedCount(CurrBlock);
  3078. }
  3079. // Reset after processing (because we may mark ourselves as touched when
  3080. // we propagate equalities).
  3081. TouchedInstructions.reset(InstrNum);
  3082. if (auto *MP = dyn_cast<MemoryPhi>(V)) {
  3083. LLVM_DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
  3084. valueNumberMemoryPhi(MP);
  3085. } else if (auto *I = dyn_cast<Instruction>(V)) {
  3086. valueNumberInstruction(I);
  3087. } else {
  3088. llvm_unreachable("Should have been a MemoryPhi or Instruction");
  3089. }
  3090. updateProcessedCount(V);
  3091. }
  3092. }
  3093. NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
  3094. }
  3095. // This is the main transformation entry point.
  3096. bool NewGVN::runGVN() {
  3097. if (DebugCounter::isCounterSet(VNCounter))
  3098. StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
  3099. bool Changed = false;
  3100. NumFuncArgs = F.arg_size();
  3101. MSSAWalker = MSSA->getWalker();
  3102. SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
  3103. // Count number of instructions for sizing of hash tables, and come
  3104. // up with a global dfs numbering for instructions.
  3105. unsigned ICount = 1;
  3106. // Add an empty instruction to account for the fact that we start at 1
  3107. DFSToInstr.emplace_back(nullptr);
  3108. // Note: We want ideal RPO traversal of the blocks, which is not quite the
  3109. // same as dominator tree order, particularly with regard whether backedges
  3110. // get visited first or second, given a block with multiple successors.
  3111. // If we visit in the wrong order, we will end up performing N times as many
  3112. // iterations.
  3113. // The dominator tree does guarantee that, for a given dom tree node, it's
  3114. // parent must occur before it in the RPO ordering. Thus, we only need to sort
  3115. // the siblings.
  3116. ReversePostOrderTraversal<Function *> RPOT(&F);
  3117. unsigned Counter = 0;
  3118. for (auto &B : RPOT) {
  3119. auto *Node = DT->getNode(B);
  3120. assert(Node && "RPO and Dominator tree should have same reachability");
  3121. RPOOrdering[Node] = ++Counter;
  3122. }
  3123. // Sort dominator tree children arrays into RPO.
  3124. for (auto &B : RPOT) {
  3125. auto *Node = DT->getNode(B);
  3126. if (Node->getNumChildren() > 1)
  3127. llvm::sort(*Node, [&](const DomTreeNode *A, const DomTreeNode *B) {
  3128. return RPOOrdering[A] < RPOOrdering[B];
  3129. });
  3130. }
  3131. // Now a standard depth first ordering of the domtree is equivalent to RPO.
  3132. for (auto DTN : depth_first(DT->getRootNode())) {
  3133. BasicBlock *B = DTN->getBlock();
  3134. const auto &BlockRange = assignDFSNumbers(B, ICount);
  3135. BlockInstRange.insert({B, BlockRange});
  3136. ICount += BlockRange.second - BlockRange.first;
  3137. }
  3138. initializeCongruenceClasses(F);
  3139. TouchedInstructions.resize(ICount);
  3140. // Ensure we don't end up resizing the expressionToClass map, as
  3141. // that can be quite expensive. At most, we have one expression per
  3142. // instruction.
  3143. ExpressionToClass.reserve(ICount);
  3144. // Initialize the touched instructions to include the entry block.
  3145. const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
  3146. TouchedInstructions.set(InstRange.first, InstRange.second);
  3147. LLVM_DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
  3148. << " marked reachable\n");
  3149. ReachableBlocks.insert(&F.getEntryBlock());
  3150. iterateTouchedInstructions();
  3151. verifyMemoryCongruency();
  3152. verifyIterationSettled(F);
  3153. verifyStoreExpressions();
  3154. Changed |= eliminateInstructions(F);
  3155. // Delete all instructions marked for deletion.
  3156. for (Instruction *ToErase : InstructionsToErase) {
  3157. if (!ToErase->use_empty())
  3158. ToErase->replaceAllUsesWith(PoisonValue::get(ToErase->getType()));
  3159. assert(ToErase->getParent() &&
  3160. "BB containing ToErase deleted unexpectedly!");
  3161. ToErase->eraseFromParent();
  3162. }
  3163. Changed |= !InstructionsToErase.empty();
  3164. // Delete all unreachable blocks.
  3165. auto UnreachableBlockPred = [&](const BasicBlock &BB) {
  3166. return !ReachableBlocks.count(&BB);
  3167. };
  3168. for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
  3169. LLVM_DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
  3170. << " is unreachable\n");
  3171. deleteInstructionsInBlock(&BB);
  3172. Changed = true;
  3173. }
  3174. cleanupTables();
  3175. return Changed;
  3176. }
  3177. struct NewGVN::ValueDFS {
  3178. int DFSIn = 0;
  3179. int DFSOut = 0;
  3180. int LocalNum = 0;
  3181. // Only one of Def and U will be set.
  3182. // The bool in the Def tells us whether the Def is the stored value of a
  3183. // store.
  3184. PointerIntPair<Value *, 1, bool> Def;
  3185. Use *U = nullptr;
  3186. bool operator<(const ValueDFS &Other) const {
  3187. // It's not enough that any given field be less than - we have sets
  3188. // of fields that need to be evaluated together to give a proper ordering.
  3189. // For example, if you have;
  3190. // DFS (1, 3)
  3191. // Val 0
  3192. // DFS (1, 2)
  3193. // Val 50
  3194. // We want the second to be less than the first, but if we just go field
  3195. // by field, we will get to Val 0 < Val 50 and say the first is less than
  3196. // the second. We only want it to be less than if the DFS orders are equal.
  3197. //
  3198. // Each LLVM instruction only produces one value, and thus the lowest-level
  3199. // differentiator that really matters for the stack (and what we use as as a
  3200. // replacement) is the local dfs number.
  3201. // Everything else in the structure is instruction level, and only affects
  3202. // the order in which we will replace operands of a given instruction.
  3203. //
  3204. // For a given instruction (IE things with equal dfsin, dfsout, localnum),
  3205. // the order of replacement of uses does not matter.
  3206. // IE given,
  3207. // a = 5
  3208. // b = a + a
  3209. // When you hit b, you will have two valuedfs with the same dfsin, out, and
  3210. // localnum.
  3211. // The .val will be the same as well.
  3212. // The .u's will be different.
  3213. // You will replace both, and it does not matter what order you replace them
  3214. // in (IE whether you replace operand 2, then operand 1, or operand 1, then
  3215. // operand 2).
  3216. // Similarly for the case of same dfsin, dfsout, localnum, but different
  3217. // .val's
  3218. // a = 5
  3219. // b = 6
  3220. // c = a + b
  3221. // in c, we will a valuedfs for a, and one for b,with everything the same
  3222. // but .val and .u.
  3223. // It does not matter what order we replace these operands in.
  3224. // You will always end up with the same IR, and this is guaranteed.
  3225. return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
  3226. std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
  3227. Other.U);
  3228. }
  3229. };
  3230. // This function converts the set of members for a congruence class from values,
  3231. // to sets of defs and uses with associated DFS info. The total number of
  3232. // reachable uses for each value is stored in UseCount, and instructions that
  3233. // seem
  3234. // dead (have no non-dead uses) are stored in ProbablyDead.
  3235. void NewGVN::convertClassToDFSOrdered(
  3236. const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
  3237. DenseMap<const Value *, unsigned int> &UseCounts,
  3238. SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
  3239. for (auto D : Dense) {
  3240. // First add the value.
  3241. BasicBlock *BB = getBlockForValue(D);
  3242. // Constants are handled prior to ever calling this function, so
  3243. // we should only be left with instructions as members.
  3244. assert(BB && "Should have figured out a basic block for value");
  3245. ValueDFS VDDef;
  3246. DomTreeNode *DomNode = DT->getNode(BB);
  3247. VDDef.DFSIn = DomNode->getDFSNumIn();
  3248. VDDef.DFSOut = DomNode->getDFSNumOut();
  3249. // If it's a store, use the leader of the value operand, if it's always
  3250. // available, or the value operand. TODO: We could do dominance checks to
  3251. // find a dominating leader, but not worth it ATM.
  3252. if (auto *SI = dyn_cast<StoreInst>(D)) {
  3253. auto Leader = lookupOperandLeader(SI->getValueOperand());
  3254. if (alwaysAvailable(Leader)) {
  3255. VDDef.Def.setPointer(Leader);
  3256. } else {
  3257. VDDef.Def.setPointer(SI->getValueOperand());
  3258. VDDef.Def.setInt(true);
  3259. }
  3260. } else {
  3261. VDDef.Def.setPointer(D);
  3262. }
  3263. assert(isa<Instruction>(D) &&
  3264. "The dense set member should always be an instruction");
  3265. Instruction *Def = cast<Instruction>(D);
  3266. VDDef.LocalNum = InstrToDFSNum(D);
  3267. DFSOrderedSet.push_back(VDDef);
  3268. // If there is a phi node equivalent, add it
  3269. if (auto *PN = RealToTemp.lookup(Def)) {
  3270. auto *PHIE =
  3271. dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
  3272. if (PHIE) {
  3273. VDDef.Def.setInt(false);
  3274. VDDef.Def.setPointer(PN);
  3275. VDDef.LocalNum = 0;
  3276. DFSOrderedSet.push_back(VDDef);
  3277. }
  3278. }
  3279. unsigned int UseCount = 0;
  3280. // Now add the uses.
  3281. for (auto &U : Def->uses()) {
  3282. if (auto *I = dyn_cast<Instruction>(U.getUser())) {
  3283. // Don't try to replace into dead uses
  3284. if (InstructionsToErase.count(I))
  3285. continue;
  3286. ValueDFS VDUse;
  3287. // Put the phi node uses in the incoming block.
  3288. BasicBlock *IBlock;
  3289. if (auto *P = dyn_cast<PHINode>(I)) {
  3290. IBlock = P->getIncomingBlock(U);
  3291. // Make phi node users appear last in the incoming block
  3292. // they are from.
  3293. VDUse.LocalNum = InstrDFS.size() + 1;
  3294. } else {
  3295. IBlock = getBlockForValue(I);
  3296. VDUse.LocalNum = InstrToDFSNum(I);
  3297. }
  3298. // Skip uses in unreachable blocks, as we're going
  3299. // to delete them.
  3300. if (!ReachableBlocks.contains(IBlock))
  3301. continue;
  3302. DomTreeNode *DomNode = DT->getNode(IBlock);
  3303. VDUse.DFSIn = DomNode->getDFSNumIn();
  3304. VDUse.DFSOut = DomNode->getDFSNumOut();
  3305. VDUse.U = &U;
  3306. ++UseCount;
  3307. DFSOrderedSet.emplace_back(VDUse);
  3308. }
  3309. }
  3310. // If there are no uses, it's probably dead (but it may have side-effects,
  3311. // so not definitely dead. Otherwise, store the number of uses so we can
  3312. // track if it becomes dead later).
  3313. if (UseCount == 0)
  3314. ProbablyDead.insert(Def);
  3315. else
  3316. UseCounts[Def] = UseCount;
  3317. }
  3318. }
  3319. // This function converts the set of members for a congruence class from values,
  3320. // to the set of defs for loads and stores, with associated DFS info.
  3321. void NewGVN::convertClassToLoadsAndStores(
  3322. const CongruenceClass &Dense,
  3323. SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
  3324. for (auto D : Dense) {
  3325. if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
  3326. continue;
  3327. BasicBlock *BB = getBlockForValue(D);
  3328. ValueDFS VD;
  3329. DomTreeNode *DomNode = DT->getNode(BB);
  3330. VD.DFSIn = DomNode->getDFSNumIn();
  3331. VD.DFSOut = DomNode->getDFSNumOut();
  3332. VD.Def.setPointer(D);
  3333. // If it's an instruction, use the real local dfs number.
  3334. if (auto *I = dyn_cast<Instruction>(D))
  3335. VD.LocalNum = InstrToDFSNum(I);
  3336. else
  3337. llvm_unreachable("Should have been an instruction");
  3338. LoadsAndStores.emplace_back(VD);
  3339. }
  3340. }
  3341. static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
  3342. patchReplacementInstruction(I, Repl);
  3343. I->replaceAllUsesWith(Repl);
  3344. }
  3345. void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
  3346. LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
  3347. ++NumGVNBlocksDeleted;
  3348. // Delete the instructions backwards, as it has a reduced likelihood of having
  3349. // to update as many def-use and use-def chains. Start after the terminator.
  3350. auto StartPoint = BB->rbegin();
  3351. ++StartPoint;
  3352. // Note that we explicitly recalculate BB->rend() on each iteration,
  3353. // as it may change when we remove the first instruction.
  3354. for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
  3355. Instruction &Inst = *I++;
  3356. if (!Inst.use_empty())
  3357. Inst.replaceAllUsesWith(PoisonValue::get(Inst.getType()));
  3358. if (isa<LandingPadInst>(Inst))
  3359. continue;
  3360. salvageKnowledge(&Inst, AC);
  3361. Inst.eraseFromParent();
  3362. ++NumGVNInstrDeleted;
  3363. }
  3364. // Now insert something that simplifycfg will turn into an unreachable.
  3365. Type *Int8Ty = Type::getInt8Ty(BB->getContext());
  3366. new StoreInst(PoisonValue::get(Int8Ty),
  3367. Constant::getNullValue(Int8Ty->getPointerTo()),
  3368. BB->getTerminator());
  3369. }
  3370. void NewGVN::markInstructionForDeletion(Instruction *I) {
  3371. LLVM_DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
  3372. InstructionsToErase.insert(I);
  3373. }
  3374. void NewGVN::replaceInstruction(Instruction *I, Value *V) {
  3375. LLVM_DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
  3376. patchAndReplaceAllUsesWith(I, V);
  3377. // We save the actual erasing to avoid invalidating memory
  3378. // dependencies until we are done with everything.
  3379. markInstructionForDeletion(I);
  3380. }
  3381. namespace {
  3382. // This is a stack that contains both the value and dfs info of where
  3383. // that value is valid.
  3384. class ValueDFSStack {
  3385. public:
  3386. Value *back() const { return ValueStack.back(); }
  3387. std::pair<int, int> dfs_back() const { return DFSStack.back(); }
  3388. void push_back(Value *V, int DFSIn, int DFSOut) {
  3389. ValueStack.emplace_back(V);
  3390. DFSStack.emplace_back(DFSIn, DFSOut);
  3391. }
  3392. bool empty() const { return DFSStack.empty(); }
  3393. bool isInScope(int DFSIn, int DFSOut) const {
  3394. if (empty())
  3395. return false;
  3396. return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
  3397. }
  3398. void popUntilDFSScope(int DFSIn, int DFSOut) {
  3399. // These two should always be in sync at this point.
  3400. assert(ValueStack.size() == DFSStack.size() &&
  3401. "Mismatch between ValueStack and DFSStack");
  3402. while (
  3403. !DFSStack.empty() &&
  3404. !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
  3405. DFSStack.pop_back();
  3406. ValueStack.pop_back();
  3407. }
  3408. }
  3409. private:
  3410. SmallVector<Value *, 8> ValueStack;
  3411. SmallVector<std::pair<int, int>, 8> DFSStack;
  3412. };
  3413. } // end anonymous namespace
  3414. // Given an expression, get the congruence class for it.
  3415. CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
  3416. if (auto *VE = dyn_cast<VariableExpression>(E))
  3417. return ValueToClass.lookup(VE->getVariableValue());
  3418. else if (isa<DeadExpression>(E))
  3419. return TOPClass;
  3420. return ExpressionToClass.lookup(E);
  3421. }
  3422. // Given a value and a basic block we are trying to see if it is available in,
  3423. // see if the value has a leader available in that block.
  3424. Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
  3425. const Instruction *OrigInst,
  3426. const BasicBlock *BB) const {
  3427. // It would already be constant if we could make it constant
  3428. if (auto *CE = dyn_cast<ConstantExpression>(E))
  3429. return CE->getConstantValue();
  3430. if (auto *VE = dyn_cast<VariableExpression>(E)) {
  3431. auto *V = VE->getVariableValue();
  3432. if (alwaysAvailable(V) || DT->dominates(getBlockForValue(V), BB))
  3433. return VE->getVariableValue();
  3434. }
  3435. auto *CC = getClassForExpression(E);
  3436. if (!CC)
  3437. return nullptr;
  3438. if (alwaysAvailable(CC->getLeader()))
  3439. return CC->getLeader();
  3440. for (auto Member : *CC) {
  3441. auto *MemberInst = dyn_cast<Instruction>(Member);
  3442. if (MemberInst == OrigInst)
  3443. continue;
  3444. // Anything that isn't an instruction is always available.
  3445. if (!MemberInst)
  3446. return Member;
  3447. if (DT->dominates(getBlockForValue(MemberInst), BB))
  3448. return Member;
  3449. }
  3450. return nullptr;
  3451. }
  3452. bool NewGVN::eliminateInstructions(Function &F) {
  3453. // This is a non-standard eliminator. The normal way to eliminate is
  3454. // to walk the dominator tree in order, keeping track of available
  3455. // values, and eliminating them. However, this is mildly
  3456. // pointless. It requires doing lookups on every instruction,
  3457. // regardless of whether we will ever eliminate it. For
  3458. // instructions part of most singleton congruence classes, we know we
  3459. // will never eliminate them.
  3460. // Instead, this eliminator looks at the congruence classes directly, sorts
  3461. // them into a DFS ordering of the dominator tree, and then we just
  3462. // perform elimination straight on the sets by walking the congruence
  3463. // class member uses in order, and eliminate the ones dominated by the
  3464. // last member. This is worst case O(E log E) where E = number of
  3465. // instructions in a single congruence class. In theory, this is all
  3466. // instructions. In practice, it is much faster, as most instructions are
  3467. // either in singleton congruence classes or can't possibly be eliminated
  3468. // anyway (if there are no overlapping DFS ranges in class).
  3469. // When we find something not dominated, it becomes the new leader
  3470. // for elimination purposes.
  3471. // TODO: If we wanted to be faster, We could remove any members with no
  3472. // overlapping ranges while sorting, as we will never eliminate anything
  3473. // with those members, as they don't dominate anything else in our set.
  3474. bool AnythingReplaced = false;
  3475. // Since we are going to walk the domtree anyway, and we can't guarantee the
  3476. // DFS numbers are updated, we compute some ourselves.
  3477. DT->updateDFSNumbers();
  3478. // Go through all of our phi nodes, and kill the arguments associated with
  3479. // unreachable edges.
  3480. auto ReplaceUnreachablePHIArgs = [&](PHINode *PHI, BasicBlock *BB) {
  3481. for (auto &Operand : PHI->incoming_values())
  3482. if (!ReachableEdges.count({PHI->getIncomingBlock(Operand), BB})) {
  3483. LLVM_DEBUG(dbgs() << "Replacing incoming value of " << PHI
  3484. << " for block "
  3485. << getBlockName(PHI->getIncomingBlock(Operand))
  3486. << " with poison due to it being unreachable\n");
  3487. Operand.set(PoisonValue::get(PHI->getType()));
  3488. }
  3489. };
  3490. // Replace unreachable phi arguments.
  3491. // At this point, RevisitOnReachabilityChange only contains:
  3492. //
  3493. // 1. PHIs
  3494. // 2. Temporaries that will convert to PHIs
  3495. // 3. Operations that are affected by an unreachable edge but do not fit into
  3496. // 1 or 2 (rare).
  3497. // So it is a slight overshoot of what we want. We could make it exact by
  3498. // using two SparseBitVectors per block.
  3499. DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
  3500. for (auto &KV : ReachableEdges)
  3501. ReachablePredCount[KV.getEnd()]++;
  3502. for (auto &BBPair : RevisitOnReachabilityChange) {
  3503. for (auto InstNum : BBPair.second) {
  3504. auto *Inst = InstrFromDFSNum(InstNum);
  3505. auto *PHI = dyn_cast<PHINode>(Inst);
  3506. PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
  3507. if (!PHI)
  3508. continue;
  3509. auto *BB = BBPair.first;
  3510. if (ReachablePredCount.lookup(BB) != PHI->getNumIncomingValues())
  3511. ReplaceUnreachablePHIArgs(PHI, BB);
  3512. }
  3513. }
  3514. // Map to store the use counts
  3515. DenseMap<const Value *, unsigned int> UseCounts;
  3516. for (auto *CC : reverse(CongruenceClasses)) {
  3517. LLVM_DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
  3518. << "\n");
  3519. // Track the equivalent store info so we can decide whether to try
  3520. // dead store elimination.
  3521. SmallVector<ValueDFS, 8> PossibleDeadStores;
  3522. SmallPtrSet<Instruction *, 8> ProbablyDead;
  3523. if (CC->isDead() || CC->empty())
  3524. continue;
  3525. // Everything still in the TOP class is unreachable or dead.
  3526. if (CC == TOPClass) {
  3527. for (auto M : *CC) {
  3528. auto *VTE = ValueToExpression.lookup(M);
  3529. if (VTE && isa<DeadExpression>(VTE))
  3530. markInstructionForDeletion(cast<Instruction>(M));
  3531. assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
  3532. InstructionsToErase.count(cast<Instruction>(M))) &&
  3533. "Everything in TOP should be unreachable or dead at this "
  3534. "point");
  3535. }
  3536. continue;
  3537. }
  3538. assert(CC->getLeader() && "We should have had a leader");
  3539. // If this is a leader that is always available, and it's a
  3540. // constant or has no equivalences, just replace everything with
  3541. // it. We then update the congruence class with whatever members
  3542. // are left.
  3543. Value *Leader =
  3544. CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
  3545. if (alwaysAvailable(Leader)) {
  3546. CongruenceClass::MemberSet MembersLeft;
  3547. for (auto M : *CC) {
  3548. Value *Member = M;
  3549. // Void things have no uses we can replace.
  3550. if (Member == Leader || !isa<Instruction>(Member) ||
  3551. Member->getType()->isVoidTy()) {
  3552. MembersLeft.insert(Member);
  3553. continue;
  3554. }
  3555. LLVM_DEBUG(dbgs() << "Found replacement " << *(Leader) << " for "
  3556. << *Member << "\n");
  3557. auto *I = cast<Instruction>(Member);
  3558. assert(Leader != I && "About to accidentally remove our leader");
  3559. replaceInstruction(I, Leader);
  3560. AnythingReplaced = true;
  3561. }
  3562. CC->swap(MembersLeft);
  3563. } else {
  3564. // If this is a singleton, we can skip it.
  3565. if (CC->size() != 1 || RealToTemp.count(Leader)) {
  3566. // This is a stack because equality replacement/etc may place
  3567. // constants in the middle of the member list, and we want to use
  3568. // those constant values in preference to the current leader, over
  3569. // the scope of those constants.
  3570. ValueDFSStack EliminationStack;
  3571. // Convert the members to DFS ordered sets and then merge them.
  3572. SmallVector<ValueDFS, 8> DFSOrderedSet;
  3573. convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
  3574. // Sort the whole thing.
  3575. llvm::sort(DFSOrderedSet);
  3576. for (auto &VD : DFSOrderedSet) {
  3577. int MemberDFSIn = VD.DFSIn;
  3578. int MemberDFSOut = VD.DFSOut;
  3579. Value *Def = VD.Def.getPointer();
  3580. bool FromStore = VD.Def.getInt();
  3581. Use *U = VD.U;
  3582. // We ignore void things because we can't get a value from them.
  3583. if (Def && Def->getType()->isVoidTy())
  3584. continue;
  3585. auto *DefInst = dyn_cast_or_null<Instruction>(Def);
  3586. if (DefInst && AllTempInstructions.count(DefInst)) {
  3587. auto *PN = cast<PHINode>(DefInst);
  3588. // If this is a value phi and that's the expression we used, insert
  3589. // it into the program
  3590. // remove from temp instruction list.
  3591. AllTempInstructions.erase(PN);
  3592. auto *DefBlock = getBlockForValue(Def);
  3593. LLVM_DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
  3594. << " into block "
  3595. << getBlockName(getBlockForValue(Def)) << "\n");
  3596. PN->insertBefore(&DefBlock->front());
  3597. Def = PN;
  3598. NumGVNPHIOfOpsEliminations++;
  3599. }
  3600. if (EliminationStack.empty()) {
  3601. LLVM_DEBUG(dbgs() << "Elimination Stack is empty\n");
  3602. } else {
  3603. LLVM_DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
  3604. << EliminationStack.dfs_back().first << ","
  3605. << EliminationStack.dfs_back().second << ")\n");
  3606. }
  3607. LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
  3608. << MemberDFSOut << ")\n");
  3609. // First, we see if we are out of scope or empty. If so,
  3610. // and there equivalences, we try to replace the top of
  3611. // stack with equivalences (if it's on the stack, it must
  3612. // not have been eliminated yet).
  3613. // Then we synchronize to our current scope, by
  3614. // popping until we are back within a DFS scope that
  3615. // dominates the current member.
  3616. // Then, what happens depends on a few factors
  3617. // If the stack is now empty, we need to push
  3618. // If we have a constant or a local equivalence we want to
  3619. // start using, we also push.
  3620. // Otherwise, we walk along, processing members who are
  3621. // dominated by this scope, and eliminate them.
  3622. bool ShouldPush = Def && EliminationStack.empty();
  3623. bool OutOfScope =
  3624. !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
  3625. if (OutOfScope || ShouldPush) {
  3626. // Sync to our current scope.
  3627. EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
  3628. bool ShouldPush = Def && EliminationStack.empty();
  3629. if (ShouldPush) {
  3630. EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
  3631. }
  3632. }
  3633. // Skip the Def's, we only want to eliminate on their uses. But mark
  3634. // dominated defs as dead.
  3635. if (Def) {
  3636. // For anything in this case, what and how we value number
  3637. // guarantees that any side-effets that would have occurred (ie
  3638. // throwing, etc) can be proven to either still occur (because it's
  3639. // dominated by something that has the same side-effects), or never
  3640. // occur. Otherwise, we would not have been able to prove it value
  3641. // equivalent to something else. For these things, we can just mark
  3642. // it all dead. Note that this is different from the "ProbablyDead"
  3643. // set, which may not be dominated by anything, and thus, are only
  3644. // easy to prove dead if they are also side-effect free. Note that
  3645. // because stores are put in terms of the stored value, we skip
  3646. // stored values here. If the stored value is really dead, it will
  3647. // still be marked for deletion when we process it in its own class.
  3648. if (!EliminationStack.empty() && Def != EliminationStack.back() &&
  3649. isa<Instruction>(Def) && !FromStore)
  3650. markInstructionForDeletion(cast<Instruction>(Def));
  3651. continue;
  3652. }
  3653. // At this point, we know it is a Use we are trying to possibly
  3654. // replace.
  3655. assert(isa<Instruction>(U->get()) &&
  3656. "Current def should have been an instruction");
  3657. assert(isa<Instruction>(U->getUser()) &&
  3658. "Current user should have been an instruction");
  3659. // If the thing we are replacing into is already marked to be dead,
  3660. // this use is dead. Note that this is true regardless of whether
  3661. // we have anything dominating the use or not. We do this here
  3662. // because we are already walking all the uses anyway.
  3663. Instruction *InstUse = cast<Instruction>(U->getUser());
  3664. if (InstructionsToErase.count(InstUse)) {
  3665. auto &UseCount = UseCounts[U->get()];
  3666. if (--UseCount == 0) {
  3667. ProbablyDead.insert(cast<Instruction>(U->get()));
  3668. }
  3669. }
  3670. // If we get to this point, and the stack is empty we must have a use
  3671. // with nothing we can use to eliminate this use, so just skip it.
  3672. if (EliminationStack.empty())
  3673. continue;
  3674. Value *DominatingLeader = EliminationStack.back();
  3675. auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
  3676. bool isSSACopy = II && II->getIntrinsicID() == Intrinsic::ssa_copy;
  3677. if (isSSACopy)
  3678. DominatingLeader = II->getOperand(0);
  3679. // Don't replace our existing users with ourselves.
  3680. if (U->get() == DominatingLeader)
  3681. continue;
  3682. LLVM_DEBUG(dbgs()
  3683. << "Found replacement " << *DominatingLeader << " for "
  3684. << *U->get() << " in " << *(U->getUser()) << "\n");
  3685. // If we replaced something in an instruction, handle the patching of
  3686. // metadata. Skip this if we are replacing predicateinfo with its
  3687. // original operand, as we already know we can just drop it.
  3688. auto *ReplacedInst = cast<Instruction>(U->get());
  3689. auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
  3690. if (!PI || DominatingLeader != PI->OriginalOp)
  3691. patchReplacementInstruction(ReplacedInst, DominatingLeader);
  3692. U->set(DominatingLeader);
  3693. // This is now a use of the dominating leader, which means if the
  3694. // dominating leader was dead, it's now live!
  3695. auto &LeaderUseCount = UseCounts[DominatingLeader];
  3696. // It's about to be alive again.
  3697. if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
  3698. ProbablyDead.erase(cast<Instruction>(DominatingLeader));
  3699. // For copy instructions, we use their operand as a leader,
  3700. // which means we remove a user of the copy and it may become dead.
  3701. if (isSSACopy) {
  3702. unsigned &IIUseCount = UseCounts[II];
  3703. if (--IIUseCount == 0)
  3704. ProbablyDead.insert(II);
  3705. }
  3706. ++LeaderUseCount;
  3707. AnythingReplaced = true;
  3708. }
  3709. }
  3710. }
  3711. // At this point, anything still in the ProbablyDead set is actually dead if
  3712. // would be trivially dead.
  3713. for (auto *I : ProbablyDead)
  3714. if (wouldInstructionBeTriviallyDead(I))
  3715. markInstructionForDeletion(I);
  3716. // Cleanup the congruence class.
  3717. CongruenceClass::MemberSet MembersLeft;
  3718. for (auto *Member : *CC)
  3719. if (!isa<Instruction>(Member) ||
  3720. !InstructionsToErase.count(cast<Instruction>(Member)))
  3721. MembersLeft.insert(Member);
  3722. CC->swap(MembersLeft);
  3723. // If we have possible dead stores to look at, try to eliminate them.
  3724. if (CC->getStoreCount() > 0) {
  3725. convertClassToLoadsAndStores(*CC, PossibleDeadStores);
  3726. llvm::sort(PossibleDeadStores);
  3727. ValueDFSStack EliminationStack;
  3728. for (auto &VD : PossibleDeadStores) {
  3729. int MemberDFSIn = VD.DFSIn;
  3730. int MemberDFSOut = VD.DFSOut;
  3731. Instruction *Member = cast<Instruction>(VD.Def.getPointer());
  3732. if (EliminationStack.empty() ||
  3733. !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
  3734. // Sync to our current scope.
  3735. EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
  3736. if (EliminationStack.empty()) {
  3737. EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
  3738. continue;
  3739. }
  3740. }
  3741. // We already did load elimination, so nothing to do here.
  3742. if (isa<LoadInst>(Member))
  3743. continue;
  3744. assert(!EliminationStack.empty());
  3745. Instruction *Leader = cast<Instruction>(EliminationStack.back());
  3746. (void)Leader;
  3747. assert(DT->dominates(Leader->getParent(), Member->getParent()));
  3748. // Member is dominater by Leader, and thus dead
  3749. LLVM_DEBUG(dbgs() << "Marking dead store " << *Member
  3750. << " that is dominated by " << *Leader << "\n");
  3751. markInstructionForDeletion(Member);
  3752. CC->erase(Member);
  3753. ++NumGVNDeadStores;
  3754. }
  3755. }
  3756. }
  3757. return AnythingReplaced;
  3758. }
  3759. // This function provides global ranking of operations so that we can place them
  3760. // in a canonical order. Note that rank alone is not necessarily enough for a
  3761. // complete ordering, as constants all have the same rank. However, generally,
  3762. // we will simplify an operation with all constants so that it doesn't matter
  3763. // what order they appear in.
  3764. unsigned int NewGVN::getRank(const Value *V) const {
  3765. // Prefer constants to undef to anything else
  3766. // Undef is a constant, have to check it first.
  3767. // Prefer poison to undef as it's less defined.
  3768. // Prefer smaller constants to constantexprs
  3769. // Note that the order here matters because of class inheritance
  3770. if (isa<ConstantExpr>(V))
  3771. return 3;
  3772. if (isa<PoisonValue>(V))
  3773. return 1;
  3774. if (isa<UndefValue>(V))
  3775. return 2;
  3776. if (isa<Constant>(V))
  3777. return 0;
  3778. if (auto *A = dyn_cast<Argument>(V))
  3779. return 4 + A->getArgNo();
  3780. // Need to shift the instruction DFS by number of arguments + 5 to account for
  3781. // the constant and argument ranking above.
  3782. unsigned Result = InstrToDFSNum(V);
  3783. if (Result > 0)
  3784. return 5 + NumFuncArgs + Result;
  3785. // Unreachable or something else, just return a really large number.
  3786. return ~0;
  3787. }
  3788. // This is a function that says whether two commutative operations should
  3789. // have their order swapped when canonicalizing.
  3790. bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
  3791. // Because we only care about a total ordering, and don't rewrite expressions
  3792. // in this order, we order by rank, which will give a strict weak ordering to
  3793. // everything but constants, and then we order by pointer address.
  3794. return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
  3795. }
  3796. bool NewGVN::shouldSwapOperandsForIntrinsic(const Value *A, const Value *B,
  3797. const IntrinsicInst *I) const {
  3798. auto LookupResult = IntrinsicInstPred.find(I);
  3799. if (shouldSwapOperands(A, B)) {
  3800. if (LookupResult == IntrinsicInstPred.end())
  3801. IntrinsicInstPred.insert({I, B});
  3802. else
  3803. LookupResult->second = B;
  3804. return true;
  3805. }
  3806. if (LookupResult != IntrinsicInstPred.end()) {
  3807. auto *SeenPredicate = LookupResult->second;
  3808. if (SeenPredicate) {
  3809. if (SeenPredicate == B)
  3810. return true;
  3811. else
  3812. LookupResult->second = nullptr;
  3813. }
  3814. }
  3815. return false;
  3816. }
  3817. namespace {
  3818. class NewGVNLegacyPass : public FunctionPass {
  3819. public:
  3820. // Pass identification, replacement for typeid.
  3821. static char ID;
  3822. NewGVNLegacyPass() : FunctionPass(ID) {
  3823. initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
  3824. }
  3825. bool runOnFunction(Function &F) override;
  3826. private:
  3827. void getAnalysisUsage(AnalysisUsage &AU) const override {
  3828. AU.addRequired<AssumptionCacheTracker>();
  3829. AU.addRequired<DominatorTreeWrapperPass>();
  3830. AU.addRequired<TargetLibraryInfoWrapperPass>();
  3831. AU.addRequired<MemorySSAWrapperPass>();
  3832. AU.addRequired<AAResultsWrapperPass>();
  3833. AU.addPreserved<DominatorTreeWrapperPass>();
  3834. AU.addPreserved<GlobalsAAWrapperPass>();
  3835. }
  3836. };
  3837. } // end anonymous namespace
  3838. bool NewGVNLegacyPass::runOnFunction(Function &F) {
  3839. if (skipFunction(F))
  3840. return false;
  3841. return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  3842. &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
  3843. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
  3844. &getAnalysis<AAResultsWrapperPass>().getAAResults(),
  3845. &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
  3846. F.getParent()->getDataLayout())
  3847. .runGVN();
  3848. }
  3849. char NewGVNLegacyPass::ID = 0;
  3850. INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
  3851. false, false)
  3852. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  3853. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  3854. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  3855. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  3856. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  3857. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  3858. INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
  3859. false)
  3860. // createGVNPass - The public interface to this file.
  3861. FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
  3862. PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
  3863. // Apparently the order in which we get these results matter for
  3864. // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
  3865. // the same order here, just in case.
  3866. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  3867. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  3868. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  3869. auto &AA = AM.getResult<AAManager>(F);
  3870. auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
  3871. bool Changed =
  3872. NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
  3873. .runGVN();
  3874. if (!Changed)
  3875. return PreservedAnalyses::all();
  3876. PreservedAnalyses PA;
  3877. PA.preserve<DominatorTreeAnalysis>();
  3878. return PA;
  3879. }