CodeGenPrepare.cpp 210 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass munges the code in the input function to better prepare it for
  11. // SelectionDAG-based code generation. This works around limitations in it's
  12. // basic-block-at-a-time approach. It should eventually be removed.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/Analysis/TargetLibraryInfo.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/Analysis/MemoryBuiltins.h"
  25. #include "llvm/IR/CallSite.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/GetElementPtrTypeIterator.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/InlineAsm.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/PatternMatch.h"
  38. #include "llvm/IR/Statepoint.h"
  39. #include "llvm/IR/ValueHandle.h"
  40. #include "llvm/IR/ValueMap.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/CommandLine.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Target/TargetLowering.h"
  46. #include "llvm/Target/TargetSubtargetInfo.h"
  47. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  48. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  49. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  50. #include "llvm/Transforms/Utils/Local.h"
  51. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  52. using namespace llvm;
  53. using namespace llvm::PatternMatch;
  54. #define DEBUG_TYPE "codegenprepare"
  55. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  56. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  57. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  58. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  59. "sunken Cmps");
  60. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  61. "of sunken Casts");
  62. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  63. "computations were sunk");
  64. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  65. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  66. STATISTIC(NumAndsAdded,
  67. "Number of and mask instructions added to form ext loads");
  68. STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
  69. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  70. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  71. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  72. STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
  73. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  74. static cl::opt<bool> DisableBranchOpts(
  75. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  76. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  77. static cl::opt<bool>
  78. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  79. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  80. static cl::opt<bool> DisableSelectToBranch(
  81. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  82. cl::desc("Disable select to branch conversion."));
  83. static cl::opt<bool> AddrSinkUsingGEPs(
  84. "addr-sink-using-gep", cl::Hidden, cl::init(false),
  85. cl::desc("Address sinking in CGP using GEPs."));
  86. static cl::opt<bool> EnableAndCmpSinking(
  87. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  88. cl::desc("Enable sinkinig and/cmp into branches."));
  89. static cl::opt<bool> DisableStoreExtract(
  90. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  91. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  92. static cl::opt<bool> StressStoreExtract(
  93. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  94. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  95. static cl::opt<bool> DisableExtLdPromotion(
  96. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  97. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  98. "CodeGenPrepare"));
  99. static cl::opt<bool> StressExtLdPromotion(
  100. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  101. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  102. "optimization in CodeGenPrepare"));
  103. static cl::opt<bool> DisablePreheaderProtect(
  104. "disable-preheader-prot", cl::Hidden, cl::init(false),
  105. cl::desc("Disable protection against removing loop preheaders"));
  106. namespace {
  107. typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
  108. typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
  109. typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
  110. class TypePromotionTransaction;
  111. class CodeGenPrepare : public FunctionPass {
  112. const TargetMachine *TM;
  113. const TargetLowering *TLI;
  114. const TargetTransformInfo *TTI;
  115. const TargetLibraryInfo *TLInfo;
  116. const LoopInfo *LI;
  117. /// As we scan instructions optimizing them, this is the next instruction
  118. /// to optimize. Transforms that can invalidate this should update it.
  119. BasicBlock::iterator CurInstIterator;
  120. /// Keeps track of non-local addresses that have been sunk into a block.
  121. /// This allows us to avoid inserting duplicate code for blocks with
  122. /// multiple load/stores of the same address.
  123. ValueMap<Value*, Value*> SunkAddrs;
  124. /// Keeps track of all instructions inserted for the current function.
  125. SetOfInstrs InsertedInsts;
  126. /// Keeps track of the type of the related instruction before their
  127. /// promotion for the current function.
  128. InstrToOrigTy PromotedInsts;
  129. /// True if CFG is modified in any way.
  130. bool ModifiedDT;
  131. /// True if optimizing for size.
  132. bool OptSize;
  133. /// DataLayout for the Function being processed.
  134. const DataLayout *DL;
  135. public:
  136. static char ID; // Pass identification, replacement for typeid
  137. explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
  138. : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
  139. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  140. }
  141. bool runOnFunction(Function &F) override;
  142. const char *getPassName() const override { return "CodeGen Prepare"; }
  143. void getAnalysisUsage(AnalysisUsage &AU) const override {
  144. // FIXME: When we can selectively preserve passes, preserve the domtree.
  145. AU.addRequired<TargetLibraryInfoWrapperPass>();
  146. AU.addRequired<TargetTransformInfoWrapperPass>();
  147. AU.addRequired<LoopInfoWrapperPass>();
  148. }
  149. private:
  150. bool eliminateFallThrough(Function &F);
  151. bool eliminateMostlyEmptyBlocks(Function &F);
  152. bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  153. void eliminateMostlyEmptyBlock(BasicBlock *BB);
  154. bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
  155. bool optimizeInst(Instruction *I, bool& ModifiedDT);
  156. bool optimizeMemoryInst(Instruction *I, Value *Addr,
  157. Type *AccessTy, unsigned AS);
  158. bool optimizeInlineAsmInst(CallInst *CS);
  159. bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
  160. bool moveExtToFormExtLoad(Instruction *&I);
  161. bool optimizeExtUses(Instruction *I);
  162. bool optimizeLoadExt(LoadInst *I);
  163. bool optimizeSelectInst(SelectInst *SI);
  164. bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
  165. bool optimizeSwitchInst(SwitchInst *CI);
  166. bool optimizeExtractElementInst(Instruction *Inst);
  167. bool dupRetToEnableTailCallOpts(BasicBlock *BB);
  168. bool placeDbgValues(Function &F);
  169. bool sinkAndCmp(Function &F);
  170. bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
  171. Instruction *&Inst,
  172. const SmallVectorImpl<Instruction *> &Exts,
  173. unsigned CreatedInstCost);
  174. bool splitBranchCondition(Function &F);
  175. bool simplifyOffsetableRelocate(Instruction &I);
  176. void stripInvariantGroupMetadata(Instruction &I);
  177. };
  178. }
  179. char CodeGenPrepare::ID = 0;
  180. INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
  181. "Optimize for code generation", false, false)
  182. FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
  183. return new CodeGenPrepare(TM);
  184. }
  185. bool CodeGenPrepare::runOnFunction(Function &F) {
  186. if (skipFunction(F))
  187. return false;
  188. DL = &F.getParent()->getDataLayout();
  189. bool EverMadeChange = false;
  190. // Clear per function information.
  191. InsertedInsts.clear();
  192. PromotedInsts.clear();
  193. ModifiedDT = false;
  194. if (TM)
  195. TLI = TM->getSubtargetImpl(F)->getTargetLowering();
  196. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  197. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  198. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  199. OptSize = F.optForSize();
  200. /// This optimization identifies DIV instructions that can be
  201. /// profitably bypassed and carried out with a shorter, faster divide.
  202. if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
  203. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  204. TLI->getBypassSlowDivWidths();
  205. BasicBlock* BB = &*F.begin();
  206. while (BB != nullptr) {
  207. // bypassSlowDivision may create new BBs, but we don't want to reapply the
  208. // optimization to those blocks.
  209. BasicBlock* Next = BB->getNextNode();
  210. EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
  211. BB = Next;
  212. }
  213. }
  214. // Eliminate blocks that contain only PHI nodes and an
  215. // unconditional branch.
  216. EverMadeChange |= eliminateMostlyEmptyBlocks(F);
  217. // llvm.dbg.value is far away from the value then iSel may not be able
  218. // handle it properly. iSel will drop llvm.dbg.value if it can not
  219. // find a node corresponding to the value.
  220. EverMadeChange |= placeDbgValues(F);
  221. // If there is a mask, compare against zero, and branch that can be combined
  222. // into a single target instruction, push the mask and compare into branch
  223. // users. Do this before OptimizeBlock -> OptimizeInst ->
  224. // OptimizeCmpExpression, which perturbs the pattern being searched for.
  225. if (!DisableBranchOpts) {
  226. EverMadeChange |= sinkAndCmp(F);
  227. EverMadeChange |= splitBranchCondition(F);
  228. }
  229. bool MadeChange = true;
  230. while (MadeChange) {
  231. MadeChange = false;
  232. for (Function::iterator I = F.begin(); I != F.end(); ) {
  233. BasicBlock *BB = &*I++;
  234. bool ModifiedDTOnIteration = false;
  235. MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
  236. // Restart BB iteration if the dominator tree of the Function was changed
  237. if (ModifiedDTOnIteration)
  238. break;
  239. }
  240. EverMadeChange |= MadeChange;
  241. }
  242. SunkAddrs.clear();
  243. if (!DisableBranchOpts) {
  244. MadeChange = false;
  245. SmallPtrSet<BasicBlock*, 8> WorkList;
  246. for (BasicBlock &BB : F) {
  247. SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
  248. MadeChange |= ConstantFoldTerminator(&BB, true);
  249. if (!MadeChange) continue;
  250. for (SmallVectorImpl<BasicBlock*>::iterator
  251. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  252. if (pred_begin(*II) == pred_end(*II))
  253. WorkList.insert(*II);
  254. }
  255. // Delete the dead blocks and any of their dead successors.
  256. MadeChange |= !WorkList.empty();
  257. while (!WorkList.empty()) {
  258. BasicBlock *BB = *WorkList.begin();
  259. WorkList.erase(BB);
  260. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  261. DeleteDeadBlock(BB);
  262. for (SmallVectorImpl<BasicBlock*>::iterator
  263. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  264. if (pred_begin(*II) == pred_end(*II))
  265. WorkList.insert(*II);
  266. }
  267. // Merge pairs of basic blocks with unconditional branches, connected by
  268. // a single edge.
  269. if (EverMadeChange || MadeChange)
  270. MadeChange |= eliminateFallThrough(F);
  271. EverMadeChange |= MadeChange;
  272. }
  273. if (!DisableGCOpts) {
  274. SmallVector<Instruction *, 2> Statepoints;
  275. for (BasicBlock &BB : F)
  276. for (Instruction &I : BB)
  277. if (isStatepoint(I))
  278. Statepoints.push_back(&I);
  279. for (auto &I : Statepoints)
  280. EverMadeChange |= simplifyOffsetableRelocate(*I);
  281. }
  282. return EverMadeChange;
  283. }
  284. /// Merge basic blocks which are connected by a single edge, where one of the
  285. /// basic blocks has a single successor pointing to the other basic block,
  286. /// which has a single predecessor.
  287. bool CodeGenPrepare::eliminateFallThrough(Function &F) {
  288. bool Changed = false;
  289. // Scan all of the blocks in the function, except for the entry block.
  290. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  291. BasicBlock *BB = &*I++;
  292. // If the destination block has a single pred, then this is a trivial
  293. // edge, just collapse it.
  294. BasicBlock *SinglePred = BB->getSinglePredecessor();
  295. // Don't merge if BB's address is taken.
  296. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  297. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  298. if (Term && !Term->isConditional()) {
  299. Changed = true;
  300. DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
  301. // Remember if SinglePred was the entry block of the function.
  302. // If so, we will need to move BB back to the entry position.
  303. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  304. MergeBasicBlockIntoOnlyPred(BB, nullptr);
  305. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  306. BB->moveBefore(&BB->getParent()->getEntryBlock());
  307. // We have erased a block. Update the iterator.
  308. I = BB->getIterator();
  309. }
  310. }
  311. return Changed;
  312. }
  313. /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
  314. /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
  315. /// edges in ways that are non-optimal for isel. Start by eliminating these
  316. /// blocks so we can split them the way we want them.
  317. bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
  318. SmallPtrSet<BasicBlock *, 16> Preheaders;
  319. SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
  320. while (!LoopList.empty()) {
  321. Loop *L = LoopList.pop_back_val();
  322. LoopList.insert(LoopList.end(), L->begin(), L->end());
  323. if (BasicBlock *Preheader = L->getLoopPreheader())
  324. Preheaders.insert(Preheader);
  325. }
  326. bool MadeChange = false;
  327. // Note that this intentionally skips the entry block.
  328. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  329. BasicBlock *BB = &*I++;
  330. // If this block doesn't end with an uncond branch, ignore it.
  331. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  332. if (!BI || !BI->isUnconditional())
  333. continue;
  334. // If the instruction before the branch (skipping debug info) isn't a phi
  335. // node, then other stuff is happening here.
  336. BasicBlock::iterator BBI = BI->getIterator();
  337. if (BBI != BB->begin()) {
  338. --BBI;
  339. while (isa<DbgInfoIntrinsic>(BBI)) {
  340. if (BBI == BB->begin())
  341. break;
  342. --BBI;
  343. }
  344. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  345. continue;
  346. }
  347. // Do not break infinite loops.
  348. BasicBlock *DestBB = BI->getSuccessor(0);
  349. if (DestBB == BB)
  350. continue;
  351. if (!canMergeBlocks(BB, DestBB))
  352. continue;
  353. // Do not delete loop preheaders if doing so would create a critical edge.
  354. // Loop preheaders can be good locations to spill registers. If the
  355. // preheader is deleted and we create a critical edge, registers may be
  356. // spilled in the loop body instead.
  357. if (!DisablePreheaderProtect && Preheaders.count(BB) &&
  358. !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor()))
  359. continue;
  360. eliminateMostlyEmptyBlock(BB);
  361. MadeChange = true;
  362. }
  363. return MadeChange;
  364. }
  365. /// Return true if we can merge BB into DestBB if there is a single
  366. /// unconditional branch between them, and BB contains no other non-phi
  367. /// instructions.
  368. bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
  369. const BasicBlock *DestBB) const {
  370. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  371. // the successor. If there are more complex condition (e.g. preheaders),
  372. // don't mess around with them.
  373. BasicBlock::const_iterator BBI = BB->begin();
  374. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  375. for (const User *U : PN->users()) {
  376. const Instruction *UI = cast<Instruction>(U);
  377. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  378. return false;
  379. // If User is inside DestBB block and it is a PHINode then check
  380. // incoming value. If incoming value is not from BB then this is
  381. // a complex condition (e.g. preheaders) we want to avoid here.
  382. if (UI->getParent() == DestBB) {
  383. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  384. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  385. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  386. if (Insn && Insn->getParent() == BB &&
  387. Insn->getParent() != UPN->getIncomingBlock(I))
  388. return false;
  389. }
  390. }
  391. }
  392. }
  393. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  394. // and DestBB may have conflicting incoming values for the block. If so, we
  395. // can't merge the block.
  396. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  397. if (!DestBBPN) return true; // no conflict.
  398. // Collect the preds of BB.
  399. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  400. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  401. // It is faster to get preds from a PHI than with pred_iterator.
  402. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  403. BBPreds.insert(BBPN->getIncomingBlock(i));
  404. } else {
  405. BBPreds.insert(pred_begin(BB), pred_end(BB));
  406. }
  407. // Walk the preds of DestBB.
  408. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  409. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  410. if (BBPreds.count(Pred)) { // Common predecessor?
  411. BBI = DestBB->begin();
  412. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  413. const Value *V1 = PN->getIncomingValueForBlock(Pred);
  414. const Value *V2 = PN->getIncomingValueForBlock(BB);
  415. // If V2 is a phi node in BB, look up what the mapped value will be.
  416. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  417. if (V2PN->getParent() == BB)
  418. V2 = V2PN->getIncomingValueForBlock(Pred);
  419. // If there is a conflict, bail out.
  420. if (V1 != V2) return false;
  421. }
  422. }
  423. }
  424. return true;
  425. }
  426. /// Eliminate a basic block that has only phi's and an unconditional branch in
  427. /// it.
  428. void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
  429. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  430. BasicBlock *DestBB = BI->getSuccessor(0);
  431. DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
  432. // If the destination block has a single pred, then this is a trivial edge,
  433. // just collapse it.
  434. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  435. if (SinglePred != DestBB) {
  436. // Remember if SinglePred was the entry block of the function. If so, we
  437. // will need to move BB back to the entry position.
  438. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  439. MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
  440. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  441. BB->moveBefore(&BB->getParent()->getEntryBlock());
  442. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  443. return;
  444. }
  445. }
  446. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  447. // to handle the new incoming edges it is about to have.
  448. PHINode *PN;
  449. for (BasicBlock::iterator BBI = DestBB->begin();
  450. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  451. // Remove the incoming value for BB, and remember it.
  452. Value *InVal = PN->removeIncomingValue(BB, false);
  453. // Two options: either the InVal is a phi node defined in BB or it is some
  454. // value that dominates BB.
  455. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  456. if (InValPhi && InValPhi->getParent() == BB) {
  457. // Add all of the input values of the input PHI as inputs of this phi.
  458. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  459. PN->addIncoming(InValPhi->getIncomingValue(i),
  460. InValPhi->getIncomingBlock(i));
  461. } else {
  462. // Otherwise, add one instance of the dominating value for each edge that
  463. // we will be adding.
  464. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  465. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  466. PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
  467. } else {
  468. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  469. PN->addIncoming(InVal, *PI);
  470. }
  471. }
  472. }
  473. // The PHIs are now updated, change everything that refers to BB to use
  474. // DestBB and remove BB.
  475. BB->replaceAllUsesWith(DestBB);
  476. BB->eraseFromParent();
  477. ++NumBlocksElim;
  478. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  479. }
  480. // Computes a map of base pointer relocation instructions to corresponding
  481. // derived pointer relocation instructions given a vector of all relocate calls
  482. static void computeBaseDerivedRelocateMap(
  483. const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
  484. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
  485. &RelocateInstMap) {
  486. // Collect information in two maps: one primarily for locating the base object
  487. // while filling the second map; the second map is the final structure holding
  488. // a mapping between Base and corresponding Derived relocate calls
  489. DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
  490. for (auto *ThisRelocate : AllRelocateCalls) {
  491. auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
  492. ThisRelocate->getDerivedPtrIndex());
  493. RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
  494. }
  495. for (auto &Item : RelocateIdxMap) {
  496. std::pair<unsigned, unsigned> Key = Item.first;
  497. if (Key.first == Key.second)
  498. // Base relocation: nothing to insert
  499. continue;
  500. GCRelocateInst *I = Item.second;
  501. auto BaseKey = std::make_pair(Key.first, Key.first);
  502. // We're iterating over RelocateIdxMap so we cannot modify it.
  503. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  504. if (MaybeBase == RelocateIdxMap.end())
  505. // TODO: We might want to insert a new base object relocate and gep off
  506. // that, if there are enough derived object relocates.
  507. continue;
  508. RelocateInstMap[MaybeBase->second].push_back(I);
  509. }
  510. }
  511. // Accepts a GEP and extracts the operands into a vector provided they're all
  512. // small integer constants
  513. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  514. SmallVectorImpl<Value *> &OffsetV) {
  515. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  516. // Only accept small constant integer operands
  517. auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  518. if (!Op || Op->getZExtValue() > 20)
  519. return false;
  520. }
  521. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  522. OffsetV.push_back(GEP->getOperand(i));
  523. return true;
  524. }
  525. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  526. // replace, computes a replacement, and affects it.
  527. static bool
  528. simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
  529. const SmallVectorImpl<GCRelocateInst *> &Targets) {
  530. bool MadeChange = false;
  531. for (GCRelocateInst *ToReplace : Targets) {
  532. assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
  533. "Not relocating a derived object of the original base object");
  534. if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
  535. // A duplicate relocate call. TODO: coalesce duplicates.
  536. continue;
  537. }
  538. if (RelocatedBase->getParent() != ToReplace->getParent()) {
  539. // Base and derived relocates are in different basic blocks.
  540. // In this case transform is only valid when base dominates derived
  541. // relocate. However it would be too expensive to check dominance
  542. // for each such relocate, so we skip the whole transformation.
  543. continue;
  544. }
  545. Value *Base = ToReplace->getBasePtr();
  546. auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
  547. if (!Derived || Derived->getPointerOperand() != Base)
  548. continue;
  549. SmallVector<Value *, 2> OffsetV;
  550. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  551. continue;
  552. // Create a Builder and replace the target callsite with a gep
  553. assert(RelocatedBase->getNextNode() &&
  554. "Should always have one since it's not a terminator");
  555. // Insert after RelocatedBase
  556. IRBuilder<> Builder(RelocatedBase->getNextNode());
  557. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  558. // If gc_relocate does not match the actual type, cast it to the right type.
  559. // In theory, there must be a bitcast after gc_relocate if the type does not
  560. // match, and we should reuse it to get the derived pointer. But it could be
  561. // cases like this:
  562. // bb1:
  563. // ...
  564. // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  565. // br label %merge
  566. //
  567. // bb2:
  568. // ...
  569. // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  570. // br label %merge
  571. //
  572. // merge:
  573. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  574. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  575. //
  576. // In this case, we can not find the bitcast any more. So we insert a new bitcast
  577. // no matter there is already one or not. In this way, we can handle all cases, and
  578. // the extra bitcast should be optimized away in later passes.
  579. Value *ActualRelocatedBase = RelocatedBase;
  580. if (RelocatedBase->getType() != Base->getType()) {
  581. ActualRelocatedBase =
  582. Builder.CreateBitCast(RelocatedBase, Base->getType());
  583. }
  584. Value *Replacement = Builder.CreateGEP(
  585. Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
  586. Replacement->takeName(ToReplace);
  587. // If the newly generated derived pointer's type does not match the original derived
  588. // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
  589. Value *ActualReplacement = Replacement;
  590. if (Replacement->getType() != ToReplace->getType()) {
  591. ActualReplacement =
  592. Builder.CreateBitCast(Replacement, ToReplace->getType());
  593. }
  594. ToReplace->replaceAllUsesWith(ActualReplacement);
  595. ToReplace->eraseFromParent();
  596. MadeChange = true;
  597. }
  598. return MadeChange;
  599. }
  600. // Turns this:
  601. //
  602. // %base = ...
  603. // %ptr = gep %base + 15
  604. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  605. // %base' = relocate(%tok, i32 4, i32 4)
  606. // %ptr' = relocate(%tok, i32 4, i32 5)
  607. // %val = load %ptr'
  608. //
  609. // into this:
  610. //
  611. // %base = ...
  612. // %ptr = gep %base + 15
  613. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  614. // %base' = gc.relocate(%tok, i32 4, i32 4)
  615. // %ptr' = gep %base' + 15
  616. // %val = load %ptr'
  617. bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
  618. bool MadeChange = false;
  619. SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
  620. for (auto *U : I.users())
  621. if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
  622. // Collect all the relocate calls associated with a statepoint
  623. AllRelocateCalls.push_back(Relocate);
  624. // We need atleast one base pointer relocation + one derived pointer
  625. // relocation to mangle
  626. if (AllRelocateCalls.size() < 2)
  627. return false;
  628. // RelocateInstMap is a mapping from the base relocate instruction to the
  629. // corresponding derived relocate instructions
  630. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
  631. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  632. if (RelocateInstMap.empty())
  633. return false;
  634. for (auto &Item : RelocateInstMap)
  635. // Item.first is the RelocatedBase to offset against
  636. // Item.second is the vector of Targets to replace
  637. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  638. return MadeChange;
  639. }
  640. /// SinkCast - Sink the specified cast instruction into its user blocks
  641. static bool SinkCast(CastInst *CI) {
  642. BasicBlock *DefBB = CI->getParent();
  643. /// InsertedCasts - Only insert a cast in each block once.
  644. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  645. bool MadeChange = false;
  646. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  647. UI != E; ) {
  648. Use &TheUse = UI.getUse();
  649. Instruction *User = cast<Instruction>(*UI);
  650. // Figure out which BB this cast is used in. For PHI's this is the
  651. // appropriate predecessor block.
  652. BasicBlock *UserBB = User->getParent();
  653. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  654. UserBB = PN->getIncomingBlock(TheUse);
  655. }
  656. // Preincrement use iterator so we don't invalidate it.
  657. ++UI;
  658. // If the block selected to receive the cast is an EH pad that does not
  659. // allow non-PHI instructions before the terminator, we can't sink the
  660. // cast.
  661. if (UserBB->getTerminator()->isEHPad())
  662. continue;
  663. // If this user is in the same block as the cast, don't change the cast.
  664. if (UserBB == DefBB) continue;
  665. // If we have already inserted a cast into this block, use it.
  666. CastInst *&InsertedCast = InsertedCasts[UserBB];
  667. if (!InsertedCast) {
  668. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  669. assert(InsertPt != UserBB->end());
  670. InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
  671. CI->getType(), "", &*InsertPt);
  672. }
  673. // Replace a use of the cast with a use of the new cast.
  674. TheUse = InsertedCast;
  675. MadeChange = true;
  676. ++NumCastUses;
  677. }
  678. // If we removed all uses, nuke the cast.
  679. if (CI->use_empty()) {
  680. CI->eraseFromParent();
  681. MadeChange = true;
  682. }
  683. return MadeChange;
  684. }
  685. /// If the specified cast instruction is a noop copy (e.g. it's casting from
  686. /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
  687. /// reduce the number of virtual registers that must be created and coalesced.
  688. ///
  689. /// Return true if any changes are made.
  690. ///
  691. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  692. const DataLayout &DL) {
  693. // If this is a noop copy,
  694. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  695. EVT DstVT = TLI.getValueType(DL, CI->getType());
  696. // This is an fp<->int conversion?
  697. if (SrcVT.isInteger() != DstVT.isInteger())
  698. return false;
  699. // If this is an extension, it will be a zero or sign extension, which
  700. // isn't a noop.
  701. if (SrcVT.bitsLT(DstVT)) return false;
  702. // If these values will be promoted, find out what they will be promoted
  703. // to. This helps us consider truncates on PPC as noop copies when they
  704. // are.
  705. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  706. TargetLowering::TypePromoteInteger)
  707. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  708. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  709. TargetLowering::TypePromoteInteger)
  710. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  711. // If, after promotion, these are the same types, this is a noop copy.
  712. if (SrcVT != DstVT)
  713. return false;
  714. return SinkCast(CI);
  715. }
  716. /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
  717. /// possible.
  718. ///
  719. /// Return true if any changes were made.
  720. static bool CombineUAddWithOverflow(CmpInst *CI) {
  721. Value *A, *B;
  722. Instruction *AddI;
  723. if (!match(CI,
  724. m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
  725. return false;
  726. Type *Ty = AddI->getType();
  727. if (!isa<IntegerType>(Ty))
  728. return false;
  729. // We don't want to move around uses of condition values this late, so we we
  730. // check if it is legal to create the call to the intrinsic in the basic
  731. // block containing the icmp:
  732. if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
  733. return false;
  734. #ifndef NDEBUG
  735. // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
  736. // for now:
  737. if (AddI->hasOneUse())
  738. assert(*AddI->user_begin() == CI && "expected!");
  739. #endif
  740. Module *M = CI->getModule();
  741. Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
  742. auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
  743. auto *UAddWithOverflow =
  744. CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
  745. auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
  746. auto *Overflow =
  747. ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
  748. CI->replaceAllUsesWith(Overflow);
  749. AddI->replaceAllUsesWith(UAdd);
  750. CI->eraseFromParent();
  751. AddI->eraseFromParent();
  752. return true;
  753. }
  754. /// Sink the given CmpInst into user blocks to reduce the number of virtual
  755. /// registers that must be created and coalesced. This is a clear win except on
  756. /// targets with multiple condition code registers (PowerPC), where it might
  757. /// lose; some adjustment may be wanted there.
  758. ///
  759. /// Return true if any changes are made.
  760. static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
  761. BasicBlock *DefBB = CI->getParent();
  762. // Avoid sinking soft-FP comparisons, since this can move them into a loop.
  763. if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
  764. return false;
  765. // Only insert a cmp in each block once.
  766. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  767. bool MadeChange = false;
  768. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  769. UI != E; ) {
  770. Use &TheUse = UI.getUse();
  771. Instruction *User = cast<Instruction>(*UI);
  772. // Preincrement use iterator so we don't invalidate it.
  773. ++UI;
  774. // Don't bother for PHI nodes.
  775. if (isa<PHINode>(User))
  776. continue;
  777. // Figure out which BB this cmp is used in.
  778. BasicBlock *UserBB = User->getParent();
  779. // If this user is in the same block as the cmp, don't change the cmp.
  780. if (UserBB == DefBB) continue;
  781. // If we have already inserted a cmp into this block, use it.
  782. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  783. if (!InsertedCmp) {
  784. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  785. assert(InsertPt != UserBB->end());
  786. InsertedCmp =
  787. CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
  788. CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
  789. }
  790. // Replace a use of the cmp with a use of the new cmp.
  791. TheUse = InsertedCmp;
  792. MadeChange = true;
  793. ++NumCmpUses;
  794. }
  795. // If we removed all uses, nuke the cmp.
  796. if (CI->use_empty()) {
  797. CI->eraseFromParent();
  798. MadeChange = true;
  799. }
  800. return MadeChange;
  801. }
  802. static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
  803. if (SinkCmpExpression(CI, TLI))
  804. return true;
  805. if (CombineUAddWithOverflow(CI))
  806. return true;
  807. return false;
  808. }
  809. /// Check if the candidates could be combined with a shift instruction, which
  810. /// includes:
  811. /// 1. Truncate instruction
  812. /// 2. And instruction and the imm is a mask of the low bits:
  813. /// imm & (imm+1) == 0
  814. static bool isExtractBitsCandidateUse(Instruction *User) {
  815. if (!isa<TruncInst>(User)) {
  816. if (User->getOpcode() != Instruction::And ||
  817. !isa<ConstantInt>(User->getOperand(1)))
  818. return false;
  819. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  820. if ((Cimm & (Cimm + 1)).getBoolValue())
  821. return false;
  822. }
  823. return true;
  824. }
  825. /// Sink both shift and truncate instruction to the use of truncate's BB.
  826. static bool
  827. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  828. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  829. const TargetLowering &TLI, const DataLayout &DL) {
  830. BasicBlock *UserBB = User->getParent();
  831. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  832. TruncInst *TruncI = dyn_cast<TruncInst>(User);
  833. bool MadeChange = false;
  834. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  835. TruncE = TruncI->user_end();
  836. TruncUI != TruncE;) {
  837. Use &TruncTheUse = TruncUI.getUse();
  838. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  839. // Preincrement use iterator so we don't invalidate it.
  840. ++TruncUI;
  841. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  842. if (!ISDOpcode)
  843. continue;
  844. // If the use is actually a legal node, there will not be an
  845. // implicit truncate.
  846. // FIXME: always querying the result type is just an
  847. // approximation; some nodes' legality is determined by the
  848. // operand or other means. There's no good way to find out though.
  849. if (TLI.isOperationLegalOrCustom(
  850. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  851. continue;
  852. // Don't bother for PHI nodes.
  853. if (isa<PHINode>(TruncUser))
  854. continue;
  855. BasicBlock *TruncUserBB = TruncUser->getParent();
  856. if (UserBB == TruncUserBB)
  857. continue;
  858. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  859. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  860. if (!InsertedShift && !InsertedTrunc) {
  861. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  862. assert(InsertPt != TruncUserBB->end());
  863. // Sink the shift
  864. if (ShiftI->getOpcode() == Instruction::AShr)
  865. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  866. "", &*InsertPt);
  867. else
  868. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  869. "", &*InsertPt);
  870. // Sink the trunc
  871. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  872. TruncInsertPt++;
  873. assert(TruncInsertPt != TruncUserBB->end());
  874. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  875. TruncI->getType(), "", &*TruncInsertPt);
  876. MadeChange = true;
  877. TruncTheUse = InsertedTrunc;
  878. }
  879. }
  880. return MadeChange;
  881. }
  882. /// Sink the shift *right* instruction into user blocks if the uses could
  883. /// potentially be combined with this shift instruction and generate BitExtract
  884. /// instruction. It will only be applied if the architecture supports BitExtract
  885. /// instruction. Here is an example:
  886. /// BB1:
  887. /// %x.extract.shift = lshr i64 %arg1, 32
  888. /// BB2:
  889. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  890. /// ==>
  891. ///
  892. /// BB2:
  893. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  894. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  895. ///
  896. /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
  897. /// instruction.
  898. /// Return true if any changes are made.
  899. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  900. const TargetLowering &TLI,
  901. const DataLayout &DL) {
  902. BasicBlock *DefBB = ShiftI->getParent();
  903. /// Only insert instructions in each block once.
  904. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  905. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  906. bool MadeChange = false;
  907. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  908. UI != E;) {
  909. Use &TheUse = UI.getUse();
  910. Instruction *User = cast<Instruction>(*UI);
  911. // Preincrement use iterator so we don't invalidate it.
  912. ++UI;
  913. // Don't bother for PHI nodes.
  914. if (isa<PHINode>(User))
  915. continue;
  916. if (!isExtractBitsCandidateUse(User))
  917. continue;
  918. BasicBlock *UserBB = User->getParent();
  919. if (UserBB == DefBB) {
  920. // If the shift and truncate instruction are in the same BB. The use of
  921. // the truncate(TruncUse) may still introduce another truncate if not
  922. // legal. In this case, we would like to sink both shift and truncate
  923. // instruction to the BB of TruncUse.
  924. // for example:
  925. // BB1:
  926. // i64 shift.result = lshr i64 opnd, imm
  927. // trunc.result = trunc shift.result to i16
  928. //
  929. // BB2:
  930. // ----> We will have an implicit truncate here if the architecture does
  931. // not have i16 compare.
  932. // cmp i16 trunc.result, opnd2
  933. //
  934. if (isa<TruncInst>(User) && shiftIsLegal
  935. // If the type of the truncate is legal, no trucate will be
  936. // introduced in other basic blocks.
  937. &&
  938. (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  939. MadeChange =
  940. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  941. continue;
  942. }
  943. // If we have already inserted a shift into this block, use it.
  944. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  945. if (!InsertedShift) {
  946. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  947. assert(InsertPt != UserBB->end());
  948. if (ShiftI->getOpcode() == Instruction::AShr)
  949. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  950. "", &*InsertPt);
  951. else
  952. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  953. "", &*InsertPt);
  954. MadeChange = true;
  955. }
  956. // Replace a use of the shift with a use of the new shift.
  957. TheUse = InsertedShift;
  958. }
  959. // If we removed all uses, nuke the shift.
  960. if (ShiftI->use_empty())
  961. ShiftI->eraseFromParent();
  962. return MadeChange;
  963. }
  964. // Translate a masked load intrinsic like
  965. // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
  966. // <16 x i1> %mask, <16 x i32> %passthru)
  967. // to a chain of basic blocks, with loading element one-by-one if
  968. // the appropriate mask bit is set
  969. //
  970. // %1 = bitcast i8* %addr to i32*
  971. // %2 = extractelement <16 x i1> %mask, i32 0
  972. // %3 = icmp eq i1 %2, true
  973. // br i1 %3, label %cond.load, label %else
  974. //
  975. //cond.load: ; preds = %0
  976. // %4 = getelementptr i32* %1, i32 0
  977. // %5 = load i32* %4
  978. // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
  979. // br label %else
  980. //
  981. //else: ; preds = %0, %cond.load
  982. // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
  983. // %7 = extractelement <16 x i1> %mask, i32 1
  984. // %8 = icmp eq i1 %7, true
  985. // br i1 %8, label %cond.load1, label %else2
  986. //
  987. //cond.load1: ; preds = %else
  988. // %9 = getelementptr i32* %1, i32 1
  989. // %10 = load i32* %9
  990. // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
  991. // br label %else2
  992. //
  993. //else2: ; preds = %else, %cond.load1
  994. // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
  995. // %12 = extractelement <16 x i1> %mask, i32 2
  996. // %13 = icmp eq i1 %12, true
  997. // br i1 %13, label %cond.load4, label %else5
  998. //
  999. static void scalarizeMaskedLoad(CallInst *CI) {
  1000. Value *Ptr = CI->getArgOperand(0);
  1001. Value *Alignment = CI->getArgOperand(1);
  1002. Value *Mask = CI->getArgOperand(2);
  1003. Value *Src0 = CI->getArgOperand(3);
  1004. unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
  1005. VectorType *VecType = dyn_cast<VectorType>(CI->getType());
  1006. assert(VecType && "Unexpected return type of masked load intrinsic");
  1007. Type *EltTy = CI->getType()->getVectorElementType();
  1008. IRBuilder<> Builder(CI->getContext());
  1009. Instruction *InsertPt = CI;
  1010. BasicBlock *IfBlock = CI->getParent();
  1011. BasicBlock *CondBlock = nullptr;
  1012. BasicBlock *PrevIfBlock = CI->getParent();
  1013. Builder.SetInsertPoint(InsertPt);
  1014. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  1015. // Short-cut if the mask is all-true.
  1016. bool IsAllOnesMask = isa<Constant>(Mask) &&
  1017. cast<Constant>(Mask)->isAllOnesValue();
  1018. if (IsAllOnesMask) {
  1019. Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
  1020. CI->replaceAllUsesWith(NewI);
  1021. CI->eraseFromParent();
  1022. return;
  1023. }
  1024. // Adjust alignment for the scalar instruction.
  1025. AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
  1026. // Bitcast %addr fron i8* to EltTy*
  1027. Type *NewPtrType =
  1028. EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
  1029. Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
  1030. unsigned VectorWidth = VecType->getNumElements();
  1031. Value *UndefVal = UndefValue::get(VecType);
  1032. // The result vector
  1033. Value *VResult = UndefVal;
  1034. if (isa<ConstantVector>(Mask)) {
  1035. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1036. if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
  1037. continue;
  1038. Value *Gep =
  1039. Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
  1040. LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
  1041. VResult = Builder.CreateInsertElement(VResult, Load,
  1042. Builder.getInt32(Idx));
  1043. }
  1044. Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
  1045. CI->replaceAllUsesWith(NewI);
  1046. CI->eraseFromParent();
  1047. return;
  1048. }
  1049. PHINode *Phi = nullptr;
  1050. Value *PrevPhi = UndefVal;
  1051. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1052. // Fill the "else" block, created in the previous iteration
  1053. //
  1054. // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
  1055. // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
  1056. // %to_load = icmp eq i1 %mask_1, true
  1057. // br i1 %to_load, label %cond.load, label %else
  1058. //
  1059. if (Idx > 0) {
  1060. Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
  1061. Phi->addIncoming(VResult, CondBlock);
  1062. Phi->addIncoming(PrevPhi, PrevIfBlock);
  1063. PrevPhi = Phi;
  1064. VResult = Phi;
  1065. }
  1066. Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
  1067. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
  1068. ConstantInt::get(Predicate->getType(), 1));
  1069. // Create "cond" block
  1070. //
  1071. // %EltAddr = getelementptr i32* %1, i32 0
  1072. // %Elt = load i32* %EltAddr
  1073. // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
  1074. //
  1075. CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
  1076. Builder.SetInsertPoint(InsertPt);
  1077. Value *Gep =
  1078. Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
  1079. LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
  1080. VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
  1081. // Create "else" block, fill it in the next iteration
  1082. BasicBlock *NewIfBlock =
  1083. CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
  1084. Builder.SetInsertPoint(InsertPt);
  1085. Instruction *OldBr = IfBlock->getTerminator();
  1086. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1087. OldBr->eraseFromParent();
  1088. PrevIfBlock = IfBlock;
  1089. IfBlock = NewIfBlock;
  1090. }
  1091. Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
  1092. Phi->addIncoming(VResult, CondBlock);
  1093. Phi->addIncoming(PrevPhi, PrevIfBlock);
  1094. Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
  1095. CI->replaceAllUsesWith(NewI);
  1096. CI->eraseFromParent();
  1097. }
  1098. // Translate a masked store intrinsic, like
  1099. // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
  1100. // <16 x i1> %mask)
  1101. // to a chain of basic blocks, that stores element one-by-one if
  1102. // the appropriate mask bit is set
  1103. //
  1104. // %1 = bitcast i8* %addr to i32*
  1105. // %2 = extractelement <16 x i1> %mask, i32 0
  1106. // %3 = icmp eq i1 %2, true
  1107. // br i1 %3, label %cond.store, label %else
  1108. //
  1109. // cond.store: ; preds = %0
  1110. // %4 = extractelement <16 x i32> %val, i32 0
  1111. // %5 = getelementptr i32* %1, i32 0
  1112. // store i32 %4, i32* %5
  1113. // br label %else
  1114. //
  1115. // else: ; preds = %0, %cond.store
  1116. // %6 = extractelement <16 x i1> %mask, i32 1
  1117. // %7 = icmp eq i1 %6, true
  1118. // br i1 %7, label %cond.store1, label %else2
  1119. //
  1120. // cond.store1: ; preds = %else
  1121. // %8 = extractelement <16 x i32> %val, i32 1
  1122. // %9 = getelementptr i32* %1, i32 1
  1123. // store i32 %8, i32* %9
  1124. // br label %else2
  1125. // . . .
  1126. static void scalarizeMaskedStore(CallInst *CI) {
  1127. Value *Src = CI->getArgOperand(0);
  1128. Value *Ptr = CI->getArgOperand(1);
  1129. Value *Alignment = CI->getArgOperand(2);
  1130. Value *Mask = CI->getArgOperand(3);
  1131. unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
  1132. VectorType *VecType = dyn_cast<VectorType>(Src->getType());
  1133. assert(VecType && "Unexpected data type in masked store intrinsic");
  1134. Type *EltTy = VecType->getElementType();
  1135. IRBuilder<> Builder(CI->getContext());
  1136. Instruction *InsertPt = CI;
  1137. BasicBlock *IfBlock = CI->getParent();
  1138. Builder.SetInsertPoint(InsertPt);
  1139. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  1140. // Short-cut if the mask is all-true.
  1141. bool IsAllOnesMask = isa<Constant>(Mask) &&
  1142. cast<Constant>(Mask)->isAllOnesValue();
  1143. if (IsAllOnesMask) {
  1144. Builder.CreateAlignedStore(Src, Ptr, AlignVal);
  1145. CI->eraseFromParent();
  1146. return;
  1147. }
  1148. // Adjust alignment for the scalar instruction.
  1149. AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
  1150. // Bitcast %addr fron i8* to EltTy*
  1151. Type *NewPtrType =
  1152. EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
  1153. Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
  1154. unsigned VectorWidth = VecType->getNumElements();
  1155. if (isa<ConstantVector>(Mask)) {
  1156. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1157. if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
  1158. continue;
  1159. Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
  1160. Value *Gep =
  1161. Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
  1162. Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
  1163. }
  1164. CI->eraseFromParent();
  1165. return;
  1166. }
  1167. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1168. // Fill the "else" block, created in the previous iteration
  1169. //
  1170. // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
  1171. // %to_store = icmp eq i1 %mask_1, true
  1172. // br i1 %to_store, label %cond.store, label %else
  1173. //
  1174. Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
  1175. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
  1176. ConstantInt::get(Predicate->getType(), 1));
  1177. // Create "cond" block
  1178. //
  1179. // %OneElt = extractelement <16 x i32> %Src, i32 Idx
  1180. // %EltAddr = getelementptr i32* %1, i32 0
  1181. // %store i32 %OneElt, i32* %EltAddr
  1182. //
  1183. BasicBlock *CondBlock =
  1184. IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
  1185. Builder.SetInsertPoint(InsertPt);
  1186. Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
  1187. Value *Gep =
  1188. Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
  1189. Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
  1190. // Create "else" block, fill it in the next iteration
  1191. BasicBlock *NewIfBlock =
  1192. CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
  1193. Builder.SetInsertPoint(InsertPt);
  1194. Instruction *OldBr = IfBlock->getTerminator();
  1195. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1196. OldBr->eraseFromParent();
  1197. IfBlock = NewIfBlock;
  1198. }
  1199. CI->eraseFromParent();
  1200. }
  1201. // Translate a masked gather intrinsic like
  1202. // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
  1203. // <16 x i1> %Mask, <16 x i32> %Src)
  1204. // to a chain of basic blocks, with loading element one-by-one if
  1205. // the appropriate mask bit is set
  1206. //
  1207. // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
  1208. // % Mask0 = extractelement <16 x i1> %Mask, i32 0
  1209. // % ToLoad0 = icmp eq i1 % Mask0, true
  1210. // br i1 % ToLoad0, label %cond.load, label %else
  1211. //
  1212. // cond.load:
  1213. // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
  1214. // % Load0 = load i32, i32* % Ptr0, align 4
  1215. // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
  1216. // br label %else
  1217. //
  1218. // else:
  1219. // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
  1220. // % Mask1 = extractelement <16 x i1> %Mask, i32 1
  1221. // % ToLoad1 = icmp eq i1 % Mask1, true
  1222. // br i1 % ToLoad1, label %cond.load1, label %else2
  1223. //
  1224. // cond.load1:
  1225. // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
  1226. // % Load1 = load i32, i32* % Ptr1, align 4
  1227. // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
  1228. // br label %else2
  1229. // . . .
  1230. // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
  1231. // ret <16 x i32> %Result
  1232. static void scalarizeMaskedGather(CallInst *CI) {
  1233. Value *Ptrs = CI->getArgOperand(0);
  1234. Value *Alignment = CI->getArgOperand(1);
  1235. Value *Mask = CI->getArgOperand(2);
  1236. Value *Src0 = CI->getArgOperand(3);
  1237. VectorType *VecType = dyn_cast<VectorType>(CI->getType());
  1238. assert(VecType && "Unexpected return type of masked load intrinsic");
  1239. IRBuilder<> Builder(CI->getContext());
  1240. Instruction *InsertPt = CI;
  1241. BasicBlock *IfBlock = CI->getParent();
  1242. BasicBlock *CondBlock = nullptr;
  1243. BasicBlock *PrevIfBlock = CI->getParent();
  1244. Builder.SetInsertPoint(InsertPt);
  1245. unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
  1246. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  1247. Value *UndefVal = UndefValue::get(VecType);
  1248. // The result vector
  1249. Value *VResult = UndefVal;
  1250. unsigned VectorWidth = VecType->getNumElements();
  1251. // Shorten the way if the mask is a vector of constants.
  1252. bool IsConstMask = isa<ConstantVector>(Mask);
  1253. if (IsConstMask) {
  1254. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1255. if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
  1256. continue;
  1257. Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
  1258. "Ptr" + Twine(Idx));
  1259. LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
  1260. "Load" + Twine(Idx));
  1261. VResult = Builder.CreateInsertElement(VResult, Load,
  1262. Builder.getInt32(Idx),
  1263. "Res" + Twine(Idx));
  1264. }
  1265. Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
  1266. CI->replaceAllUsesWith(NewI);
  1267. CI->eraseFromParent();
  1268. return;
  1269. }
  1270. PHINode *Phi = nullptr;
  1271. Value *PrevPhi = UndefVal;
  1272. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1273. // Fill the "else" block, created in the previous iteration
  1274. //
  1275. // %Mask1 = extractelement <16 x i1> %Mask, i32 1
  1276. // %ToLoad1 = icmp eq i1 %Mask1, true
  1277. // br i1 %ToLoad1, label %cond.load, label %else
  1278. //
  1279. if (Idx > 0) {
  1280. Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
  1281. Phi->addIncoming(VResult, CondBlock);
  1282. Phi->addIncoming(PrevPhi, PrevIfBlock);
  1283. PrevPhi = Phi;
  1284. VResult = Phi;
  1285. }
  1286. Value *Predicate = Builder.CreateExtractElement(Mask,
  1287. Builder.getInt32(Idx),
  1288. "Mask" + Twine(Idx));
  1289. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
  1290. ConstantInt::get(Predicate->getType(), 1),
  1291. "ToLoad" + Twine(Idx));
  1292. // Create "cond" block
  1293. //
  1294. // %EltAddr = getelementptr i32* %1, i32 0
  1295. // %Elt = load i32* %EltAddr
  1296. // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
  1297. //
  1298. CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
  1299. Builder.SetInsertPoint(InsertPt);
  1300. Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
  1301. "Ptr" + Twine(Idx));
  1302. LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
  1303. "Load" + Twine(Idx));
  1304. VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
  1305. "Res" + Twine(Idx));
  1306. // Create "else" block, fill it in the next iteration
  1307. BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
  1308. Builder.SetInsertPoint(InsertPt);
  1309. Instruction *OldBr = IfBlock->getTerminator();
  1310. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1311. OldBr->eraseFromParent();
  1312. PrevIfBlock = IfBlock;
  1313. IfBlock = NewIfBlock;
  1314. }
  1315. Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
  1316. Phi->addIncoming(VResult, CondBlock);
  1317. Phi->addIncoming(PrevPhi, PrevIfBlock);
  1318. Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
  1319. CI->replaceAllUsesWith(NewI);
  1320. CI->eraseFromParent();
  1321. }
  1322. // Translate a masked scatter intrinsic, like
  1323. // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
  1324. // <16 x i1> %Mask)
  1325. // to a chain of basic blocks, that stores element one-by-one if
  1326. // the appropriate mask bit is set.
  1327. //
  1328. // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
  1329. // % Mask0 = extractelement <16 x i1> % Mask, i32 0
  1330. // % ToStore0 = icmp eq i1 % Mask0, true
  1331. // br i1 %ToStore0, label %cond.store, label %else
  1332. //
  1333. // cond.store:
  1334. // % Elt0 = extractelement <16 x i32> %Src, i32 0
  1335. // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
  1336. // store i32 %Elt0, i32* % Ptr0, align 4
  1337. // br label %else
  1338. //
  1339. // else:
  1340. // % Mask1 = extractelement <16 x i1> % Mask, i32 1
  1341. // % ToStore1 = icmp eq i1 % Mask1, true
  1342. // br i1 % ToStore1, label %cond.store1, label %else2
  1343. //
  1344. // cond.store1:
  1345. // % Elt1 = extractelement <16 x i32> %Src, i32 1
  1346. // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
  1347. // store i32 % Elt1, i32* % Ptr1, align 4
  1348. // br label %else2
  1349. // . . .
  1350. static void scalarizeMaskedScatter(CallInst *CI) {
  1351. Value *Src = CI->getArgOperand(0);
  1352. Value *Ptrs = CI->getArgOperand(1);
  1353. Value *Alignment = CI->getArgOperand(2);
  1354. Value *Mask = CI->getArgOperand(3);
  1355. assert(isa<VectorType>(Src->getType()) &&
  1356. "Unexpected data type in masked scatter intrinsic");
  1357. assert(isa<VectorType>(Ptrs->getType()) &&
  1358. isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
  1359. "Vector of pointers is expected in masked scatter intrinsic");
  1360. IRBuilder<> Builder(CI->getContext());
  1361. Instruction *InsertPt = CI;
  1362. BasicBlock *IfBlock = CI->getParent();
  1363. Builder.SetInsertPoint(InsertPt);
  1364. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  1365. unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
  1366. unsigned VectorWidth = Src->getType()->getVectorNumElements();
  1367. // Shorten the way if the mask is a vector of constants.
  1368. bool IsConstMask = isa<ConstantVector>(Mask);
  1369. if (IsConstMask) {
  1370. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1371. if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
  1372. continue;
  1373. Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
  1374. "Elt" + Twine(Idx));
  1375. Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
  1376. "Ptr" + Twine(Idx));
  1377. Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
  1378. }
  1379. CI->eraseFromParent();
  1380. return;
  1381. }
  1382. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1383. // Fill the "else" block, created in the previous iteration
  1384. //
  1385. // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
  1386. // % ToStore = icmp eq i1 % Mask1, true
  1387. // br i1 % ToStore, label %cond.store, label %else
  1388. //
  1389. Value *Predicate = Builder.CreateExtractElement(Mask,
  1390. Builder.getInt32(Idx),
  1391. "Mask" + Twine(Idx));
  1392. Value *Cmp =
  1393. Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
  1394. ConstantInt::get(Predicate->getType(), 1),
  1395. "ToStore" + Twine(Idx));
  1396. // Create "cond" block
  1397. //
  1398. // % Elt1 = extractelement <16 x i32> %Src, i32 1
  1399. // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
  1400. // %store i32 % Elt1, i32* % Ptr1
  1401. //
  1402. BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
  1403. Builder.SetInsertPoint(InsertPt);
  1404. Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
  1405. "Elt" + Twine(Idx));
  1406. Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
  1407. "Ptr" + Twine(Idx));
  1408. Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
  1409. // Create "else" block, fill it in the next iteration
  1410. BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
  1411. Builder.SetInsertPoint(InsertPt);
  1412. Instruction *OldBr = IfBlock->getTerminator();
  1413. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1414. OldBr->eraseFromParent();
  1415. IfBlock = NewIfBlock;
  1416. }
  1417. CI->eraseFromParent();
  1418. }
  1419. /// If counting leading or trailing zeros is an expensive operation and a zero
  1420. /// input is defined, add a check for zero to avoid calling the intrinsic.
  1421. ///
  1422. /// We want to transform:
  1423. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
  1424. ///
  1425. /// into:
  1426. /// entry:
  1427. /// %cmpz = icmp eq i64 %A, 0
  1428. /// br i1 %cmpz, label %cond.end, label %cond.false
  1429. /// cond.false:
  1430. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
  1431. /// br label %cond.end
  1432. /// cond.end:
  1433. /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
  1434. ///
  1435. /// If the transform is performed, return true and set ModifiedDT to true.
  1436. static bool despeculateCountZeros(IntrinsicInst *CountZeros,
  1437. const TargetLowering *TLI,
  1438. const DataLayout *DL,
  1439. bool &ModifiedDT) {
  1440. if (!TLI || !DL)
  1441. return false;
  1442. // If a zero input is undefined, it doesn't make sense to despeculate that.
  1443. if (match(CountZeros->getOperand(1), m_One()))
  1444. return false;
  1445. // If it's cheap to speculate, there's nothing to do.
  1446. auto IntrinsicID = CountZeros->getIntrinsicID();
  1447. if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
  1448. (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
  1449. return false;
  1450. // Only handle legal scalar cases. Anything else requires too much work.
  1451. Type *Ty = CountZeros->getType();
  1452. unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
  1453. if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
  1454. return false;
  1455. // The intrinsic will be sunk behind a compare against zero and branch.
  1456. BasicBlock *StartBlock = CountZeros->getParent();
  1457. BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
  1458. // Create another block after the count zero intrinsic. A PHI will be added
  1459. // in this block to select the result of the intrinsic or the bit-width
  1460. // constant if the input to the intrinsic is zero.
  1461. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
  1462. BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
  1463. // Set up a builder to create a compare, conditional branch, and PHI.
  1464. IRBuilder<> Builder(CountZeros->getContext());
  1465. Builder.SetInsertPoint(StartBlock->getTerminator());
  1466. Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
  1467. // Replace the unconditional branch that was created by the first split with
  1468. // a compare against zero and a conditional branch.
  1469. Value *Zero = Constant::getNullValue(Ty);
  1470. Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
  1471. Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
  1472. StartBlock->getTerminator()->eraseFromParent();
  1473. // Create a PHI in the end block to select either the output of the intrinsic
  1474. // or the bit width of the operand.
  1475. Builder.SetInsertPoint(&EndBlock->front());
  1476. PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
  1477. CountZeros->replaceAllUsesWith(PN);
  1478. Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
  1479. PN->addIncoming(BitWidth, StartBlock);
  1480. PN->addIncoming(CountZeros, CallBlock);
  1481. // We are explicitly handling the zero case, so we can set the intrinsic's
  1482. // undefined zero argument to 'true'. This will also prevent reprocessing the
  1483. // intrinsic; we only despeculate when a zero input is defined.
  1484. CountZeros->setArgOperand(1, Builder.getTrue());
  1485. ModifiedDT = true;
  1486. return true;
  1487. }
  1488. bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
  1489. BasicBlock *BB = CI->getParent();
  1490. // Lower inline assembly if we can.
  1491. // If we found an inline asm expession, and if the target knows how to
  1492. // lower it to normal LLVM code, do so now.
  1493. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  1494. if (TLI->ExpandInlineAsm(CI)) {
  1495. // Avoid invalidating the iterator.
  1496. CurInstIterator = BB->begin();
  1497. // Avoid processing instructions out of order, which could cause
  1498. // reuse before a value is defined.
  1499. SunkAddrs.clear();
  1500. return true;
  1501. }
  1502. // Sink address computing for memory operands into the block.
  1503. if (optimizeInlineAsmInst(CI))
  1504. return true;
  1505. }
  1506. // Align the pointer arguments to this call if the target thinks it's a good
  1507. // idea
  1508. unsigned MinSize, PrefAlign;
  1509. if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1510. for (auto &Arg : CI->arg_operands()) {
  1511. // We want to align both objects whose address is used directly and
  1512. // objects whose address is used in casts and GEPs, though it only makes
  1513. // sense for GEPs if the offset is a multiple of the desired alignment and
  1514. // if size - offset meets the size threshold.
  1515. if (!Arg->getType()->isPointerTy())
  1516. continue;
  1517. APInt Offset(DL->getPointerSizeInBits(
  1518. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1519. 0);
  1520. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1521. uint64_t Offset2 = Offset.getLimitedValue();
  1522. if ((Offset2 & (PrefAlign-1)) != 0)
  1523. continue;
  1524. AllocaInst *AI;
  1525. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
  1526. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1527. AI->setAlignment(PrefAlign);
  1528. // Global variables can only be aligned if they are defined in this
  1529. // object (i.e. they are uniquely initialized in this object), and
  1530. // over-aligning global variables that have an explicit section is
  1531. // forbidden.
  1532. GlobalVariable *GV;
  1533. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
  1534. GV->getAlignment() < PrefAlign &&
  1535. DL->getTypeAllocSize(GV->getValueType()) >=
  1536. MinSize + Offset2)
  1537. GV->setAlignment(PrefAlign);
  1538. }
  1539. // If this is a memcpy (or similar) then we may be able to improve the
  1540. // alignment
  1541. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1542. unsigned Align = getKnownAlignment(MI->getDest(), *DL);
  1543. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
  1544. Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
  1545. if (Align > MI->getAlignment())
  1546. MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
  1547. }
  1548. }
  1549. // If we have a cold call site, try to sink addressing computation into the
  1550. // cold block. This interacts with our handling for loads and stores to
  1551. // ensure that we can fold all uses of a potential addressing computation
  1552. // into their uses. TODO: generalize this to work over profiling data
  1553. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  1554. for (auto &Arg : CI->arg_operands()) {
  1555. if (!Arg->getType()->isPointerTy())
  1556. continue;
  1557. unsigned AS = Arg->getType()->getPointerAddressSpace();
  1558. return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
  1559. }
  1560. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1561. if (II) {
  1562. switch (II->getIntrinsicID()) {
  1563. default: break;
  1564. case Intrinsic::objectsize: {
  1565. // Lower all uses of llvm.objectsize.*
  1566. uint64_t Size;
  1567. Type *ReturnTy = CI->getType();
  1568. Constant *RetVal = nullptr;
  1569. ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
  1570. ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
  1571. if (getObjectSize(II->getArgOperand(0),
  1572. Size, *DL, TLInfo, false, Mode)) {
  1573. RetVal = ConstantInt::get(ReturnTy, Size);
  1574. } else {
  1575. RetVal = ConstantInt::get(ReturnTy,
  1576. Mode == ObjSizeMode::Min ? 0 : -1ULL);
  1577. }
  1578. // Substituting this can cause recursive simplifications, which can
  1579. // invalidate our iterator. Use a WeakVH to hold onto it in case this
  1580. // happens.
  1581. Value *CurValue = &*CurInstIterator;
  1582. WeakVH IterHandle(CurValue);
  1583. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1584. // If the iterator instruction was recursively deleted, start over at the
  1585. // start of the block.
  1586. if (IterHandle != CurValue) {
  1587. CurInstIterator = BB->begin();
  1588. SunkAddrs.clear();
  1589. }
  1590. return true;
  1591. }
  1592. case Intrinsic::masked_load: {
  1593. // Scalarize unsupported vector masked load
  1594. if (!TTI->isLegalMaskedLoad(CI->getType())) {
  1595. scalarizeMaskedLoad(CI);
  1596. ModifiedDT = true;
  1597. return true;
  1598. }
  1599. return false;
  1600. }
  1601. case Intrinsic::masked_store: {
  1602. if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
  1603. scalarizeMaskedStore(CI);
  1604. ModifiedDT = true;
  1605. return true;
  1606. }
  1607. return false;
  1608. }
  1609. case Intrinsic::masked_gather: {
  1610. if (!TTI->isLegalMaskedGather(CI->getType())) {
  1611. scalarizeMaskedGather(CI);
  1612. ModifiedDT = true;
  1613. return true;
  1614. }
  1615. return false;
  1616. }
  1617. case Intrinsic::masked_scatter: {
  1618. if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
  1619. scalarizeMaskedScatter(CI);
  1620. ModifiedDT = true;
  1621. return true;
  1622. }
  1623. return false;
  1624. }
  1625. case Intrinsic::aarch64_stlxr:
  1626. case Intrinsic::aarch64_stxr: {
  1627. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  1628. if (!ExtVal || !ExtVal->hasOneUse() ||
  1629. ExtVal->getParent() == CI->getParent())
  1630. return false;
  1631. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  1632. ExtVal->moveBefore(CI);
  1633. // Mark this instruction as "inserted by CGP", so that other
  1634. // optimizations don't touch it.
  1635. InsertedInsts.insert(ExtVal);
  1636. return true;
  1637. }
  1638. case Intrinsic::invariant_group_barrier:
  1639. II->replaceAllUsesWith(II->getArgOperand(0));
  1640. II->eraseFromParent();
  1641. return true;
  1642. case Intrinsic::cttz:
  1643. case Intrinsic::ctlz:
  1644. // If counting zeros is expensive, try to avoid it.
  1645. return despeculateCountZeros(II, TLI, DL, ModifiedDT);
  1646. }
  1647. if (TLI) {
  1648. // Unknown address space.
  1649. // TODO: Target hook to pick which address space the intrinsic cares
  1650. // about?
  1651. unsigned AddrSpace = ~0u;
  1652. SmallVector<Value*, 2> PtrOps;
  1653. Type *AccessTy;
  1654. if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
  1655. while (!PtrOps.empty())
  1656. if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
  1657. return true;
  1658. }
  1659. }
  1660. // From here on out we're working with named functions.
  1661. if (!CI->getCalledFunction()) return false;
  1662. // Lower all default uses of _chk calls. This is very similar
  1663. // to what InstCombineCalls does, but here we are only lowering calls
  1664. // to fortified library functions (e.g. __memcpy_chk) that have the default
  1665. // "don't know" as the objectsize. Anything else should be left alone.
  1666. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  1667. if (Value *V = Simplifier.optimizeCall(CI)) {
  1668. CI->replaceAllUsesWith(V);
  1669. CI->eraseFromParent();
  1670. return true;
  1671. }
  1672. return false;
  1673. }
  1674. /// Look for opportunities to duplicate return instructions to the predecessor
  1675. /// to enable tail call optimizations. The case it is currently looking for is:
  1676. /// @code
  1677. /// bb0:
  1678. /// %tmp0 = tail call i32 @f0()
  1679. /// br label %return
  1680. /// bb1:
  1681. /// %tmp1 = tail call i32 @f1()
  1682. /// br label %return
  1683. /// bb2:
  1684. /// %tmp2 = tail call i32 @f2()
  1685. /// br label %return
  1686. /// return:
  1687. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  1688. /// ret i32 %retval
  1689. /// @endcode
  1690. ///
  1691. /// =>
  1692. ///
  1693. /// @code
  1694. /// bb0:
  1695. /// %tmp0 = tail call i32 @f0()
  1696. /// ret i32 %tmp0
  1697. /// bb1:
  1698. /// %tmp1 = tail call i32 @f1()
  1699. /// ret i32 %tmp1
  1700. /// bb2:
  1701. /// %tmp2 = tail call i32 @f2()
  1702. /// ret i32 %tmp2
  1703. /// @endcode
  1704. bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
  1705. if (!TLI)
  1706. return false;
  1707. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  1708. if (!RI)
  1709. return false;
  1710. PHINode *PN = nullptr;
  1711. BitCastInst *BCI = nullptr;
  1712. Value *V = RI->getReturnValue();
  1713. if (V) {
  1714. BCI = dyn_cast<BitCastInst>(V);
  1715. if (BCI)
  1716. V = BCI->getOperand(0);
  1717. PN = dyn_cast<PHINode>(V);
  1718. if (!PN)
  1719. return false;
  1720. }
  1721. if (PN && PN->getParent() != BB)
  1722. return false;
  1723. // It's not safe to eliminate the sign / zero extension of the return value.
  1724. // See llvm::isInTailCallPosition().
  1725. const Function *F = BB->getParent();
  1726. AttributeSet CallerAttrs = F->getAttributes();
  1727. if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
  1728. CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
  1729. return false;
  1730. // Make sure there are no instructions between the PHI and return, or that the
  1731. // return is the first instruction in the block.
  1732. if (PN) {
  1733. BasicBlock::iterator BI = BB->begin();
  1734. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
  1735. if (&*BI == BCI)
  1736. // Also skip over the bitcast.
  1737. ++BI;
  1738. if (&*BI != RI)
  1739. return false;
  1740. } else {
  1741. BasicBlock::iterator BI = BB->begin();
  1742. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  1743. if (&*BI != RI)
  1744. return false;
  1745. }
  1746. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  1747. /// call.
  1748. SmallVector<CallInst*, 4> TailCalls;
  1749. if (PN) {
  1750. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  1751. CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
  1752. // Make sure the phi value is indeed produced by the tail call.
  1753. if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
  1754. TLI->mayBeEmittedAsTailCall(CI))
  1755. TailCalls.push_back(CI);
  1756. }
  1757. } else {
  1758. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  1759. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  1760. if (!VisitedBBs.insert(*PI).second)
  1761. continue;
  1762. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  1763. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  1764. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  1765. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  1766. if (RI == RE)
  1767. continue;
  1768. CallInst *CI = dyn_cast<CallInst>(&*RI);
  1769. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
  1770. TailCalls.push_back(CI);
  1771. }
  1772. }
  1773. bool Changed = false;
  1774. for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
  1775. CallInst *CI = TailCalls[i];
  1776. CallSite CS(CI);
  1777. // Conservatively require the attributes of the call to match those of the
  1778. // return. Ignore noalias because it doesn't affect the call sequence.
  1779. AttributeSet CalleeAttrs = CS.getAttributes();
  1780. if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  1781. removeAttribute(Attribute::NoAlias) !=
  1782. AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  1783. removeAttribute(Attribute::NoAlias))
  1784. continue;
  1785. // Make sure the call instruction is followed by an unconditional branch to
  1786. // the return block.
  1787. BasicBlock *CallBB = CI->getParent();
  1788. BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
  1789. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  1790. continue;
  1791. // Duplicate the return into CallBB.
  1792. (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
  1793. ModifiedDT = Changed = true;
  1794. ++NumRetsDup;
  1795. }
  1796. // If we eliminated all predecessors of the block, delete the block now.
  1797. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  1798. BB->eraseFromParent();
  1799. return Changed;
  1800. }
  1801. //===----------------------------------------------------------------------===//
  1802. // Memory Optimization
  1803. //===----------------------------------------------------------------------===//
  1804. namespace {
  1805. /// This is an extended version of TargetLowering::AddrMode
  1806. /// which holds actual Value*'s for register values.
  1807. struct ExtAddrMode : public TargetLowering::AddrMode {
  1808. Value *BaseReg;
  1809. Value *ScaledReg;
  1810. ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
  1811. void print(raw_ostream &OS) const;
  1812. void dump() const;
  1813. bool operator==(const ExtAddrMode& O) const {
  1814. return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
  1815. (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
  1816. (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
  1817. }
  1818. };
  1819. #ifndef NDEBUG
  1820. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  1821. AM.print(OS);
  1822. return OS;
  1823. }
  1824. #endif
  1825. void ExtAddrMode::print(raw_ostream &OS) const {
  1826. bool NeedPlus = false;
  1827. OS << "[";
  1828. if (BaseGV) {
  1829. OS << (NeedPlus ? " + " : "")
  1830. << "GV:";
  1831. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  1832. NeedPlus = true;
  1833. }
  1834. if (BaseOffs) {
  1835. OS << (NeedPlus ? " + " : "")
  1836. << BaseOffs;
  1837. NeedPlus = true;
  1838. }
  1839. if (BaseReg) {
  1840. OS << (NeedPlus ? " + " : "")
  1841. << "Base:";
  1842. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  1843. NeedPlus = true;
  1844. }
  1845. if (Scale) {
  1846. OS << (NeedPlus ? " + " : "")
  1847. << Scale << "*";
  1848. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  1849. }
  1850. OS << ']';
  1851. }
  1852. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1853. LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
  1854. print(dbgs());
  1855. dbgs() << '\n';
  1856. }
  1857. #endif
  1858. /// \brief This class provides transaction based operation on the IR.
  1859. /// Every change made through this class is recorded in the internal state and
  1860. /// can be undone (rollback) until commit is called.
  1861. class TypePromotionTransaction {
  1862. /// \brief This represents the common interface of the individual transaction.
  1863. /// Each class implements the logic for doing one specific modification on
  1864. /// the IR via the TypePromotionTransaction.
  1865. class TypePromotionAction {
  1866. protected:
  1867. /// The Instruction modified.
  1868. Instruction *Inst;
  1869. public:
  1870. /// \brief Constructor of the action.
  1871. /// The constructor performs the related action on the IR.
  1872. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  1873. virtual ~TypePromotionAction() {}
  1874. /// \brief Undo the modification done by this action.
  1875. /// When this method is called, the IR must be in the same state as it was
  1876. /// before this action was applied.
  1877. /// \pre Undoing the action works if and only if the IR is in the exact same
  1878. /// state as it was directly after this action was applied.
  1879. virtual void undo() = 0;
  1880. /// \brief Advocate every change made by this action.
  1881. /// When the results on the IR of the action are to be kept, it is important
  1882. /// to call this function, otherwise hidden information may be kept forever.
  1883. virtual void commit() {
  1884. // Nothing to be done, this action is not doing anything.
  1885. }
  1886. };
  1887. /// \brief Utility to remember the position of an instruction.
  1888. class InsertionHandler {
  1889. /// Position of an instruction.
  1890. /// Either an instruction:
  1891. /// - Is the first in a basic block: BB is used.
  1892. /// - Has a previous instructon: PrevInst is used.
  1893. union {
  1894. Instruction *PrevInst;
  1895. BasicBlock *BB;
  1896. } Point;
  1897. /// Remember whether or not the instruction had a previous instruction.
  1898. bool HasPrevInstruction;
  1899. public:
  1900. /// \brief Record the position of \p Inst.
  1901. InsertionHandler(Instruction *Inst) {
  1902. BasicBlock::iterator It = Inst->getIterator();
  1903. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  1904. if (HasPrevInstruction)
  1905. Point.PrevInst = &*--It;
  1906. else
  1907. Point.BB = Inst->getParent();
  1908. }
  1909. /// \brief Insert \p Inst at the recorded position.
  1910. void insert(Instruction *Inst) {
  1911. if (HasPrevInstruction) {
  1912. if (Inst->getParent())
  1913. Inst->removeFromParent();
  1914. Inst->insertAfter(Point.PrevInst);
  1915. } else {
  1916. Instruction *Position = &*Point.BB->getFirstInsertionPt();
  1917. if (Inst->getParent())
  1918. Inst->moveBefore(Position);
  1919. else
  1920. Inst->insertBefore(Position);
  1921. }
  1922. }
  1923. };
  1924. /// \brief Move an instruction before another.
  1925. class InstructionMoveBefore : public TypePromotionAction {
  1926. /// Original position of the instruction.
  1927. InsertionHandler Position;
  1928. public:
  1929. /// \brief Move \p Inst before \p Before.
  1930. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  1931. : TypePromotionAction(Inst), Position(Inst) {
  1932. DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
  1933. Inst->moveBefore(Before);
  1934. }
  1935. /// \brief Move the instruction back to its original position.
  1936. void undo() override {
  1937. DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  1938. Position.insert(Inst);
  1939. }
  1940. };
  1941. /// \brief Set the operand of an instruction with a new value.
  1942. class OperandSetter : public TypePromotionAction {
  1943. /// Original operand of the instruction.
  1944. Value *Origin;
  1945. /// Index of the modified instruction.
  1946. unsigned Idx;
  1947. public:
  1948. /// \brief Set \p Idx operand of \p Inst with \p NewVal.
  1949. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  1950. : TypePromotionAction(Inst), Idx(Idx) {
  1951. DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  1952. << "for:" << *Inst << "\n"
  1953. << "with:" << *NewVal << "\n");
  1954. Origin = Inst->getOperand(Idx);
  1955. Inst->setOperand(Idx, NewVal);
  1956. }
  1957. /// \brief Restore the original value of the instruction.
  1958. void undo() override {
  1959. DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  1960. << "for: " << *Inst << "\n"
  1961. << "with: " << *Origin << "\n");
  1962. Inst->setOperand(Idx, Origin);
  1963. }
  1964. };
  1965. /// \brief Hide the operands of an instruction.
  1966. /// Do as if this instruction was not using any of its operands.
  1967. class OperandsHider : public TypePromotionAction {
  1968. /// The list of original operands.
  1969. SmallVector<Value *, 4> OriginalValues;
  1970. public:
  1971. /// \brief Remove \p Inst from the uses of the operands of \p Inst.
  1972. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  1973. DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  1974. unsigned NumOpnds = Inst->getNumOperands();
  1975. OriginalValues.reserve(NumOpnds);
  1976. for (unsigned It = 0; It < NumOpnds; ++It) {
  1977. // Save the current operand.
  1978. Value *Val = Inst->getOperand(It);
  1979. OriginalValues.push_back(Val);
  1980. // Set a dummy one.
  1981. // We could use OperandSetter here, but that would imply an overhead
  1982. // that we are not willing to pay.
  1983. Inst->setOperand(It, UndefValue::get(Val->getType()));
  1984. }
  1985. }
  1986. /// \brief Restore the original list of uses.
  1987. void undo() override {
  1988. DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  1989. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  1990. Inst->setOperand(It, OriginalValues[It]);
  1991. }
  1992. };
  1993. /// \brief Build a truncate instruction.
  1994. class TruncBuilder : public TypePromotionAction {
  1995. Value *Val;
  1996. public:
  1997. /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
  1998. /// result.
  1999. /// trunc Opnd to Ty.
  2000. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  2001. IRBuilder<> Builder(Opnd);
  2002. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  2003. DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  2004. }
  2005. /// \brief Get the built value.
  2006. Value *getBuiltValue() { return Val; }
  2007. /// \brief Remove the built instruction.
  2008. void undo() override {
  2009. DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  2010. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2011. IVal->eraseFromParent();
  2012. }
  2013. };
  2014. /// \brief Build a sign extension instruction.
  2015. class SExtBuilder : public TypePromotionAction {
  2016. Value *Val;
  2017. public:
  2018. /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
  2019. /// result.
  2020. /// sext Opnd to Ty.
  2021. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2022. : TypePromotionAction(InsertPt) {
  2023. IRBuilder<> Builder(InsertPt);
  2024. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  2025. DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  2026. }
  2027. /// \brief Get the built value.
  2028. Value *getBuiltValue() { return Val; }
  2029. /// \brief Remove the built instruction.
  2030. void undo() override {
  2031. DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  2032. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2033. IVal->eraseFromParent();
  2034. }
  2035. };
  2036. /// \brief Build a zero extension instruction.
  2037. class ZExtBuilder : public TypePromotionAction {
  2038. Value *Val;
  2039. public:
  2040. /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
  2041. /// result.
  2042. /// zext Opnd to Ty.
  2043. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2044. : TypePromotionAction(InsertPt) {
  2045. IRBuilder<> Builder(InsertPt);
  2046. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  2047. DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  2048. }
  2049. /// \brief Get the built value.
  2050. Value *getBuiltValue() { return Val; }
  2051. /// \brief Remove the built instruction.
  2052. void undo() override {
  2053. DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  2054. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2055. IVal->eraseFromParent();
  2056. }
  2057. };
  2058. /// \brief Mutate an instruction to another type.
  2059. class TypeMutator : public TypePromotionAction {
  2060. /// Record the original type.
  2061. Type *OrigTy;
  2062. public:
  2063. /// \brief Mutate the type of \p Inst into \p NewTy.
  2064. TypeMutator(Instruction *Inst, Type *NewTy)
  2065. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  2066. DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  2067. << "\n");
  2068. Inst->mutateType(NewTy);
  2069. }
  2070. /// \brief Mutate the instruction back to its original type.
  2071. void undo() override {
  2072. DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  2073. << "\n");
  2074. Inst->mutateType(OrigTy);
  2075. }
  2076. };
  2077. /// \brief Replace the uses of an instruction by another instruction.
  2078. class UsesReplacer : public TypePromotionAction {
  2079. /// Helper structure to keep track of the replaced uses.
  2080. struct InstructionAndIdx {
  2081. /// The instruction using the instruction.
  2082. Instruction *Inst;
  2083. /// The index where this instruction is used for Inst.
  2084. unsigned Idx;
  2085. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  2086. : Inst(Inst), Idx(Idx) {}
  2087. };
  2088. /// Keep track of the original uses (pair Instruction, Index).
  2089. SmallVector<InstructionAndIdx, 4> OriginalUses;
  2090. typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
  2091. public:
  2092. /// \brief Replace all the use of \p Inst by \p New.
  2093. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  2094. DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  2095. << "\n");
  2096. // Record the original uses.
  2097. for (Use &U : Inst->uses()) {
  2098. Instruction *UserI = cast<Instruction>(U.getUser());
  2099. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  2100. }
  2101. // Now, we can replace the uses.
  2102. Inst->replaceAllUsesWith(New);
  2103. }
  2104. /// \brief Reassign the original uses of Inst to Inst.
  2105. void undo() override {
  2106. DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  2107. for (use_iterator UseIt = OriginalUses.begin(),
  2108. EndIt = OriginalUses.end();
  2109. UseIt != EndIt; ++UseIt) {
  2110. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  2111. }
  2112. }
  2113. };
  2114. /// \brief Remove an instruction from the IR.
  2115. class InstructionRemover : public TypePromotionAction {
  2116. /// Original position of the instruction.
  2117. InsertionHandler Inserter;
  2118. /// Helper structure to hide all the link to the instruction. In other
  2119. /// words, this helps to do as if the instruction was removed.
  2120. OperandsHider Hider;
  2121. /// Keep track of the uses replaced, if any.
  2122. UsesReplacer *Replacer;
  2123. public:
  2124. /// \brief Remove all reference of \p Inst and optinally replace all its
  2125. /// uses with New.
  2126. /// \pre If !Inst->use_empty(), then New != nullptr
  2127. InstructionRemover(Instruction *Inst, Value *New = nullptr)
  2128. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  2129. Replacer(nullptr) {
  2130. if (New)
  2131. Replacer = new UsesReplacer(Inst, New);
  2132. DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  2133. Inst->removeFromParent();
  2134. }
  2135. ~InstructionRemover() override { delete Replacer; }
  2136. /// \brief Really remove the instruction.
  2137. void commit() override { delete Inst; }
  2138. /// \brief Resurrect the instruction and reassign it to the proper uses if
  2139. /// new value was provided when build this action.
  2140. void undo() override {
  2141. DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  2142. Inserter.insert(Inst);
  2143. if (Replacer)
  2144. Replacer->undo();
  2145. Hider.undo();
  2146. }
  2147. };
  2148. public:
  2149. /// Restoration point.
  2150. /// The restoration point is a pointer to an action instead of an iterator
  2151. /// because the iterator may be invalidated but not the pointer.
  2152. typedef const TypePromotionAction *ConstRestorationPt;
  2153. /// Advocate every changes made in that transaction.
  2154. void commit();
  2155. /// Undo all the changes made after the given point.
  2156. void rollback(ConstRestorationPt Point);
  2157. /// Get the current restoration point.
  2158. ConstRestorationPt getRestorationPoint() const;
  2159. /// \name API for IR modification with state keeping to support rollback.
  2160. /// @{
  2161. /// Same as Instruction::setOperand.
  2162. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  2163. /// Same as Instruction::eraseFromParent.
  2164. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  2165. /// Same as Value::replaceAllUsesWith.
  2166. void replaceAllUsesWith(Instruction *Inst, Value *New);
  2167. /// Same as Value::mutateType.
  2168. void mutateType(Instruction *Inst, Type *NewTy);
  2169. /// Same as IRBuilder::createTrunc.
  2170. Value *createTrunc(Instruction *Opnd, Type *Ty);
  2171. /// Same as IRBuilder::createSExt.
  2172. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2173. /// Same as IRBuilder::createZExt.
  2174. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2175. /// Same as Instruction::moveBefore.
  2176. void moveBefore(Instruction *Inst, Instruction *Before);
  2177. /// @}
  2178. private:
  2179. /// The ordered list of actions made so far.
  2180. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  2181. typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
  2182. };
  2183. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  2184. Value *NewVal) {
  2185. Actions.push_back(
  2186. make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
  2187. }
  2188. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  2189. Value *NewVal) {
  2190. Actions.push_back(
  2191. make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
  2192. }
  2193. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  2194. Value *New) {
  2195. Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  2196. }
  2197. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  2198. Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  2199. }
  2200. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  2201. Type *Ty) {
  2202. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  2203. Value *Val = Ptr->getBuiltValue();
  2204. Actions.push_back(std::move(Ptr));
  2205. return Val;
  2206. }
  2207. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  2208. Value *Opnd, Type *Ty) {
  2209. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  2210. Value *Val = Ptr->getBuiltValue();
  2211. Actions.push_back(std::move(Ptr));
  2212. return Val;
  2213. }
  2214. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  2215. Value *Opnd, Type *Ty) {
  2216. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  2217. Value *Val = Ptr->getBuiltValue();
  2218. Actions.push_back(std::move(Ptr));
  2219. return Val;
  2220. }
  2221. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  2222. Instruction *Before) {
  2223. Actions.push_back(
  2224. make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
  2225. }
  2226. TypePromotionTransaction::ConstRestorationPt
  2227. TypePromotionTransaction::getRestorationPoint() const {
  2228. return !Actions.empty() ? Actions.back().get() : nullptr;
  2229. }
  2230. void TypePromotionTransaction::commit() {
  2231. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  2232. ++It)
  2233. (*It)->commit();
  2234. Actions.clear();
  2235. }
  2236. void TypePromotionTransaction::rollback(
  2237. TypePromotionTransaction::ConstRestorationPt Point) {
  2238. while (!Actions.empty() && Point != Actions.back().get()) {
  2239. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  2240. Curr->undo();
  2241. }
  2242. }
  2243. /// \brief A helper class for matching addressing modes.
  2244. ///
  2245. /// This encapsulates the logic for matching the target-legal addressing modes.
  2246. class AddressingModeMatcher {
  2247. SmallVectorImpl<Instruction*> &AddrModeInsts;
  2248. const TargetMachine &TM;
  2249. const TargetLowering &TLI;
  2250. const DataLayout &DL;
  2251. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  2252. /// the memory instruction that we're computing this address for.
  2253. Type *AccessTy;
  2254. unsigned AddrSpace;
  2255. Instruction *MemoryInst;
  2256. /// This is the addressing mode that we're building up. This is
  2257. /// part of the return value of this addressing mode matching stuff.
  2258. ExtAddrMode &AddrMode;
  2259. /// The instructions inserted by other CodeGenPrepare optimizations.
  2260. const SetOfInstrs &InsertedInsts;
  2261. /// A map from the instructions to their type before promotion.
  2262. InstrToOrigTy &PromotedInsts;
  2263. /// The ongoing transaction where every action should be registered.
  2264. TypePromotionTransaction &TPT;
  2265. /// This is set to true when we should not do profitability checks.
  2266. /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
  2267. bool IgnoreProfitability;
  2268. AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
  2269. const TargetMachine &TM, Type *AT, unsigned AS,
  2270. Instruction *MI, ExtAddrMode &AM,
  2271. const SetOfInstrs &InsertedInsts,
  2272. InstrToOrigTy &PromotedInsts,
  2273. TypePromotionTransaction &TPT)
  2274. : AddrModeInsts(AMI), TM(TM),
  2275. TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
  2276. ->getTargetLowering()),
  2277. DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
  2278. MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
  2279. PromotedInsts(PromotedInsts), TPT(TPT) {
  2280. IgnoreProfitability = false;
  2281. }
  2282. public:
  2283. /// Find the maximal addressing mode that a load/store of V can fold,
  2284. /// give an access type of AccessTy. This returns a list of involved
  2285. /// instructions in AddrModeInsts.
  2286. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  2287. /// optimizations.
  2288. /// \p PromotedInsts maps the instructions to their type before promotion.
  2289. /// \p The ongoing transaction where every action should be registered.
  2290. static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
  2291. Instruction *MemoryInst,
  2292. SmallVectorImpl<Instruction*> &AddrModeInsts,
  2293. const TargetMachine &TM,
  2294. const SetOfInstrs &InsertedInsts,
  2295. InstrToOrigTy &PromotedInsts,
  2296. TypePromotionTransaction &TPT) {
  2297. ExtAddrMode Result;
  2298. bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
  2299. MemoryInst, Result, InsertedInsts,
  2300. PromotedInsts, TPT).matchAddr(V, 0);
  2301. (void)Success; assert(Success && "Couldn't select *anything*?");
  2302. return Result;
  2303. }
  2304. private:
  2305. bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  2306. bool matchAddr(Value *V, unsigned Depth);
  2307. bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
  2308. bool *MovedAway = nullptr);
  2309. bool isProfitableToFoldIntoAddressingMode(Instruction *I,
  2310. ExtAddrMode &AMBefore,
  2311. ExtAddrMode &AMAfter);
  2312. bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  2313. bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
  2314. Value *PromotedOperand) const;
  2315. };
  2316. /// Try adding ScaleReg*Scale to the current addressing mode.
  2317. /// Return true and update AddrMode if this addr mode is legal for the target,
  2318. /// false if not.
  2319. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  2320. unsigned Depth) {
  2321. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  2322. // mode. Just process that directly.
  2323. if (Scale == 1)
  2324. return matchAddr(ScaleReg, Depth);
  2325. // If the scale is 0, it takes nothing to add this.
  2326. if (Scale == 0)
  2327. return true;
  2328. // If we already have a scale of this value, we can add to it, otherwise, we
  2329. // need an available scale field.
  2330. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  2331. return false;
  2332. ExtAddrMode TestAddrMode = AddrMode;
  2333. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  2334. // [A+B + A*7] -> [B+A*8].
  2335. TestAddrMode.Scale += Scale;
  2336. TestAddrMode.ScaledReg = ScaleReg;
  2337. // If the new address isn't legal, bail out.
  2338. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  2339. return false;
  2340. // It was legal, so commit it.
  2341. AddrMode = TestAddrMode;
  2342. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  2343. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  2344. // X*Scale + C*Scale to addr mode.
  2345. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  2346. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  2347. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  2348. TestAddrMode.ScaledReg = AddLHS;
  2349. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  2350. // If this addressing mode is legal, commit it and remember that we folded
  2351. // this instruction.
  2352. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  2353. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  2354. AddrMode = TestAddrMode;
  2355. return true;
  2356. }
  2357. }
  2358. // Otherwise, not (x+c)*scale, just return what we have.
  2359. return true;
  2360. }
  2361. /// This is a little filter, which returns true if an addressing computation
  2362. /// involving I might be folded into a load/store accessing it.
  2363. /// This doesn't need to be perfect, but needs to accept at least
  2364. /// the set of instructions that MatchOperationAddr can.
  2365. static bool MightBeFoldableInst(Instruction *I) {
  2366. switch (I->getOpcode()) {
  2367. case Instruction::BitCast:
  2368. case Instruction::AddrSpaceCast:
  2369. // Don't touch identity bitcasts.
  2370. if (I->getType() == I->getOperand(0)->getType())
  2371. return false;
  2372. return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
  2373. case Instruction::PtrToInt:
  2374. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  2375. return true;
  2376. case Instruction::IntToPtr:
  2377. // We know the input is intptr_t, so this is foldable.
  2378. return true;
  2379. case Instruction::Add:
  2380. return true;
  2381. case Instruction::Mul:
  2382. case Instruction::Shl:
  2383. // Can only handle X*C and X << C.
  2384. return isa<ConstantInt>(I->getOperand(1));
  2385. case Instruction::GetElementPtr:
  2386. return true;
  2387. default:
  2388. return false;
  2389. }
  2390. }
  2391. /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
  2392. /// \note \p Val is assumed to be the product of some type promotion.
  2393. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  2394. /// to be legal, as the non-promoted value would have had the same state.
  2395. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  2396. const DataLayout &DL, Value *Val) {
  2397. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  2398. if (!PromotedInst)
  2399. return false;
  2400. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  2401. // If the ISDOpcode is undefined, it was undefined before the promotion.
  2402. if (!ISDOpcode)
  2403. return true;
  2404. // Otherwise, check if the promoted instruction is legal or not.
  2405. return TLI.isOperationLegalOrCustom(
  2406. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  2407. }
  2408. /// \brief Hepler class to perform type promotion.
  2409. class TypePromotionHelper {
  2410. /// \brief Utility function to check whether or not a sign or zero extension
  2411. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  2412. /// either using the operands of \p Inst or promoting \p Inst.
  2413. /// The type of the extension is defined by \p IsSExt.
  2414. /// In other words, check if:
  2415. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  2416. /// #1 Promotion applies:
  2417. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  2418. /// #2 Operand reuses:
  2419. /// ext opnd1 to ConsideredExtType.
  2420. /// \p PromotedInsts maps the instructions to their type before promotion.
  2421. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  2422. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  2423. /// \brief Utility function to determine if \p OpIdx should be promoted when
  2424. /// promoting \p Inst.
  2425. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  2426. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  2427. }
  2428. /// \brief Utility function to promote the operand of \p Ext when this
  2429. /// operand is a promotable trunc or sext or zext.
  2430. /// \p PromotedInsts maps the instructions to their type before promotion.
  2431. /// \p CreatedInstsCost[out] contains the cost of all instructions
  2432. /// created to promote the operand of Ext.
  2433. /// Newly added extensions are inserted in \p Exts.
  2434. /// Newly added truncates are inserted in \p Truncs.
  2435. /// Should never be called directly.
  2436. /// \return The promoted value which is used instead of Ext.
  2437. static Value *promoteOperandForTruncAndAnyExt(
  2438. Instruction *Ext, TypePromotionTransaction &TPT,
  2439. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2440. SmallVectorImpl<Instruction *> *Exts,
  2441. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  2442. /// \brief Utility function to promote the operand of \p Ext when this
  2443. /// operand is promotable and is not a supported trunc or sext.
  2444. /// \p PromotedInsts maps the instructions to their type before promotion.
  2445. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  2446. /// created to promote the operand of Ext.
  2447. /// Newly added extensions are inserted in \p Exts.
  2448. /// Newly added truncates are inserted in \p Truncs.
  2449. /// Should never be called directly.
  2450. /// \return The promoted value which is used instead of Ext.
  2451. static Value *promoteOperandForOther(Instruction *Ext,
  2452. TypePromotionTransaction &TPT,
  2453. InstrToOrigTy &PromotedInsts,
  2454. unsigned &CreatedInstsCost,
  2455. SmallVectorImpl<Instruction *> *Exts,
  2456. SmallVectorImpl<Instruction *> *Truncs,
  2457. const TargetLowering &TLI, bool IsSExt);
  2458. /// \see promoteOperandForOther.
  2459. static Value *signExtendOperandForOther(
  2460. Instruction *Ext, TypePromotionTransaction &TPT,
  2461. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2462. SmallVectorImpl<Instruction *> *Exts,
  2463. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2464. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2465. Exts, Truncs, TLI, true);
  2466. }
  2467. /// \see promoteOperandForOther.
  2468. static Value *zeroExtendOperandForOther(
  2469. Instruction *Ext, TypePromotionTransaction &TPT,
  2470. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2471. SmallVectorImpl<Instruction *> *Exts,
  2472. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2473. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2474. Exts, Truncs, TLI, false);
  2475. }
  2476. public:
  2477. /// Type for the utility function that promotes the operand of Ext.
  2478. typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
  2479. InstrToOrigTy &PromotedInsts,
  2480. unsigned &CreatedInstsCost,
  2481. SmallVectorImpl<Instruction *> *Exts,
  2482. SmallVectorImpl<Instruction *> *Truncs,
  2483. const TargetLowering &TLI);
  2484. /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
  2485. /// action to promote the operand of \p Ext instead of using Ext.
  2486. /// \return NULL if no promotable action is possible with the current
  2487. /// sign extension.
  2488. /// \p InsertedInsts keeps track of all the instructions inserted by the
  2489. /// other CodeGenPrepare optimizations. This information is important
  2490. /// because we do not want to promote these instructions as CodeGenPrepare
  2491. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  2492. /// \p PromotedInsts maps the instructions to their type before promotion.
  2493. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2494. const TargetLowering &TLI,
  2495. const InstrToOrigTy &PromotedInsts);
  2496. };
  2497. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  2498. Type *ConsideredExtType,
  2499. const InstrToOrigTy &PromotedInsts,
  2500. bool IsSExt) {
  2501. // The promotion helper does not know how to deal with vector types yet.
  2502. // To be able to fix that, we would need to fix the places where we
  2503. // statically extend, e.g., constants and such.
  2504. if (Inst->getType()->isVectorTy())
  2505. return false;
  2506. // We can always get through zext.
  2507. if (isa<ZExtInst>(Inst))
  2508. return true;
  2509. // sext(sext) is ok too.
  2510. if (IsSExt && isa<SExtInst>(Inst))
  2511. return true;
  2512. // We can get through binary operator, if it is legal. In other words, the
  2513. // binary operator must have a nuw or nsw flag.
  2514. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  2515. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  2516. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  2517. (IsSExt && BinOp->hasNoSignedWrap())))
  2518. return true;
  2519. // Check if we can do the following simplification.
  2520. // ext(trunc(opnd)) --> ext(opnd)
  2521. if (!isa<TruncInst>(Inst))
  2522. return false;
  2523. Value *OpndVal = Inst->getOperand(0);
  2524. // Check if we can use this operand in the extension.
  2525. // If the type is larger than the result type of the extension, we cannot.
  2526. if (!OpndVal->getType()->isIntegerTy() ||
  2527. OpndVal->getType()->getIntegerBitWidth() >
  2528. ConsideredExtType->getIntegerBitWidth())
  2529. return false;
  2530. // If the operand of the truncate is not an instruction, we will not have
  2531. // any information on the dropped bits.
  2532. // (Actually we could for constant but it is not worth the extra logic).
  2533. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  2534. if (!Opnd)
  2535. return false;
  2536. // Check if the source of the type is narrow enough.
  2537. // I.e., check that trunc just drops extended bits of the same kind of
  2538. // the extension.
  2539. // #1 get the type of the operand and check the kind of the extended bits.
  2540. const Type *OpndType;
  2541. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  2542. if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
  2543. OpndType = It->second.getPointer();
  2544. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  2545. OpndType = Opnd->getOperand(0)->getType();
  2546. else
  2547. return false;
  2548. // #2 check that the truncate just drops extended bits.
  2549. return Inst->getType()->getIntegerBitWidth() >=
  2550. OpndType->getIntegerBitWidth();
  2551. }
  2552. TypePromotionHelper::Action TypePromotionHelper::getAction(
  2553. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2554. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  2555. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  2556. "Unexpected instruction type");
  2557. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  2558. Type *ExtTy = Ext->getType();
  2559. bool IsSExt = isa<SExtInst>(Ext);
  2560. // If the operand of the extension is not an instruction, we cannot
  2561. // get through.
  2562. // If it, check we can get through.
  2563. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  2564. return nullptr;
  2565. // Do not promote if the operand has been added by codegenprepare.
  2566. // Otherwise, it means we are undoing an optimization that is likely to be
  2567. // redone, thus causing potential infinite loop.
  2568. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  2569. return nullptr;
  2570. // SExt or Trunc instructions.
  2571. // Return the related handler.
  2572. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  2573. isa<ZExtInst>(ExtOpnd))
  2574. return promoteOperandForTruncAndAnyExt;
  2575. // Regular instruction.
  2576. // Abort early if we will have to insert non-free instructions.
  2577. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  2578. return nullptr;
  2579. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  2580. }
  2581. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  2582. llvm::Instruction *SExt, TypePromotionTransaction &TPT,
  2583. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2584. SmallVectorImpl<Instruction *> *Exts,
  2585. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2586. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  2587. // get through it and this method should not be called.
  2588. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  2589. Value *ExtVal = SExt;
  2590. bool HasMergedNonFreeExt = false;
  2591. if (isa<ZExtInst>(SExtOpnd)) {
  2592. // Replace s|zext(zext(opnd))
  2593. // => zext(opnd).
  2594. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  2595. Value *ZExt =
  2596. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  2597. TPT.replaceAllUsesWith(SExt, ZExt);
  2598. TPT.eraseInstruction(SExt);
  2599. ExtVal = ZExt;
  2600. } else {
  2601. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  2602. // => z|sext(opnd).
  2603. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  2604. }
  2605. CreatedInstsCost = 0;
  2606. // Remove dead code.
  2607. if (SExtOpnd->use_empty())
  2608. TPT.eraseInstruction(SExtOpnd);
  2609. // Check if the extension is still needed.
  2610. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  2611. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  2612. if (ExtInst) {
  2613. if (Exts)
  2614. Exts->push_back(ExtInst);
  2615. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  2616. }
  2617. return ExtVal;
  2618. }
  2619. // At this point we have: ext ty opnd to ty.
  2620. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  2621. Value *NextVal = ExtInst->getOperand(0);
  2622. TPT.eraseInstruction(ExtInst, NextVal);
  2623. return NextVal;
  2624. }
  2625. Value *TypePromotionHelper::promoteOperandForOther(
  2626. Instruction *Ext, TypePromotionTransaction &TPT,
  2627. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2628. SmallVectorImpl<Instruction *> *Exts,
  2629. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  2630. bool IsSExt) {
  2631. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  2632. // get through it and this method should not be called.
  2633. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  2634. CreatedInstsCost = 0;
  2635. if (!ExtOpnd->hasOneUse()) {
  2636. // ExtOpnd will be promoted.
  2637. // All its uses, but Ext, will need to use a truncated value of the
  2638. // promoted version.
  2639. // Create the truncate now.
  2640. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  2641. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  2642. ITrunc->removeFromParent();
  2643. // Insert it just after the definition.
  2644. ITrunc->insertAfter(ExtOpnd);
  2645. if (Truncs)
  2646. Truncs->push_back(ITrunc);
  2647. }
  2648. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  2649. // Restore the operand of Ext (which has been replaced by the previous call
  2650. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  2651. TPT.setOperand(Ext, 0, ExtOpnd);
  2652. }
  2653. // Get through the Instruction:
  2654. // 1. Update its type.
  2655. // 2. Replace the uses of Ext by Inst.
  2656. // 3. Extend each operand that needs to be extended.
  2657. // Remember the original type of the instruction before promotion.
  2658. // This is useful to know that the high bits are sign extended bits.
  2659. PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
  2660. ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
  2661. // Step #1.
  2662. TPT.mutateType(ExtOpnd, Ext->getType());
  2663. // Step #2.
  2664. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  2665. // Step #3.
  2666. Instruction *ExtForOpnd = Ext;
  2667. DEBUG(dbgs() << "Propagate Ext to operands\n");
  2668. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  2669. ++OpIdx) {
  2670. DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  2671. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  2672. !shouldExtOperand(ExtOpnd, OpIdx)) {
  2673. DEBUG(dbgs() << "No need to propagate\n");
  2674. continue;
  2675. }
  2676. // Check if we can statically extend the operand.
  2677. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  2678. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  2679. DEBUG(dbgs() << "Statically extend\n");
  2680. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  2681. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  2682. : Cst->getValue().zext(BitWidth);
  2683. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  2684. continue;
  2685. }
  2686. // UndefValue are typed, so we have to statically sign extend them.
  2687. if (isa<UndefValue>(Opnd)) {
  2688. DEBUG(dbgs() << "Statically extend\n");
  2689. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  2690. continue;
  2691. }
  2692. // Otherwise we have to explicity sign extend the operand.
  2693. // Check if Ext was reused to extend an operand.
  2694. if (!ExtForOpnd) {
  2695. // If yes, create a new one.
  2696. DEBUG(dbgs() << "More operands to ext\n");
  2697. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  2698. : TPT.createZExt(Ext, Opnd, Ext->getType());
  2699. if (!isa<Instruction>(ValForExtOpnd)) {
  2700. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  2701. continue;
  2702. }
  2703. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  2704. }
  2705. if (Exts)
  2706. Exts->push_back(ExtForOpnd);
  2707. TPT.setOperand(ExtForOpnd, 0, Opnd);
  2708. // Move the sign extension before the insertion point.
  2709. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  2710. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  2711. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  2712. // If more sext are required, new instructions will have to be created.
  2713. ExtForOpnd = nullptr;
  2714. }
  2715. if (ExtForOpnd == Ext) {
  2716. DEBUG(dbgs() << "Extension is useless now\n");
  2717. TPT.eraseInstruction(Ext);
  2718. }
  2719. return ExtOpnd;
  2720. }
  2721. /// Check whether or not promoting an instruction to a wider type is profitable.
  2722. /// \p NewCost gives the cost of extension instructions created by the
  2723. /// promotion.
  2724. /// \p OldCost gives the cost of extension instructions before the promotion
  2725. /// plus the number of instructions that have been
  2726. /// matched in the addressing mode the promotion.
  2727. /// \p PromotedOperand is the value that has been promoted.
  2728. /// \return True if the promotion is profitable, false otherwise.
  2729. bool AddressingModeMatcher::isPromotionProfitable(
  2730. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  2731. DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
  2732. // The cost of the new extensions is greater than the cost of the
  2733. // old extension plus what we folded.
  2734. // This is not profitable.
  2735. if (NewCost > OldCost)
  2736. return false;
  2737. if (NewCost < OldCost)
  2738. return true;
  2739. // The promotion is neutral but it may help folding the sign extension in
  2740. // loads for instance.
  2741. // Check that we did not create an illegal instruction.
  2742. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  2743. }
  2744. /// Given an instruction or constant expr, see if we can fold the operation
  2745. /// into the addressing mode. If so, update the addressing mode and return
  2746. /// true, otherwise return false without modifying AddrMode.
  2747. /// If \p MovedAway is not NULL, it contains the information of whether or
  2748. /// not AddrInst has to be folded into the addressing mode on success.
  2749. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  2750. /// because it has been moved away.
  2751. /// Thus AddrInst must not be added in the matched instructions.
  2752. /// This state can happen when AddrInst is a sext, since it may be moved away.
  2753. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  2754. /// not be referenced anymore.
  2755. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  2756. unsigned Depth,
  2757. bool *MovedAway) {
  2758. // Avoid exponential behavior on extremely deep expression trees.
  2759. if (Depth >= 5) return false;
  2760. // By default, all matched instructions stay in place.
  2761. if (MovedAway)
  2762. *MovedAway = false;
  2763. switch (Opcode) {
  2764. case Instruction::PtrToInt:
  2765. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  2766. return matchAddr(AddrInst->getOperand(0), Depth);
  2767. case Instruction::IntToPtr: {
  2768. auto AS = AddrInst->getType()->getPointerAddressSpace();
  2769. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  2770. // This inttoptr is a no-op if the integer type is pointer sized.
  2771. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  2772. return matchAddr(AddrInst->getOperand(0), Depth);
  2773. return false;
  2774. }
  2775. case Instruction::BitCast:
  2776. // BitCast is always a noop, and we can handle it as long as it is
  2777. // int->int or pointer->pointer (we don't want int<->fp or something).
  2778. if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
  2779. AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
  2780. // Don't touch identity bitcasts. These were probably put here by LSR,
  2781. // and we don't want to mess around with them. Assume it knows what it
  2782. // is doing.
  2783. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  2784. return matchAddr(AddrInst->getOperand(0), Depth);
  2785. return false;
  2786. case Instruction::AddrSpaceCast: {
  2787. unsigned SrcAS
  2788. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  2789. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  2790. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2791. return matchAddr(AddrInst->getOperand(0), Depth);
  2792. return false;
  2793. }
  2794. case Instruction::Add: {
  2795. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  2796. ExtAddrMode BackupAddrMode = AddrMode;
  2797. unsigned OldSize = AddrModeInsts.size();
  2798. // Start a transaction at this point.
  2799. // The LHS may match but not the RHS.
  2800. // Therefore, we need a higher level restoration point to undo partially
  2801. // matched operation.
  2802. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2803. TPT.getRestorationPoint();
  2804. if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
  2805. matchAddr(AddrInst->getOperand(0), Depth+1))
  2806. return true;
  2807. // Restore the old addr mode info.
  2808. AddrMode = BackupAddrMode;
  2809. AddrModeInsts.resize(OldSize);
  2810. TPT.rollback(LastKnownGood);
  2811. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  2812. if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
  2813. matchAddr(AddrInst->getOperand(1), Depth+1))
  2814. return true;
  2815. // Otherwise we definitely can't merge the ADD in.
  2816. AddrMode = BackupAddrMode;
  2817. AddrModeInsts.resize(OldSize);
  2818. TPT.rollback(LastKnownGood);
  2819. break;
  2820. }
  2821. //case Instruction::Or:
  2822. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  2823. //break;
  2824. case Instruction::Mul:
  2825. case Instruction::Shl: {
  2826. // Can only handle X*C and X << C.
  2827. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  2828. if (!RHS)
  2829. return false;
  2830. int64_t Scale = RHS->getSExtValue();
  2831. if (Opcode == Instruction::Shl)
  2832. Scale = 1LL << Scale;
  2833. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  2834. }
  2835. case Instruction::GetElementPtr: {
  2836. // Scan the GEP. We check it if it contains constant offsets and at most
  2837. // one variable offset.
  2838. int VariableOperand = -1;
  2839. unsigned VariableScale = 0;
  2840. int64_t ConstantOffset = 0;
  2841. gep_type_iterator GTI = gep_type_begin(AddrInst);
  2842. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  2843. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  2844. const StructLayout *SL = DL.getStructLayout(STy);
  2845. unsigned Idx =
  2846. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  2847. ConstantOffset += SL->getElementOffset(Idx);
  2848. } else {
  2849. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  2850. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  2851. ConstantOffset += CI->getSExtValue()*TypeSize;
  2852. } else if (TypeSize) { // Scales of zero don't do anything.
  2853. // We only allow one variable index at the moment.
  2854. if (VariableOperand != -1)
  2855. return false;
  2856. // Remember the variable index.
  2857. VariableOperand = i;
  2858. VariableScale = TypeSize;
  2859. }
  2860. }
  2861. }
  2862. // A common case is for the GEP to only do a constant offset. In this case,
  2863. // just add it to the disp field and check validity.
  2864. if (VariableOperand == -1) {
  2865. AddrMode.BaseOffs += ConstantOffset;
  2866. if (ConstantOffset == 0 ||
  2867. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  2868. // Check to see if we can fold the base pointer in too.
  2869. if (matchAddr(AddrInst->getOperand(0), Depth+1))
  2870. return true;
  2871. }
  2872. AddrMode.BaseOffs -= ConstantOffset;
  2873. return false;
  2874. }
  2875. // Save the valid addressing mode in case we can't match.
  2876. ExtAddrMode BackupAddrMode = AddrMode;
  2877. unsigned OldSize = AddrModeInsts.size();
  2878. // See if the scale and offset amount is valid for this target.
  2879. AddrMode.BaseOffs += ConstantOffset;
  2880. // Match the base operand of the GEP.
  2881. if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
  2882. // If it couldn't be matched, just stuff the value in a register.
  2883. if (AddrMode.HasBaseReg) {
  2884. AddrMode = BackupAddrMode;
  2885. AddrModeInsts.resize(OldSize);
  2886. return false;
  2887. }
  2888. AddrMode.HasBaseReg = true;
  2889. AddrMode.BaseReg = AddrInst->getOperand(0);
  2890. }
  2891. // Match the remaining variable portion of the GEP.
  2892. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  2893. Depth)) {
  2894. // If it couldn't be matched, try stuffing the base into a register
  2895. // instead of matching it, and retrying the match of the scale.
  2896. AddrMode = BackupAddrMode;
  2897. AddrModeInsts.resize(OldSize);
  2898. if (AddrMode.HasBaseReg)
  2899. return false;
  2900. AddrMode.HasBaseReg = true;
  2901. AddrMode.BaseReg = AddrInst->getOperand(0);
  2902. AddrMode.BaseOffs += ConstantOffset;
  2903. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  2904. VariableScale, Depth)) {
  2905. // If even that didn't work, bail.
  2906. AddrMode = BackupAddrMode;
  2907. AddrModeInsts.resize(OldSize);
  2908. return false;
  2909. }
  2910. }
  2911. return true;
  2912. }
  2913. case Instruction::SExt:
  2914. case Instruction::ZExt: {
  2915. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  2916. if (!Ext)
  2917. return false;
  2918. // Try to move this ext out of the way of the addressing mode.
  2919. // Ask for a method for doing so.
  2920. TypePromotionHelper::Action TPH =
  2921. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  2922. if (!TPH)
  2923. return false;
  2924. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2925. TPT.getRestorationPoint();
  2926. unsigned CreatedInstsCost = 0;
  2927. unsigned ExtCost = !TLI.isExtFree(Ext);
  2928. Value *PromotedOperand =
  2929. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  2930. // SExt has been moved away.
  2931. // Thus either it will be rematched later in the recursive calls or it is
  2932. // gone. Anyway, we must not fold it into the addressing mode at this point.
  2933. // E.g.,
  2934. // op = add opnd, 1
  2935. // idx = ext op
  2936. // addr = gep base, idx
  2937. // is now:
  2938. // promotedOpnd = ext opnd <- no match here
  2939. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  2940. // addr = gep base, op <- match
  2941. if (MovedAway)
  2942. *MovedAway = true;
  2943. assert(PromotedOperand &&
  2944. "TypePromotionHelper should have filtered out those cases");
  2945. ExtAddrMode BackupAddrMode = AddrMode;
  2946. unsigned OldSize = AddrModeInsts.size();
  2947. if (!matchAddr(PromotedOperand, Depth) ||
  2948. // The total of the new cost is equal to the cost of the created
  2949. // instructions.
  2950. // The total of the old cost is equal to the cost of the extension plus
  2951. // what we have saved in the addressing mode.
  2952. !isPromotionProfitable(CreatedInstsCost,
  2953. ExtCost + (AddrModeInsts.size() - OldSize),
  2954. PromotedOperand)) {
  2955. AddrMode = BackupAddrMode;
  2956. AddrModeInsts.resize(OldSize);
  2957. DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  2958. TPT.rollback(LastKnownGood);
  2959. return false;
  2960. }
  2961. return true;
  2962. }
  2963. }
  2964. return false;
  2965. }
  2966. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  2967. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  2968. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  2969. /// for the target.
  2970. ///
  2971. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  2972. // Start a transaction at this point that we will rollback if the matching
  2973. // fails.
  2974. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2975. TPT.getRestorationPoint();
  2976. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  2977. // Fold in immediates if legal for the target.
  2978. AddrMode.BaseOffs += CI->getSExtValue();
  2979. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2980. return true;
  2981. AddrMode.BaseOffs -= CI->getSExtValue();
  2982. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  2983. // If this is a global variable, try to fold it into the addressing mode.
  2984. if (!AddrMode.BaseGV) {
  2985. AddrMode.BaseGV = GV;
  2986. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2987. return true;
  2988. AddrMode.BaseGV = nullptr;
  2989. }
  2990. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  2991. ExtAddrMode BackupAddrMode = AddrMode;
  2992. unsigned OldSize = AddrModeInsts.size();
  2993. // Check to see if it is possible to fold this operation.
  2994. bool MovedAway = false;
  2995. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  2996. // This instruction may have been moved away. If so, there is nothing
  2997. // to check here.
  2998. if (MovedAway)
  2999. return true;
  3000. // Okay, it's possible to fold this. Check to see if it is actually
  3001. // *profitable* to do so. We use a simple cost model to avoid increasing
  3002. // register pressure too much.
  3003. if (I->hasOneUse() ||
  3004. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  3005. AddrModeInsts.push_back(I);
  3006. return true;
  3007. }
  3008. // It isn't profitable to do this, roll back.
  3009. //cerr << "NOT FOLDING: " << *I;
  3010. AddrMode = BackupAddrMode;
  3011. AddrModeInsts.resize(OldSize);
  3012. TPT.rollback(LastKnownGood);
  3013. }
  3014. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  3015. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  3016. return true;
  3017. TPT.rollback(LastKnownGood);
  3018. } else if (isa<ConstantPointerNull>(Addr)) {
  3019. // Null pointer gets folded without affecting the addressing mode.
  3020. return true;
  3021. }
  3022. // Worse case, the target should support [reg] addressing modes. :)
  3023. if (!AddrMode.HasBaseReg) {
  3024. AddrMode.HasBaseReg = true;
  3025. AddrMode.BaseReg = Addr;
  3026. // Still check for legality in case the target supports [imm] but not [i+r].
  3027. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3028. return true;
  3029. AddrMode.HasBaseReg = false;
  3030. AddrMode.BaseReg = nullptr;
  3031. }
  3032. // If the base register is already taken, see if we can do [r+r].
  3033. if (AddrMode.Scale == 0) {
  3034. AddrMode.Scale = 1;
  3035. AddrMode.ScaledReg = Addr;
  3036. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3037. return true;
  3038. AddrMode.Scale = 0;
  3039. AddrMode.ScaledReg = nullptr;
  3040. }
  3041. // Couldn't match.
  3042. TPT.rollback(LastKnownGood);
  3043. return false;
  3044. }
  3045. /// Check to see if all uses of OpVal by the specified inline asm call are due
  3046. /// to memory operands. If so, return true, otherwise return false.
  3047. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  3048. const TargetMachine &TM) {
  3049. const Function *F = CI->getParent()->getParent();
  3050. const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
  3051. const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
  3052. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3053. TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
  3054. ImmutableCallSite(CI));
  3055. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3056. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3057. // Compute the constraint code and ConstraintType to use.
  3058. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  3059. // If this asm operand is our Value*, and if it isn't an indirect memory
  3060. // operand, we can't fold it!
  3061. if (OpInfo.CallOperandVal == OpVal &&
  3062. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  3063. !OpInfo.isIndirect))
  3064. return false;
  3065. }
  3066. return true;
  3067. }
  3068. /// Recursively walk all the uses of I until we find a memory use.
  3069. /// If we find an obviously non-foldable instruction, return true.
  3070. /// Add the ultimately found memory instructions to MemoryUses.
  3071. static bool FindAllMemoryUses(
  3072. Instruction *I,
  3073. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  3074. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
  3075. // If we already considered this instruction, we're done.
  3076. if (!ConsideredInsts.insert(I).second)
  3077. return false;
  3078. // If this is an obviously unfoldable instruction, bail out.
  3079. if (!MightBeFoldableInst(I))
  3080. return true;
  3081. const bool OptSize = I->getFunction()->optForSize();
  3082. // Loop over all the uses, recursively processing them.
  3083. for (Use &U : I->uses()) {
  3084. Instruction *UserI = cast<Instruction>(U.getUser());
  3085. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  3086. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  3087. continue;
  3088. }
  3089. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  3090. unsigned opNo = U.getOperandNo();
  3091. if (opNo == 0) return true; // Storing addr, not into addr.
  3092. MemoryUses.push_back(std::make_pair(SI, opNo));
  3093. continue;
  3094. }
  3095. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  3096. // If this is a cold call, we can sink the addressing calculation into
  3097. // the cold path. See optimizeCallInst
  3098. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  3099. continue;
  3100. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  3101. if (!IA) return true;
  3102. // If this is a memory operand, we're cool, otherwise bail out.
  3103. if (!IsOperandAMemoryOperand(CI, IA, I, TM))
  3104. return true;
  3105. continue;
  3106. }
  3107. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
  3108. return true;
  3109. }
  3110. return false;
  3111. }
  3112. /// Return true if Val is already known to be live at the use site that we're
  3113. /// folding it into. If so, there is no cost to include it in the addressing
  3114. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  3115. /// instruction already.
  3116. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  3117. Value *KnownLive2) {
  3118. // If Val is either of the known-live values, we know it is live!
  3119. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  3120. return true;
  3121. // All values other than instructions and arguments (e.g. constants) are live.
  3122. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  3123. // If Val is a constant sized alloca in the entry block, it is live, this is
  3124. // true because it is just a reference to the stack/frame pointer, which is
  3125. // live for the whole function.
  3126. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  3127. if (AI->isStaticAlloca())
  3128. return true;
  3129. // Check to see if this value is already used in the memory instruction's
  3130. // block. If so, it's already live into the block at the very least, so we
  3131. // can reasonably fold it.
  3132. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  3133. }
  3134. /// It is possible for the addressing mode of the machine to fold the specified
  3135. /// instruction into a load or store that ultimately uses it.
  3136. /// However, the specified instruction has multiple uses.
  3137. /// Given this, it may actually increase register pressure to fold it
  3138. /// into the load. For example, consider this code:
  3139. ///
  3140. /// X = ...
  3141. /// Y = X+1
  3142. /// use(Y) -> nonload/store
  3143. /// Z = Y+1
  3144. /// load Z
  3145. ///
  3146. /// In this case, Y has multiple uses, and can be folded into the load of Z
  3147. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  3148. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  3149. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  3150. /// number of computations either.
  3151. ///
  3152. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  3153. /// X was live across 'load Z' for other reasons, we actually *would* want to
  3154. /// fold the addressing mode in the Z case. This would make Y die earlier.
  3155. bool AddressingModeMatcher::
  3156. isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  3157. ExtAddrMode &AMAfter) {
  3158. if (IgnoreProfitability) return true;
  3159. // AMBefore is the addressing mode before this instruction was folded into it,
  3160. // and AMAfter is the addressing mode after the instruction was folded. Get
  3161. // the set of registers referenced by AMAfter and subtract out those
  3162. // referenced by AMBefore: this is the set of values which folding in this
  3163. // address extends the lifetime of.
  3164. //
  3165. // Note that there are only two potential values being referenced here,
  3166. // BaseReg and ScaleReg (global addresses are always available, as are any
  3167. // folded immediates).
  3168. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  3169. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  3170. // lifetime wasn't extended by adding this instruction.
  3171. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3172. BaseReg = nullptr;
  3173. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3174. ScaledReg = nullptr;
  3175. // If folding this instruction (and it's subexprs) didn't extend any live
  3176. // ranges, we're ok with it.
  3177. if (!BaseReg && !ScaledReg)
  3178. return true;
  3179. // If all uses of this instruction can have the address mode sunk into them,
  3180. // we can remove the addressing mode and effectively trade one live register
  3181. // for another (at worst.) In this context, folding an addressing mode into
  3182. // the use is just a particularly nice way of sinking it.
  3183. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  3184. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  3185. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
  3186. return false; // Has a non-memory, non-foldable use!
  3187. // Now that we know that all uses of this instruction are part of a chain of
  3188. // computation involving only operations that could theoretically be folded
  3189. // into a memory use, loop over each of these memory operation uses and see
  3190. // if they could *actually* fold the instruction. The assumption is that
  3191. // addressing modes are cheap and that duplicating the computation involved
  3192. // many times is worthwhile, even on a fastpath. For sinking candidates
  3193. // (i.e. cold call sites), this serves as a way to prevent excessive code
  3194. // growth since most architectures have some reasonable small and fast way to
  3195. // compute an effective address. (i.e LEA on x86)
  3196. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  3197. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  3198. Instruction *User = MemoryUses[i].first;
  3199. unsigned OpNo = MemoryUses[i].second;
  3200. // Get the access type of this use. If the use isn't a pointer, we don't
  3201. // know what it accesses.
  3202. Value *Address = User->getOperand(OpNo);
  3203. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  3204. if (!AddrTy)
  3205. return false;
  3206. Type *AddressAccessTy = AddrTy->getElementType();
  3207. unsigned AS = AddrTy->getAddressSpace();
  3208. // Do a match against the root of this address, ignoring profitability. This
  3209. // will tell us if the addressing mode for the memory operation will
  3210. // *actually* cover the shared instruction.
  3211. ExtAddrMode Result;
  3212. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3213. TPT.getRestorationPoint();
  3214. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
  3215. MemoryInst, Result, InsertedInsts,
  3216. PromotedInsts, TPT);
  3217. Matcher.IgnoreProfitability = true;
  3218. bool Success = Matcher.matchAddr(Address, 0);
  3219. (void)Success; assert(Success && "Couldn't select *anything*?");
  3220. // The match was to check the profitability, the changes made are not
  3221. // part of the original matcher. Therefore, they should be dropped
  3222. // otherwise the original matcher will not present the right state.
  3223. TPT.rollback(LastKnownGood);
  3224. // If the match didn't cover I, then it won't be shared by it.
  3225. if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
  3226. I) == MatchedAddrModeInsts.end())
  3227. return false;
  3228. MatchedAddrModeInsts.clear();
  3229. }
  3230. return true;
  3231. }
  3232. } // end anonymous namespace
  3233. /// Return true if the specified values are defined in a
  3234. /// different basic block than BB.
  3235. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  3236. if (Instruction *I = dyn_cast<Instruction>(V))
  3237. return I->getParent() != BB;
  3238. return false;
  3239. }
  3240. /// Sink addressing mode computation immediate before MemoryInst if doing so
  3241. /// can be done without increasing register pressure. The need for the
  3242. /// register pressure constraint means this can end up being an all or nothing
  3243. /// decision for all uses of the same addressing computation.
  3244. ///
  3245. /// Load and Store Instructions often have addressing modes that can do
  3246. /// significant amounts of computation. As such, instruction selection will try
  3247. /// to get the load or store to do as much computation as possible for the
  3248. /// program. The problem is that isel can only see within a single block. As
  3249. /// such, we sink as much legal addressing mode work into the block as possible.
  3250. ///
  3251. /// This method is used to optimize both load/store and inline asms with memory
  3252. /// operands. It's also used to sink addressing computations feeding into cold
  3253. /// call sites into their (cold) basic block.
  3254. ///
  3255. /// The motivation for handling sinking into cold blocks is that doing so can
  3256. /// both enable other address mode sinking (by satisfying the register pressure
  3257. /// constraint above), and reduce register pressure globally (by removing the
  3258. /// addressing mode computation from the fast path entirely.).
  3259. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  3260. Type *AccessTy, unsigned AddrSpace) {
  3261. Value *Repl = Addr;
  3262. // Try to collapse single-value PHI nodes. This is necessary to undo
  3263. // unprofitable PRE transformations.
  3264. SmallVector<Value*, 8> worklist;
  3265. SmallPtrSet<Value*, 16> Visited;
  3266. worklist.push_back(Addr);
  3267. // Use a worklist to iteratively look through PHI nodes, and ensure that
  3268. // the addressing mode obtained from the non-PHI roots of the graph
  3269. // are equivalent.
  3270. Value *Consensus = nullptr;
  3271. unsigned NumUsesConsensus = 0;
  3272. bool IsNumUsesConsensusValid = false;
  3273. SmallVector<Instruction*, 16> AddrModeInsts;
  3274. ExtAddrMode AddrMode;
  3275. TypePromotionTransaction TPT;
  3276. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3277. TPT.getRestorationPoint();
  3278. while (!worklist.empty()) {
  3279. Value *V = worklist.back();
  3280. worklist.pop_back();
  3281. // Break use-def graph loops.
  3282. if (!Visited.insert(V).second) {
  3283. Consensus = nullptr;
  3284. break;
  3285. }
  3286. // For a PHI node, push all of its incoming values.
  3287. if (PHINode *P = dyn_cast<PHINode>(V)) {
  3288. for (Value *IncValue : P->incoming_values())
  3289. worklist.push_back(IncValue);
  3290. continue;
  3291. }
  3292. // For non-PHIs, determine the addressing mode being computed. Note that
  3293. // the result may differ depending on what other uses our candidate
  3294. // addressing instructions might have.
  3295. SmallVector<Instruction*, 16> NewAddrModeInsts;
  3296. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  3297. V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
  3298. InsertedInsts, PromotedInsts, TPT);
  3299. // This check is broken into two cases with very similar code to avoid using
  3300. // getNumUses() as much as possible. Some values have a lot of uses, so
  3301. // calling getNumUses() unconditionally caused a significant compile-time
  3302. // regression.
  3303. if (!Consensus) {
  3304. Consensus = V;
  3305. AddrMode = NewAddrMode;
  3306. AddrModeInsts = NewAddrModeInsts;
  3307. continue;
  3308. } else if (NewAddrMode == AddrMode) {
  3309. if (!IsNumUsesConsensusValid) {
  3310. NumUsesConsensus = Consensus->getNumUses();
  3311. IsNumUsesConsensusValid = true;
  3312. }
  3313. // Ensure that the obtained addressing mode is equivalent to that obtained
  3314. // for all other roots of the PHI traversal. Also, when choosing one
  3315. // such root as representative, select the one with the most uses in order
  3316. // to keep the cost modeling heuristics in AddressingModeMatcher
  3317. // applicable.
  3318. unsigned NumUses = V->getNumUses();
  3319. if (NumUses > NumUsesConsensus) {
  3320. Consensus = V;
  3321. NumUsesConsensus = NumUses;
  3322. AddrModeInsts = NewAddrModeInsts;
  3323. }
  3324. continue;
  3325. }
  3326. Consensus = nullptr;
  3327. break;
  3328. }
  3329. // If the addressing mode couldn't be determined, or if multiple different
  3330. // ones were determined, bail out now.
  3331. if (!Consensus) {
  3332. TPT.rollback(LastKnownGood);
  3333. return false;
  3334. }
  3335. TPT.commit();
  3336. // Check to see if any of the instructions supersumed by this addr mode are
  3337. // non-local to I's BB.
  3338. bool AnyNonLocal = false;
  3339. for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
  3340. if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
  3341. AnyNonLocal = true;
  3342. break;
  3343. }
  3344. }
  3345. // If all the instructions matched are already in this BB, don't do anything.
  3346. if (!AnyNonLocal) {
  3347. DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
  3348. return false;
  3349. }
  3350. // Insert this computation right after this user. Since our caller is
  3351. // scanning from the top of the BB to the bottom, reuse of the expr are
  3352. // guaranteed to happen later.
  3353. IRBuilder<> Builder(MemoryInst);
  3354. // Now that we determined the addressing expression we want to use and know
  3355. // that we have to sink it into this block. Check to see if we have already
  3356. // done this for some other load/store instr in this block. If so, reuse the
  3357. // computation.
  3358. Value *&SunkAddr = SunkAddrs[Addr];
  3359. if (SunkAddr) {
  3360. DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
  3361. << *MemoryInst << "\n");
  3362. if (SunkAddr->getType() != Addr->getType())
  3363. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  3364. } else if (AddrSinkUsingGEPs ||
  3365. (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
  3366. TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
  3367. ->useAA())) {
  3368. // By default, we use the GEP-based method when AA is used later. This
  3369. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  3370. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3371. << *MemoryInst << "\n");
  3372. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3373. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  3374. // First, find the pointer.
  3375. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  3376. ResultPtr = AddrMode.BaseReg;
  3377. AddrMode.BaseReg = nullptr;
  3378. }
  3379. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  3380. // We can't add more than one pointer together, nor can we scale a
  3381. // pointer (both of which seem meaningless).
  3382. if (ResultPtr || AddrMode.Scale != 1)
  3383. return false;
  3384. ResultPtr = AddrMode.ScaledReg;
  3385. AddrMode.Scale = 0;
  3386. }
  3387. if (AddrMode.BaseGV) {
  3388. if (ResultPtr)
  3389. return false;
  3390. ResultPtr = AddrMode.BaseGV;
  3391. }
  3392. // If the real base value actually came from an inttoptr, then the matcher
  3393. // will look through it and provide only the integer value. In that case,
  3394. // use it here.
  3395. if (!ResultPtr && AddrMode.BaseReg) {
  3396. ResultPtr =
  3397. Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
  3398. AddrMode.BaseReg = nullptr;
  3399. } else if (!ResultPtr && AddrMode.Scale == 1) {
  3400. ResultPtr =
  3401. Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
  3402. AddrMode.Scale = 0;
  3403. }
  3404. if (!ResultPtr &&
  3405. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  3406. SunkAddr = Constant::getNullValue(Addr->getType());
  3407. } else if (!ResultPtr) {
  3408. return false;
  3409. } else {
  3410. Type *I8PtrTy =
  3411. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  3412. Type *I8Ty = Builder.getInt8Ty();
  3413. // Start with the base register. Do this first so that subsequent address
  3414. // matching finds it last, which will prevent it from trying to match it
  3415. // as the scaled value in case it happens to be a mul. That would be
  3416. // problematic if we've sunk a different mul for the scale, because then
  3417. // we'd end up sinking both muls.
  3418. if (AddrMode.BaseReg) {
  3419. Value *V = AddrMode.BaseReg;
  3420. if (V->getType() != IntPtrTy)
  3421. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3422. ResultIndex = V;
  3423. }
  3424. // Add the scale value.
  3425. if (AddrMode.Scale) {
  3426. Value *V = AddrMode.ScaledReg;
  3427. if (V->getType() == IntPtrTy) {
  3428. // done.
  3429. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3430. cast<IntegerType>(V->getType())->getBitWidth()) {
  3431. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3432. } else {
  3433. // It is only safe to sign extend the BaseReg if we know that the math
  3434. // required to create it did not overflow before we extend it. Since
  3435. // the original IR value was tossed in favor of a constant back when
  3436. // the AddrMode was created we need to bail out gracefully if widths
  3437. // do not match instead of extending it.
  3438. Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
  3439. if (I && (ResultIndex != AddrMode.BaseReg))
  3440. I->eraseFromParent();
  3441. return false;
  3442. }
  3443. if (AddrMode.Scale != 1)
  3444. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3445. "sunkaddr");
  3446. if (ResultIndex)
  3447. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  3448. else
  3449. ResultIndex = V;
  3450. }
  3451. // Add in the Base Offset if present.
  3452. if (AddrMode.BaseOffs) {
  3453. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3454. if (ResultIndex) {
  3455. // We need to add this separately from the scale above to help with
  3456. // SDAG consecutive load/store merging.
  3457. if (ResultPtr->getType() != I8PtrTy)
  3458. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  3459. ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3460. }
  3461. ResultIndex = V;
  3462. }
  3463. if (!ResultIndex) {
  3464. SunkAddr = ResultPtr;
  3465. } else {
  3466. if (ResultPtr->getType() != I8PtrTy)
  3467. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  3468. SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3469. }
  3470. if (SunkAddr->getType() != Addr->getType())
  3471. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  3472. }
  3473. } else {
  3474. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3475. << *MemoryInst << "\n");
  3476. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3477. Value *Result = nullptr;
  3478. // Start with the base register. Do this first so that subsequent address
  3479. // matching finds it last, which will prevent it from trying to match it
  3480. // as the scaled value in case it happens to be a mul. That would be
  3481. // problematic if we've sunk a different mul for the scale, because then
  3482. // we'd end up sinking both muls.
  3483. if (AddrMode.BaseReg) {
  3484. Value *V = AddrMode.BaseReg;
  3485. if (V->getType()->isPointerTy())
  3486. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3487. if (V->getType() != IntPtrTy)
  3488. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3489. Result = V;
  3490. }
  3491. // Add the scale value.
  3492. if (AddrMode.Scale) {
  3493. Value *V = AddrMode.ScaledReg;
  3494. if (V->getType() == IntPtrTy) {
  3495. // done.
  3496. } else if (V->getType()->isPointerTy()) {
  3497. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3498. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3499. cast<IntegerType>(V->getType())->getBitWidth()) {
  3500. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3501. } else {
  3502. // It is only safe to sign extend the BaseReg if we know that the math
  3503. // required to create it did not overflow before we extend it. Since
  3504. // the original IR value was tossed in favor of a constant back when
  3505. // the AddrMode was created we need to bail out gracefully if widths
  3506. // do not match instead of extending it.
  3507. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  3508. if (I && (Result != AddrMode.BaseReg))
  3509. I->eraseFromParent();
  3510. return false;
  3511. }
  3512. if (AddrMode.Scale != 1)
  3513. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3514. "sunkaddr");
  3515. if (Result)
  3516. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3517. else
  3518. Result = V;
  3519. }
  3520. // Add in the BaseGV if present.
  3521. if (AddrMode.BaseGV) {
  3522. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  3523. if (Result)
  3524. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3525. else
  3526. Result = V;
  3527. }
  3528. // Add in the Base Offset if present.
  3529. if (AddrMode.BaseOffs) {
  3530. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3531. if (Result)
  3532. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3533. else
  3534. Result = V;
  3535. }
  3536. if (!Result)
  3537. SunkAddr = Constant::getNullValue(Addr->getType());
  3538. else
  3539. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  3540. }
  3541. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  3542. // If we have no uses, recursively delete the value and all dead instructions
  3543. // using it.
  3544. if (Repl->use_empty()) {
  3545. // This can cause recursive deletion, which can invalidate our iterator.
  3546. // Use a WeakVH to hold onto it in case this happens.
  3547. Value *CurValue = &*CurInstIterator;
  3548. WeakVH IterHandle(CurValue);
  3549. BasicBlock *BB = CurInstIterator->getParent();
  3550. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  3551. if (IterHandle != CurValue) {
  3552. // If the iterator instruction was recursively deleted, start over at the
  3553. // start of the block.
  3554. CurInstIterator = BB->begin();
  3555. SunkAddrs.clear();
  3556. }
  3557. }
  3558. ++NumMemoryInsts;
  3559. return true;
  3560. }
  3561. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  3562. /// address computing into the block when possible / profitable.
  3563. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  3564. bool MadeChange = false;
  3565. const TargetRegisterInfo *TRI =
  3566. TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
  3567. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3568. TLI->ParseConstraints(*DL, TRI, CS);
  3569. unsigned ArgNo = 0;
  3570. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3571. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3572. // Compute the constraint code and ConstraintType to use.
  3573. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  3574. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  3575. OpInfo.isIndirect) {
  3576. Value *OpVal = CS->getArgOperand(ArgNo++);
  3577. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  3578. } else if (OpInfo.Type == InlineAsm::isInput)
  3579. ArgNo++;
  3580. }
  3581. return MadeChange;
  3582. }
  3583. /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
  3584. /// sign extensions.
  3585. static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
  3586. assert(!Inst->use_empty() && "Input must have at least one use");
  3587. const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
  3588. bool IsSExt = isa<SExtInst>(FirstUser);
  3589. Type *ExtTy = FirstUser->getType();
  3590. for (const User *U : Inst->users()) {
  3591. const Instruction *UI = cast<Instruction>(U);
  3592. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  3593. return false;
  3594. Type *CurTy = UI->getType();
  3595. // Same input and output types: Same instruction after CSE.
  3596. if (CurTy == ExtTy)
  3597. continue;
  3598. // If IsSExt is true, we are in this situation:
  3599. // a = Inst
  3600. // b = sext ty1 a to ty2
  3601. // c = sext ty1 a to ty3
  3602. // Assuming ty2 is shorter than ty3, this could be turned into:
  3603. // a = Inst
  3604. // b = sext ty1 a to ty2
  3605. // c = sext ty2 b to ty3
  3606. // However, the last sext is not free.
  3607. if (IsSExt)
  3608. return false;
  3609. // This is a ZExt, maybe this is free to extend from one type to another.
  3610. // In that case, we would not account for a different use.
  3611. Type *NarrowTy;
  3612. Type *LargeTy;
  3613. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  3614. CurTy->getScalarType()->getIntegerBitWidth()) {
  3615. NarrowTy = CurTy;
  3616. LargeTy = ExtTy;
  3617. } else {
  3618. NarrowTy = ExtTy;
  3619. LargeTy = CurTy;
  3620. }
  3621. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  3622. return false;
  3623. }
  3624. // All uses are the same or can be derived from one another for free.
  3625. return true;
  3626. }
  3627. /// \brief Try to form ExtLd by promoting \p Exts until they reach a
  3628. /// load instruction.
  3629. /// If an ext(load) can be formed, it is returned via \p LI for the load
  3630. /// and \p Inst for the extension.
  3631. /// Otherwise LI == nullptr and Inst == nullptr.
  3632. /// When some promotion happened, \p TPT contains the proper state to
  3633. /// revert them.
  3634. ///
  3635. /// \return true when promoting was necessary to expose the ext(load)
  3636. /// opportunity, false otherwise.
  3637. ///
  3638. /// Example:
  3639. /// \code
  3640. /// %ld = load i32* %addr
  3641. /// %add = add nuw i32 %ld, 4
  3642. /// %zext = zext i32 %add to i64
  3643. /// \endcode
  3644. /// =>
  3645. /// \code
  3646. /// %ld = load i32* %addr
  3647. /// %zext = zext i32 %ld to i64
  3648. /// %add = add nuw i64 %zext, 4
  3649. /// \encode
  3650. /// Thanks to the promotion, we can match zext(load i32*) to i64.
  3651. bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
  3652. LoadInst *&LI, Instruction *&Inst,
  3653. const SmallVectorImpl<Instruction *> &Exts,
  3654. unsigned CreatedInstsCost = 0) {
  3655. // Iterate over all the extensions to see if one form an ext(load).
  3656. for (auto I : Exts) {
  3657. // Check if we directly have ext(load).
  3658. if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
  3659. Inst = I;
  3660. // No promotion happened here.
  3661. return false;
  3662. }
  3663. // Check whether or not we want to do any promotion.
  3664. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  3665. continue;
  3666. // Get the action to perform the promotion.
  3667. TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
  3668. I, InsertedInsts, *TLI, PromotedInsts);
  3669. // Check if we can promote.
  3670. if (!TPH)
  3671. continue;
  3672. // Save the current state.
  3673. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3674. TPT.getRestorationPoint();
  3675. SmallVector<Instruction *, 4> NewExts;
  3676. unsigned NewCreatedInstsCost = 0;
  3677. unsigned ExtCost = !TLI->isExtFree(I);
  3678. // Promote.
  3679. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  3680. &NewExts, nullptr, *TLI);
  3681. assert(PromotedVal &&
  3682. "TypePromotionHelper should have filtered out those cases");
  3683. // We would be able to merge only one extension in a load.
  3684. // Therefore, if we have more than 1 new extension we heuristically
  3685. // cut this search path, because it means we degrade the code quality.
  3686. // With exactly 2, the transformation is neutral, because we will merge
  3687. // one extension but leave one. However, we optimistically keep going,
  3688. // because the new extension may be removed too.
  3689. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  3690. TotalCreatedInstsCost -= ExtCost;
  3691. if (!StressExtLdPromotion &&
  3692. (TotalCreatedInstsCost > 1 ||
  3693. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  3694. // The promotion is not profitable, rollback to the previous state.
  3695. TPT.rollback(LastKnownGood);
  3696. continue;
  3697. }
  3698. // The promotion is profitable.
  3699. // Check if it exposes an ext(load).
  3700. (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
  3701. if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  3702. // If we have created a new extension, i.e., now we have two
  3703. // extensions. We must make sure one of them is merged with
  3704. // the load, otherwise we may degrade the code quality.
  3705. (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
  3706. // Promotion happened.
  3707. return true;
  3708. // If this does not help to expose an ext(load) then, rollback.
  3709. TPT.rollback(LastKnownGood);
  3710. }
  3711. // None of the extension can form an ext(load).
  3712. LI = nullptr;
  3713. Inst = nullptr;
  3714. return false;
  3715. }
  3716. /// Move a zext or sext fed by a load into the same basic block as the load,
  3717. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  3718. /// extend into the load.
  3719. /// \p I[in/out] the extension may be modified during the process if some
  3720. /// promotions apply.
  3721. ///
  3722. bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
  3723. // Try to promote a chain of computation if it allows to form
  3724. // an extended load.
  3725. TypePromotionTransaction TPT;
  3726. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3727. TPT.getRestorationPoint();
  3728. SmallVector<Instruction *, 1> Exts;
  3729. Exts.push_back(I);
  3730. // Look for a load being extended.
  3731. LoadInst *LI = nullptr;
  3732. Instruction *OldExt = I;
  3733. bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
  3734. if (!LI || !I) {
  3735. assert(!HasPromoted && !LI && "If we did not match any load instruction "
  3736. "the code must remain the same");
  3737. I = OldExt;
  3738. return false;
  3739. }
  3740. // If they're already in the same block, there's nothing to do.
  3741. // Make the cheap checks first if we did not promote.
  3742. // If we promoted, we need to check if it is indeed profitable.
  3743. if (!HasPromoted && LI->getParent() == I->getParent())
  3744. return false;
  3745. EVT VT = TLI->getValueType(*DL, I->getType());
  3746. EVT LoadVT = TLI->getValueType(*DL, LI->getType());
  3747. // If the load has other users and the truncate is not free, this probably
  3748. // isn't worthwhile.
  3749. if (!LI->hasOneUse() && TLI &&
  3750. (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
  3751. !TLI->isTruncateFree(I->getType(), LI->getType())) {
  3752. I = OldExt;
  3753. TPT.rollback(LastKnownGood);
  3754. return false;
  3755. }
  3756. // Check whether the target supports casts folded into loads.
  3757. unsigned LType;
  3758. if (isa<ZExtInst>(I))
  3759. LType = ISD::ZEXTLOAD;
  3760. else {
  3761. assert(isa<SExtInst>(I) && "Unexpected ext type!");
  3762. LType = ISD::SEXTLOAD;
  3763. }
  3764. if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
  3765. I = OldExt;
  3766. TPT.rollback(LastKnownGood);
  3767. return false;
  3768. }
  3769. // Move the extend into the same block as the load, so that SelectionDAG
  3770. // can fold it.
  3771. TPT.commit();
  3772. I->removeFromParent();
  3773. I->insertAfter(LI);
  3774. ++NumExtsMoved;
  3775. return true;
  3776. }
  3777. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  3778. BasicBlock *DefBB = I->getParent();
  3779. // If the result of a {s|z}ext and its source are both live out, rewrite all
  3780. // other uses of the source with result of extension.
  3781. Value *Src = I->getOperand(0);
  3782. if (Src->hasOneUse())
  3783. return false;
  3784. // Only do this xform if truncating is free.
  3785. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  3786. return false;
  3787. // Only safe to perform the optimization if the source is also defined in
  3788. // this block.
  3789. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  3790. return false;
  3791. bool DefIsLiveOut = false;
  3792. for (User *U : I->users()) {
  3793. Instruction *UI = cast<Instruction>(U);
  3794. // Figure out which BB this ext is used in.
  3795. BasicBlock *UserBB = UI->getParent();
  3796. if (UserBB == DefBB) continue;
  3797. DefIsLiveOut = true;
  3798. break;
  3799. }
  3800. if (!DefIsLiveOut)
  3801. return false;
  3802. // Make sure none of the uses are PHI nodes.
  3803. for (User *U : Src->users()) {
  3804. Instruction *UI = cast<Instruction>(U);
  3805. BasicBlock *UserBB = UI->getParent();
  3806. if (UserBB == DefBB) continue;
  3807. // Be conservative. We don't want this xform to end up introducing
  3808. // reloads just before load / store instructions.
  3809. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  3810. return false;
  3811. }
  3812. // InsertedTruncs - Only insert one trunc in each block once.
  3813. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  3814. bool MadeChange = false;
  3815. for (Use &U : Src->uses()) {
  3816. Instruction *User = cast<Instruction>(U.getUser());
  3817. // Figure out which BB this ext is used in.
  3818. BasicBlock *UserBB = User->getParent();
  3819. if (UserBB == DefBB) continue;
  3820. // Both src and def are live in this block. Rewrite the use.
  3821. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  3822. if (!InsertedTrunc) {
  3823. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  3824. assert(InsertPt != UserBB->end());
  3825. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  3826. InsertedInsts.insert(InsertedTrunc);
  3827. }
  3828. // Replace a use of the {s|z}ext source with a use of the result.
  3829. U = InsertedTrunc;
  3830. ++NumExtUses;
  3831. MadeChange = true;
  3832. }
  3833. return MadeChange;
  3834. }
  3835. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  3836. // just after the load if the target can fold this into one extload instruction,
  3837. // with the hope of eliminating some of the other later "and" instructions using
  3838. // the loaded value. "and"s that are made trivially redundant by the insertion
  3839. // of the new "and" are removed by this function, while others (e.g. those whose
  3840. // path from the load goes through a phi) are left for isel to potentially
  3841. // remove.
  3842. //
  3843. // For example:
  3844. //
  3845. // b0:
  3846. // x = load i32
  3847. // ...
  3848. // b1:
  3849. // y = and x, 0xff
  3850. // z = use y
  3851. //
  3852. // becomes:
  3853. //
  3854. // b0:
  3855. // x = load i32
  3856. // x' = and x, 0xff
  3857. // ...
  3858. // b1:
  3859. // z = use x'
  3860. //
  3861. // whereas:
  3862. //
  3863. // b0:
  3864. // x1 = load i32
  3865. // ...
  3866. // b1:
  3867. // x2 = load i32
  3868. // ...
  3869. // b2:
  3870. // x = phi x1, x2
  3871. // y = and x, 0xff
  3872. //
  3873. // becomes (after a call to optimizeLoadExt for each load):
  3874. //
  3875. // b0:
  3876. // x1 = load i32
  3877. // x1' = and x1, 0xff
  3878. // ...
  3879. // b1:
  3880. // x2 = load i32
  3881. // x2' = and x2, 0xff
  3882. // ...
  3883. // b2:
  3884. // x = phi x1', x2'
  3885. // y = and x, 0xff
  3886. //
  3887. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  3888. if (!Load->isSimple() ||
  3889. !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
  3890. return false;
  3891. // Skip loads we've already transformed or have no reason to transform.
  3892. if (Load->hasOneUse()) {
  3893. User *LoadUser = *Load->user_begin();
  3894. if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
  3895. !dyn_cast<PHINode>(LoadUser))
  3896. return false;
  3897. }
  3898. // Look at all uses of Load, looking through phis, to determine how many bits
  3899. // of the loaded value are needed.
  3900. SmallVector<Instruction *, 8> WorkList;
  3901. SmallPtrSet<Instruction *, 16> Visited;
  3902. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  3903. for (auto *U : Load->users())
  3904. WorkList.push_back(cast<Instruction>(U));
  3905. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  3906. unsigned BitWidth = LoadResultVT.getSizeInBits();
  3907. APInt DemandBits(BitWidth, 0);
  3908. APInt WidestAndBits(BitWidth, 0);
  3909. while (!WorkList.empty()) {
  3910. Instruction *I = WorkList.back();
  3911. WorkList.pop_back();
  3912. // Break use-def graph loops.
  3913. if (!Visited.insert(I).second)
  3914. continue;
  3915. // For a PHI node, push all of its users.
  3916. if (auto *Phi = dyn_cast<PHINode>(I)) {
  3917. for (auto *U : Phi->users())
  3918. WorkList.push_back(cast<Instruction>(U));
  3919. continue;
  3920. }
  3921. switch (I->getOpcode()) {
  3922. case llvm::Instruction::And: {
  3923. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  3924. if (!AndC)
  3925. return false;
  3926. APInt AndBits = AndC->getValue();
  3927. DemandBits |= AndBits;
  3928. // Keep track of the widest and mask we see.
  3929. if (AndBits.ugt(WidestAndBits))
  3930. WidestAndBits = AndBits;
  3931. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  3932. AndsToMaybeRemove.push_back(I);
  3933. break;
  3934. }
  3935. case llvm::Instruction::Shl: {
  3936. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  3937. if (!ShlC)
  3938. return false;
  3939. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  3940. auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
  3941. DemandBits |= ShlDemandBits;
  3942. break;
  3943. }
  3944. case llvm::Instruction::Trunc: {
  3945. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  3946. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  3947. auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
  3948. DemandBits |= TruncBits;
  3949. break;
  3950. }
  3951. default:
  3952. return false;
  3953. }
  3954. }
  3955. uint32_t ActiveBits = DemandBits.getActiveBits();
  3956. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  3957. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  3958. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  3959. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  3960. // followed by an AND.
  3961. // TODO: Look into removing this restriction by fixing backends to either
  3962. // return false for isLoadExtLegal for i1 or have them select this pattern to
  3963. // a single instruction.
  3964. //
  3965. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  3966. // mask, since these are the only ands that will be removed by isel.
  3967. if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
  3968. WidestAndBits != DemandBits)
  3969. return false;
  3970. LLVMContext &Ctx = Load->getType()->getContext();
  3971. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  3972. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  3973. // Reject cases that won't be matched as extloads.
  3974. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  3975. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  3976. return false;
  3977. IRBuilder<> Builder(Load->getNextNode());
  3978. auto *NewAnd = dyn_cast<Instruction>(
  3979. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  3980. // Replace all uses of load with new and (except for the use of load in the
  3981. // new and itself).
  3982. Load->replaceAllUsesWith(NewAnd);
  3983. NewAnd->setOperand(0, Load);
  3984. // Remove any and instructions that are now redundant.
  3985. for (auto *And : AndsToMaybeRemove)
  3986. // Check that the and mask is the same as the one we decided to put on the
  3987. // new and.
  3988. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  3989. And->replaceAllUsesWith(NewAnd);
  3990. if (&*CurInstIterator == And)
  3991. CurInstIterator = std::next(And->getIterator());
  3992. And->eraseFromParent();
  3993. ++NumAndUses;
  3994. }
  3995. ++NumAndsAdded;
  3996. return true;
  3997. }
  3998. /// Check if V (an operand of a select instruction) is an expensive instruction
  3999. /// that is only used once.
  4000. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  4001. auto *I = dyn_cast<Instruction>(V);
  4002. // If it's safe to speculatively execute, then it should not have side
  4003. // effects; therefore, it's safe to sink and possibly *not* execute.
  4004. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  4005. TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
  4006. }
  4007. /// Returns true if a SelectInst should be turned into an explicit branch.
  4008. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  4009. SelectInst *SI) {
  4010. // FIXME: This should use the same heuristics as IfConversion to determine
  4011. // whether a select is better represented as a branch. This requires that
  4012. // branch probability metadata is preserved for the select, which is not the
  4013. // case currently.
  4014. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  4015. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  4016. // comparison condition. If the compare has more than one use, there's
  4017. // probably another cmov or setcc around, so it's not worth emitting a branch.
  4018. if (!Cmp || !Cmp->hasOneUse())
  4019. return false;
  4020. // If either operand of the select is expensive and only needed on one side
  4021. // of the select, we should form a branch.
  4022. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  4023. sinkSelectOperand(TTI, SI->getFalseValue()))
  4024. return true;
  4025. return false;
  4026. }
  4027. /// If we have a SelectInst that will likely profit from branch prediction,
  4028. /// turn it into a branch.
  4029. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  4030. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  4031. // Can we convert the 'select' to CF ?
  4032. if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
  4033. return false;
  4034. TargetLowering::SelectSupportKind SelectKind;
  4035. if (VectorCond)
  4036. SelectKind = TargetLowering::VectorMaskSelect;
  4037. else if (SI->getType()->isVectorTy())
  4038. SelectKind = TargetLowering::ScalarCondVectorVal;
  4039. else
  4040. SelectKind = TargetLowering::ScalarValSelect;
  4041. // Do we have efficient codegen support for this kind of 'selects' ?
  4042. if (TLI->isSelectSupported(SelectKind)) {
  4043. // We have efficient codegen support for the select instruction.
  4044. // Check if it is profitable to keep this 'select'.
  4045. if (!TLI->isPredictableSelectExpensive() ||
  4046. !isFormingBranchFromSelectProfitable(TTI, SI))
  4047. return false;
  4048. }
  4049. ModifiedDT = true;
  4050. // Transform a sequence like this:
  4051. // start:
  4052. // %cmp = cmp uge i32 %a, %b
  4053. // %sel = select i1 %cmp, i32 %c, i32 %d
  4054. //
  4055. // Into:
  4056. // start:
  4057. // %cmp = cmp uge i32 %a, %b
  4058. // br i1 %cmp, label %select.true, label %select.false
  4059. // select.true:
  4060. // br label %select.end
  4061. // select.false:
  4062. // br label %select.end
  4063. // select.end:
  4064. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  4065. //
  4066. // In addition, we may sink instructions that produce %c or %d from
  4067. // the entry block into the destination(s) of the new branch.
  4068. // If the true or false blocks do not contain a sunken instruction, that
  4069. // block and its branch may be optimized away. In that case, one side of the
  4070. // first branch will point directly to select.end, and the corresponding PHI
  4071. // predecessor block will be the start block.
  4072. // First, we split the block containing the select into 2 blocks.
  4073. BasicBlock *StartBlock = SI->getParent();
  4074. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
  4075. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  4076. // Delete the unconditional branch that was just created by the split.
  4077. StartBlock->getTerminator()->eraseFromParent();
  4078. // These are the new basic blocks for the conditional branch.
  4079. // At least one will become an actual new basic block.
  4080. BasicBlock *TrueBlock = nullptr;
  4081. BasicBlock *FalseBlock = nullptr;
  4082. // Sink expensive instructions into the conditional blocks to avoid executing
  4083. // them speculatively.
  4084. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  4085. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  4086. EndBlock->getParent(), EndBlock);
  4087. auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  4088. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  4089. TrueInst->moveBefore(TrueBranch);
  4090. }
  4091. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  4092. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  4093. EndBlock->getParent(), EndBlock);
  4094. auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  4095. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  4096. FalseInst->moveBefore(FalseBranch);
  4097. }
  4098. // If there was nothing to sink, then arbitrarily choose the 'false' side
  4099. // for a new input value to the PHI.
  4100. if (TrueBlock == FalseBlock) {
  4101. assert(TrueBlock == nullptr &&
  4102. "Unexpected basic block transform while optimizing select");
  4103. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  4104. EndBlock->getParent(), EndBlock);
  4105. BranchInst::Create(EndBlock, FalseBlock);
  4106. }
  4107. // Insert the real conditional branch based on the original condition.
  4108. // If we did not create a new block for one of the 'true' or 'false' paths
  4109. // of the condition, it means that side of the branch goes to the end block
  4110. // directly and the path originates from the start block from the point of
  4111. // view of the new PHI.
  4112. if (TrueBlock == nullptr) {
  4113. BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
  4114. TrueBlock = StartBlock;
  4115. } else if (FalseBlock == nullptr) {
  4116. BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
  4117. FalseBlock = StartBlock;
  4118. } else {
  4119. BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
  4120. }
  4121. // The select itself is replaced with a PHI Node.
  4122. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  4123. PN->takeName(SI);
  4124. PN->addIncoming(SI->getTrueValue(), TrueBlock);
  4125. PN->addIncoming(SI->getFalseValue(), FalseBlock);
  4126. SI->replaceAllUsesWith(PN);
  4127. SI->eraseFromParent();
  4128. // Instruct OptimizeBlock to skip to the next block.
  4129. CurInstIterator = StartBlock->end();
  4130. ++NumSelectsExpanded;
  4131. return true;
  4132. }
  4133. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  4134. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  4135. int SplatElem = -1;
  4136. for (unsigned i = 0; i < Mask.size(); ++i) {
  4137. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  4138. return false;
  4139. SplatElem = Mask[i];
  4140. }
  4141. return true;
  4142. }
  4143. /// Some targets have expensive vector shifts if the lanes aren't all the same
  4144. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  4145. /// it's often worth sinking a shufflevector splat down to its use so that
  4146. /// codegen can spot all lanes are identical.
  4147. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  4148. BasicBlock *DefBB = SVI->getParent();
  4149. // Only do this xform if variable vector shifts are particularly expensive.
  4150. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  4151. return false;
  4152. // We only expect better codegen by sinking a shuffle if we can recognise a
  4153. // constant splat.
  4154. if (!isBroadcastShuffle(SVI))
  4155. return false;
  4156. // InsertedShuffles - Only insert a shuffle in each block once.
  4157. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  4158. bool MadeChange = false;
  4159. for (User *U : SVI->users()) {
  4160. Instruction *UI = cast<Instruction>(U);
  4161. // Figure out which BB this ext is used in.
  4162. BasicBlock *UserBB = UI->getParent();
  4163. if (UserBB == DefBB) continue;
  4164. // For now only apply this when the splat is used by a shift instruction.
  4165. if (!UI->isShift()) continue;
  4166. // Everything checks out, sink the shuffle if the user's block doesn't
  4167. // already have a copy.
  4168. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  4169. if (!InsertedShuffle) {
  4170. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4171. assert(InsertPt != UserBB->end());
  4172. InsertedShuffle =
  4173. new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
  4174. SVI->getOperand(2), "", &*InsertPt);
  4175. }
  4176. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  4177. MadeChange = true;
  4178. }
  4179. // If we removed all uses, nuke the shuffle.
  4180. if (SVI->use_empty()) {
  4181. SVI->eraseFromParent();
  4182. MadeChange = true;
  4183. }
  4184. return MadeChange;
  4185. }
  4186. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  4187. if (!TLI || !DL)
  4188. return false;
  4189. Value *Cond = SI->getCondition();
  4190. Type *OldType = Cond->getType();
  4191. LLVMContext &Context = Cond->getContext();
  4192. MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
  4193. unsigned RegWidth = RegType.getSizeInBits();
  4194. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  4195. return false;
  4196. // If the register width is greater than the type width, expand the condition
  4197. // of the switch instruction and each case constant to the width of the
  4198. // register. By widening the type of the switch condition, subsequent
  4199. // comparisons (for case comparisons) will not need to be extended to the
  4200. // preferred register width, so we will potentially eliminate N-1 extends,
  4201. // where N is the number of cases in the switch.
  4202. auto *NewType = Type::getIntNTy(Context, RegWidth);
  4203. // Zero-extend the switch condition and case constants unless the switch
  4204. // condition is a function argument that is already being sign-extended.
  4205. // In that case, we can avoid an unnecessary mask/extension by sign-extending
  4206. // everything instead.
  4207. Instruction::CastOps ExtType = Instruction::ZExt;
  4208. if (auto *Arg = dyn_cast<Argument>(Cond))
  4209. if (Arg->hasSExtAttr())
  4210. ExtType = Instruction::SExt;
  4211. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  4212. ExtInst->insertBefore(SI);
  4213. SI->setCondition(ExtInst);
  4214. for (SwitchInst::CaseIt Case : SI->cases()) {
  4215. APInt NarrowConst = Case.getCaseValue()->getValue();
  4216. APInt WideConst = (ExtType == Instruction::ZExt) ?
  4217. NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
  4218. Case.setValue(ConstantInt::get(Context, WideConst));
  4219. }
  4220. return true;
  4221. }
  4222. namespace {
  4223. /// \brief Helper class to promote a scalar operation to a vector one.
  4224. /// This class is used to move downward extractelement transition.
  4225. /// E.g.,
  4226. /// a = vector_op <2 x i32>
  4227. /// b = extractelement <2 x i32> a, i32 0
  4228. /// c = scalar_op b
  4229. /// store c
  4230. ///
  4231. /// =>
  4232. /// a = vector_op <2 x i32>
  4233. /// c = vector_op a (equivalent to scalar_op on the related lane)
  4234. /// * d = extractelement <2 x i32> c, i32 0
  4235. /// * store d
  4236. /// Assuming both extractelement and store can be combine, we get rid of the
  4237. /// transition.
  4238. class VectorPromoteHelper {
  4239. /// DataLayout associated with the current module.
  4240. const DataLayout &DL;
  4241. /// Used to perform some checks on the legality of vector operations.
  4242. const TargetLowering &TLI;
  4243. /// Used to estimated the cost of the promoted chain.
  4244. const TargetTransformInfo &TTI;
  4245. /// The transition being moved downwards.
  4246. Instruction *Transition;
  4247. /// The sequence of instructions to be promoted.
  4248. SmallVector<Instruction *, 4> InstsToBePromoted;
  4249. /// Cost of combining a store and an extract.
  4250. unsigned StoreExtractCombineCost;
  4251. /// Instruction that will be combined with the transition.
  4252. Instruction *CombineInst;
  4253. /// \brief The instruction that represents the current end of the transition.
  4254. /// Since we are faking the promotion until we reach the end of the chain
  4255. /// of computation, we need a way to get the current end of the transition.
  4256. Instruction *getEndOfTransition() const {
  4257. if (InstsToBePromoted.empty())
  4258. return Transition;
  4259. return InstsToBePromoted.back();
  4260. }
  4261. /// \brief Return the index of the original value in the transition.
  4262. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  4263. /// c, is at index 0.
  4264. unsigned getTransitionOriginalValueIdx() const {
  4265. assert(isa<ExtractElementInst>(Transition) &&
  4266. "Other kind of transitions are not supported yet");
  4267. return 0;
  4268. }
  4269. /// \brief Return the index of the index in the transition.
  4270. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  4271. /// is at index 1.
  4272. unsigned getTransitionIdx() const {
  4273. assert(isa<ExtractElementInst>(Transition) &&
  4274. "Other kind of transitions are not supported yet");
  4275. return 1;
  4276. }
  4277. /// \brief Get the type of the transition.
  4278. /// This is the type of the original value.
  4279. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  4280. /// transition is <2 x i32>.
  4281. Type *getTransitionType() const {
  4282. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  4283. }
  4284. /// \brief Promote \p ToBePromoted by moving \p Def downward through.
  4285. /// I.e., we have the following sequence:
  4286. /// Def = Transition <ty1> a to <ty2>
  4287. /// b = ToBePromoted <ty2> Def, ...
  4288. /// =>
  4289. /// b = ToBePromoted <ty1> a, ...
  4290. /// Def = Transition <ty1> ToBePromoted to <ty2>
  4291. void promoteImpl(Instruction *ToBePromoted);
  4292. /// \brief Check whether or not it is profitable to promote all the
  4293. /// instructions enqueued to be promoted.
  4294. bool isProfitableToPromote() {
  4295. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  4296. unsigned Index = isa<ConstantInt>(ValIdx)
  4297. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  4298. : -1;
  4299. Type *PromotedType = getTransitionType();
  4300. StoreInst *ST = cast<StoreInst>(CombineInst);
  4301. unsigned AS = ST->getPointerAddressSpace();
  4302. unsigned Align = ST->getAlignment();
  4303. // Check if this store is supported.
  4304. if (!TLI.allowsMisalignedMemoryAccesses(
  4305. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  4306. Align)) {
  4307. // If this is not supported, there is no way we can combine
  4308. // the extract with the store.
  4309. return false;
  4310. }
  4311. // The scalar chain of computation has to pay for the transition
  4312. // scalar to vector.
  4313. // The vector chain has to account for the combining cost.
  4314. uint64_t ScalarCost =
  4315. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  4316. uint64_t VectorCost = StoreExtractCombineCost;
  4317. for (const auto &Inst : InstsToBePromoted) {
  4318. // Compute the cost.
  4319. // By construction, all instructions being promoted are arithmetic ones.
  4320. // Moreover, one argument is a constant that can be viewed as a splat
  4321. // constant.
  4322. Value *Arg0 = Inst->getOperand(0);
  4323. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  4324. isa<ConstantFP>(Arg0);
  4325. TargetTransformInfo::OperandValueKind Arg0OVK =
  4326. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  4327. : TargetTransformInfo::OK_AnyValue;
  4328. TargetTransformInfo::OperandValueKind Arg1OVK =
  4329. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  4330. : TargetTransformInfo::OK_AnyValue;
  4331. ScalarCost += TTI.getArithmeticInstrCost(
  4332. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  4333. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  4334. Arg0OVK, Arg1OVK);
  4335. }
  4336. DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  4337. << ScalarCost << "\nVector: " << VectorCost << '\n');
  4338. return ScalarCost > VectorCost;
  4339. }
  4340. /// \brief Generate a constant vector with \p Val with the same
  4341. /// number of elements as the transition.
  4342. /// \p UseSplat defines whether or not \p Val should be replicated
  4343. /// across the whole vector.
  4344. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  4345. /// otherwise we generate a vector with as many undef as possible:
  4346. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  4347. /// used at the index of the extract.
  4348. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  4349. unsigned ExtractIdx = UINT_MAX;
  4350. if (!UseSplat) {
  4351. // If we cannot determine where the constant must be, we have to
  4352. // use a splat constant.
  4353. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  4354. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  4355. ExtractIdx = CstVal->getSExtValue();
  4356. else
  4357. UseSplat = true;
  4358. }
  4359. unsigned End = getTransitionType()->getVectorNumElements();
  4360. if (UseSplat)
  4361. return ConstantVector::getSplat(End, Val);
  4362. SmallVector<Constant *, 4> ConstVec;
  4363. UndefValue *UndefVal = UndefValue::get(Val->getType());
  4364. for (unsigned Idx = 0; Idx != End; ++Idx) {
  4365. if (Idx == ExtractIdx)
  4366. ConstVec.push_back(Val);
  4367. else
  4368. ConstVec.push_back(UndefVal);
  4369. }
  4370. return ConstantVector::get(ConstVec);
  4371. }
  4372. /// \brief Check if promoting to a vector type an operand at \p OperandIdx
  4373. /// in \p Use can trigger undefined behavior.
  4374. static bool canCauseUndefinedBehavior(const Instruction *Use,
  4375. unsigned OperandIdx) {
  4376. // This is not safe to introduce undef when the operand is on
  4377. // the right hand side of a division-like instruction.
  4378. if (OperandIdx != 1)
  4379. return false;
  4380. switch (Use->getOpcode()) {
  4381. default:
  4382. return false;
  4383. case Instruction::SDiv:
  4384. case Instruction::UDiv:
  4385. case Instruction::SRem:
  4386. case Instruction::URem:
  4387. return true;
  4388. case Instruction::FDiv:
  4389. case Instruction::FRem:
  4390. return !Use->hasNoNaNs();
  4391. }
  4392. llvm_unreachable(nullptr);
  4393. }
  4394. public:
  4395. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  4396. const TargetTransformInfo &TTI, Instruction *Transition,
  4397. unsigned CombineCost)
  4398. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  4399. StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
  4400. assert(Transition && "Do not know how to promote null");
  4401. }
  4402. /// \brief Check if we can promote \p ToBePromoted to \p Type.
  4403. bool canPromote(const Instruction *ToBePromoted) const {
  4404. // We could support CastInst too.
  4405. return isa<BinaryOperator>(ToBePromoted);
  4406. }
  4407. /// \brief Check if it is profitable to promote \p ToBePromoted
  4408. /// by moving downward the transition through.
  4409. bool shouldPromote(const Instruction *ToBePromoted) const {
  4410. // Promote only if all the operands can be statically expanded.
  4411. // Indeed, we do not want to introduce any new kind of transitions.
  4412. for (const Use &U : ToBePromoted->operands()) {
  4413. const Value *Val = U.get();
  4414. if (Val == getEndOfTransition()) {
  4415. // If the use is a division and the transition is on the rhs,
  4416. // we cannot promote the operation, otherwise we may create a
  4417. // division by zero.
  4418. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  4419. return false;
  4420. continue;
  4421. }
  4422. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  4423. !isa<ConstantFP>(Val))
  4424. return false;
  4425. }
  4426. // Check that the resulting operation is legal.
  4427. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  4428. if (!ISDOpcode)
  4429. return false;
  4430. return StressStoreExtract ||
  4431. TLI.isOperationLegalOrCustom(
  4432. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  4433. }
  4434. /// \brief Check whether or not \p Use can be combined
  4435. /// with the transition.
  4436. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  4437. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  4438. /// \brief Record \p ToBePromoted as part of the chain to be promoted.
  4439. void enqueueForPromotion(Instruction *ToBePromoted) {
  4440. InstsToBePromoted.push_back(ToBePromoted);
  4441. }
  4442. /// \brief Set the instruction that will be combined with the transition.
  4443. void recordCombineInstruction(Instruction *ToBeCombined) {
  4444. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  4445. CombineInst = ToBeCombined;
  4446. }
  4447. /// \brief Promote all the instructions enqueued for promotion if it is
  4448. /// is profitable.
  4449. /// \return True if the promotion happened, false otherwise.
  4450. bool promote() {
  4451. // Check if there is something to promote.
  4452. // Right now, if we do not have anything to combine with,
  4453. // we assume the promotion is not profitable.
  4454. if (InstsToBePromoted.empty() || !CombineInst)
  4455. return false;
  4456. // Check cost.
  4457. if (!StressStoreExtract && !isProfitableToPromote())
  4458. return false;
  4459. // Promote.
  4460. for (auto &ToBePromoted : InstsToBePromoted)
  4461. promoteImpl(ToBePromoted);
  4462. InstsToBePromoted.clear();
  4463. return true;
  4464. }
  4465. };
  4466. } // End of anonymous namespace.
  4467. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  4468. // At this point, we know that all the operands of ToBePromoted but Def
  4469. // can be statically promoted.
  4470. // For Def, we need to use its parameter in ToBePromoted:
  4471. // b = ToBePromoted ty1 a
  4472. // Def = Transition ty1 b to ty2
  4473. // Move the transition down.
  4474. // 1. Replace all uses of the promoted operation by the transition.
  4475. // = ... b => = ... Def.
  4476. assert(ToBePromoted->getType() == Transition->getType() &&
  4477. "The type of the result of the transition does not match "
  4478. "the final type");
  4479. ToBePromoted->replaceAllUsesWith(Transition);
  4480. // 2. Update the type of the uses.
  4481. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  4482. Type *TransitionTy = getTransitionType();
  4483. ToBePromoted->mutateType(TransitionTy);
  4484. // 3. Update all the operands of the promoted operation with promoted
  4485. // operands.
  4486. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  4487. for (Use &U : ToBePromoted->operands()) {
  4488. Value *Val = U.get();
  4489. Value *NewVal = nullptr;
  4490. if (Val == Transition)
  4491. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  4492. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  4493. isa<ConstantFP>(Val)) {
  4494. // Use a splat constant if it is not safe to use undef.
  4495. NewVal = getConstantVector(
  4496. cast<Constant>(Val),
  4497. isa<UndefValue>(Val) ||
  4498. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  4499. } else
  4500. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  4501. "this?");
  4502. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  4503. }
  4504. Transition->removeFromParent();
  4505. Transition->insertAfter(ToBePromoted);
  4506. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  4507. }
  4508. /// Some targets can do store(extractelement) with one instruction.
  4509. /// Try to push the extractelement towards the stores when the target
  4510. /// has this feature and this is profitable.
  4511. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  4512. unsigned CombineCost = UINT_MAX;
  4513. if (DisableStoreExtract || !TLI ||
  4514. (!StressStoreExtract &&
  4515. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  4516. Inst->getOperand(1), CombineCost)))
  4517. return false;
  4518. // At this point we know that Inst is a vector to scalar transition.
  4519. // Try to move it down the def-use chain, until:
  4520. // - We can combine the transition with its single use
  4521. // => we got rid of the transition.
  4522. // - We escape the current basic block
  4523. // => we would need to check that we are moving it at a cheaper place and
  4524. // we do not do that for now.
  4525. BasicBlock *Parent = Inst->getParent();
  4526. DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  4527. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  4528. // If the transition has more than one use, assume this is not going to be
  4529. // beneficial.
  4530. while (Inst->hasOneUse()) {
  4531. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  4532. DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  4533. if (ToBePromoted->getParent() != Parent) {
  4534. DEBUG(dbgs() << "Instruction to promote is in a different block ("
  4535. << ToBePromoted->getParent()->getName()
  4536. << ") than the transition (" << Parent->getName() << ").\n");
  4537. return false;
  4538. }
  4539. if (VPH.canCombine(ToBePromoted)) {
  4540. DEBUG(dbgs() << "Assume " << *Inst << '\n'
  4541. << "will be combined with: " << *ToBePromoted << '\n');
  4542. VPH.recordCombineInstruction(ToBePromoted);
  4543. bool Changed = VPH.promote();
  4544. NumStoreExtractExposed += Changed;
  4545. return Changed;
  4546. }
  4547. DEBUG(dbgs() << "Try promoting.\n");
  4548. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  4549. return false;
  4550. DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  4551. VPH.enqueueForPromotion(ToBePromoted);
  4552. Inst = ToBePromoted;
  4553. }
  4554. return false;
  4555. }
  4556. bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
  4557. // Bail out if we inserted the instruction to prevent optimizations from
  4558. // stepping on each other's toes.
  4559. if (InsertedInsts.count(I))
  4560. return false;
  4561. if (PHINode *P = dyn_cast<PHINode>(I)) {
  4562. // It is possible for very late stage optimizations (such as SimplifyCFG)
  4563. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  4564. // trivial PHI, go ahead and zap it here.
  4565. if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
  4566. P->replaceAllUsesWith(V);
  4567. P->eraseFromParent();
  4568. ++NumPHIsElim;
  4569. return true;
  4570. }
  4571. return false;
  4572. }
  4573. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  4574. // If the source of the cast is a constant, then this should have
  4575. // already been constant folded. The only reason NOT to constant fold
  4576. // it is if something (e.g. LSR) was careful to place the constant
  4577. // evaluation in a block other than then one that uses it (e.g. to hoist
  4578. // the address of globals out of a loop). If this is the case, we don't
  4579. // want to forward-subst the cast.
  4580. if (isa<Constant>(CI->getOperand(0)))
  4581. return false;
  4582. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  4583. return true;
  4584. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  4585. /// Sink a zext or sext into its user blocks if the target type doesn't
  4586. /// fit in one register
  4587. if (TLI &&
  4588. TLI->getTypeAction(CI->getContext(),
  4589. TLI->getValueType(*DL, CI->getType())) ==
  4590. TargetLowering::TypeExpandInteger) {
  4591. return SinkCast(CI);
  4592. } else {
  4593. bool MadeChange = moveExtToFormExtLoad(I);
  4594. return MadeChange | optimizeExtUses(I);
  4595. }
  4596. }
  4597. return false;
  4598. }
  4599. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  4600. if (!TLI || !TLI->hasMultipleConditionRegisters())
  4601. return OptimizeCmpExpression(CI, TLI);
  4602. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  4603. stripInvariantGroupMetadata(*LI);
  4604. if (TLI) {
  4605. bool Modified = optimizeLoadExt(LI);
  4606. unsigned AS = LI->getPointerAddressSpace();
  4607. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  4608. return Modified;
  4609. }
  4610. return false;
  4611. }
  4612. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  4613. stripInvariantGroupMetadata(*SI);
  4614. if (TLI) {
  4615. unsigned AS = SI->getPointerAddressSpace();
  4616. return optimizeMemoryInst(I, SI->getOperand(1),
  4617. SI->getOperand(0)->getType(), AS);
  4618. }
  4619. return false;
  4620. }
  4621. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  4622. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  4623. BinOp->getOpcode() == Instruction::LShr)) {
  4624. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  4625. if (TLI && CI && TLI->hasExtractBitsInsn())
  4626. return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
  4627. return false;
  4628. }
  4629. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  4630. if (GEPI->hasAllZeroIndices()) {
  4631. /// The GEP operand must be a pointer, so must its result -> BitCast
  4632. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  4633. GEPI->getName(), GEPI);
  4634. GEPI->replaceAllUsesWith(NC);
  4635. GEPI->eraseFromParent();
  4636. ++NumGEPsElim;
  4637. optimizeInst(NC, ModifiedDT);
  4638. return true;
  4639. }
  4640. return false;
  4641. }
  4642. if (CallInst *CI = dyn_cast<CallInst>(I))
  4643. return optimizeCallInst(CI, ModifiedDT);
  4644. if (SelectInst *SI = dyn_cast<SelectInst>(I))
  4645. return optimizeSelectInst(SI);
  4646. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
  4647. return optimizeShuffleVectorInst(SVI);
  4648. if (auto *Switch = dyn_cast<SwitchInst>(I))
  4649. return optimizeSwitchInst(Switch);
  4650. if (isa<ExtractElementInst>(I))
  4651. return optimizeExtractElementInst(I);
  4652. return false;
  4653. }
  4654. /// Given an OR instruction, check to see if this is a bitreverse
  4655. /// idiom. If so, insert the new intrinsic and return true.
  4656. static bool makeBitReverse(Instruction &I, const DataLayout &DL,
  4657. const TargetLowering &TLI) {
  4658. if (!I.getType()->isIntegerTy() ||
  4659. !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
  4660. TLI.getValueType(DL, I.getType(), true)))
  4661. return false;
  4662. SmallVector<Instruction*, 4> Insts;
  4663. if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
  4664. return false;
  4665. Instruction *LastInst = Insts.back();
  4666. I.replaceAllUsesWith(LastInst);
  4667. RecursivelyDeleteTriviallyDeadInstructions(&I);
  4668. return true;
  4669. }
  4670. // In this pass we look for GEP and cast instructions that are used
  4671. // across basic blocks and rewrite them to improve basic-block-at-a-time
  4672. // selection.
  4673. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
  4674. SunkAddrs.clear();
  4675. bool MadeChange = false;
  4676. CurInstIterator = BB.begin();
  4677. while (CurInstIterator != BB.end()) {
  4678. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  4679. if (ModifiedDT)
  4680. return true;
  4681. }
  4682. bool MadeBitReverse = true;
  4683. while (TLI && MadeBitReverse) {
  4684. MadeBitReverse = false;
  4685. for (auto &I : reverse(BB)) {
  4686. if (makeBitReverse(I, *DL, *TLI)) {
  4687. MadeBitReverse = MadeChange = true;
  4688. ModifiedDT = true;
  4689. break;
  4690. }
  4691. }
  4692. }
  4693. MadeChange |= dupRetToEnableTailCallOpts(&BB);
  4694. return MadeChange;
  4695. }
  4696. // llvm.dbg.value is far away from the value then iSel may not be able
  4697. // handle it properly. iSel will drop llvm.dbg.value if it can not
  4698. // find a node corresponding to the value.
  4699. bool CodeGenPrepare::placeDbgValues(Function &F) {
  4700. bool MadeChange = false;
  4701. for (BasicBlock &BB : F) {
  4702. Instruction *PrevNonDbgInst = nullptr;
  4703. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  4704. Instruction *Insn = &*BI++;
  4705. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  4706. // Leave dbg.values that refer to an alloca alone. These
  4707. // instrinsics describe the address of a variable (= the alloca)
  4708. // being taken. They should not be moved next to the alloca
  4709. // (and to the beginning of the scope), but rather stay close to
  4710. // where said address is used.
  4711. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  4712. PrevNonDbgInst = Insn;
  4713. continue;
  4714. }
  4715. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  4716. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  4717. // If VI is a phi in a block with an EHPad terminator, we can't insert
  4718. // after it.
  4719. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  4720. continue;
  4721. DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
  4722. DVI->removeFromParent();
  4723. if (isa<PHINode>(VI))
  4724. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  4725. else
  4726. DVI->insertAfter(VI);
  4727. MadeChange = true;
  4728. ++NumDbgValueMoved;
  4729. }
  4730. }
  4731. }
  4732. return MadeChange;
  4733. }
  4734. // If there is a sequence that branches based on comparing a single bit
  4735. // against zero that can be combined into a single instruction, and the
  4736. // target supports folding these into a single instruction, sink the
  4737. // mask and compare into the branch uses. Do this before OptimizeBlock ->
  4738. // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
  4739. // searched for.
  4740. bool CodeGenPrepare::sinkAndCmp(Function &F) {
  4741. if (!EnableAndCmpSinking)
  4742. return false;
  4743. if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
  4744. return false;
  4745. bool MadeChange = false;
  4746. for (BasicBlock &BB : F) {
  4747. // Does this BB end with the following?
  4748. // %andVal = and %val, #single-bit-set
  4749. // %icmpVal = icmp %andResult, 0
  4750. // br i1 %cmpVal label %dest1, label %dest2"
  4751. BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
  4752. if (!Brcc || !Brcc->isConditional())
  4753. continue;
  4754. ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
  4755. if (!Cmp || Cmp->getParent() != &BB)
  4756. continue;
  4757. ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
  4758. if (!Zero || !Zero->isZero())
  4759. continue;
  4760. Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
  4761. if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
  4762. continue;
  4763. ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
  4764. if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
  4765. continue;
  4766. DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
  4767. // Push the "and; icmp" for any users that are conditional branches.
  4768. // Since there can only be one branch use per BB, we don't need to keep
  4769. // track of which BBs we insert into.
  4770. for (Use &TheUse : Cmp->uses()) {
  4771. // Find brcc use.
  4772. BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
  4773. if (!BrccUser || !BrccUser->isConditional())
  4774. continue;
  4775. BasicBlock *UserBB = BrccUser->getParent();
  4776. if (UserBB == &BB) continue;
  4777. DEBUG(dbgs() << "found Brcc use\n");
  4778. // Sink the "and; icmp" to use.
  4779. MadeChange = true;
  4780. BinaryOperator *NewAnd =
  4781. BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
  4782. BrccUser);
  4783. CmpInst *NewCmp =
  4784. CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
  4785. "", BrccUser);
  4786. TheUse = NewCmp;
  4787. ++NumAndCmpsMoved;
  4788. DEBUG(BrccUser->getParent()->dump());
  4789. }
  4790. }
  4791. return MadeChange;
  4792. }
  4793. /// \brief Retrieve the probabilities of a conditional branch. Returns true on
  4794. /// success, or returns false if no or invalid metadata was found.
  4795. static bool extractBranchMetadata(BranchInst *BI,
  4796. uint64_t &ProbTrue, uint64_t &ProbFalse) {
  4797. assert(BI->isConditional() &&
  4798. "Looking for probabilities on unconditional branch?");
  4799. auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  4800. if (!ProfileData || ProfileData->getNumOperands() != 3)
  4801. return false;
  4802. const auto *CITrue =
  4803. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  4804. const auto *CIFalse =
  4805. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  4806. if (!CITrue || !CIFalse)
  4807. return false;
  4808. ProbTrue = CITrue->getValue().getZExtValue();
  4809. ProbFalse = CIFalse->getValue().getZExtValue();
  4810. return true;
  4811. }
  4812. /// \brief Scale down both weights to fit into uint32_t.
  4813. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  4814. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  4815. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  4816. NewTrue = NewTrue / Scale;
  4817. NewFalse = NewFalse / Scale;
  4818. }
  4819. /// \brief Some targets prefer to split a conditional branch like:
  4820. /// \code
  4821. /// %0 = icmp ne i32 %a, 0
  4822. /// %1 = icmp ne i32 %b, 0
  4823. /// %or.cond = or i1 %0, %1
  4824. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  4825. /// \endcode
  4826. /// into multiple branch instructions like:
  4827. /// \code
  4828. /// bb1:
  4829. /// %0 = icmp ne i32 %a, 0
  4830. /// br i1 %0, label %TrueBB, label %bb2
  4831. /// bb2:
  4832. /// %1 = icmp ne i32 %b, 0
  4833. /// br i1 %1, label %TrueBB, label %FalseBB
  4834. /// \endcode
  4835. /// This usually allows instruction selection to do even further optimizations
  4836. /// and combine the compare with the branch instruction. Currently this is
  4837. /// applied for targets which have "cheap" jump instructions.
  4838. ///
  4839. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  4840. ///
  4841. bool CodeGenPrepare::splitBranchCondition(Function &F) {
  4842. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  4843. return false;
  4844. bool MadeChange = false;
  4845. for (auto &BB : F) {
  4846. // Does this BB end with the following?
  4847. // %cond1 = icmp|fcmp|binary instruction ...
  4848. // %cond2 = icmp|fcmp|binary instruction ...
  4849. // %cond.or = or|and i1 %cond1, cond2
  4850. // br i1 %cond.or label %dest1, label %dest2"
  4851. BinaryOperator *LogicOp;
  4852. BasicBlock *TBB, *FBB;
  4853. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  4854. continue;
  4855. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  4856. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  4857. continue;
  4858. unsigned Opc;
  4859. Value *Cond1, *Cond2;
  4860. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  4861. m_OneUse(m_Value(Cond2)))))
  4862. Opc = Instruction::And;
  4863. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  4864. m_OneUse(m_Value(Cond2)))))
  4865. Opc = Instruction::Or;
  4866. else
  4867. continue;
  4868. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  4869. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  4870. continue;
  4871. DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  4872. // Create a new BB.
  4873. auto TmpBB =
  4874. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  4875. BB.getParent(), BB.getNextNode());
  4876. // Update original basic block by using the first condition directly by the
  4877. // branch instruction and removing the no longer needed and/or instruction.
  4878. Br1->setCondition(Cond1);
  4879. LogicOp->eraseFromParent();
  4880. // Depending on the conditon we have to either replace the true or the false
  4881. // successor of the original branch instruction.
  4882. if (Opc == Instruction::And)
  4883. Br1->setSuccessor(0, TmpBB);
  4884. else
  4885. Br1->setSuccessor(1, TmpBB);
  4886. // Fill in the new basic block.
  4887. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  4888. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  4889. I->removeFromParent();
  4890. I->insertBefore(Br2);
  4891. }
  4892. // Update PHI nodes in both successors. The original BB needs to be
  4893. // replaced in one succesor's PHI nodes, because the branch comes now from
  4894. // the newly generated BB (NewBB). In the other successor we need to add one
  4895. // incoming edge to the PHI nodes, because both branch instructions target
  4896. // now the same successor. Depending on the original branch condition
  4897. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  4898. // we perfrom the correct update for the PHI nodes.
  4899. // This doesn't change the successor order of the just created branch
  4900. // instruction (or any other instruction).
  4901. if (Opc == Instruction::Or)
  4902. std::swap(TBB, FBB);
  4903. // Replace the old BB with the new BB.
  4904. for (auto &I : *TBB) {
  4905. PHINode *PN = dyn_cast<PHINode>(&I);
  4906. if (!PN)
  4907. break;
  4908. int i;
  4909. while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
  4910. PN->setIncomingBlock(i, TmpBB);
  4911. }
  4912. // Add another incoming edge form the new BB.
  4913. for (auto &I : *FBB) {
  4914. PHINode *PN = dyn_cast<PHINode>(&I);
  4915. if (!PN)
  4916. break;
  4917. auto *Val = PN->getIncomingValueForBlock(&BB);
  4918. PN->addIncoming(Val, TmpBB);
  4919. }
  4920. // Update the branch weights (from SelectionDAGBuilder::
  4921. // FindMergedConditions).
  4922. if (Opc == Instruction::Or) {
  4923. // Codegen X | Y as:
  4924. // BB1:
  4925. // jmp_if_X TBB
  4926. // jmp TmpBB
  4927. // TmpBB:
  4928. // jmp_if_Y TBB
  4929. // jmp FBB
  4930. //
  4931. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  4932. // The requirement is that
  4933. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  4934. // = TrueProb for orignal BB.
  4935. // Assuming the orignal weights are A and B, one choice is to set BB1's
  4936. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  4937. // assumes that
  4938. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  4939. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  4940. // TmpBB, but the math is more complicated.
  4941. uint64_t TrueWeight, FalseWeight;
  4942. if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
  4943. uint64_t NewTrueWeight = TrueWeight;
  4944. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  4945. scaleWeights(NewTrueWeight, NewFalseWeight);
  4946. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  4947. .createBranchWeights(TrueWeight, FalseWeight));
  4948. NewTrueWeight = TrueWeight;
  4949. NewFalseWeight = 2 * FalseWeight;
  4950. scaleWeights(NewTrueWeight, NewFalseWeight);
  4951. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  4952. .createBranchWeights(TrueWeight, FalseWeight));
  4953. }
  4954. } else {
  4955. // Codegen X & Y as:
  4956. // BB1:
  4957. // jmp_if_X TmpBB
  4958. // jmp FBB
  4959. // TmpBB:
  4960. // jmp_if_Y TBB
  4961. // jmp FBB
  4962. //
  4963. // This requires creation of TmpBB after CurBB.
  4964. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  4965. // The requirement is that
  4966. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  4967. // = FalseProb for orignal BB.
  4968. // Assuming the orignal weights are A and B, one choice is to set BB1's
  4969. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  4970. // assumes that
  4971. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  4972. uint64_t TrueWeight, FalseWeight;
  4973. if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
  4974. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  4975. uint64_t NewFalseWeight = FalseWeight;
  4976. scaleWeights(NewTrueWeight, NewFalseWeight);
  4977. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  4978. .createBranchWeights(TrueWeight, FalseWeight));
  4979. NewTrueWeight = 2 * TrueWeight;
  4980. NewFalseWeight = FalseWeight;
  4981. scaleWeights(NewTrueWeight, NewFalseWeight);
  4982. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  4983. .createBranchWeights(TrueWeight, FalseWeight));
  4984. }
  4985. }
  4986. // Note: No point in getting fancy here, since the DT info is never
  4987. // available to CodeGenPrepare.
  4988. ModifiedDT = true;
  4989. MadeChange = true;
  4990. DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  4991. TmpBB->dump());
  4992. }
  4993. return MadeChange;
  4994. }
  4995. void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
  4996. if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
  4997. I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
  4998. }