CombinerHelper.cpp 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387
  1. //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/CodeGen/GlobalISel/CombinerHelper.h"
  9. #include "llvm/ADT/SetVector.h"
  10. #include "llvm/ADT/SmallBitVector.h"
  11. #include "llvm/CodeGen/GlobalISel/Combiner.h"
  12. #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
  13. #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
  14. #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
  15. #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
  16. #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
  17. #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
  18. #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
  19. #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
  20. #include "llvm/CodeGen/GlobalISel/Utils.h"
  21. #include "llvm/CodeGen/LowLevelType.h"
  22. #include "llvm/CodeGen/MachineBasicBlock.h"
  23. #include "llvm/CodeGen/MachineDominators.h"
  24. #include "llvm/CodeGen/MachineFrameInfo.h"
  25. #include "llvm/CodeGen/MachineInstr.h"
  26. #include "llvm/CodeGen/MachineMemOperand.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/CodeGen/TargetInstrInfo.h"
  29. #include "llvm/CodeGen/TargetLowering.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/CodeGen/TargetOpcodes.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/DivisionByConstantInfo.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include <tuple>
  37. #define DEBUG_TYPE "gi-combiner"
  38. using namespace llvm;
  39. using namespace MIPatternMatch;
  40. // Option to allow testing of the combiner while no targets know about indexed
  41. // addressing.
  42. static cl::opt<bool>
  43. ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
  44. cl::desc("Force all indexed operations to be "
  45. "legal for the GlobalISel combiner"));
  46. CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
  47. MachineIRBuilder &B, GISelKnownBits *KB,
  48. MachineDominatorTree *MDT,
  49. const LegalizerInfo *LI)
  50. : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB),
  51. MDT(MDT), LI(LI), RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
  52. TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
  53. (void)this->KB;
  54. }
  55. const TargetLowering &CombinerHelper::getTargetLowering() const {
  56. return *Builder.getMF().getSubtarget().getTargetLowering();
  57. }
  58. /// \returns The little endian in-memory byte position of byte \p I in a
  59. /// \p ByteWidth bytes wide type.
  60. ///
  61. /// E.g. Given a 4-byte type x, x[0] -> byte 0
  62. static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
  63. assert(I < ByteWidth && "I must be in [0, ByteWidth)");
  64. return I;
  65. }
  66. /// Determines the LogBase2 value for a non-null input value using the
  67. /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
  68. static Register buildLogBase2(Register V, MachineIRBuilder &MIB) {
  69. auto &MRI = *MIB.getMRI();
  70. LLT Ty = MRI.getType(V);
  71. auto Ctlz = MIB.buildCTLZ(Ty, V);
  72. auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
  73. return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
  74. }
  75. /// \returns The big endian in-memory byte position of byte \p I in a
  76. /// \p ByteWidth bytes wide type.
  77. ///
  78. /// E.g. Given a 4-byte type x, x[0] -> byte 3
  79. static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
  80. assert(I < ByteWidth && "I must be in [0, ByteWidth)");
  81. return ByteWidth - I - 1;
  82. }
  83. /// Given a map from byte offsets in memory to indices in a load/store,
  84. /// determine if that map corresponds to a little or big endian byte pattern.
  85. ///
  86. /// \param MemOffset2Idx maps memory offsets to address offsets.
  87. /// \param LowestIdx is the lowest index in \p MemOffset2Idx.
  88. ///
  89. /// \returns true if the map corresponds to a big endian byte pattern, false
  90. /// if it corresponds to a little endian byte pattern, and None otherwise.
  91. ///
  92. /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
  93. /// are as follows:
  94. ///
  95. /// AddrOffset Little endian Big endian
  96. /// 0 0 3
  97. /// 1 1 2
  98. /// 2 2 1
  99. /// 3 3 0
  100. static Optional<bool>
  101. isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
  102. int64_t LowestIdx) {
  103. // Need at least two byte positions to decide on endianness.
  104. unsigned Width = MemOffset2Idx.size();
  105. if (Width < 2)
  106. return None;
  107. bool BigEndian = true, LittleEndian = true;
  108. for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
  109. auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
  110. if (MemOffsetAndIdx == MemOffset2Idx.end())
  111. return None;
  112. const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
  113. assert(Idx >= 0 && "Expected non-negative byte offset?");
  114. LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
  115. BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
  116. if (!BigEndian && !LittleEndian)
  117. return None;
  118. }
  119. assert((BigEndian != LittleEndian) &&
  120. "Pattern cannot be both big and little endian!");
  121. return BigEndian;
  122. }
  123. bool CombinerHelper::isLegalOrBeforeLegalizer(
  124. const LegalityQuery &Query) const {
  125. return !LI || LI->getAction(Query).Action == LegalizeActions::Legal;
  126. }
  127. void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
  128. Register ToReg) const {
  129. Observer.changingAllUsesOfReg(MRI, FromReg);
  130. if (MRI.constrainRegAttrs(ToReg, FromReg))
  131. MRI.replaceRegWith(FromReg, ToReg);
  132. else
  133. Builder.buildCopy(ToReg, FromReg);
  134. Observer.finishedChangingAllUsesOfReg();
  135. }
  136. void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
  137. MachineOperand &FromRegOp,
  138. Register ToReg) const {
  139. assert(FromRegOp.getParent() && "Expected an operand in an MI");
  140. Observer.changingInstr(*FromRegOp.getParent());
  141. FromRegOp.setReg(ToReg);
  142. Observer.changedInstr(*FromRegOp.getParent());
  143. }
  144. void CombinerHelper::replaceOpcodeWith(MachineInstr &FromMI,
  145. unsigned ToOpcode) const {
  146. Observer.changingInstr(FromMI);
  147. FromMI.setDesc(Builder.getTII().get(ToOpcode));
  148. Observer.changedInstr(FromMI);
  149. }
  150. const RegisterBank *CombinerHelper::getRegBank(Register Reg) const {
  151. return RBI->getRegBank(Reg, MRI, *TRI);
  152. }
  153. void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) {
  154. if (RegBank)
  155. MRI.setRegBank(Reg, *RegBank);
  156. }
  157. bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
  158. if (matchCombineCopy(MI)) {
  159. applyCombineCopy(MI);
  160. return true;
  161. }
  162. return false;
  163. }
  164. bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
  165. if (MI.getOpcode() != TargetOpcode::COPY)
  166. return false;
  167. Register DstReg = MI.getOperand(0).getReg();
  168. Register SrcReg = MI.getOperand(1).getReg();
  169. return canReplaceReg(DstReg, SrcReg, MRI);
  170. }
  171. void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
  172. Register DstReg = MI.getOperand(0).getReg();
  173. Register SrcReg = MI.getOperand(1).getReg();
  174. MI.eraseFromParent();
  175. replaceRegWith(MRI, DstReg, SrcReg);
  176. }
  177. bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
  178. bool IsUndef = false;
  179. SmallVector<Register, 4> Ops;
  180. if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
  181. applyCombineConcatVectors(MI, IsUndef, Ops);
  182. return true;
  183. }
  184. return false;
  185. }
  186. bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
  187. SmallVectorImpl<Register> &Ops) {
  188. assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
  189. "Invalid instruction");
  190. IsUndef = true;
  191. MachineInstr *Undef = nullptr;
  192. // Walk over all the operands of concat vectors and check if they are
  193. // build_vector themselves or undef.
  194. // Then collect their operands in Ops.
  195. for (const MachineOperand &MO : MI.uses()) {
  196. Register Reg = MO.getReg();
  197. MachineInstr *Def = MRI.getVRegDef(Reg);
  198. assert(Def && "Operand not defined");
  199. switch (Def->getOpcode()) {
  200. case TargetOpcode::G_BUILD_VECTOR:
  201. IsUndef = false;
  202. // Remember the operands of the build_vector to fold
  203. // them into the yet-to-build flattened concat vectors.
  204. for (const MachineOperand &BuildVecMO : Def->uses())
  205. Ops.push_back(BuildVecMO.getReg());
  206. break;
  207. case TargetOpcode::G_IMPLICIT_DEF: {
  208. LLT OpType = MRI.getType(Reg);
  209. // Keep one undef value for all the undef operands.
  210. if (!Undef) {
  211. Builder.setInsertPt(*MI.getParent(), MI);
  212. Undef = Builder.buildUndef(OpType.getScalarType());
  213. }
  214. assert(MRI.getType(Undef->getOperand(0).getReg()) ==
  215. OpType.getScalarType() &&
  216. "All undefs should have the same type");
  217. // Break the undef vector in as many scalar elements as needed
  218. // for the flattening.
  219. for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
  220. EltIdx != EltEnd; ++EltIdx)
  221. Ops.push_back(Undef->getOperand(0).getReg());
  222. break;
  223. }
  224. default:
  225. return false;
  226. }
  227. }
  228. return true;
  229. }
  230. void CombinerHelper::applyCombineConcatVectors(
  231. MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
  232. // We determined that the concat_vectors can be flatten.
  233. // Generate the flattened build_vector.
  234. Register DstReg = MI.getOperand(0).getReg();
  235. Builder.setInsertPt(*MI.getParent(), MI);
  236. Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
  237. // Note: IsUndef is sort of redundant. We could have determine it by
  238. // checking that at all Ops are undef. Alternatively, we could have
  239. // generate a build_vector of undefs and rely on another combine to
  240. // clean that up. For now, given we already gather this information
  241. // in tryCombineConcatVectors, just save compile time and issue the
  242. // right thing.
  243. if (IsUndef)
  244. Builder.buildUndef(NewDstReg);
  245. else
  246. Builder.buildBuildVector(NewDstReg, Ops);
  247. MI.eraseFromParent();
  248. replaceRegWith(MRI, DstReg, NewDstReg);
  249. }
  250. bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
  251. SmallVector<Register, 4> Ops;
  252. if (matchCombineShuffleVector(MI, Ops)) {
  253. applyCombineShuffleVector(MI, Ops);
  254. return true;
  255. }
  256. return false;
  257. }
  258. bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
  259. SmallVectorImpl<Register> &Ops) {
  260. assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
  261. "Invalid instruction kind");
  262. LLT DstType = MRI.getType(MI.getOperand(0).getReg());
  263. Register Src1 = MI.getOperand(1).getReg();
  264. LLT SrcType = MRI.getType(Src1);
  265. // As bizarre as it may look, shuffle vector can actually produce
  266. // scalar! This is because at the IR level a <1 x ty> shuffle
  267. // vector is perfectly valid.
  268. unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
  269. unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
  270. // If the resulting vector is smaller than the size of the source
  271. // vectors being concatenated, we won't be able to replace the
  272. // shuffle vector into a concat_vectors.
  273. //
  274. // Note: We may still be able to produce a concat_vectors fed by
  275. // extract_vector_elt and so on. It is less clear that would
  276. // be better though, so don't bother for now.
  277. //
  278. // If the destination is a scalar, the size of the sources doesn't
  279. // matter. we will lower the shuffle to a plain copy. This will
  280. // work only if the source and destination have the same size. But
  281. // that's covered by the next condition.
  282. //
  283. // TODO: If the size between the source and destination don't match
  284. // we could still emit an extract vector element in that case.
  285. if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
  286. return false;
  287. // Check that the shuffle mask can be broken evenly between the
  288. // different sources.
  289. if (DstNumElts % SrcNumElts != 0)
  290. return false;
  291. // Mask length is a multiple of the source vector length.
  292. // Check if the shuffle is some kind of concatenation of the input
  293. // vectors.
  294. unsigned NumConcat = DstNumElts / SrcNumElts;
  295. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  296. ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
  297. for (unsigned i = 0; i != DstNumElts; ++i) {
  298. int Idx = Mask[i];
  299. // Undef value.
  300. if (Idx < 0)
  301. continue;
  302. // Ensure the indices in each SrcType sized piece are sequential and that
  303. // the same source is used for the whole piece.
  304. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  305. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  306. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
  307. return false;
  308. // Remember which source this index came from.
  309. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  310. }
  311. // The shuffle is concatenating multiple vectors together.
  312. // Collect the different operands for that.
  313. Register UndefReg;
  314. Register Src2 = MI.getOperand(2).getReg();
  315. for (auto Src : ConcatSrcs) {
  316. if (Src < 0) {
  317. if (!UndefReg) {
  318. Builder.setInsertPt(*MI.getParent(), MI);
  319. UndefReg = Builder.buildUndef(SrcType).getReg(0);
  320. }
  321. Ops.push_back(UndefReg);
  322. } else if (Src == 0)
  323. Ops.push_back(Src1);
  324. else
  325. Ops.push_back(Src2);
  326. }
  327. return true;
  328. }
  329. void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
  330. const ArrayRef<Register> Ops) {
  331. Register DstReg = MI.getOperand(0).getReg();
  332. Builder.setInsertPt(*MI.getParent(), MI);
  333. Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
  334. if (Ops.size() == 1)
  335. Builder.buildCopy(NewDstReg, Ops[0]);
  336. else
  337. Builder.buildMerge(NewDstReg, Ops);
  338. MI.eraseFromParent();
  339. replaceRegWith(MRI, DstReg, NewDstReg);
  340. }
  341. namespace {
  342. /// Select a preference between two uses. CurrentUse is the current preference
  343. /// while *ForCandidate is attributes of the candidate under consideration.
  344. PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse,
  345. const LLT TyForCandidate,
  346. unsigned OpcodeForCandidate,
  347. MachineInstr *MIForCandidate) {
  348. if (!CurrentUse.Ty.isValid()) {
  349. if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
  350. CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
  351. return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
  352. return CurrentUse;
  353. }
  354. // We permit the extend to hoist through basic blocks but this is only
  355. // sensible if the target has extending loads. If you end up lowering back
  356. // into a load and extend during the legalizer then the end result is
  357. // hoisting the extend up to the load.
  358. // Prefer defined extensions to undefined extensions as these are more
  359. // likely to reduce the number of instructions.
  360. if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
  361. CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
  362. return CurrentUse;
  363. else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
  364. OpcodeForCandidate != TargetOpcode::G_ANYEXT)
  365. return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
  366. // Prefer sign extensions to zero extensions as sign-extensions tend to be
  367. // more expensive.
  368. if (CurrentUse.Ty == TyForCandidate) {
  369. if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
  370. OpcodeForCandidate == TargetOpcode::G_ZEXT)
  371. return CurrentUse;
  372. else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
  373. OpcodeForCandidate == TargetOpcode::G_SEXT)
  374. return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
  375. }
  376. // This is potentially target specific. We've chosen the largest type
  377. // because G_TRUNC is usually free. One potential catch with this is that
  378. // some targets have a reduced number of larger registers than smaller
  379. // registers and this choice potentially increases the live-range for the
  380. // larger value.
  381. if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
  382. return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
  383. }
  384. return CurrentUse;
  385. }
  386. /// Find a suitable place to insert some instructions and insert them. This
  387. /// function accounts for special cases like inserting before a PHI node.
  388. /// The current strategy for inserting before PHI's is to duplicate the
  389. /// instructions for each predecessor. However, while that's ok for G_TRUNC
  390. /// on most targets since it generally requires no code, other targets/cases may
  391. /// want to try harder to find a dominating block.
  392. static void InsertInsnsWithoutSideEffectsBeforeUse(
  393. MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
  394. std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
  395. MachineOperand &UseMO)>
  396. Inserter) {
  397. MachineInstr &UseMI = *UseMO.getParent();
  398. MachineBasicBlock *InsertBB = UseMI.getParent();
  399. // If the use is a PHI then we want the predecessor block instead.
  400. if (UseMI.isPHI()) {
  401. MachineOperand *PredBB = std::next(&UseMO);
  402. InsertBB = PredBB->getMBB();
  403. }
  404. // If the block is the same block as the def then we want to insert just after
  405. // the def instead of at the start of the block.
  406. if (InsertBB == DefMI.getParent()) {
  407. MachineBasicBlock::iterator InsertPt = &DefMI;
  408. Inserter(InsertBB, std::next(InsertPt), UseMO);
  409. return;
  410. }
  411. // Otherwise we want the start of the BB
  412. Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
  413. }
  414. } // end anonymous namespace
  415. bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
  416. PreferredTuple Preferred;
  417. if (matchCombineExtendingLoads(MI, Preferred)) {
  418. applyCombineExtendingLoads(MI, Preferred);
  419. return true;
  420. }
  421. return false;
  422. }
  423. bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
  424. PreferredTuple &Preferred) {
  425. // We match the loads and follow the uses to the extend instead of matching
  426. // the extends and following the def to the load. This is because the load
  427. // must remain in the same position for correctness (unless we also add code
  428. // to find a safe place to sink it) whereas the extend is freely movable.
  429. // It also prevents us from duplicating the load for the volatile case or just
  430. // for performance.
  431. GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
  432. if (!LoadMI)
  433. return false;
  434. Register LoadReg = LoadMI->getDstReg();
  435. LLT LoadValueTy = MRI.getType(LoadReg);
  436. if (!LoadValueTy.isScalar())
  437. return false;
  438. // Most architectures are going to legalize <s8 loads into at least a 1 byte
  439. // load, and the MMOs can only describe memory accesses in multiples of bytes.
  440. // If we try to perform extload combining on those, we can end up with
  441. // %a(s8) = extload %ptr (load 1 byte from %ptr)
  442. // ... which is an illegal extload instruction.
  443. if (LoadValueTy.getSizeInBits() < 8)
  444. return false;
  445. // For non power-of-2 types, they will very likely be legalized into multiple
  446. // loads. Don't bother trying to match them into extending loads.
  447. if (!isPowerOf2_32(LoadValueTy.getSizeInBits()))
  448. return false;
  449. // Find the preferred type aside from the any-extends (unless it's the only
  450. // one) and non-extending ops. We'll emit an extending load to that type and
  451. // and emit a variant of (extend (trunc X)) for the others according to the
  452. // relative type sizes. At the same time, pick an extend to use based on the
  453. // extend involved in the chosen type.
  454. unsigned PreferredOpcode =
  455. isa<GLoad>(&MI)
  456. ? TargetOpcode::G_ANYEXT
  457. : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
  458. Preferred = {LLT(), PreferredOpcode, nullptr};
  459. for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
  460. if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
  461. UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
  462. (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
  463. const auto &MMO = LoadMI->getMMO();
  464. // For atomics, only form anyextending loads.
  465. if (MMO.isAtomic() && UseMI.getOpcode() != TargetOpcode::G_ANYEXT)
  466. continue;
  467. // Check for legality.
  468. if (LI) {
  469. LegalityQuery::MemDesc MMDesc(MMO);
  470. LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
  471. LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
  472. if (LI->getAction({LoadMI->getOpcode(), {UseTy, SrcTy}, {MMDesc}})
  473. .Action != LegalizeActions::Legal)
  474. continue;
  475. }
  476. Preferred = ChoosePreferredUse(Preferred,
  477. MRI.getType(UseMI.getOperand(0).getReg()),
  478. UseMI.getOpcode(), &UseMI);
  479. }
  480. }
  481. // There were no extends
  482. if (!Preferred.MI)
  483. return false;
  484. // It should be impossible to chose an extend without selecting a different
  485. // type since by definition the result of an extend is larger.
  486. assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
  487. LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
  488. return true;
  489. }
  490. void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
  491. PreferredTuple &Preferred) {
  492. // Rewrite the load to the chosen extending load.
  493. Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
  494. // Inserter to insert a truncate back to the original type at a given point
  495. // with some basic CSE to limit truncate duplication to one per BB.
  496. DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
  497. auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
  498. MachineBasicBlock::iterator InsertBefore,
  499. MachineOperand &UseMO) {
  500. MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
  501. if (PreviouslyEmitted) {
  502. Observer.changingInstr(*UseMO.getParent());
  503. UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
  504. Observer.changedInstr(*UseMO.getParent());
  505. return;
  506. }
  507. Builder.setInsertPt(*InsertIntoBB, InsertBefore);
  508. Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
  509. MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
  510. EmittedInsns[InsertIntoBB] = NewMI;
  511. replaceRegOpWith(MRI, UseMO, NewDstReg);
  512. };
  513. Observer.changingInstr(MI);
  514. MI.setDesc(
  515. Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT
  516. ? TargetOpcode::G_SEXTLOAD
  517. : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT
  518. ? TargetOpcode::G_ZEXTLOAD
  519. : TargetOpcode::G_LOAD));
  520. // Rewrite all the uses to fix up the types.
  521. auto &LoadValue = MI.getOperand(0);
  522. SmallVector<MachineOperand *, 4> Uses;
  523. for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
  524. Uses.push_back(&UseMO);
  525. for (auto *UseMO : Uses) {
  526. MachineInstr *UseMI = UseMO->getParent();
  527. // If the extend is compatible with the preferred extend then we should fix
  528. // up the type and extend so that it uses the preferred use.
  529. if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
  530. UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
  531. Register UseDstReg = UseMI->getOperand(0).getReg();
  532. MachineOperand &UseSrcMO = UseMI->getOperand(1);
  533. const LLT UseDstTy = MRI.getType(UseDstReg);
  534. if (UseDstReg != ChosenDstReg) {
  535. if (Preferred.Ty == UseDstTy) {
  536. // If the use has the same type as the preferred use, then merge
  537. // the vregs and erase the extend. For example:
  538. // %1:_(s8) = G_LOAD ...
  539. // %2:_(s32) = G_SEXT %1(s8)
  540. // %3:_(s32) = G_ANYEXT %1(s8)
  541. // ... = ... %3(s32)
  542. // rewrites to:
  543. // %2:_(s32) = G_SEXTLOAD ...
  544. // ... = ... %2(s32)
  545. replaceRegWith(MRI, UseDstReg, ChosenDstReg);
  546. Observer.erasingInstr(*UseMO->getParent());
  547. UseMO->getParent()->eraseFromParent();
  548. } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
  549. // If the preferred size is smaller, then keep the extend but extend
  550. // from the result of the extending load. For example:
  551. // %1:_(s8) = G_LOAD ...
  552. // %2:_(s32) = G_SEXT %1(s8)
  553. // %3:_(s64) = G_ANYEXT %1(s8)
  554. // ... = ... %3(s64)
  555. /// rewrites to:
  556. // %2:_(s32) = G_SEXTLOAD ...
  557. // %3:_(s64) = G_ANYEXT %2:_(s32)
  558. // ... = ... %3(s64)
  559. replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
  560. } else {
  561. // If the preferred size is large, then insert a truncate. For
  562. // example:
  563. // %1:_(s8) = G_LOAD ...
  564. // %2:_(s64) = G_SEXT %1(s8)
  565. // %3:_(s32) = G_ZEXT %1(s8)
  566. // ... = ... %3(s32)
  567. /// rewrites to:
  568. // %2:_(s64) = G_SEXTLOAD ...
  569. // %4:_(s8) = G_TRUNC %2:_(s32)
  570. // %3:_(s64) = G_ZEXT %2:_(s8)
  571. // ... = ... %3(s64)
  572. InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
  573. InsertTruncAt);
  574. }
  575. continue;
  576. }
  577. // The use is (one of) the uses of the preferred use we chose earlier.
  578. // We're going to update the load to def this value later so just erase
  579. // the old extend.
  580. Observer.erasingInstr(*UseMO->getParent());
  581. UseMO->getParent()->eraseFromParent();
  582. continue;
  583. }
  584. // The use isn't an extend. Truncate back to the type we originally loaded.
  585. // This is free on many targets.
  586. InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
  587. }
  588. MI.getOperand(0).setReg(ChosenDstReg);
  589. Observer.changedInstr(MI);
  590. }
  591. bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI,
  592. BuildFnTy &MatchInfo) {
  593. assert(MI.getOpcode() == TargetOpcode::G_AND);
  594. // If we have the following code:
  595. // %mask = G_CONSTANT 255
  596. // %ld = G_LOAD %ptr, (load s16)
  597. // %and = G_AND %ld, %mask
  598. //
  599. // Try to fold it into
  600. // %ld = G_ZEXTLOAD %ptr, (load s8)
  601. Register Dst = MI.getOperand(0).getReg();
  602. if (MRI.getType(Dst).isVector())
  603. return false;
  604. auto MaybeMask =
  605. getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
  606. if (!MaybeMask)
  607. return false;
  608. APInt MaskVal = MaybeMask->Value;
  609. if (!MaskVal.isMask())
  610. return false;
  611. Register SrcReg = MI.getOperand(1).getReg();
  612. GAnyLoad *LoadMI = getOpcodeDef<GAnyLoad>(SrcReg, MRI);
  613. if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()) ||
  614. !LoadMI->isSimple())
  615. return false;
  616. Register LoadReg = LoadMI->getDstReg();
  617. LLT LoadTy = MRI.getType(LoadReg);
  618. Register PtrReg = LoadMI->getPointerReg();
  619. uint64_t LoadSizeBits = LoadMI->getMemSizeInBits();
  620. unsigned MaskSizeBits = MaskVal.countTrailingOnes();
  621. // The mask may not be larger than the in-memory type, as it might cover sign
  622. // extended bits
  623. if (MaskSizeBits > LoadSizeBits)
  624. return false;
  625. // If the mask covers the whole destination register, there's nothing to
  626. // extend
  627. if (MaskSizeBits >= LoadTy.getSizeInBits())
  628. return false;
  629. // Most targets cannot deal with loads of size < 8 and need to re-legalize to
  630. // at least byte loads. Avoid creating such loads here
  631. if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
  632. return false;
  633. const MachineMemOperand &MMO = LoadMI->getMMO();
  634. LegalityQuery::MemDesc MemDesc(MMO);
  635. MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
  636. if (!isLegalOrBeforeLegalizer(
  637. {TargetOpcode::G_ZEXTLOAD, {LoadTy, MRI.getType(PtrReg)}, {MemDesc}}))
  638. return false;
  639. MatchInfo = [=](MachineIRBuilder &B) {
  640. B.setInstrAndDebugLoc(*LoadMI);
  641. auto &MF = B.getMF();
  642. auto PtrInfo = MMO.getPointerInfo();
  643. auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MaskSizeBits / 8);
  644. B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
  645. };
  646. return true;
  647. }
  648. bool CombinerHelper::isPredecessor(const MachineInstr &DefMI,
  649. const MachineInstr &UseMI) {
  650. assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
  651. "shouldn't consider debug uses");
  652. assert(DefMI.getParent() == UseMI.getParent());
  653. if (&DefMI == &UseMI)
  654. return true;
  655. const MachineBasicBlock &MBB = *DefMI.getParent();
  656. auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
  657. return &MI == &DefMI || &MI == &UseMI;
  658. });
  659. if (DefOrUse == MBB.end())
  660. llvm_unreachable("Block must contain both DefMI and UseMI!");
  661. return &*DefOrUse == &DefMI;
  662. }
  663. bool CombinerHelper::dominates(const MachineInstr &DefMI,
  664. const MachineInstr &UseMI) {
  665. assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
  666. "shouldn't consider debug uses");
  667. if (MDT)
  668. return MDT->dominates(&DefMI, &UseMI);
  669. else if (DefMI.getParent() != UseMI.getParent())
  670. return false;
  671. return isPredecessor(DefMI, UseMI);
  672. }
  673. bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) {
  674. assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
  675. Register SrcReg = MI.getOperand(1).getReg();
  676. Register LoadUser = SrcReg;
  677. if (MRI.getType(SrcReg).isVector())
  678. return false;
  679. Register TruncSrc;
  680. if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
  681. LoadUser = TruncSrc;
  682. uint64_t SizeInBits = MI.getOperand(2).getImm();
  683. // If the source is a G_SEXTLOAD from the same bit width, then we don't
  684. // need any extend at all, just a truncate.
  685. if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
  686. // If truncating more than the original extended value, abort.
  687. auto LoadSizeBits = LoadMI->getMemSizeInBits();
  688. if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits)
  689. return false;
  690. if (LoadSizeBits == SizeInBits)
  691. return true;
  692. }
  693. return false;
  694. }
  695. void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) {
  696. assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
  697. Builder.setInstrAndDebugLoc(MI);
  698. Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
  699. MI.eraseFromParent();
  700. }
  701. bool CombinerHelper::matchSextInRegOfLoad(
  702. MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
  703. assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
  704. // Only supports scalars for now.
  705. if (MRI.getType(MI.getOperand(0).getReg()).isVector())
  706. return false;
  707. Register SrcReg = MI.getOperand(1).getReg();
  708. auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI);
  709. if (!LoadDef || !MRI.hasOneNonDBGUse(LoadDef->getOperand(0).getReg()) ||
  710. !LoadDef->isSimple())
  711. return false;
  712. // If the sign extend extends from a narrower width than the load's width,
  713. // then we can narrow the load width when we combine to a G_SEXTLOAD.
  714. // Avoid widening the load at all.
  715. unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(),
  716. LoadDef->getMemSizeInBits());
  717. // Don't generate G_SEXTLOADs with a < 1 byte width.
  718. if (NewSizeBits < 8)
  719. return false;
  720. // Don't bother creating a non-power-2 sextload, it will likely be broken up
  721. // anyway for most targets.
  722. if (!isPowerOf2_32(NewSizeBits))
  723. return false;
  724. const MachineMemOperand &MMO = LoadDef->getMMO();
  725. LegalityQuery::MemDesc MMDesc(MMO);
  726. MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
  727. if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD,
  728. {MRI.getType(LoadDef->getDstReg()),
  729. MRI.getType(LoadDef->getPointerReg())},
  730. {MMDesc}}))
  731. return false;
  732. MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits);
  733. return true;
  734. }
  735. void CombinerHelper::applySextInRegOfLoad(
  736. MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
  737. assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
  738. Register LoadReg;
  739. unsigned ScalarSizeBits;
  740. std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
  741. GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
  742. // If we have the following:
  743. // %ld = G_LOAD %ptr, (load 2)
  744. // %ext = G_SEXT_INREG %ld, 8
  745. // ==>
  746. // %ld = G_SEXTLOAD %ptr (load 1)
  747. auto &MMO = LoadDef->getMMO();
  748. Builder.setInstrAndDebugLoc(*LoadDef);
  749. auto &MF = Builder.getMF();
  750. auto PtrInfo = MMO.getPointerInfo();
  751. auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
  752. Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
  753. LoadDef->getPointerReg(), *NewMMO);
  754. MI.eraseFromParent();
  755. }
  756. bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr,
  757. Register &Base, Register &Offset) {
  758. auto &MF = *MI.getParent()->getParent();
  759. const auto &TLI = *MF.getSubtarget().getTargetLowering();
  760. #ifndef NDEBUG
  761. unsigned Opcode = MI.getOpcode();
  762. assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
  763. Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
  764. #endif
  765. Base = MI.getOperand(1).getReg();
  766. MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base);
  767. if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
  768. return false;
  769. LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI);
  770. // FIXME: The following use traversal needs a bail out for patholigical cases.
  771. for (auto &Use : MRI.use_nodbg_instructions(Base)) {
  772. if (Use.getOpcode() != TargetOpcode::G_PTR_ADD)
  773. continue;
  774. Offset = Use.getOperand(2).getReg();
  775. if (!ForceLegalIndexing &&
  776. !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) {
  777. LLVM_DEBUG(dbgs() << " Ignoring candidate with illegal addrmode: "
  778. << Use);
  779. continue;
  780. }
  781. // Make sure the offset calculation is before the potentially indexed op.
  782. // FIXME: we really care about dependency here. The offset calculation might
  783. // be movable.
  784. MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset);
  785. if (!OffsetDef || !dominates(*OffsetDef, MI)) {
  786. LLVM_DEBUG(dbgs() << " Ignoring candidate with offset after mem-op: "
  787. << Use);
  788. continue;
  789. }
  790. // FIXME: check whether all uses of Base are load/store with foldable
  791. // addressing modes. If so, using the normal addr-modes is better than
  792. // forming an indexed one.
  793. bool MemOpDominatesAddrUses = true;
  794. for (auto &PtrAddUse :
  795. MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) {
  796. if (!dominates(MI, PtrAddUse)) {
  797. MemOpDominatesAddrUses = false;
  798. break;
  799. }
  800. }
  801. if (!MemOpDominatesAddrUses) {
  802. LLVM_DEBUG(
  803. dbgs() << " Ignoring candidate as memop does not dominate uses: "
  804. << Use);
  805. continue;
  806. }
  807. LLVM_DEBUG(dbgs() << " Found match: " << Use);
  808. Addr = Use.getOperand(0).getReg();
  809. return true;
  810. }
  811. return false;
  812. }
  813. bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr,
  814. Register &Base, Register &Offset) {
  815. auto &MF = *MI.getParent()->getParent();
  816. const auto &TLI = *MF.getSubtarget().getTargetLowering();
  817. #ifndef NDEBUG
  818. unsigned Opcode = MI.getOpcode();
  819. assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
  820. Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
  821. #endif
  822. Addr = MI.getOperand(1).getReg();
  823. MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI);
  824. if (!AddrDef || MRI.hasOneNonDBGUse(Addr))
  825. return false;
  826. Base = AddrDef->getOperand(1).getReg();
  827. Offset = AddrDef->getOperand(2).getReg();
  828. LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI);
  829. if (!ForceLegalIndexing &&
  830. !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) {
  831. LLVM_DEBUG(dbgs() << " Skipping, not legal for target");
  832. return false;
  833. }
  834. MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
  835. if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
  836. LLVM_DEBUG(dbgs() << " Skipping, frame index would need copy anyway.");
  837. return false;
  838. }
  839. if (MI.getOpcode() == TargetOpcode::G_STORE) {
  840. // Would require a copy.
  841. if (Base == MI.getOperand(0).getReg()) {
  842. LLVM_DEBUG(dbgs() << " Skipping, storing base so need copy anyway.");
  843. return false;
  844. }
  845. // We're expecting one use of Addr in MI, but it could also be the
  846. // value stored, which isn't actually dominated by the instruction.
  847. if (MI.getOperand(0).getReg() == Addr) {
  848. LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses");
  849. return false;
  850. }
  851. }
  852. // FIXME: check whether all uses of the base pointer are constant PtrAdds.
  853. // That might allow us to end base's liveness here by adjusting the constant.
  854. for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) {
  855. if (!dominates(MI, UseMI)) {
  856. LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses.");
  857. return false;
  858. }
  859. }
  860. return true;
  861. }
  862. bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) {
  863. IndexedLoadStoreMatchInfo MatchInfo;
  864. if (matchCombineIndexedLoadStore(MI, MatchInfo)) {
  865. applyCombineIndexedLoadStore(MI, MatchInfo);
  866. return true;
  867. }
  868. return false;
  869. }
  870. bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
  871. unsigned Opcode = MI.getOpcode();
  872. if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD &&
  873. Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE)
  874. return false;
  875. // For now, no targets actually support these opcodes so don't waste time
  876. // running these unless we're forced to for testing.
  877. if (!ForceLegalIndexing)
  878. return false;
  879. MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
  880. MatchInfo.Offset);
  881. if (!MatchInfo.IsPre &&
  882. !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
  883. MatchInfo.Offset))
  884. return false;
  885. return true;
  886. }
  887. void CombinerHelper::applyCombineIndexedLoadStore(
  888. MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
  889. MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
  890. MachineIRBuilder MIRBuilder(MI);
  891. unsigned Opcode = MI.getOpcode();
  892. bool IsStore = Opcode == TargetOpcode::G_STORE;
  893. unsigned NewOpcode;
  894. switch (Opcode) {
  895. case TargetOpcode::G_LOAD:
  896. NewOpcode = TargetOpcode::G_INDEXED_LOAD;
  897. break;
  898. case TargetOpcode::G_SEXTLOAD:
  899. NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD;
  900. break;
  901. case TargetOpcode::G_ZEXTLOAD:
  902. NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD;
  903. break;
  904. case TargetOpcode::G_STORE:
  905. NewOpcode = TargetOpcode::G_INDEXED_STORE;
  906. break;
  907. default:
  908. llvm_unreachable("Unknown load/store opcode");
  909. }
  910. auto MIB = MIRBuilder.buildInstr(NewOpcode);
  911. if (IsStore) {
  912. MIB.addDef(MatchInfo.Addr);
  913. MIB.addUse(MI.getOperand(0).getReg());
  914. } else {
  915. MIB.addDef(MI.getOperand(0).getReg());
  916. MIB.addDef(MatchInfo.Addr);
  917. }
  918. MIB.addUse(MatchInfo.Base);
  919. MIB.addUse(MatchInfo.Offset);
  920. MIB.addImm(MatchInfo.IsPre);
  921. MI.eraseFromParent();
  922. AddrDef.eraseFromParent();
  923. LLVM_DEBUG(dbgs() << " Combinined to indexed operation");
  924. }
  925. bool CombinerHelper::matchCombineDivRem(MachineInstr &MI,
  926. MachineInstr *&OtherMI) {
  927. unsigned Opcode = MI.getOpcode();
  928. bool IsDiv, IsSigned;
  929. switch (Opcode) {
  930. default:
  931. llvm_unreachable("Unexpected opcode!");
  932. case TargetOpcode::G_SDIV:
  933. case TargetOpcode::G_UDIV: {
  934. IsDiv = true;
  935. IsSigned = Opcode == TargetOpcode::G_SDIV;
  936. break;
  937. }
  938. case TargetOpcode::G_SREM:
  939. case TargetOpcode::G_UREM: {
  940. IsDiv = false;
  941. IsSigned = Opcode == TargetOpcode::G_SREM;
  942. break;
  943. }
  944. }
  945. Register Src1 = MI.getOperand(1).getReg();
  946. unsigned DivOpcode, RemOpcode, DivremOpcode;
  947. if (IsSigned) {
  948. DivOpcode = TargetOpcode::G_SDIV;
  949. RemOpcode = TargetOpcode::G_SREM;
  950. DivremOpcode = TargetOpcode::G_SDIVREM;
  951. } else {
  952. DivOpcode = TargetOpcode::G_UDIV;
  953. RemOpcode = TargetOpcode::G_UREM;
  954. DivremOpcode = TargetOpcode::G_UDIVREM;
  955. }
  956. if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
  957. return false;
  958. // Combine:
  959. // %div:_ = G_[SU]DIV %src1:_, %src2:_
  960. // %rem:_ = G_[SU]REM %src1:_, %src2:_
  961. // into:
  962. // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
  963. // Combine:
  964. // %rem:_ = G_[SU]REM %src1:_, %src2:_
  965. // %div:_ = G_[SU]DIV %src1:_, %src2:_
  966. // into:
  967. // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
  968. for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
  969. if (MI.getParent() == UseMI.getParent() &&
  970. ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
  971. (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
  972. matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2))) {
  973. OtherMI = &UseMI;
  974. return true;
  975. }
  976. }
  977. return false;
  978. }
  979. void CombinerHelper::applyCombineDivRem(MachineInstr &MI,
  980. MachineInstr *&OtherMI) {
  981. unsigned Opcode = MI.getOpcode();
  982. assert(OtherMI && "OtherMI shouldn't be empty.");
  983. Register DestDivReg, DestRemReg;
  984. if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
  985. DestDivReg = MI.getOperand(0).getReg();
  986. DestRemReg = OtherMI->getOperand(0).getReg();
  987. } else {
  988. DestDivReg = OtherMI->getOperand(0).getReg();
  989. DestRemReg = MI.getOperand(0).getReg();
  990. }
  991. bool IsSigned =
  992. Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
  993. // Check which instruction is first in the block so we don't break def-use
  994. // deps by "moving" the instruction incorrectly.
  995. if (dominates(MI, *OtherMI))
  996. Builder.setInstrAndDebugLoc(MI);
  997. else
  998. Builder.setInstrAndDebugLoc(*OtherMI);
  999. Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
  1000. : TargetOpcode::G_UDIVREM,
  1001. {DestDivReg, DestRemReg},
  1002. {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()});
  1003. MI.eraseFromParent();
  1004. OtherMI->eraseFromParent();
  1005. }
  1006. bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI,
  1007. MachineInstr *&BrCond) {
  1008. assert(MI.getOpcode() == TargetOpcode::G_BR);
  1009. // Try to match the following:
  1010. // bb1:
  1011. // G_BRCOND %c1, %bb2
  1012. // G_BR %bb3
  1013. // bb2:
  1014. // ...
  1015. // bb3:
  1016. // The above pattern does not have a fall through to the successor bb2, always
  1017. // resulting in a branch no matter which path is taken. Here we try to find
  1018. // and replace that pattern with conditional branch to bb3 and otherwise
  1019. // fallthrough to bb2. This is generally better for branch predictors.
  1020. MachineBasicBlock *MBB = MI.getParent();
  1021. MachineBasicBlock::iterator BrIt(MI);
  1022. if (BrIt == MBB->begin())
  1023. return false;
  1024. assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
  1025. BrCond = &*std::prev(BrIt);
  1026. if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
  1027. return false;
  1028. // Check that the next block is the conditional branch target. Also make sure
  1029. // that it isn't the same as the G_BR's target (otherwise, this will loop.)
  1030. MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
  1031. return BrCondTarget != MI.getOperand(0).getMBB() &&
  1032. MBB->isLayoutSuccessor(BrCondTarget);
  1033. }
  1034. void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI,
  1035. MachineInstr *&BrCond) {
  1036. MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
  1037. Builder.setInstrAndDebugLoc(*BrCond);
  1038. LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
  1039. // FIXME: Does int/fp matter for this? If so, we might need to restrict
  1040. // this to i1 only since we might not know for sure what kind of
  1041. // compare generated the condition value.
  1042. auto True = Builder.buildConstant(
  1043. Ty, getICmpTrueVal(getTargetLowering(), false, false));
  1044. auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
  1045. auto *FallthroughBB = BrCond->getOperand(1).getMBB();
  1046. Observer.changingInstr(MI);
  1047. MI.getOperand(0).setMBB(FallthroughBB);
  1048. Observer.changedInstr(MI);
  1049. // Change the conditional branch to use the inverted condition and
  1050. // new target block.
  1051. Observer.changingInstr(*BrCond);
  1052. BrCond->getOperand(0).setReg(Xor.getReg(0));
  1053. BrCond->getOperand(1).setMBB(BrTarget);
  1054. Observer.changedInstr(*BrCond);
  1055. }
  1056. static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
  1057. if (Ty.isVector())
  1058. return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
  1059. Ty.getNumElements());
  1060. return IntegerType::get(C, Ty.getSizeInBits());
  1061. }
  1062. bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) {
  1063. MachineIRBuilder HelperBuilder(MI);
  1064. GISelObserverWrapper DummyObserver;
  1065. LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
  1066. return Helper.lowerMemcpyInline(MI) ==
  1067. LegalizerHelper::LegalizeResult::Legalized;
  1068. }
  1069. bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
  1070. MachineIRBuilder HelperBuilder(MI);
  1071. GISelObserverWrapper DummyObserver;
  1072. LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
  1073. return Helper.lowerMemCpyFamily(MI, MaxLen) ==
  1074. LegalizerHelper::LegalizeResult::Legalized;
  1075. }
  1076. static Optional<APFloat> constantFoldFpUnary(unsigned Opcode, LLT DstTy,
  1077. const Register Op,
  1078. const MachineRegisterInfo &MRI) {
  1079. const ConstantFP *MaybeCst = getConstantFPVRegVal(Op, MRI);
  1080. if (!MaybeCst)
  1081. return None;
  1082. APFloat V = MaybeCst->getValueAPF();
  1083. switch (Opcode) {
  1084. default:
  1085. llvm_unreachable("Unexpected opcode!");
  1086. case TargetOpcode::G_FNEG: {
  1087. V.changeSign();
  1088. return V;
  1089. }
  1090. case TargetOpcode::G_FABS: {
  1091. V.clearSign();
  1092. return V;
  1093. }
  1094. case TargetOpcode::G_FPTRUNC:
  1095. break;
  1096. case TargetOpcode::G_FSQRT: {
  1097. bool Unused;
  1098. V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
  1099. V = APFloat(sqrt(V.convertToDouble()));
  1100. break;
  1101. }
  1102. case TargetOpcode::G_FLOG2: {
  1103. bool Unused;
  1104. V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
  1105. V = APFloat(log2(V.convertToDouble()));
  1106. break;
  1107. }
  1108. }
  1109. // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise,
  1110. // `buildFConstant` will assert on size mismatch. Only `G_FPTRUNC`, `G_FSQRT`,
  1111. // and `G_FLOG2` reach here.
  1112. bool Unused;
  1113. V.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven, &Unused);
  1114. return V;
  1115. }
  1116. bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI,
  1117. Optional<APFloat> &Cst) {
  1118. Register DstReg = MI.getOperand(0).getReg();
  1119. Register SrcReg = MI.getOperand(1).getReg();
  1120. LLT DstTy = MRI.getType(DstReg);
  1121. Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI);
  1122. return Cst.hasValue();
  1123. }
  1124. void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
  1125. Optional<APFloat> &Cst) {
  1126. assert(Cst.hasValue() && "Optional is unexpectedly empty!");
  1127. Builder.setInstrAndDebugLoc(MI);
  1128. MachineFunction &MF = Builder.getMF();
  1129. auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst);
  1130. Register DstReg = MI.getOperand(0).getReg();
  1131. Builder.buildFConstant(DstReg, *FPVal);
  1132. MI.eraseFromParent();
  1133. }
  1134. bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
  1135. PtrAddChain &MatchInfo) {
  1136. // We're trying to match the following pattern:
  1137. // %t1 = G_PTR_ADD %base, G_CONSTANT imm1
  1138. // %root = G_PTR_ADD %t1, G_CONSTANT imm2
  1139. // -->
  1140. // %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
  1141. if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
  1142. return false;
  1143. Register Add2 = MI.getOperand(1).getReg();
  1144. Register Imm1 = MI.getOperand(2).getReg();
  1145. auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
  1146. if (!MaybeImmVal)
  1147. return false;
  1148. MachineInstr *Add2Def = MRI.getVRegDef(Add2);
  1149. if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
  1150. return false;
  1151. Register Base = Add2Def->getOperand(1).getReg();
  1152. Register Imm2 = Add2Def->getOperand(2).getReg();
  1153. auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
  1154. if (!MaybeImm2Val)
  1155. return false;
  1156. // Check if the new combined immediate forms an illegal addressing mode.
  1157. // Do not combine if it was legal before but would get illegal.
  1158. // To do so, we need to find a load/store user of the pointer to get
  1159. // the access type.
  1160. Type *AccessTy = nullptr;
  1161. auto &MF = *MI.getMF();
  1162. for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
  1163. if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
  1164. AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
  1165. MF.getFunction().getContext());
  1166. break;
  1167. }
  1168. }
  1169. TargetLoweringBase::AddrMode AMNew;
  1170. APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
  1171. AMNew.BaseOffs = CombinedImm.getSExtValue();
  1172. if (AccessTy) {
  1173. AMNew.HasBaseReg = true;
  1174. TargetLoweringBase::AddrMode AMOld;
  1175. AMOld.BaseOffs = MaybeImm2Val->Value.getSExtValue();
  1176. AMOld.HasBaseReg = true;
  1177. unsigned AS = MRI.getType(Add2).getAddressSpace();
  1178. const auto &TLI = *MF.getSubtarget().getTargetLowering();
  1179. if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
  1180. !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
  1181. return false;
  1182. }
  1183. // Pass the combined immediate to the apply function.
  1184. MatchInfo.Imm = AMNew.BaseOffs;
  1185. MatchInfo.Base = Base;
  1186. MatchInfo.Bank = getRegBank(Imm2);
  1187. return true;
  1188. }
  1189. void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
  1190. PtrAddChain &MatchInfo) {
  1191. assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
  1192. MachineIRBuilder MIB(MI);
  1193. LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
  1194. auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
  1195. setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
  1196. Observer.changingInstr(MI);
  1197. MI.getOperand(1).setReg(MatchInfo.Base);
  1198. MI.getOperand(2).setReg(NewOffset.getReg(0));
  1199. Observer.changedInstr(MI);
  1200. }
  1201. bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI,
  1202. RegisterImmPair &MatchInfo) {
  1203. // We're trying to match the following pattern with any of
  1204. // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
  1205. // %t1 = SHIFT %base, G_CONSTANT imm1
  1206. // %root = SHIFT %t1, G_CONSTANT imm2
  1207. // -->
  1208. // %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
  1209. unsigned Opcode = MI.getOpcode();
  1210. assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
  1211. Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
  1212. Opcode == TargetOpcode::G_USHLSAT) &&
  1213. "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
  1214. Register Shl2 = MI.getOperand(1).getReg();
  1215. Register Imm1 = MI.getOperand(2).getReg();
  1216. auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
  1217. if (!MaybeImmVal)
  1218. return false;
  1219. MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2);
  1220. if (Shl2Def->getOpcode() != Opcode)
  1221. return false;
  1222. Register Base = Shl2Def->getOperand(1).getReg();
  1223. Register Imm2 = Shl2Def->getOperand(2).getReg();
  1224. auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
  1225. if (!MaybeImm2Val)
  1226. return false;
  1227. // Pass the combined immediate to the apply function.
  1228. MatchInfo.Imm =
  1229. (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue();
  1230. MatchInfo.Reg = Base;
  1231. // There is no simple replacement for a saturating unsigned left shift that
  1232. // exceeds the scalar size.
  1233. if (Opcode == TargetOpcode::G_USHLSAT &&
  1234. MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
  1235. return false;
  1236. return true;
  1237. }
  1238. void CombinerHelper::applyShiftImmedChain(MachineInstr &MI,
  1239. RegisterImmPair &MatchInfo) {
  1240. unsigned Opcode = MI.getOpcode();
  1241. assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
  1242. Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
  1243. Opcode == TargetOpcode::G_USHLSAT) &&
  1244. "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
  1245. Builder.setInstrAndDebugLoc(MI);
  1246. LLT Ty = MRI.getType(MI.getOperand(1).getReg());
  1247. unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
  1248. auto Imm = MatchInfo.Imm;
  1249. if (Imm >= ScalarSizeInBits) {
  1250. // Any logical shift that exceeds scalar size will produce zero.
  1251. if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
  1252. Builder.buildConstant(MI.getOperand(0), 0);
  1253. MI.eraseFromParent();
  1254. return;
  1255. }
  1256. // Arithmetic shift and saturating signed left shift have no effect beyond
  1257. // scalar size.
  1258. Imm = ScalarSizeInBits - 1;
  1259. }
  1260. LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
  1261. Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
  1262. Observer.changingInstr(MI);
  1263. MI.getOperand(1).setReg(MatchInfo.Reg);
  1264. MI.getOperand(2).setReg(NewImm);
  1265. Observer.changedInstr(MI);
  1266. }
  1267. bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI,
  1268. ShiftOfShiftedLogic &MatchInfo) {
  1269. // We're trying to match the following pattern with any of
  1270. // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination
  1271. // with any of G_AND/G_OR/G_XOR logic instructions.
  1272. // %t1 = SHIFT %X, G_CONSTANT C0
  1273. // %t2 = LOGIC %t1, %Y
  1274. // %root = SHIFT %t2, G_CONSTANT C1
  1275. // -->
  1276. // %t3 = SHIFT %X, G_CONSTANT (C0+C1)
  1277. // %t4 = SHIFT %Y, G_CONSTANT C1
  1278. // %root = LOGIC %t3, %t4
  1279. unsigned ShiftOpcode = MI.getOpcode();
  1280. assert((ShiftOpcode == TargetOpcode::G_SHL ||
  1281. ShiftOpcode == TargetOpcode::G_ASHR ||
  1282. ShiftOpcode == TargetOpcode::G_LSHR ||
  1283. ShiftOpcode == TargetOpcode::G_USHLSAT ||
  1284. ShiftOpcode == TargetOpcode::G_SSHLSAT) &&
  1285. "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
  1286. // Match a one-use bitwise logic op.
  1287. Register LogicDest = MI.getOperand(1).getReg();
  1288. if (!MRI.hasOneNonDBGUse(LogicDest))
  1289. return false;
  1290. MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest);
  1291. unsigned LogicOpcode = LogicMI->getOpcode();
  1292. if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
  1293. LogicOpcode != TargetOpcode::G_XOR)
  1294. return false;
  1295. // Find a matching one-use shift by constant.
  1296. const Register C1 = MI.getOperand(2).getReg();
  1297. auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
  1298. if (!MaybeImmVal)
  1299. return false;
  1300. const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
  1301. auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
  1302. // Shift should match previous one and should be a one-use.
  1303. if (MI->getOpcode() != ShiftOpcode ||
  1304. !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
  1305. return false;
  1306. // Must be a constant.
  1307. auto MaybeImmVal =
  1308. getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
  1309. if (!MaybeImmVal)
  1310. return false;
  1311. ShiftVal = MaybeImmVal->Value.getSExtValue();
  1312. return true;
  1313. };
  1314. // Logic ops are commutative, so check each operand for a match.
  1315. Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
  1316. MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1);
  1317. Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
  1318. MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2);
  1319. uint64_t C0Val;
  1320. if (matchFirstShift(LogicMIOp1, C0Val)) {
  1321. MatchInfo.LogicNonShiftReg = LogicMIReg2;
  1322. MatchInfo.Shift2 = LogicMIOp1;
  1323. } else if (matchFirstShift(LogicMIOp2, C0Val)) {
  1324. MatchInfo.LogicNonShiftReg = LogicMIReg1;
  1325. MatchInfo.Shift2 = LogicMIOp2;
  1326. } else
  1327. return false;
  1328. MatchInfo.ValSum = C0Val + C1Val;
  1329. // The fold is not valid if the sum of the shift values exceeds bitwidth.
  1330. if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
  1331. return false;
  1332. MatchInfo.Logic = LogicMI;
  1333. return true;
  1334. }
  1335. void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI,
  1336. ShiftOfShiftedLogic &MatchInfo) {
  1337. unsigned Opcode = MI.getOpcode();
  1338. assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
  1339. Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT ||
  1340. Opcode == TargetOpcode::G_SSHLSAT) &&
  1341. "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
  1342. LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
  1343. LLT DestType = MRI.getType(MI.getOperand(0).getReg());
  1344. Builder.setInstrAndDebugLoc(MI);
  1345. Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
  1346. Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
  1347. Register Shift1 =
  1348. Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
  1349. Register Shift2Const = MI.getOperand(2).getReg();
  1350. Register Shift2 = Builder
  1351. .buildInstr(Opcode, {DestType},
  1352. {MatchInfo.LogicNonShiftReg, Shift2Const})
  1353. .getReg(0);
  1354. Register Dest = MI.getOperand(0).getReg();
  1355. Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
  1356. // These were one use so it's safe to remove them.
  1357. MatchInfo.Shift2->eraseFromParent();
  1358. MatchInfo.Logic->eraseFromParent();
  1359. MI.eraseFromParent();
  1360. }
  1361. bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
  1362. unsigned &ShiftVal) {
  1363. assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
  1364. auto MaybeImmVal =
  1365. getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
  1366. if (!MaybeImmVal)
  1367. return false;
  1368. ShiftVal = MaybeImmVal->Value.exactLogBase2();
  1369. return (static_cast<int32_t>(ShiftVal) != -1);
  1370. }
  1371. void CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
  1372. unsigned &ShiftVal) {
  1373. assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
  1374. MachineIRBuilder MIB(MI);
  1375. LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
  1376. auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
  1377. Observer.changingInstr(MI);
  1378. MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
  1379. MI.getOperand(2).setReg(ShiftCst.getReg(0));
  1380. Observer.changedInstr(MI);
  1381. }
  1382. // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
  1383. bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI,
  1384. RegisterImmPair &MatchData) {
  1385. assert(MI.getOpcode() == TargetOpcode::G_SHL && KB);
  1386. Register LHS = MI.getOperand(1).getReg();
  1387. Register ExtSrc;
  1388. if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
  1389. !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
  1390. !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
  1391. return false;
  1392. // TODO: Should handle vector splat.
  1393. Register RHS = MI.getOperand(2).getReg();
  1394. auto MaybeShiftAmtVal = getIConstantVRegValWithLookThrough(RHS, MRI);
  1395. if (!MaybeShiftAmtVal)
  1396. return false;
  1397. if (LI) {
  1398. LLT SrcTy = MRI.getType(ExtSrc);
  1399. // We only really care about the legality with the shifted value. We can
  1400. // pick any type the constant shift amount, so ask the target what to
  1401. // use. Otherwise we would have to guess and hope it is reported as legal.
  1402. LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
  1403. if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
  1404. return false;
  1405. }
  1406. int64_t ShiftAmt = MaybeShiftAmtVal->Value.getSExtValue();
  1407. MatchData.Reg = ExtSrc;
  1408. MatchData.Imm = ShiftAmt;
  1409. unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countLeadingOnes();
  1410. return MinLeadingZeros >= ShiftAmt;
  1411. }
  1412. void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI,
  1413. const RegisterImmPair &MatchData) {
  1414. Register ExtSrcReg = MatchData.Reg;
  1415. int64_t ShiftAmtVal = MatchData.Imm;
  1416. LLT ExtSrcTy = MRI.getType(ExtSrcReg);
  1417. Builder.setInstrAndDebugLoc(MI);
  1418. auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
  1419. auto NarrowShift =
  1420. Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
  1421. Builder.buildZExt(MI.getOperand(0), NarrowShift);
  1422. MI.eraseFromParent();
  1423. }
  1424. bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI,
  1425. Register &MatchInfo) {
  1426. GMerge &Merge = cast<GMerge>(MI);
  1427. SmallVector<Register, 16> MergedValues;
  1428. for (unsigned I = 0; I < Merge.getNumSources(); ++I)
  1429. MergedValues.emplace_back(Merge.getSourceReg(I));
  1430. auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI);
  1431. if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources())
  1432. return false;
  1433. for (unsigned I = 0; I < MergedValues.size(); ++I)
  1434. if (MergedValues[I] != Unmerge->getReg(I))
  1435. return false;
  1436. MatchInfo = Unmerge->getSourceReg();
  1437. return true;
  1438. }
  1439. static Register peekThroughBitcast(Register Reg,
  1440. const MachineRegisterInfo &MRI) {
  1441. while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
  1442. ;
  1443. return Reg;
  1444. }
  1445. bool CombinerHelper::matchCombineUnmergeMergeToPlainValues(
  1446. MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
  1447. assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  1448. "Expected an unmerge");
  1449. auto &Unmerge = cast<GUnmerge>(MI);
  1450. Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
  1451. auto *SrcInstr = getOpcodeDef<GMergeLikeOp>(SrcReg, MRI);
  1452. if (!SrcInstr)
  1453. return false;
  1454. // Check the source type of the merge.
  1455. LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
  1456. LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
  1457. bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
  1458. if (SrcMergeTy != Dst0Ty && !SameSize)
  1459. return false;
  1460. // They are the same now (modulo a bitcast).
  1461. // We can collect all the src registers.
  1462. for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
  1463. Operands.push_back(SrcInstr->getSourceReg(Idx));
  1464. return true;
  1465. }
  1466. void CombinerHelper::applyCombineUnmergeMergeToPlainValues(
  1467. MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
  1468. assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  1469. "Expected an unmerge");
  1470. assert((MI.getNumOperands() - 1 == Operands.size()) &&
  1471. "Not enough operands to replace all defs");
  1472. unsigned NumElems = MI.getNumOperands() - 1;
  1473. LLT SrcTy = MRI.getType(Operands[0]);
  1474. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  1475. bool CanReuseInputDirectly = DstTy == SrcTy;
  1476. Builder.setInstrAndDebugLoc(MI);
  1477. for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
  1478. Register DstReg = MI.getOperand(Idx).getReg();
  1479. Register SrcReg = Operands[Idx];
  1480. if (CanReuseInputDirectly)
  1481. replaceRegWith(MRI, DstReg, SrcReg);
  1482. else
  1483. Builder.buildCast(DstReg, SrcReg);
  1484. }
  1485. MI.eraseFromParent();
  1486. }
  1487. bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI,
  1488. SmallVectorImpl<APInt> &Csts) {
  1489. unsigned SrcIdx = MI.getNumOperands() - 1;
  1490. Register SrcReg = MI.getOperand(SrcIdx).getReg();
  1491. MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg);
  1492. if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT &&
  1493. SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT)
  1494. return false;
  1495. // Break down the big constant in smaller ones.
  1496. const MachineOperand &CstVal = SrcInstr->getOperand(1);
  1497. APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT
  1498. ? CstVal.getCImm()->getValue()
  1499. : CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
  1500. LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
  1501. unsigned ShiftAmt = Dst0Ty.getSizeInBits();
  1502. // Unmerge a constant.
  1503. for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
  1504. Csts.emplace_back(Val.trunc(ShiftAmt));
  1505. Val = Val.lshr(ShiftAmt);
  1506. }
  1507. return true;
  1508. }
  1509. void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI,
  1510. SmallVectorImpl<APInt> &Csts) {
  1511. assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  1512. "Expected an unmerge");
  1513. assert((MI.getNumOperands() - 1 == Csts.size()) &&
  1514. "Not enough operands to replace all defs");
  1515. unsigned NumElems = MI.getNumOperands() - 1;
  1516. Builder.setInstrAndDebugLoc(MI);
  1517. for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
  1518. Register DstReg = MI.getOperand(Idx).getReg();
  1519. Builder.buildConstant(DstReg, Csts[Idx]);
  1520. }
  1521. MI.eraseFromParent();
  1522. }
  1523. bool CombinerHelper::matchCombineUnmergeUndef(
  1524. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  1525. unsigned SrcIdx = MI.getNumOperands() - 1;
  1526. Register SrcReg = MI.getOperand(SrcIdx).getReg();
  1527. MatchInfo = [&MI](MachineIRBuilder &B) {
  1528. unsigned NumElems = MI.getNumOperands() - 1;
  1529. for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
  1530. Register DstReg = MI.getOperand(Idx).getReg();
  1531. B.buildUndef(DstReg);
  1532. }
  1533. };
  1534. return isa<GImplicitDef>(MRI.getVRegDef(SrcReg));
  1535. }
  1536. bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
  1537. assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  1538. "Expected an unmerge");
  1539. // Check that all the lanes are dead except the first one.
  1540. for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
  1541. if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
  1542. return false;
  1543. }
  1544. return true;
  1545. }
  1546. void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
  1547. Builder.setInstrAndDebugLoc(MI);
  1548. Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
  1549. // Truncating a vector is going to truncate every single lane,
  1550. // whereas we want the full lowbits.
  1551. // Do the operation on a scalar instead.
  1552. LLT SrcTy = MRI.getType(SrcReg);
  1553. if (SrcTy.isVector())
  1554. SrcReg =
  1555. Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0);
  1556. Register Dst0Reg = MI.getOperand(0).getReg();
  1557. LLT Dst0Ty = MRI.getType(Dst0Reg);
  1558. if (Dst0Ty.isVector()) {
  1559. auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg);
  1560. Builder.buildCast(Dst0Reg, MIB);
  1561. } else
  1562. Builder.buildTrunc(Dst0Reg, SrcReg);
  1563. MI.eraseFromParent();
  1564. }
  1565. bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) {
  1566. assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  1567. "Expected an unmerge");
  1568. Register Dst0Reg = MI.getOperand(0).getReg();
  1569. LLT Dst0Ty = MRI.getType(Dst0Reg);
  1570. // G_ZEXT on vector applies to each lane, so it will
  1571. // affect all destinations. Therefore we won't be able
  1572. // to simplify the unmerge to just the first definition.
  1573. if (Dst0Ty.isVector())
  1574. return false;
  1575. Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
  1576. LLT SrcTy = MRI.getType(SrcReg);
  1577. if (SrcTy.isVector())
  1578. return false;
  1579. Register ZExtSrcReg;
  1580. if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
  1581. return false;
  1582. // Finally we can replace the first definition with
  1583. // a zext of the source if the definition is big enough to hold
  1584. // all of ZExtSrc bits.
  1585. LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
  1586. return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
  1587. }
  1588. void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) {
  1589. assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  1590. "Expected an unmerge");
  1591. Register Dst0Reg = MI.getOperand(0).getReg();
  1592. MachineInstr *ZExtInstr =
  1593. MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg());
  1594. assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT &&
  1595. "Expecting a G_ZEXT");
  1596. Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg();
  1597. LLT Dst0Ty = MRI.getType(Dst0Reg);
  1598. LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
  1599. Builder.setInstrAndDebugLoc(MI);
  1600. if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
  1601. Builder.buildZExt(Dst0Reg, ZExtSrcReg);
  1602. } else {
  1603. assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
  1604. "ZExt src doesn't fit in destination");
  1605. replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
  1606. }
  1607. Register ZeroReg;
  1608. for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
  1609. if (!ZeroReg)
  1610. ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
  1611. replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
  1612. }
  1613. MI.eraseFromParent();
  1614. }
  1615. bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
  1616. unsigned TargetShiftSize,
  1617. unsigned &ShiftVal) {
  1618. assert((MI.getOpcode() == TargetOpcode::G_SHL ||
  1619. MI.getOpcode() == TargetOpcode::G_LSHR ||
  1620. MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
  1621. LLT Ty = MRI.getType(MI.getOperand(0).getReg());
  1622. if (Ty.isVector()) // TODO:
  1623. return false;
  1624. // Don't narrow further than the requested size.
  1625. unsigned Size = Ty.getSizeInBits();
  1626. if (Size <= TargetShiftSize)
  1627. return false;
  1628. auto MaybeImmVal =
  1629. getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
  1630. if (!MaybeImmVal)
  1631. return false;
  1632. ShiftVal = MaybeImmVal->Value.getSExtValue();
  1633. return ShiftVal >= Size / 2 && ShiftVal < Size;
  1634. }
  1635. void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
  1636. const unsigned &ShiftVal) {
  1637. Register DstReg = MI.getOperand(0).getReg();
  1638. Register SrcReg = MI.getOperand(1).getReg();
  1639. LLT Ty = MRI.getType(SrcReg);
  1640. unsigned Size = Ty.getSizeInBits();
  1641. unsigned HalfSize = Size / 2;
  1642. assert(ShiftVal >= HalfSize);
  1643. LLT HalfTy = LLT::scalar(HalfSize);
  1644. Builder.setInstr(MI);
  1645. auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
  1646. unsigned NarrowShiftAmt = ShiftVal - HalfSize;
  1647. if (MI.getOpcode() == TargetOpcode::G_LSHR) {
  1648. Register Narrowed = Unmerge.getReg(1);
  1649. // dst = G_LSHR s64:x, C for C >= 32
  1650. // =>
  1651. // lo, hi = G_UNMERGE_VALUES x
  1652. // dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
  1653. if (NarrowShiftAmt != 0) {
  1654. Narrowed = Builder.buildLShr(HalfTy, Narrowed,
  1655. Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
  1656. }
  1657. auto Zero = Builder.buildConstant(HalfTy, 0);
  1658. Builder.buildMerge(DstReg, { Narrowed, Zero });
  1659. } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
  1660. Register Narrowed = Unmerge.getReg(0);
  1661. // dst = G_SHL s64:x, C for C >= 32
  1662. // =>
  1663. // lo, hi = G_UNMERGE_VALUES x
  1664. // dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
  1665. if (NarrowShiftAmt != 0) {
  1666. Narrowed = Builder.buildShl(HalfTy, Narrowed,
  1667. Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
  1668. }
  1669. auto Zero = Builder.buildConstant(HalfTy, 0);
  1670. Builder.buildMerge(DstReg, { Zero, Narrowed });
  1671. } else {
  1672. assert(MI.getOpcode() == TargetOpcode::G_ASHR);
  1673. auto Hi = Builder.buildAShr(
  1674. HalfTy, Unmerge.getReg(1),
  1675. Builder.buildConstant(HalfTy, HalfSize - 1));
  1676. if (ShiftVal == HalfSize) {
  1677. // (G_ASHR i64:x, 32) ->
  1678. // G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
  1679. Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi });
  1680. } else if (ShiftVal == Size - 1) {
  1681. // Don't need a second shift.
  1682. // (G_ASHR i64:x, 63) ->
  1683. // %narrowed = (G_ASHR hi_32(x), 31)
  1684. // G_MERGE_VALUES %narrowed, %narrowed
  1685. Builder.buildMerge(DstReg, { Hi, Hi });
  1686. } else {
  1687. auto Lo = Builder.buildAShr(
  1688. HalfTy, Unmerge.getReg(1),
  1689. Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
  1690. // (G_ASHR i64:x, C) ->, for C >= 32
  1691. // G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
  1692. Builder.buildMerge(DstReg, { Lo, Hi });
  1693. }
  1694. }
  1695. MI.eraseFromParent();
  1696. }
  1697. bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
  1698. unsigned TargetShiftAmount) {
  1699. unsigned ShiftAmt;
  1700. if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
  1701. applyCombineShiftToUnmerge(MI, ShiftAmt);
  1702. return true;
  1703. }
  1704. return false;
  1705. }
  1706. bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
  1707. assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
  1708. Register DstReg = MI.getOperand(0).getReg();
  1709. LLT DstTy = MRI.getType(DstReg);
  1710. Register SrcReg = MI.getOperand(1).getReg();
  1711. return mi_match(SrcReg, MRI,
  1712. m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg))));
  1713. }
  1714. void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
  1715. assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
  1716. Register DstReg = MI.getOperand(0).getReg();
  1717. Builder.setInstr(MI);
  1718. Builder.buildCopy(DstReg, Reg);
  1719. MI.eraseFromParent();
  1720. }
  1721. bool CombinerHelper::matchCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
  1722. assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
  1723. Register SrcReg = MI.getOperand(1).getReg();
  1724. return mi_match(SrcReg, MRI, m_GIntToPtr(m_Reg(Reg)));
  1725. }
  1726. void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
  1727. assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
  1728. Register DstReg = MI.getOperand(0).getReg();
  1729. Builder.setInstr(MI);
  1730. Builder.buildZExtOrTrunc(DstReg, Reg);
  1731. MI.eraseFromParent();
  1732. }
  1733. bool CombinerHelper::matchCombineAddP2IToPtrAdd(
  1734. MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
  1735. assert(MI.getOpcode() == TargetOpcode::G_ADD);
  1736. Register LHS = MI.getOperand(1).getReg();
  1737. Register RHS = MI.getOperand(2).getReg();
  1738. LLT IntTy = MRI.getType(LHS);
  1739. // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the
  1740. // instruction.
  1741. PtrReg.second = false;
  1742. for (Register SrcReg : {LHS, RHS}) {
  1743. if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) {
  1744. // Don't handle cases where the integer is implicitly converted to the
  1745. // pointer width.
  1746. LLT PtrTy = MRI.getType(PtrReg.first);
  1747. if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits())
  1748. return true;
  1749. }
  1750. PtrReg.second = true;
  1751. }
  1752. return false;
  1753. }
  1754. void CombinerHelper::applyCombineAddP2IToPtrAdd(
  1755. MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
  1756. Register Dst = MI.getOperand(0).getReg();
  1757. Register LHS = MI.getOperand(1).getReg();
  1758. Register RHS = MI.getOperand(2).getReg();
  1759. const bool DoCommute = PtrReg.second;
  1760. if (DoCommute)
  1761. std::swap(LHS, RHS);
  1762. LHS = PtrReg.first;
  1763. LLT PtrTy = MRI.getType(LHS);
  1764. Builder.setInstrAndDebugLoc(MI);
  1765. auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS);
  1766. Builder.buildPtrToInt(Dst, PtrAdd);
  1767. MI.eraseFromParent();
  1768. }
  1769. bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI,
  1770. APInt &NewCst) {
  1771. auto &PtrAdd = cast<GPtrAdd>(MI);
  1772. Register LHS = PtrAdd.getBaseReg();
  1773. Register RHS = PtrAdd.getOffsetReg();
  1774. MachineRegisterInfo &MRI = Builder.getMF().getRegInfo();
  1775. if (auto RHSCst = getIConstantVRegVal(RHS, MRI)) {
  1776. APInt Cst;
  1777. if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) {
  1778. auto DstTy = MRI.getType(PtrAdd.getReg(0));
  1779. // G_INTTOPTR uses zero-extension
  1780. NewCst = Cst.zextOrTrunc(DstTy.getSizeInBits());
  1781. NewCst += RHSCst->sextOrTrunc(DstTy.getSizeInBits());
  1782. return true;
  1783. }
  1784. }
  1785. return false;
  1786. }
  1787. void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI,
  1788. APInt &NewCst) {
  1789. auto &PtrAdd = cast<GPtrAdd>(MI);
  1790. Register Dst = PtrAdd.getReg(0);
  1791. Builder.setInstrAndDebugLoc(MI);
  1792. Builder.buildConstant(Dst, NewCst);
  1793. PtrAdd.eraseFromParent();
  1794. }
  1795. bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) {
  1796. assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
  1797. Register DstReg = MI.getOperand(0).getReg();
  1798. Register SrcReg = MI.getOperand(1).getReg();
  1799. LLT DstTy = MRI.getType(DstReg);
  1800. return mi_match(SrcReg, MRI,
  1801. m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))));
  1802. }
  1803. bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
  1804. assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
  1805. Register DstReg = MI.getOperand(0).getReg();
  1806. Register SrcReg = MI.getOperand(1).getReg();
  1807. LLT DstTy = MRI.getType(DstReg);
  1808. if (mi_match(SrcReg, MRI,
  1809. m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
  1810. unsigned DstSize = DstTy.getScalarSizeInBits();
  1811. unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
  1812. return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
  1813. }
  1814. return false;
  1815. }
  1816. bool CombinerHelper::matchCombineExtOfExt(
  1817. MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
  1818. assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
  1819. MI.getOpcode() == TargetOpcode::G_SEXT ||
  1820. MI.getOpcode() == TargetOpcode::G_ZEXT) &&
  1821. "Expected a G_[ASZ]EXT");
  1822. Register SrcReg = MI.getOperand(1).getReg();
  1823. MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
  1824. // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
  1825. unsigned Opc = MI.getOpcode();
  1826. unsigned SrcOpc = SrcMI->getOpcode();
  1827. if (Opc == SrcOpc ||
  1828. (Opc == TargetOpcode::G_ANYEXT &&
  1829. (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
  1830. (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
  1831. MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
  1832. return true;
  1833. }
  1834. return false;
  1835. }
  1836. void CombinerHelper::applyCombineExtOfExt(
  1837. MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
  1838. assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
  1839. MI.getOpcode() == TargetOpcode::G_SEXT ||
  1840. MI.getOpcode() == TargetOpcode::G_ZEXT) &&
  1841. "Expected a G_[ASZ]EXT");
  1842. Register Reg = std::get<0>(MatchInfo);
  1843. unsigned SrcExtOp = std::get<1>(MatchInfo);
  1844. // Combine exts with the same opcode.
  1845. if (MI.getOpcode() == SrcExtOp) {
  1846. Observer.changingInstr(MI);
  1847. MI.getOperand(1).setReg(Reg);
  1848. Observer.changedInstr(MI);
  1849. return;
  1850. }
  1851. // Combine:
  1852. // - anyext([sz]ext x) to [sz]ext x
  1853. // - sext(zext x) to zext x
  1854. if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
  1855. (MI.getOpcode() == TargetOpcode::G_SEXT &&
  1856. SrcExtOp == TargetOpcode::G_ZEXT)) {
  1857. Register DstReg = MI.getOperand(0).getReg();
  1858. Builder.setInstrAndDebugLoc(MI);
  1859. Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
  1860. MI.eraseFromParent();
  1861. }
  1862. }
  1863. void CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) {
  1864. assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
  1865. Register DstReg = MI.getOperand(0).getReg();
  1866. Register SrcReg = MI.getOperand(1).getReg();
  1867. LLT DstTy = MRI.getType(DstReg);
  1868. Builder.setInstrAndDebugLoc(MI);
  1869. Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg,
  1870. MI.getFlags());
  1871. MI.eraseFromParent();
  1872. }
  1873. bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) {
  1874. assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG");
  1875. Register SrcReg = MI.getOperand(1).getReg();
  1876. return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg)));
  1877. }
  1878. bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) {
  1879. assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
  1880. Src = MI.getOperand(1).getReg();
  1881. Register AbsSrc;
  1882. return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc)));
  1883. }
  1884. bool CombinerHelper::matchCombineFAbsOfFNeg(MachineInstr &MI,
  1885. BuildFnTy &MatchInfo) {
  1886. assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
  1887. Register Src = MI.getOperand(1).getReg();
  1888. Register NegSrc;
  1889. if (!mi_match(Src, MRI, m_GFNeg(m_Reg(NegSrc))))
  1890. return false;
  1891. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  1892. Observer.changingInstr(MI);
  1893. MI.getOperand(1).setReg(NegSrc);
  1894. Observer.changedInstr(MI);
  1895. };
  1896. return true;
  1897. }
  1898. bool CombinerHelper::matchCombineTruncOfExt(
  1899. MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
  1900. assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
  1901. Register SrcReg = MI.getOperand(1).getReg();
  1902. MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
  1903. unsigned SrcOpc = SrcMI->getOpcode();
  1904. if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
  1905. SrcOpc == TargetOpcode::G_ZEXT) {
  1906. MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
  1907. return true;
  1908. }
  1909. return false;
  1910. }
  1911. void CombinerHelper::applyCombineTruncOfExt(
  1912. MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
  1913. assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
  1914. Register SrcReg = MatchInfo.first;
  1915. unsigned SrcExtOp = MatchInfo.second;
  1916. Register DstReg = MI.getOperand(0).getReg();
  1917. LLT SrcTy = MRI.getType(SrcReg);
  1918. LLT DstTy = MRI.getType(DstReg);
  1919. if (SrcTy == DstTy) {
  1920. MI.eraseFromParent();
  1921. replaceRegWith(MRI, DstReg, SrcReg);
  1922. return;
  1923. }
  1924. Builder.setInstrAndDebugLoc(MI);
  1925. if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
  1926. Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
  1927. else
  1928. Builder.buildTrunc(DstReg, SrcReg);
  1929. MI.eraseFromParent();
  1930. }
  1931. bool CombinerHelper::matchCombineTruncOfShl(
  1932. MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
  1933. assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
  1934. Register DstReg = MI.getOperand(0).getReg();
  1935. Register SrcReg = MI.getOperand(1).getReg();
  1936. LLT DstTy = MRI.getType(DstReg);
  1937. Register ShiftSrc;
  1938. Register ShiftAmt;
  1939. if (MRI.hasOneNonDBGUse(SrcReg) &&
  1940. mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) &&
  1941. isLegalOrBeforeLegalizer(
  1942. {TargetOpcode::G_SHL,
  1943. {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) {
  1944. KnownBits Known = KB->getKnownBits(ShiftAmt);
  1945. unsigned Size = DstTy.getSizeInBits();
  1946. if (Known.countMaxActiveBits() <= Log2_32(Size)) {
  1947. MatchInfo = std::make_pair(ShiftSrc, ShiftAmt);
  1948. return true;
  1949. }
  1950. }
  1951. return false;
  1952. }
  1953. void CombinerHelper::applyCombineTruncOfShl(
  1954. MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
  1955. assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
  1956. Register DstReg = MI.getOperand(0).getReg();
  1957. Register SrcReg = MI.getOperand(1).getReg();
  1958. LLT DstTy = MRI.getType(DstReg);
  1959. MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
  1960. Register ShiftSrc = MatchInfo.first;
  1961. Register ShiftAmt = MatchInfo.second;
  1962. Builder.setInstrAndDebugLoc(MI);
  1963. auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc);
  1964. Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags());
  1965. MI.eraseFromParent();
  1966. }
  1967. bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
  1968. return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
  1969. return MO.isReg() &&
  1970. getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
  1971. });
  1972. }
  1973. bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
  1974. return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
  1975. return !MO.isReg() ||
  1976. getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
  1977. });
  1978. }
  1979. bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
  1980. assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
  1981. ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
  1982. return all_of(Mask, [](int Elt) { return Elt < 0; });
  1983. }
  1984. bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
  1985. assert(MI.getOpcode() == TargetOpcode::G_STORE);
  1986. return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
  1987. MRI);
  1988. }
  1989. bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
  1990. assert(MI.getOpcode() == TargetOpcode::G_SELECT);
  1991. return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
  1992. MRI);
  1993. }
  1994. bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
  1995. GSelect &SelMI = cast<GSelect>(MI);
  1996. auto Cst =
  1997. isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI);
  1998. if (!Cst)
  1999. return false;
  2000. OpIdx = Cst->isZero() ? 3 : 2;
  2001. return true;
  2002. }
  2003. bool CombinerHelper::eraseInst(MachineInstr &MI) {
  2004. MI.eraseFromParent();
  2005. return true;
  2006. }
  2007. bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
  2008. const MachineOperand &MOP2) {
  2009. if (!MOP1.isReg() || !MOP2.isReg())
  2010. return false;
  2011. auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
  2012. if (!InstAndDef1)
  2013. return false;
  2014. auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
  2015. if (!InstAndDef2)
  2016. return false;
  2017. MachineInstr *I1 = InstAndDef1->MI;
  2018. MachineInstr *I2 = InstAndDef2->MI;
  2019. // Handle a case like this:
  2020. //
  2021. // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
  2022. //
  2023. // Even though %0 and %1 are produced by the same instruction they are not
  2024. // the same values.
  2025. if (I1 == I2)
  2026. return MOP1.getReg() == MOP2.getReg();
  2027. // If we have an instruction which loads or stores, we can't guarantee that
  2028. // it is identical.
  2029. //
  2030. // For example, we may have
  2031. //
  2032. // %x1 = G_LOAD %addr (load N from @somewhere)
  2033. // ...
  2034. // call @foo
  2035. // ...
  2036. // %x2 = G_LOAD %addr (load N from @somewhere)
  2037. // ...
  2038. // %or = G_OR %x1, %x2
  2039. //
  2040. // It's possible that @foo will modify whatever lives at the address we're
  2041. // loading from. To be safe, let's just assume that all loads and stores
  2042. // are different (unless we have something which is guaranteed to not
  2043. // change.)
  2044. if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr))
  2045. return false;
  2046. // Check for physical registers on the instructions first to avoid cases
  2047. // like this:
  2048. //
  2049. // %a = COPY $physreg
  2050. // ...
  2051. // SOMETHING implicit-def $physreg
  2052. // ...
  2053. // %b = COPY $physreg
  2054. //
  2055. // These copies are not equivalent.
  2056. if (any_of(I1->uses(), [](const MachineOperand &MO) {
  2057. return MO.isReg() && MO.getReg().isPhysical();
  2058. })) {
  2059. // Check if we have a case like this:
  2060. //
  2061. // %a = COPY $physreg
  2062. // %b = COPY %a
  2063. //
  2064. // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
  2065. // From that, we know that they must have the same value, since they must
  2066. // have come from the same COPY.
  2067. return I1->isIdenticalTo(*I2);
  2068. }
  2069. // We don't have any physical registers, so we don't necessarily need the
  2070. // same vreg defs.
  2071. //
  2072. // On the off-chance that there's some target instruction feeding into the
  2073. // instruction, let's use produceSameValue instead of isIdenticalTo.
  2074. if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
  2075. // Handle instructions with multiple defs that produce same values. Values
  2076. // are same for operands with same index.
  2077. // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
  2078. // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
  2079. // I1 and I2 are different instructions but produce same values,
  2080. // %1 and %6 are same, %1 and %7 are not the same value.
  2081. return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) ==
  2082. I2->findRegisterDefOperandIdx(InstAndDef2->Reg);
  2083. }
  2084. return false;
  2085. }
  2086. bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
  2087. if (!MOP.isReg())
  2088. return false;
  2089. auto *MI = MRI.getVRegDef(MOP.getReg());
  2090. auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI);
  2091. return MaybeCst.hasValue() && MaybeCst->getBitWidth() <= 64 &&
  2092. MaybeCst->getSExtValue() == C;
  2093. }
  2094. bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
  2095. unsigned OpIdx) {
  2096. assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
  2097. Register OldReg = MI.getOperand(0).getReg();
  2098. Register Replacement = MI.getOperand(OpIdx).getReg();
  2099. assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
  2100. MI.eraseFromParent();
  2101. replaceRegWith(MRI, OldReg, Replacement);
  2102. return true;
  2103. }
  2104. bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
  2105. Register Replacement) {
  2106. assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
  2107. Register OldReg = MI.getOperand(0).getReg();
  2108. assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
  2109. MI.eraseFromParent();
  2110. replaceRegWith(MRI, OldReg, Replacement);
  2111. return true;
  2112. }
  2113. bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
  2114. assert(MI.getOpcode() == TargetOpcode::G_SELECT);
  2115. // Match (cond ? x : x)
  2116. return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
  2117. canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
  2118. MRI);
  2119. }
  2120. bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
  2121. return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
  2122. canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
  2123. MRI);
  2124. }
  2125. bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
  2126. return matchConstantOp(MI.getOperand(OpIdx), 0) &&
  2127. canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
  2128. MRI);
  2129. }
  2130. bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
  2131. MachineOperand &MO = MI.getOperand(OpIdx);
  2132. return MO.isReg() &&
  2133. getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
  2134. }
  2135. bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
  2136. unsigned OpIdx) {
  2137. MachineOperand &MO = MI.getOperand(OpIdx);
  2138. return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
  2139. }
  2140. bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
  2141. assert(MI.getNumDefs() == 1 && "Expected only one def?");
  2142. Builder.setInstr(MI);
  2143. Builder.buildFConstant(MI.getOperand(0), C);
  2144. MI.eraseFromParent();
  2145. return true;
  2146. }
  2147. bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
  2148. assert(MI.getNumDefs() == 1 && "Expected only one def?");
  2149. Builder.setInstr(MI);
  2150. Builder.buildConstant(MI.getOperand(0), C);
  2151. MI.eraseFromParent();
  2152. return true;
  2153. }
  2154. bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) {
  2155. assert(MI.getNumDefs() == 1 && "Expected only one def?");
  2156. Builder.setInstr(MI);
  2157. Builder.buildConstant(MI.getOperand(0), C);
  2158. MI.eraseFromParent();
  2159. return true;
  2160. }
  2161. bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
  2162. assert(MI.getNumDefs() == 1 && "Expected only one def?");
  2163. Builder.setInstr(MI);
  2164. Builder.buildUndef(MI.getOperand(0));
  2165. MI.eraseFromParent();
  2166. return true;
  2167. }
  2168. bool CombinerHelper::matchSimplifyAddToSub(
  2169. MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
  2170. Register LHS = MI.getOperand(1).getReg();
  2171. Register RHS = MI.getOperand(2).getReg();
  2172. Register &NewLHS = std::get<0>(MatchInfo);
  2173. Register &NewRHS = std::get<1>(MatchInfo);
  2174. // Helper lambda to check for opportunities for
  2175. // ((0-A) + B) -> B - A
  2176. // (A + (0-B)) -> A - B
  2177. auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
  2178. if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
  2179. return false;
  2180. NewLHS = MaybeNewLHS;
  2181. return true;
  2182. };
  2183. return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
  2184. }
  2185. bool CombinerHelper::matchCombineInsertVecElts(
  2186. MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
  2187. assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
  2188. "Invalid opcode");
  2189. Register DstReg = MI.getOperand(0).getReg();
  2190. LLT DstTy = MRI.getType(DstReg);
  2191. assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
  2192. unsigned NumElts = DstTy.getNumElements();
  2193. // If this MI is part of a sequence of insert_vec_elts, then
  2194. // don't do the combine in the middle of the sequence.
  2195. if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
  2196. TargetOpcode::G_INSERT_VECTOR_ELT)
  2197. return false;
  2198. MachineInstr *CurrInst = &MI;
  2199. MachineInstr *TmpInst;
  2200. int64_t IntImm;
  2201. Register TmpReg;
  2202. MatchInfo.resize(NumElts);
  2203. while (mi_match(
  2204. CurrInst->getOperand(0).getReg(), MRI,
  2205. m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
  2206. if (IntImm >= NumElts)
  2207. return false;
  2208. if (!MatchInfo[IntImm])
  2209. MatchInfo[IntImm] = TmpReg;
  2210. CurrInst = TmpInst;
  2211. }
  2212. // Variable index.
  2213. if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
  2214. return false;
  2215. if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
  2216. for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
  2217. if (!MatchInfo[I - 1].isValid())
  2218. MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
  2219. }
  2220. return true;
  2221. }
  2222. // If we didn't end in a G_IMPLICIT_DEF, bail out.
  2223. return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
  2224. }
  2225. void CombinerHelper::applyCombineInsertVecElts(
  2226. MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
  2227. Builder.setInstr(MI);
  2228. Register UndefReg;
  2229. auto GetUndef = [&]() {
  2230. if (UndefReg)
  2231. return UndefReg;
  2232. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  2233. UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
  2234. return UndefReg;
  2235. };
  2236. for (unsigned I = 0; I < MatchInfo.size(); ++I) {
  2237. if (!MatchInfo[I])
  2238. MatchInfo[I] = GetUndef();
  2239. }
  2240. Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
  2241. MI.eraseFromParent();
  2242. }
  2243. void CombinerHelper::applySimplifyAddToSub(
  2244. MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
  2245. Builder.setInstr(MI);
  2246. Register SubLHS, SubRHS;
  2247. std::tie(SubLHS, SubRHS) = MatchInfo;
  2248. Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
  2249. MI.eraseFromParent();
  2250. }
  2251. bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
  2252. MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
  2253. // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
  2254. //
  2255. // Creates the new hand + logic instruction (but does not insert them.)
  2256. //
  2257. // On success, MatchInfo is populated with the new instructions. These are
  2258. // inserted in applyHoistLogicOpWithSameOpcodeHands.
  2259. unsigned LogicOpcode = MI.getOpcode();
  2260. assert(LogicOpcode == TargetOpcode::G_AND ||
  2261. LogicOpcode == TargetOpcode::G_OR ||
  2262. LogicOpcode == TargetOpcode::G_XOR);
  2263. MachineIRBuilder MIB(MI);
  2264. Register Dst = MI.getOperand(0).getReg();
  2265. Register LHSReg = MI.getOperand(1).getReg();
  2266. Register RHSReg = MI.getOperand(2).getReg();
  2267. // Don't recompute anything.
  2268. if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
  2269. return false;
  2270. // Make sure we have (hand x, ...), (hand y, ...)
  2271. MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
  2272. MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
  2273. if (!LeftHandInst || !RightHandInst)
  2274. return false;
  2275. unsigned HandOpcode = LeftHandInst->getOpcode();
  2276. if (HandOpcode != RightHandInst->getOpcode())
  2277. return false;
  2278. if (!LeftHandInst->getOperand(1).isReg() ||
  2279. !RightHandInst->getOperand(1).isReg())
  2280. return false;
  2281. // Make sure the types match up, and if we're doing this post-legalization,
  2282. // we end up with legal types.
  2283. Register X = LeftHandInst->getOperand(1).getReg();
  2284. Register Y = RightHandInst->getOperand(1).getReg();
  2285. LLT XTy = MRI.getType(X);
  2286. LLT YTy = MRI.getType(Y);
  2287. if (XTy != YTy)
  2288. return false;
  2289. if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
  2290. return false;
  2291. // Optional extra source register.
  2292. Register ExtraHandOpSrcReg;
  2293. switch (HandOpcode) {
  2294. default:
  2295. return false;
  2296. case TargetOpcode::G_ANYEXT:
  2297. case TargetOpcode::G_SEXT:
  2298. case TargetOpcode::G_ZEXT: {
  2299. // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
  2300. break;
  2301. }
  2302. case TargetOpcode::G_AND:
  2303. case TargetOpcode::G_ASHR:
  2304. case TargetOpcode::G_LSHR:
  2305. case TargetOpcode::G_SHL: {
  2306. // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
  2307. MachineOperand &ZOp = LeftHandInst->getOperand(2);
  2308. if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
  2309. return false;
  2310. ExtraHandOpSrcReg = ZOp.getReg();
  2311. break;
  2312. }
  2313. }
  2314. // Record the steps to build the new instructions.
  2315. //
  2316. // Steps to build (logic x, y)
  2317. auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
  2318. OperandBuildSteps LogicBuildSteps = {
  2319. [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
  2320. [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
  2321. [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
  2322. InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
  2323. // Steps to build hand (logic x, y), ...z
  2324. OperandBuildSteps HandBuildSteps = {
  2325. [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
  2326. [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
  2327. if (ExtraHandOpSrcReg.isValid())
  2328. HandBuildSteps.push_back(
  2329. [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
  2330. InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
  2331. MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
  2332. return true;
  2333. }
  2334. void CombinerHelper::applyBuildInstructionSteps(
  2335. MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
  2336. assert(MatchInfo.InstrsToBuild.size() &&
  2337. "Expected at least one instr to build?");
  2338. Builder.setInstr(MI);
  2339. for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
  2340. assert(InstrToBuild.Opcode && "Expected a valid opcode?");
  2341. assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
  2342. MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
  2343. for (auto &OperandFn : InstrToBuild.OperandFns)
  2344. OperandFn(Instr);
  2345. }
  2346. MI.eraseFromParent();
  2347. }
  2348. bool CombinerHelper::matchAshrShlToSextInreg(
  2349. MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
  2350. assert(MI.getOpcode() == TargetOpcode::G_ASHR);
  2351. int64_t ShlCst, AshrCst;
  2352. Register Src;
  2353. // FIXME: detect splat constant vectors.
  2354. if (!mi_match(MI.getOperand(0).getReg(), MRI,
  2355. m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst))))
  2356. return false;
  2357. if (ShlCst != AshrCst)
  2358. return false;
  2359. if (!isLegalOrBeforeLegalizer(
  2360. {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
  2361. return false;
  2362. MatchInfo = std::make_tuple(Src, ShlCst);
  2363. return true;
  2364. }
  2365. void CombinerHelper::applyAshShlToSextInreg(
  2366. MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
  2367. assert(MI.getOpcode() == TargetOpcode::G_ASHR);
  2368. Register Src;
  2369. int64_t ShiftAmt;
  2370. std::tie(Src, ShiftAmt) = MatchInfo;
  2371. unsigned Size = MRI.getType(Src).getScalarSizeInBits();
  2372. Builder.setInstrAndDebugLoc(MI);
  2373. Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
  2374. MI.eraseFromParent();
  2375. }
  2376. /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
  2377. bool CombinerHelper::matchOverlappingAnd(
  2378. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  2379. assert(MI.getOpcode() == TargetOpcode::G_AND);
  2380. Register Dst = MI.getOperand(0).getReg();
  2381. LLT Ty = MRI.getType(Dst);
  2382. Register R;
  2383. int64_t C1;
  2384. int64_t C2;
  2385. if (!mi_match(
  2386. Dst, MRI,
  2387. m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
  2388. return false;
  2389. MatchInfo = [=](MachineIRBuilder &B) {
  2390. if (C1 & C2) {
  2391. B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
  2392. return;
  2393. }
  2394. auto Zero = B.buildConstant(Ty, 0);
  2395. replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
  2396. };
  2397. return true;
  2398. }
  2399. bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
  2400. Register &Replacement) {
  2401. // Given
  2402. //
  2403. // %y:_(sN) = G_SOMETHING
  2404. // %x:_(sN) = G_SOMETHING
  2405. // %res:_(sN) = G_AND %x, %y
  2406. //
  2407. // Eliminate the G_AND when it is known that x & y == x or x & y == y.
  2408. //
  2409. // Patterns like this can appear as a result of legalization. E.g.
  2410. //
  2411. // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
  2412. // %one:_(s32) = G_CONSTANT i32 1
  2413. // %and:_(s32) = G_AND %cmp, %one
  2414. //
  2415. // In this case, G_ICMP only produces a single bit, so x & 1 == x.
  2416. assert(MI.getOpcode() == TargetOpcode::G_AND);
  2417. if (!KB)
  2418. return false;
  2419. Register AndDst = MI.getOperand(0).getReg();
  2420. LLT DstTy = MRI.getType(AndDst);
  2421. // FIXME: This should be removed once GISelKnownBits supports vectors.
  2422. if (DstTy.isVector())
  2423. return false;
  2424. Register LHS = MI.getOperand(1).getReg();
  2425. Register RHS = MI.getOperand(2).getReg();
  2426. KnownBits LHSBits = KB->getKnownBits(LHS);
  2427. KnownBits RHSBits = KB->getKnownBits(RHS);
  2428. // Check that x & Mask == x.
  2429. // x & 1 == x, always
  2430. // x & 0 == x, only if x is also 0
  2431. // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
  2432. //
  2433. // Check if we can replace AndDst with the LHS of the G_AND
  2434. if (canReplaceReg(AndDst, LHS, MRI) &&
  2435. (LHSBits.Zero | RHSBits.One).isAllOnes()) {
  2436. Replacement = LHS;
  2437. return true;
  2438. }
  2439. // Check if we can replace AndDst with the RHS of the G_AND
  2440. if (canReplaceReg(AndDst, RHS, MRI) &&
  2441. (LHSBits.One | RHSBits.Zero).isAllOnes()) {
  2442. Replacement = RHS;
  2443. return true;
  2444. }
  2445. return false;
  2446. }
  2447. bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
  2448. // Given
  2449. //
  2450. // %y:_(sN) = G_SOMETHING
  2451. // %x:_(sN) = G_SOMETHING
  2452. // %res:_(sN) = G_OR %x, %y
  2453. //
  2454. // Eliminate the G_OR when it is known that x | y == x or x | y == y.
  2455. assert(MI.getOpcode() == TargetOpcode::G_OR);
  2456. if (!KB)
  2457. return false;
  2458. Register OrDst = MI.getOperand(0).getReg();
  2459. LLT DstTy = MRI.getType(OrDst);
  2460. // FIXME: This should be removed once GISelKnownBits supports vectors.
  2461. if (DstTy.isVector())
  2462. return false;
  2463. Register LHS = MI.getOperand(1).getReg();
  2464. Register RHS = MI.getOperand(2).getReg();
  2465. KnownBits LHSBits = KB->getKnownBits(LHS);
  2466. KnownBits RHSBits = KB->getKnownBits(RHS);
  2467. // Check that x | Mask == x.
  2468. // x | 0 == x, always
  2469. // x | 1 == x, only if x is also 1
  2470. // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
  2471. //
  2472. // Check if we can replace OrDst with the LHS of the G_OR
  2473. if (canReplaceReg(OrDst, LHS, MRI) &&
  2474. (LHSBits.One | RHSBits.Zero).isAllOnes()) {
  2475. Replacement = LHS;
  2476. return true;
  2477. }
  2478. // Check if we can replace OrDst with the RHS of the G_OR
  2479. if (canReplaceReg(OrDst, RHS, MRI) &&
  2480. (LHSBits.Zero | RHSBits.One).isAllOnes()) {
  2481. Replacement = RHS;
  2482. return true;
  2483. }
  2484. return false;
  2485. }
  2486. bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
  2487. // If the input is already sign extended, just drop the extension.
  2488. Register Src = MI.getOperand(1).getReg();
  2489. unsigned ExtBits = MI.getOperand(2).getImm();
  2490. unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
  2491. return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
  2492. }
  2493. static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
  2494. int64_t Cst, bool IsVector, bool IsFP) {
  2495. // For i1, Cst will always be -1 regardless of boolean contents.
  2496. return (ScalarSizeBits == 1 && Cst == -1) ||
  2497. isConstTrueVal(TLI, Cst, IsVector, IsFP);
  2498. }
  2499. bool CombinerHelper::matchNotCmp(MachineInstr &MI,
  2500. SmallVectorImpl<Register> &RegsToNegate) {
  2501. assert(MI.getOpcode() == TargetOpcode::G_XOR);
  2502. LLT Ty = MRI.getType(MI.getOperand(0).getReg());
  2503. const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
  2504. Register XorSrc;
  2505. Register CstReg;
  2506. // We match xor(src, true) here.
  2507. if (!mi_match(MI.getOperand(0).getReg(), MRI,
  2508. m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
  2509. return false;
  2510. if (!MRI.hasOneNonDBGUse(XorSrc))
  2511. return false;
  2512. // Check that XorSrc is the root of a tree of comparisons combined with ANDs
  2513. // and ORs. The suffix of RegsToNegate starting from index I is used a work
  2514. // list of tree nodes to visit.
  2515. RegsToNegate.push_back(XorSrc);
  2516. // Remember whether the comparisons are all integer or all floating point.
  2517. bool IsInt = false;
  2518. bool IsFP = false;
  2519. for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
  2520. Register Reg = RegsToNegate[I];
  2521. if (!MRI.hasOneNonDBGUse(Reg))
  2522. return false;
  2523. MachineInstr *Def = MRI.getVRegDef(Reg);
  2524. switch (Def->getOpcode()) {
  2525. default:
  2526. // Don't match if the tree contains anything other than ANDs, ORs and
  2527. // comparisons.
  2528. return false;
  2529. case TargetOpcode::G_ICMP:
  2530. if (IsFP)
  2531. return false;
  2532. IsInt = true;
  2533. // When we apply the combine we will invert the predicate.
  2534. break;
  2535. case TargetOpcode::G_FCMP:
  2536. if (IsInt)
  2537. return false;
  2538. IsFP = true;
  2539. // When we apply the combine we will invert the predicate.
  2540. break;
  2541. case TargetOpcode::G_AND:
  2542. case TargetOpcode::G_OR:
  2543. // Implement De Morgan's laws:
  2544. // ~(x & y) -> ~x | ~y
  2545. // ~(x | y) -> ~x & ~y
  2546. // When we apply the combine we will change the opcode and recursively
  2547. // negate the operands.
  2548. RegsToNegate.push_back(Def->getOperand(1).getReg());
  2549. RegsToNegate.push_back(Def->getOperand(2).getReg());
  2550. break;
  2551. }
  2552. }
  2553. // Now we know whether the comparisons are integer or floating point, check
  2554. // the constant in the xor.
  2555. int64_t Cst;
  2556. if (Ty.isVector()) {
  2557. MachineInstr *CstDef = MRI.getVRegDef(CstReg);
  2558. auto MaybeCst = getBuildVectorConstantSplat(*CstDef, MRI);
  2559. if (!MaybeCst)
  2560. return false;
  2561. if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
  2562. return false;
  2563. } else {
  2564. if (!mi_match(CstReg, MRI, m_ICst(Cst)))
  2565. return false;
  2566. if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
  2567. return false;
  2568. }
  2569. return true;
  2570. }
  2571. void CombinerHelper::applyNotCmp(MachineInstr &MI,
  2572. SmallVectorImpl<Register> &RegsToNegate) {
  2573. for (Register Reg : RegsToNegate) {
  2574. MachineInstr *Def = MRI.getVRegDef(Reg);
  2575. Observer.changingInstr(*Def);
  2576. // For each comparison, invert the opcode. For each AND and OR, change the
  2577. // opcode.
  2578. switch (Def->getOpcode()) {
  2579. default:
  2580. llvm_unreachable("Unexpected opcode");
  2581. case TargetOpcode::G_ICMP:
  2582. case TargetOpcode::G_FCMP: {
  2583. MachineOperand &PredOp = Def->getOperand(1);
  2584. CmpInst::Predicate NewP = CmpInst::getInversePredicate(
  2585. (CmpInst::Predicate)PredOp.getPredicate());
  2586. PredOp.setPredicate(NewP);
  2587. break;
  2588. }
  2589. case TargetOpcode::G_AND:
  2590. Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
  2591. break;
  2592. case TargetOpcode::G_OR:
  2593. Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
  2594. break;
  2595. }
  2596. Observer.changedInstr(*Def);
  2597. }
  2598. replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
  2599. MI.eraseFromParent();
  2600. }
  2601. bool CombinerHelper::matchXorOfAndWithSameReg(
  2602. MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
  2603. // Match (xor (and x, y), y) (or any of its commuted cases)
  2604. assert(MI.getOpcode() == TargetOpcode::G_XOR);
  2605. Register &X = MatchInfo.first;
  2606. Register &Y = MatchInfo.second;
  2607. Register AndReg = MI.getOperand(1).getReg();
  2608. Register SharedReg = MI.getOperand(2).getReg();
  2609. // Find a G_AND on either side of the G_XOR.
  2610. // Look for one of
  2611. //
  2612. // (xor (and x, y), SharedReg)
  2613. // (xor SharedReg, (and x, y))
  2614. if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
  2615. std::swap(AndReg, SharedReg);
  2616. if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
  2617. return false;
  2618. }
  2619. // Only do this if we'll eliminate the G_AND.
  2620. if (!MRI.hasOneNonDBGUse(AndReg))
  2621. return false;
  2622. // We can combine if SharedReg is the same as either the LHS or RHS of the
  2623. // G_AND.
  2624. if (Y != SharedReg)
  2625. std::swap(X, Y);
  2626. return Y == SharedReg;
  2627. }
  2628. void CombinerHelper::applyXorOfAndWithSameReg(
  2629. MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
  2630. // Fold (xor (and x, y), y) -> (and (not x), y)
  2631. Builder.setInstrAndDebugLoc(MI);
  2632. Register X, Y;
  2633. std::tie(X, Y) = MatchInfo;
  2634. auto Not = Builder.buildNot(MRI.getType(X), X);
  2635. Observer.changingInstr(MI);
  2636. MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
  2637. MI.getOperand(1).setReg(Not->getOperand(0).getReg());
  2638. MI.getOperand(2).setReg(Y);
  2639. Observer.changedInstr(MI);
  2640. }
  2641. bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
  2642. auto &PtrAdd = cast<GPtrAdd>(MI);
  2643. Register DstReg = PtrAdd.getReg(0);
  2644. LLT Ty = MRI.getType(DstReg);
  2645. const DataLayout &DL = Builder.getMF().getDataLayout();
  2646. if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
  2647. return false;
  2648. if (Ty.isPointer()) {
  2649. auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI);
  2650. return ConstVal && *ConstVal == 0;
  2651. }
  2652. assert(Ty.isVector() && "Expecting a vector type");
  2653. const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg());
  2654. return isBuildVectorAllZeros(*VecMI, MRI);
  2655. }
  2656. void CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
  2657. auto &PtrAdd = cast<GPtrAdd>(MI);
  2658. Builder.setInstrAndDebugLoc(PtrAdd);
  2659. Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg());
  2660. PtrAdd.eraseFromParent();
  2661. }
  2662. /// The second source operand is known to be a power of 2.
  2663. void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
  2664. Register DstReg = MI.getOperand(0).getReg();
  2665. Register Src0 = MI.getOperand(1).getReg();
  2666. Register Pow2Src1 = MI.getOperand(2).getReg();
  2667. LLT Ty = MRI.getType(DstReg);
  2668. Builder.setInstrAndDebugLoc(MI);
  2669. // Fold (urem x, pow2) -> (and x, pow2-1)
  2670. auto NegOne = Builder.buildConstant(Ty, -1);
  2671. auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
  2672. Builder.buildAnd(DstReg, Src0, Add);
  2673. MI.eraseFromParent();
  2674. }
  2675. Optional<SmallVector<Register, 8>>
  2676. CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
  2677. assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
  2678. // We want to detect if Root is part of a tree which represents a bunch
  2679. // of loads being merged into a larger load. We'll try to recognize patterns
  2680. // like, for example:
  2681. //
  2682. // Reg Reg
  2683. // \ /
  2684. // OR_1 Reg
  2685. // \ /
  2686. // OR_2
  2687. // \ Reg
  2688. // .. /
  2689. // Root
  2690. //
  2691. // Reg Reg Reg Reg
  2692. // \ / \ /
  2693. // OR_1 OR_2
  2694. // \ /
  2695. // \ /
  2696. // ...
  2697. // Root
  2698. //
  2699. // Each "Reg" may have been produced by a load + some arithmetic. This
  2700. // function will save each of them.
  2701. SmallVector<Register, 8> RegsToVisit;
  2702. SmallVector<const MachineInstr *, 7> Ors = {Root};
  2703. // In the "worst" case, we're dealing with a load for each byte. So, there
  2704. // are at most #bytes - 1 ORs.
  2705. const unsigned MaxIter =
  2706. MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
  2707. for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
  2708. if (Ors.empty())
  2709. break;
  2710. const MachineInstr *Curr = Ors.pop_back_val();
  2711. Register OrLHS = Curr->getOperand(1).getReg();
  2712. Register OrRHS = Curr->getOperand(2).getReg();
  2713. // In the combine, we want to elimate the entire tree.
  2714. if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
  2715. return None;
  2716. // If it's a G_OR, save it and continue to walk. If it's not, then it's
  2717. // something that may be a load + arithmetic.
  2718. if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
  2719. Ors.push_back(Or);
  2720. else
  2721. RegsToVisit.push_back(OrLHS);
  2722. if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
  2723. Ors.push_back(Or);
  2724. else
  2725. RegsToVisit.push_back(OrRHS);
  2726. }
  2727. // We're going to try and merge each register into a wider power-of-2 type,
  2728. // so we ought to have an even number of registers.
  2729. if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
  2730. return None;
  2731. return RegsToVisit;
  2732. }
  2733. /// Helper function for findLoadOffsetsForLoadOrCombine.
  2734. ///
  2735. /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
  2736. /// and then moving that value into a specific byte offset.
  2737. ///
  2738. /// e.g. x[i] << 24
  2739. ///
  2740. /// \returns The load instruction and the byte offset it is moved into.
  2741. static Optional<std::pair<GZExtLoad *, int64_t>>
  2742. matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
  2743. const MachineRegisterInfo &MRI) {
  2744. assert(MRI.hasOneNonDBGUse(Reg) &&
  2745. "Expected Reg to only have one non-debug use?");
  2746. Register MaybeLoad;
  2747. int64_t Shift;
  2748. if (!mi_match(Reg, MRI,
  2749. m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
  2750. Shift = 0;
  2751. MaybeLoad = Reg;
  2752. }
  2753. if (Shift % MemSizeInBits != 0)
  2754. return None;
  2755. // TODO: Handle other types of loads.
  2756. auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
  2757. if (!Load)
  2758. return None;
  2759. if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
  2760. return None;
  2761. return std::make_pair(Load, Shift / MemSizeInBits);
  2762. }
  2763. Optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
  2764. CombinerHelper::findLoadOffsetsForLoadOrCombine(
  2765. SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
  2766. const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
  2767. // Each load found for the pattern. There should be one for each RegsToVisit.
  2768. SmallSetVector<const MachineInstr *, 8> Loads;
  2769. // The lowest index used in any load. (The lowest "i" for each x[i].)
  2770. int64_t LowestIdx = INT64_MAX;
  2771. // The load which uses the lowest index.
  2772. GZExtLoad *LowestIdxLoad = nullptr;
  2773. // Keeps track of the load indices we see. We shouldn't see any indices twice.
  2774. SmallSet<int64_t, 8> SeenIdx;
  2775. // Ensure each load is in the same MBB.
  2776. // TODO: Support multiple MachineBasicBlocks.
  2777. MachineBasicBlock *MBB = nullptr;
  2778. const MachineMemOperand *MMO = nullptr;
  2779. // Earliest instruction-order load in the pattern.
  2780. GZExtLoad *EarliestLoad = nullptr;
  2781. // Latest instruction-order load in the pattern.
  2782. GZExtLoad *LatestLoad = nullptr;
  2783. // Base pointer which every load should share.
  2784. Register BasePtr;
  2785. // We want to find a load for each register. Each load should have some
  2786. // appropriate bit twiddling arithmetic. During this loop, we will also keep
  2787. // track of the load which uses the lowest index. Later, we will check if we
  2788. // can use its pointer in the final, combined load.
  2789. for (auto Reg : RegsToVisit) {
  2790. // Find the load, and find the position that it will end up in (e.g. a
  2791. // shifted) value.
  2792. auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
  2793. if (!LoadAndPos)
  2794. return None;
  2795. GZExtLoad *Load;
  2796. int64_t DstPos;
  2797. std::tie(Load, DstPos) = *LoadAndPos;
  2798. // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
  2799. // it is difficult to check for stores/calls/etc between loads.
  2800. MachineBasicBlock *LoadMBB = Load->getParent();
  2801. if (!MBB)
  2802. MBB = LoadMBB;
  2803. if (LoadMBB != MBB)
  2804. return None;
  2805. // Make sure that the MachineMemOperands of every seen load are compatible.
  2806. auto &LoadMMO = Load->getMMO();
  2807. if (!MMO)
  2808. MMO = &LoadMMO;
  2809. if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
  2810. return None;
  2811. // Find out what the base pointer and index for the load is.
  2812. Register LoadPtr;
  2813. int64_t Idx;
  2814. if (!mi_match(Load->getOperand(1).getReg(), MRI,
  2815. m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
  2816. LoadPtr = Load->getOperand(1).getReg();
  2817. Idx = 0;
  2818. }
  2819. // Don't combine things like a[i], a[i] -> a bigger load.
  2820. if (!SeenIdx.insert(Idx).second)
  2821. return None;
  2822. // Every load must share the same base pointer; don't combine things like:
  2823. //
  2824. // a[i], b[i + 1] -> a bigger load.
  2825. if (!BasePtr.isValid())
  2826. BasePtr = LoadPtr;
  2827. if (BasePtr != LoadPtr)
  2828. return None;
  2829. if (Idx < LowestIdx) {
  2830. LowestIdx = Idx;
  2831. LowestIdxLoad = Load;
  2832. }
  2833. // Keep track of the byte offset that this load ends up at. If we have seen
  2834. // the byte offset, then stop here. We do not want to combine:
  2835. //
  2836. // a[i] << 16, a[i + k] << 16 -> a bigger load.
  2837. if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
  2838. return None;
  2839. Loads.insert(Load);
  2840. // Keep track of the position of the earliest/latest loads in the pattern.
  2841. // We will check that there are no load fold barriers between them later
  2842. // on.
  2843. //
  2844. // FIXME: Is there a better way to check for load fold barriers?
  2845. if (!EarliestLoad || dominates(*Load, *EarliestLoad))
  2846. EarliestLoad = Load;
  2847. if (!LatestLoad || dominates(*LatestLoad, *Load))
  2848. LatestLoad = Load;
  2849. }
  2850. // We found a load for each register. Let's check if each load satisfies the
  2851. // pattern.
  2852. assert(Loads.size() == RegsToVisit.size() &&
  2853. "Expected to find a load for each register?");
  2854. assert(EarliestLoad != LatestLoad && EarliestLoad &&
  2855. LatestLoad && "Expected at least two loads?");
  2856. // Check if there are any stores, calls, etc. between any of the loads. If
  2857. // there are, then we can't safely perform the combine.
  2858. //
  2859. // MaxIter is chosen based off the (worst case) number of iterations it
  2860. // typically takes to succeed in the LLVM test suite plus some padding.
  2861. //
  2862. // FIXME: Is there a better way to check for load fold barriers?
  2863. const unsigned MaxIter = 20;
  2864. unsigned Iter = 0;
  2865. for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
  2866. LatestLoad->getIterator())) {
  2867. if (Loads.count(&MI))
  2868. continue;
  2869. if (MI.isLoadFoldBarrier())
  2870. return None;
  2871. if (Iter++ == MaxIter)
  2872. return None;
  2873. }
  2874. return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
  2875. }
  2876. bool CombinerHelper::matchLoadOrCombine(
  2877. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  2878. assert(MI.getOpcode() == TargetOpcode::G_OR);
  2879. MachineFunction &MF = *MI.getMF();
  2880. // Assuming a little-endian target, transform:
  2881. // s8 *a = ...
  2882. // s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
  2883. // =>
  2884. // s32 val = *((i32)a)
  2885. //
  2886. // s8 *a = ...
  2887. // s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
  2888. // =>
  2889. // s32 val = BSWAP(*((s32)a))
  2890. Register Dst = MI.getOperand(0).getReg();
  2891. LLT Ty = MRI.getType(Dst);
  2892. if (Ty.isVector())
  2893. return false;
  2894. // We need to combine at least two loads into this type. Since the smallest
  2895. // possible load is into a byte, we need at least a 16-bit wide type.
  2896. const unsigned WideMemSizeInBits = Ty.getSizeInBits();
  2897. if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
  2898. return false;
  2899. // Match a collection of non-OR instructions in the pattern.
  2900. auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
  2901. if (!RegsToVisit)
  2902. return false;
  2903. // We have a collection of non-OR instructions. Figure out how wide each of
  2904. // the small loads should be based off of the number of potential loads we
  2905. // found.
  2906. const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
  2907. if (NarrowMemSizeInBits % 8 != 0)
  2908. return false;
  2909. // Check if each register feeding into each OR is a load from the same
  2910. // base pointer + some arithmetic.
  2911. //
  2912. // e.g. a[0], a[1] << 8, a[2] << 16, etc.
  2913. //
  2914. // Also verify that each of these ends up putting a[i] into the same memory
  2915. // offset as a load into a wide type would.
  2916. SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
  2917. GZExtLoad *LowestIdxLoad, *LatestLoad;
  2918. int64_t LowestIdx;
  2919. auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
  2920. MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
  2921. if (!MaybeLoadInfo)
  2922. return false;
  2923. std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
  2924. // We have a bunch of loads being OR'd together. Using the addresses + offsets
  2925. // we found before, check if this corresponds to a big or little endian byte
  2926. // pattern. If it does, then we can represent it using a load + possibly a
  2927. // BSWAP.
  2928. bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
  2929. Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
  2930. if (!IsBigEndian.hasValue())
  2931. return false;
  2932. bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
  2933. if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
  2934. return false;
  2935. // Make sure that the load from the lowest index produces offset 0 in the
  2936. // final value.
  2937. //
  2938. // This ensures that we won't combine something like this:
  2939. //
  2940. // load x[i] -> byte 2
  2941. // load x[i+1] -> byte 0 ---> wide_load x[i]
  2942. // load x[i+2] -> byte 1
  2943. const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
  2944. const unsigned ZeroByteOffset =
  2945. *IsBigEndian
  2946. ? bigEndianByteAt(NumLoadsInTy, 0)
  2947. : littleEndianByteAt(NumLoadsInTy, 0);
  2948. auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
  2949. if (ZeroOffsetIdx == MemOffset2Idx.end() ||
  2950. ZeroOffsetIdx->second != LowestIdx)
  2951. return false;
  2952. // We wil reuse the pointer from the load which ends up at byte offset 0. It
  2953. // may not use index 0.
  2954. Register Ptr = LowestIdxLoad->getPointerReg();
  2955. const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
  2956. LegalityQuery::MemDesc MMDesc(MMO);
  2957. MMDesc.MemoryTy = Ty;
  2958. if (!isLegalOrBeforeLegalizer(
  2959. {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
  2960. return false;
  2961. auto PtrInfo = MMO.getPointerInfo();
  2962. auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
  2963. // Load must be allowed and fast on the target.
  2964. LLVMContext &C = MF.getFunction().getContext();
  2965. auto &DL = MF.getDataLayout();
  2966. bool Fast = false;
  2967. if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
  2968. !Fast)
  2969. return false;
  2970. MatchInfo = [=](MachineIRBuilder &MIB) {
  2971. MIB.setInstrAndDebugLoc(*LatestLoad);
  2972. Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
  2973. MIB.buildLoad(LoadDst, Ptr, *NewMMO);
  2974. if (NeedsBSwap)
  2975. MIB.buildBSwap(Dst, LoadDst);
  2976. };
  2977. return true;
  2978. }
  2979. /// Check if the store \p Store is a truncstore that can be merged. That is,
  2980. /// it's a store of a shifted value of \p SrcVal. If \p SrcVal is an empty
  2981. /// Register then it does not need to match and SrcVal is set to the source
  2982. /// value found.
  2983. /// On match, returns the start byte offset of the \p SrcVal that is being
  2984. /// stored.
  2985. static Optional<int64_t> getTruncStoreByteOffset(GStore &Store, Register &SrcVal,
  2986. MachineRegisterInfo &MRI) {
  2987. Register TruncVal;
  2988. if (!mi_match(Store.getValueReg(), MRI, m_GTrunc(m_Reg(TruncVal))))
  2989. return None;
  2990. // The shift amount must be a constant multiple of the narrow type.
  2991. // It is translated to the offset address in the wide source value "y".
  2992. //
  2993. // x = G_LSHR y, ShiftAmtC
  2994. // s8 z = G_TRUNC x
  2995. // store z, ...
  2996. Register FoundSrcVal;
  2997. int64_t ShiftAmt;
  2998. if (!mi_match(TruncVal, MRI,
  2999. m_any_of(m_GLShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt)),
  3000. m_GAShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt))))) {
  3001. if (!SrcVal.isValid() || TruncVal == SrcVal) {
  3002. if (!SrcVal.isValid())
  3003. SrcVal = TruncVal;
  3004. return 0; // If it's the lowest index store.
  3005. }
  3006. return None;
  3007. }
  3008. unsigned NarrowBits = Store.getMMO().getMemoryType().getScalarSizeInBits();
  3009. if (ShiftAmt % NarrowBits!= 0)
  3010. return None;
  3011. const unsigned Offset = ShiftAmt / NarrowBits;
  3012. if (SrcVal.isValid() && FoundSrcVal != SrcVal)
  3013. return None;
  3014. if (!SrcVal.isValid())
  3015. SrcVal = FoundSrcVal;
  3016. else if (MRI.getType(SrcVal) != MRI.getType(FoundSrcVal))
  3017. return None;
  3018. return Offset;
  3019. }
  3020. /// Match a pattern where a wide type scalar value is stored by several narrow
  3021. /// stores. Fold it into a single store or a BSWAP and a store if the targets
  3022. /// supports it.
  3023. ///
  3024. /// Assuming little endian target:
  3025. /// i8 *p = ...
  3026. /// i32 val = ...
  3027. /// p[0] = (val >> 0) & 0xFF;
  3028. /// p[1] = (val >> 8) & 0xFF;
  3029. /// p[2] = (val >> 16) & 0xFF;
  3030. /// p[3] = (val >> 24) & 0xFF;
  3031. /// =>
  3032. /// *((i32)p) = val;
  3033. ///
  3034. /// i8 *p = ...
  3035. /// i32 val = ...
  3036. /// p[0] = (val >> 24) & 0xFF;
  3037. /// p[1] = (val >> 16) & 0xFF;
  3038. /// p[2] = (val >> 8) & 0xFF;
  3039. /// p[3] = (val >> 0) & 0xFF;
  3040. /// =>
  3041. /// *((i32)p) = BSWAP(val);
  3042. bool CombinerHelper::matchTruncStoreMerge(MachineInstr &MI,
  3043. MergeTruncStoresInfo &MatchInfo) {
  3044. auto &StoreMI = cast<GStore>(MI);
  3045. LLT MemTy = StoreMI.getMMO().getMemoryType();
  3046. // We only handle merging simple stores of 1-4 bytes.
  3047. if (!MemTy.isScalar())
  3048. return false;
  3049. switch (MemTy.getSizeInBits()) {
  3050. case 8:
  3051. case 16:
  3052. case 32:
  3053. break;
  3054. default:
  3055. return false;
  3056. }
  3057. if (!StoreMI.isSimple())
  3058. return false;
  3059. // We do a simple search for mergeable stores prior to this one.
  3060. // Any potential alias hazard along the way terminates the search.
  3061. SmallVector<GStore *> FoundStores;
  3062. // We're looking for:
  3063. // 1) a (store(trunc(...)))
  3064. // 2) of an LSHR/ASHR of a single wide value, by the appropriate shift to get
  3065. // the partial value stored.
  3066. // 3) where the offsets form either a little or big-endian sequence.
  3067. auto &LastStore = StoreMI;
  3068. // The single base pointer that all stores must use.
  3069. Register BaseReg;
  3070. int64_t LastOffset;
  3071. if (!mi_match(LastStore.getPointerReg(), MRI,
  3072. m_GPtrAdd(m_Reg(BaseReg), m_ICst(LastOffset)))) {
  3073. BaseReg = LastStore.getPointerReg();
  3074. LastOffset = 0;
  3075. }
  3076. GStore *LowestIdxStore = &LastStore;
  3077. int64_t LowestIdxOffset = LastOffset;
  3078. Register WideSrcVal;
  3079. auto LowestShiftAmt = getTruncStoreByteOffset(LastStore, WideSrcVal, MRI);
  3080. if (!LowestShiftAmt)
  3081. return false; // Didn't match a trunc.
  3082. assert(WideSrcVal.isValid());
  3083. LLT WideStoreTy = MRI.getType(WideSrcVal);
  3084. // The wide type might not be a multiple of the memory type, e.g. s48 and s32.
  3085. if (WideStoreTy.getSizeInBits() % MemTy.getSizeInBits() != 0)
  3086. return false;
  3087. const unsigned NumStoresRequired =
  3088. WideStoreTy.getSizeInBits() / MemTy.getSizeInBits();
  3089. SmallVector<int64_t, 8> OffsetMap(NumStoresRequired, INT64_MAX);
  3090. OffsetMap[*LowestShiftAmt] = LastOffset;
  3091. FoundStores.emplace_back(&LastStore);
  3092. // Search the block up for more stores.
  3093. // We use a search threshold of 10 instructions here because the combiner
  3094. // works top-down within a block, and we don't want to search an unbounded
  3095. // number of predecessor instructions trying to find matching stores.
  3096. // If we moved this optimization into a separate pass then we could probably
  3097. // use a more efficient search without having a hard-coded threshold.
  3098. const int MaxInstsToCheck = 10;
  3099. int NumInstsChecked = 0;
  3100. for (auto II = ++LastStore.getReverseIterator();
  3101. II != LastStore.getParent()->rend() && NumInstsChecked < MaxInstsToCheck;
  3102. ++II) {
  3103. NumInstsChecked++;
  3104. GStore *NewStore;
  3105. if ((NewStore = dyn_cast<GStore>(&*II))) {
  3106. if (NewStore->getMMO().getMemoryType() != MemTy || !NewStore->isSimple())
  3107. break;
  3108. } else if (II->isLoadFoldBarrier() || II->mayLoad()) {
  3109. break;
  3110. } else {
  3111. continue; // This is a safe instruction we can look past.
  3112. }
  3113. Register NewBaseReg;
  3114. int64_t MemOffset;
  3115. // Check we're storing to the same base + some offset.
  3116. if (!mi_match(NewStore->getPointerReg(), MRI,
  3117. m_GPtrAdd(m_Reg(NewBaseReg), m_ICst(MemOffset)))) {
  3118. NewBaseReg = NewStore->getPointerReg();
  3119. MemOffset = 0;
  3120. }
  3121. if (BaseReg != NewBaseReg)
  3122. break;
  3123. auto ShiftByteOffset = getTruncStoreByteOffset(*NewStore, WideSrcVal, MRI);
  3124. if (!ShiftByteOffset)
  3125. break;
  3126. if (MemOffset < LowestIdxOffset) {
  3127. LowestIdxOffset = MemOffset;
  3128. LowestIdxStore = NewStore;
  3129. }
  3130. // Map the offset in the store and the offset in the combined value, and
  3131. // early return if it has been set before.
  3132. if (*ShiftByteOffset < 0 || *ShiftByteOffset >= NumStoresRequired ||
  3133. OffsetMap[*ShiftByteOffset] != INT64_MAX)
  3134. break;
  3135. OffsetMap[*ShiftByteOffset] = MemOffset;
  3136. FoundStores.emplace_back(NewStore);
  3137. // Reset counter since we've found a matching inst.
  3138. NumInstsChecked = 0;
  3139. if (FoundStores.size() == NumStoresRequired)
  3140. break;
  3141. }
  3142. if (FoundStores.size() != NumStoresRequired) {
  3143. return false;
  3144. }
  3145. const auto &DL = LastStore.getMF()->getDataLayout();
  3146. auto &C = LastStore.getMF()->getFunction().getContext();
  3147. // Check that a store of the wide type is both allowed and fast on the target
  3148. bool Fast = false;
  3149. bool Allowed = getTargetLowering().allowsMemoryAccess(
  3150. C, DL, WideStoreTy, LowestIdxStore->getMMO(), &Fast);
  3151. if (!Allowed || !Fast)
  3152. return false;
  3153. // Check if the pieces of the value are going to the expected places in memory
  3154. // to merge the stores.
  3155. unsigned NarrowBits = MemTy.getScalarSizeInBits();
  3156. auto checkOffsets = [&](bool MatchLittleEndian) {
  3157. if (MatchLittleEndian) {
  3158. for (unsigned i = 0; i != NumStoresRequired; ++i)
  3159. if (OffsetMap[i] != i * (NarrowBits / 8) + LowestIdxOffset)
  3160. return false;
  3161. } else { // MatchBigEndian by reversing loop counter.
  3162. for (unsigned i = 0, j = NumStoresRequired - 1; i != NumStoresRequired;
  3163. ++i, --j)
  3164. if (OffsetMap[j] != i * (NarrowBits / 8) + LowestIdxOffset)
  3165. return false;
  3166. }
  3167. return true;
  3168. };
  3169. // Check if the offsets line up for the native data layout of this target.
  3170. bool NeedBswap = false;
  3171. bool NeedRotate = false;
  3172. if (!checkOffsets(DL.isLittleEndian())) {
  3173. // Special-case: check if byte offsets line up for the opposite endian.
  3174. if (NarrowBits == 8 && checkOffsets(DL.isBigEndian()))
  3175. NeedBswap = true;
  3176. else if (NumStoresRequired == 2 && checkOffsets(DL.isBigEndian()))
  3177. NeedRotate = true;
  3178. else
  3179. return false;
  3180. }
  3181. if (NeedBswap &&
  3182. !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {WideStoreTy}}))
  3183. return false;
  3184. if (NeedRotate &&
  3185. !isLegalOrBeforeLegalizer({TargetOpcode::G_ROTR, {WideStoreTy}}))
  3186. return false;
  3187. MatchInfo.NeedBSwap = NeedBswap;
  3188. MatchInfo.NeedRotate = NeedRotate;
  3189. MatchInfo.LowestIdxStore = LowestIdxStore;
  3190. MatchInfo.WideSrcVal = WideSrcVal;
  3191. MatchInfo.FoundStores = std::move(FoundStores);
  3192. return true;
  3193. }
  3194. void CombinerHelper::applyTruncStoreMerge(MachineInstr &MI,
  3195. MergeTruncStoresInfo &MatchInfo) {
  3196. Builder.setInstrAndDebugLoc(MI);
  3197. Register WideSrcVal = MatchInfo.WideSrcVal;
  3198. LLT WideStoreTy = MRI.getType(WideSrcVal);
  3199. if (MatchInfo.NeedBSwap) {
  3200. WideSrcVal = Builder.buildBSwap(WideStoreTy, WideSrcVal).getReg(0);
  3201. } else if (MatchInfo.NeedRotate) {
  3202. assert(WideStoreTy.getSizeInBits() % 2 == 0 &&
  3203. "Unexpected type for rotate");
  3204. auto RotAmt =
  3205. Builder.buildConstant(WideStoreTy, WideStoreTy.getSizeInBits() / 2);
  3206. WideSrcVal =
  3207. Builder.buildRotateRight(WideStoreTy, WideSrcVal, RotAmt).getReg(0);
  3208. }
  3209. Builder.buildStore(WideSrcVal, MatchInfo.LowestIdxStore->getPointerReg(),
  3210. MatchInfo.LowestIdxStore->getMMO().getPointerInfo(),
  3211. MatchInfo.LowestIdxStore->getMMO().getAlign());
  3212. // Erase the old stores.
  3213. for (auto *ST : MatchInfo.FoundStores)
  3214. ST->eraseFromParent();
  3215. }
  3216. bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
  3217. MachineInstr *&ExtMI) {
  3218. assert(MI.getOpcode() == TargetOpcode::G_PHI);
  3219. Register DstReg = MI.getOperand(0).getReg();
  3220. // TODO: Extending a vector may be expensive, don't do this until heuristics
  3221. // are better.
  3222. if (MRI.getType(DstReg).isVector())
  3223. return false;
  3224. // Try to match a phi, whose only use is an extend.
  3225. if (!MRI.hasOneNonDBGUse(DstReg))
  3226. return false;
  3227. ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
  3228. switch (ExtMI->getOpcode()) {
  3229. case TargetOpcode::G_ANYEXT:
  3230. return true; // G_ANYEXT is usually free.
  3231. case TargetOpcode::G_ZEXT:
  3232. case TargetOpcode::G_SEXT:
  3233. break;
  3234. default:
  3235. return false;
  3236. }
  3237. // If the target is likely to fold this extend away, don't propagate.
  3238. if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
  3239. return false;
  3240. // We don't want to propagate the extends unless there's a good chance that
  3241. // they'll be optimized in some way.
  3242. // Collect the unique incoming values.
  3243. SmallPtrSet<MachineInstr *, 4> InSrcs;
  3244. for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
  3245. auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI);
  3246. switch (DefMI->getOpcode()) {
  3247. case TargetOpcode::G_LOAD:
  3248. case TargetOpcode::G_TRUNC:
  3249. case TargetOpcode::G_SEXT:
  3250. case TargetOpcode::G_ZEXT:
  3251. case TargetOpcode::G_ANYEXT:
  3252. case TargetOpcode::G_CONSTANT:
  3253. InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI));
  3254. // Don't try to propagate if there are too many places to create new
  3255. // extends, chances are it'll increase code size.
  3256. if (InSrcs.size() > 2)
  3257. return false;
  3258. break;
  3259. default:
  3260. return false;
  3261. }
  3262. }
  3263. return true;
  3264. }
  3265. void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
  3266. MachineInstr *&ExtMI) {
  3267. assert(MI.getOpcode() == TargetOpcode::G_PHI);
  3268. Register DstReg = ExtMI->getOperand(0).getReg();
  3269. LLT ExtTy = MRI.getType(DstReg);
  3270. // Propagate the extension into the block of each incoming reg's block.
  3271. // Use a SetVector here because PHIs can have duplicate edges, and we want
  3272. // deterministic iteration order.
  3273. SmallSetVector<MachineInstr *, 8> SrcMIs;
  3274. SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
  3275. for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) {
  3276. auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg());
  3277. if (!SrcMIs.insert(SrcMI))
  3278. continue;
  3279. // Build an extend after each src inst.
  3280. auto *MBB = SrcMI->getParent();
  3281. MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
  3282. if (InsertPt != MBB->end() && InsertPt->isPHI())
  3283. InsertPt = MBB->getFirstNonPHI();
  3284. Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
  3285. Builder.setDebugLoc(MI.getDebugLoc());
  3286. auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy,
  3287. SrcMI->getOperand(0).getReg());
  3288. OldToNewSrcMap[SrcMI] = NewExt;
  3289. }
  3290. // Create a new phi with the extended inputs.
  3291. Builder.setInstrAndDebugLoc(MI);
  3292. auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
  3293. NewPhi.addDef(DstReg);
  3294. for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
  3295. if (!MO.isReg()) {
  3296. NewPhi.addMBB(MO.getMBB());
  3297. continue;
  3298. }
  3299. auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
  3300. NewPhi.addUse(NewSrc->getOperand(0).getReg());
  3301. }
  3302. Builder.insertInstr(NewPhi);
  3303. ExtMI->eraseFromParent();
  3304. }
  3305. bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI,
  3306. Register &Reg) {
  3307. assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
  3308. // If we have a constant index, look for a G_BUILD_VECTOR source
  3309. // and find the source register that the index maps to.
  3310. Register SrcVec = MI.getOperand(1).getReg();
  3311. LLT SrcTy = MRI.getType(SrcVec);
  3312. if (!isLegalOrBeforeLegalizer(
  3313. {TargetOpcode::G_BUILD_VECTOR, {SrcTy, SrcTy.getElementType()}}))
  3314. return false;
  3315. auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
  3316. if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
  3317. return false;
  3318. unsigned VecIdx = Cst->Value.getZExtValue();
  3319. MachineInstr *BuildVecMI =
  3320. getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, SrcVec, MRI);
  3321. if (!BuildVecMI) {
  3322. BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR_TRUNC, SrcVec, MRI);
  3323. if (!BuildVecMI)
  3324. return false;
  3325. LLT ScalarTy = MRI.getType(BuildVecMI->getOperand(1).getReg());
  3326. if (!isLegalOrBeforeLegalizer(
  3327. {TargetOpcode::G_BUILD_VECTOR_TRUNC, {SrcTy, ScalarTy}}))
  3328. return false;
  3329. }
  3330. EVT Ty(getMVTForLLT(SrcTy));
  3331. if (!MRI.hasOneNonDBGUse(SrcVec) &&
  3332. !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
  3333. return false;
  3334. Reg = BuildVecMI->getOperand(VecIdx + 1).getReg();
  3335. return true;
  3336. }
  3337. void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI,
  3338. Register &Reg) {
  3339. // Check the type of the register, since it may have come from a
  3340. // G_BUILD_VECTOR_TRUNC.
  3341. LLT ScalarTy = MRI.getType(Reg);
  3342. Register DstReg = MI.getOperand(0).getReg();
  3343. LLT DstTy = MRI.getType(DstReg);
  3344. Builder.setInstrAndDebugLoc(MI);
  3345. if (ScalarTy != DstTy) {
  3346. assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
  3347. Builder.buildTrunc(DstReg, Reg);
  3348. MI.eraseFromParent();
  3349. return;
  3350. }
  3351. replaceSingleDefInstWithReg(MI, Reg);
  3352. }
  3353. bool CombinerHelper::matchExtractAllEltsFromBuildVector(
  3354. MachineInstr &MI,
  3355. SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
  3356. assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
  3357. // This combine tries to find build_vector's which have every source element
  3358. // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
  3359. // the masked load scalarization is run late in the pipeline. There's already
  3360. // a combine for a similar pattern starting from the extract, but that
  3361. // doesn't attempt to do it if there are multiple uses of the build_vector,
  3362. // which in this case is true. Starting the combine from the build_vector
  3363. // feels more natural than trying to find sibling nodes of extracts.
  3364. // E.g.
  3365. // %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
  3366. // %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
  3367. // %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
  3368. // %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
  3369. // %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
  3370. // ==>
  3371. // replace ext{1,2,3,4} with %s{1,2,3,4}
  3372. Register DstReg = MI.getOperand(0).getReg();
  3373. LLT DstTy = MRI.getType(DstReg);
  3374. unsigned NumElts = DstTy.getNumElements();
  3375. SmallBitVector ExtractedElts(NumElts);
  3376. for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
  3377. if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
  3378. return false;
  3379. auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
  3380. if (!Cst)
  3381. return false;
  3382. unsigned Idx = Cst.getValue().getZExtValue();
  3383. if (Idx >= NumElts)
  3384. return false; // Out of range.
  3385. ExtractedElts.set(Idx);
  3386. SrcDstPairs.emplace_back(
  3387. std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
  3388. }
  3389. // Match if every element was extracted.
  3390. return ExtractedElts.all();
  3391. }
  3392. void CombinerHelper::applyExtractAllEltsFromBuildVector(
  3393. MachineInstr &MI,
  3394. SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
  3395. assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
  3396. for (auto &Pair : SrcDstPairs) {
  3397. auto *ExtMI = Pair.second;
  3398. replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
  3399. ExtMI->eraseFromParent();
  3400. }
  3401. MI.eraseFromParent();
  3402. }
  3403. void CombinerHelper::applyBuildFn(
  3404. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3405. Builder.setInstrAndDebugLoc(MI);
  3406. MatchInfo(Builder);
  3407. MI.eraseFromParent();
  3408. }
  3409. void CombinerHelper::applyBuildFnNoErase(
  3410. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3411. Builder.setInstrAndDebugLoc(MI);
  3412. MatchInfo(Builder);
  3413. }
  3414. bool CombinerHelper::matchOrShiftToFunnelShift(MachineInstr &MI,
  3415. BuildFnTy &MatchInfo) {
  3416. assert(MI.getOpcode() == TargetOpcode::G_OR);
  3417. Register Dst = MI.getOperand(0).getReg();
  3418. LLT Ty = MRI.getType(Dst);
  3419. unsigned BitWidth = Ty.getScalarSizeInBits();
  3420. Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
  3421. unsigned FshOpc = 0;
  3422. // Match (or (shl ...), (lshr ...)).
  3423. if (!mi_match(Dst, MRI,
  3424. // m_GOr() handles the commuted version as well.
  3425. m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
  3426. m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
  3427. return false;
  3428. // Given constants C0 and C1 such that C0 + C1 is bit-width:
  3429. // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
  3430. // TODO: Match constant splat.
  3431. int64_t CstShlAmt, CstLShrAmt;
  3432. if (mi_match(ShlAmt, MRI, m_ICst(CstShlAmt)) &&
  3433. mi_match(LShrAmt, MRI, m_ICst(CstLShrAmt)) &&
  3434. CstShlAmt + CstLShrAmt == BitWidth) {
  3435. FshOpc = TargetOpcode::G_FSHR;
  3436. Amt = LShrAmt;
  3437. } else if (mi_match(LShrAmt, MRI,
  3438. m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
  3439. ShlAmt == Amt) {
  3440. // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
  3441. FshOpc = TargetOpcode::G_FSHL;
  3442. } else if (mi_match(ShlAmt, MRI,
  3443. m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
  3444. LShrAmt == Amt) {
  3445. // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
  3446. FshOpc = TargetOpcode::G_FSHR;
  3447. } else {
  3448. return false;
  3449. }
  3450. LLT AmtTy = MRI.getType(Amt);
  3451. if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}))
  3452. return false;
  3453. MatchInfo = [=](MachineIRBuilder &B) {
  3454. B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
  3455. };
  3456. return true;
  3457. }
  3458. /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate.
  3459. bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) {
  3460. unsigned Opc = MI.getOpcode();
  3461. assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
  3462. Register X = MI.getOperand(1).getReg();
  3463. Register Y = MI.getOperand(2).getReg();
  3464. if (X != Y)
  3465. return false;
  3466. unsigned RotateOpc =
  3467. Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR;
  3468. return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}});
  3469. }
  3470. void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) {
  3471. unsigned Opc = MI.getOpcode();
  3472. assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
  3473. bool IsFSHL = Opc == TargetOpcode::G_FSHL;
  3474. Observer.changingInstr(MI);
  3475. MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL
  3476. : TargetOpcode::G_ROTR));
  3477. MI.RemoveOperand(2);
  3478. Observer.changedInstr(MI);
  3479. }
  3480. // Fold (rot x, c) -> (rot x, c % BitSize)
  3481. bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) {
  3482. assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
  3483. MI.getOpcode() == TargetOpcode::G_ROTR);
  3484. unsigned Bitsize =
  3485. MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
  3486. Register AmtReg = MI.getOperand(2).getReg();
  3487. bool OutOfRange = false;
  3488. auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
  3489. if (auto *CI = dyn_cast<ConstantInt>(C))
  3490. OutOfRange |= CI->getValue().uge(Bitsize);
  3491. return true;
  3492. };
  3493. return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
  3494. }
  3495. void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) {
  3496. assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
  3497. MI.getOpcode() == TargetOpcode::G_ROTR);
  3498. unsigned Bitsize =
  3499. MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
  3500. Builder.setInstrAndDebugLoc(MI);
  3501. Register Amt = MI.getOperand(2).getReg();
  3502. LLT AmtTy = MRI.getType(Amt);
  3503. auto Bits = Builder.buildConstant(AmtTy, Bitsize);
  3504. Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
  3505. Observer.changingInstr(MI);
  3506. MI.getOperand(2).setReg(Amt);
  3507. Observer.changedInstr(MI);
  3508. }
  3509. bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI,
  3510. int64_t &MatchInfo) {
  3511. assert(MI.getOpcode() == TargetOpcode::G_ICMP);
  3512. auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
  3513. auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg());
  3514. auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg());
  3515. Optional<bool> KnownVal;
  3516. switch (Pred) {
  3517. default:
  3518. llvm_unreachable("Unexpected G_ICMP predicate?");
  3519. case CmpInst::ICMP_EQ:
  3520. KnownVal = KnownBits::eq(KnownLHS, KnownRHS);
  3521. break;
  3522. case CmpInst::ICMP_NE:
  3523. KnownVal = KnownBits::ne(KnownLHS, KnownRHS);
  3524. break;
  3525. case CmpInst::ICMP_SGE:
  3526. KnownVal = KnownBits::sge(KnownLHS, KnownRHS);
  3527. break;
  3528. case CmpInst::ICMP_SGT:
  3529. KnownVal = KnownBits::sgt(KnownLHS, KnownRHS);
  3530. break;
  3531. case CmpInst::ICMP_SLE:
  3532. KnownVal = KnownBits::sle(KnownLHS, KnownRHS);
  3533. break;
  3534. case CmpInst::ICMP_SLT:
  3535. KnownVal = KnownBits::slt(KnownLHS, KnownRHS);
  3536. break;
  3537. case CmpInst::ICMP_UGE:
  3538. KnownVal = KnownBits::uge(KnownLHS, KnownRHS);
  3539. break;
  3540. case CmpInst::ICMP_UGT:
  3541. KnownVal = KnownBits::ugt(KnownLHS, KnownRHS);
  3542. break;
  3543. case CmpInst::ICMP_ULE:
  3544. KnownVal = KnownBits::ule(KnownLHS, KnownRHS);
  3545. break;
  3546. case CmpInst::ICMP_ULT:
  3547. KnownVal = KnownBits::ult(KnownLHS, KnownRHS);
  3548. break;
  3549. }
  3550. if (!KnownVal)
  3551. return false;
  3552. MatchInfo =
  3553. *KnownVal
  3554. ? getICmpTrueVal(getTargetLowering(),
  3555. /*IsVector = */
  3556. MRI.getType(MI.getOperand(0).getReg()).isVector(),
  3557. /* IsFP = */ false)
  3558. : 0;
  3559. return true;
  3560. }
  3561. bool CombinerHelper::matchICmpToLHSKnownBits(
  3562. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3563. assert(MI.getOpcode() == TargetOpcode::G_ICMP);
  3564. // Given:
  3565. //
  3566. // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
  3567. // %cmp = G_ICMP ne %x, 0
  3568. //
  3569. // Or:
  3570. //
  3571. // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
  3572. // %cmp = G_ICMP eq %x, 1
  3573. //
  3574. // We can replace %cmp with %x assuming true is 1 on the target.
  3575. auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
  3576. if (!CmpInst::isEquality(Pred))
  3577. return false;
  3578. Register Dst = MI.getOperand(0).getReg();
  3579. LLT DstTy = MRI.getType(Dst);
  3580. if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(),
  3581. /* IsFP = */ false) != 1)
  3582. return false;
  3583. int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
  3584. if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
  3585. return false;
  3586. Register LHS = MI.getOperand(2).getReg();
  3587. auto KnownLHS = KB->getKnownBits(LHS);
  3588. if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
  3589. return false;
  3590. // Make sure replacing Dst with the LHS is a legal operation.
  3591. LLT LHSTy = MRI.getType(LHS);
  3592. unsigned LHSSize = LHSTy.getSizeInBits();
  3593. unsigned DstSize = DstTy.getSizeInBits();
  3594. unsigned Op = TargetOpcode::COPY;
  3595. if (DstSize != LHSSize)
  3596. Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
  3597. if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
  3598. return false;
  3599. MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
  3600. return true;
  3601. }
  3602. // Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
  3603. bool CombinerHelper::matchAndOrDisjointMask(
  3604. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3605. assert(MI.getOpcode() == TargetOpcode::G_AND);
  3606. // Ignore vector types to simplify matching the two constants.
  3607. // TODO: do this for vectors and scalars via a demanded bits analysis.
  3608. LLT Ty = MRI.getType(MI.getOperand(0).getReg());
  3609. if (Ty.isVector())
  3610. return false;
  3611. Register Src;
  3612. int64_t MaskAnd;
  3613. int64_t MaskOr;
  3614. if (!mi_match(MI, MRI,
  3615. m_GAnd(m_GOr(m_Reg(Src), m_ICst(MaskOr)), m_ICst(MaskAnd))))
  3616. return false;
  3617. // Check if MaskOr could turn on any bits in Src.
  3618. if (MaskAnd & MaskOr)
  3619. return false;
  3620. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  3621. Observer.changingInstr(MI);
  3622. MI.getOperand(1).setReg(Src);
  3623. Observer.changedInstr(MI);
  3624. };
  3625. return true;
  3626. }
  3627. /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
  3628. bool CombinerHelper::matchBitfieldExtractFromSExtInReg(
  3629. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3630. assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
  3631. Register Dst = MI.getOperand(0).getReg();
  3632. Register Src = MI.getOperand(1).getReg();
  3633. LLT Ty = MRI.getType(Src);
  3634. LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  3635. if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
  3636. return false;
  3637. int64_t Width = MI.getOperand(2).getImm();
  3638. Register ShiftSrc;
  3639. int64_t ShiftImm;
  3640. if (!mi_match(
  3641. Src, MRI,
  3642. m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
  3643. m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
  3644. return false;
  3645. if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
  3646. return false;
  3647. MatchInfo = [=](MachineIRBuilder &B) {
  3648. auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
  3649. auto Cst2 = B.buildConstant(ExtractTy, Width);
  3650. B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
  3651. };
  3652. return true;
  3653. }
  3654. /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
  3655. bool CombinerHelper::matchBitfieldExtractFromAnd(
  3656. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3657. assert(MI.getOpcode() == TargetOpcode::G_AND);
  3658. Register Dst = MI.getOperand(0).getReg();
  3659. LLT Ty = MRI.getType(Dst);
  3660. LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  3661. if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
  3662. TargetOpcode::G_UBFX, Ty, ExtractTy))
  3663. return false;
  3664. int64_t AndImm, LSBImm;
  3665. Register ShiftSrc;
  3666. const unsigned Size = Ty.getScalarSizeInBits();
  3667. if (!mi_match(MI.getOperand(0).getReg(), MRI,
  3668. m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
  3669. m_ICst(AndImm))))
  3670. return false;
  3671. // The mask is a mask of the low bits iff imm & (imm+1) == 0.
  3672. auto MaybeMask = static_cast<uint64_t>(AndImm);
  3673. if (MaybeMask & (MaybeMask + 1))
  3674. return false;
  3675. // LSB must fit within the register.
  3676. if (static_cast<uint64_t>(LSBImm) >= Size)
  3677. return false;
  3678. uint64_t Width = APInt(Size, AndImm).countTrailingOnes();
  3679. MatchInfo = [=](MachineIRBuilder &B) {
  3680. auto WidthCst = B.buildConstant(ExtractTy, Width);
  3681. auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
  3682. B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
  3683. };
  3684. return true;
  3685. }
  3686. bool CombinerHelper::matchBitfieldExtractFromShr(
  3687. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3688. const unsigned Opcode = MI.getOpcode();
  3689. assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
  3690. const Register Dst = MI.getOperand(0).getReg();
  3691. const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
  3692. ? TargetOpcode::G_SBFX
  3693. : TargetOpcode::G_UBFX;
  3694. // Check if the type we would use for the extract is legal
  3695. LLT Ty = MRI.getType(Dst);
  3696. LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  3697. if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
  3698. return false;
  3699. Register ShlSrc;
  3700. int64_t ShrAmt;
  3701. int64_t ShlAmt;
  3702. const unsigned Size = Ty.getScalarSizeInBits();
  3703. // Try to match shr (shl x, c1), c2
  3704. if (!mi_match(Dst, MRI,
  3705. m_BinOp(Opcode,
  3706. m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
  3707. m_ICst(ShrAmt))))
  3708. return false;
  3709. // Make sure that the shift sizes can fit a bitfield extract
  3710. if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
  3711. return false;
  3712. // Skip this combine if the G_SEXT_INREG combine could handle it
  3713. if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
  3714. return false;
  3715. // Calculate start position and width of the extract
  3716. const int64_t Pos = ShrAmt - ShlAmt;
  3717. const int64_t Width = Size - ShrAmt;
  3718. MatchInfo = [=](MachineIRBuilder &B) {
  3719. auto WidthCst = B.buildConstant(ExtractTy, Width);
  3720. auto PosCst = B.buildConstant(ExtractTy, Pos);
  3721. B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
  3722. };
  3723. return true;
  3724. }
  3725. bool CombinerHelper::matchBitfieldExtractFromShrAnd(
  3726. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3727. const unsigned Opcode = MI.getOpcode();
  3728. assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
  3729. const Register Dst = MI.getOperand(0).getReg();
  3730. LLT Ty = MRI.getType(Dst);
  3731. LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  3732. if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
  3733. TargetOpcode::G_UBFX, Ty, ExtractTy))
  3734. return false;
  3735. // Try to match shr (and x, c1), c2
  3736. Register AndSrc;
  3737. int64_t ShrAmt;
  3738. int64_t SMask;
  3739. if (!mi_match(Dst, MRI,
  3740. m_BinOp(Opcode,
  3741. m_OneNonDBGUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
  3742. m_ICst(ShrAmt))))
  3743. return false;
  3744. const unsigned Size = Ty.getScalarSizeInBits();
  3745. if (ShrAmt < 0 || ShrAmt >= Size)
  3746. return false;
  3747. // Check that ubfx can do the extraction, with no holes in the mask.
  3748. uint64_t UMask = SMask;
  3749. UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
  3750. UMask &= maskTrailingOnes<uint64_t>(Size);
  3751. if (!isMask_64(UMask))
  3752. return false;
  3753. // Calculate start position and width of the extract.
  3754. const int64_t Pos = ShrAmt;
  3755. const int64_t Width = countTrailingOnes(UMask) - ShrAmt;
  3756. // It's preferable to keep the shift, rather than form G_SBFX.
  3757. // TODO: remove the G_AND via demanded bits analysis.
  3758. if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
  3759. return false;
  3760. MatchInfo = [=](MachineIRBuilder &B) {
  3761. auto WidthCst = B.buildConstant(ExtractTy, Width);
  3762. auto PosCst = B.buildConstant(ExtractTy, Pos);
  3763. B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
  3764. };
  3765. return true;
  3766. }
  3767. bool CombinerHelper::reassociationCanBreakAddressingModePattern(
  3768. MachineInstr &PtrAdd) {
  3769. assert(PtrAdd.getOpcode() == TargetOpcode::G_PTR_ADD);
  3770. Register Src1Reg = PtrAdd.getOperand(1).getReg();
  3771. MachineInstr *Src1Def = getOpcodeDef(TargetOpcode::G_PTR_ADD, Src1Reg, MRI);
  3772. if (!Src1Def)
  3773. return false;
  3774. Register Src2Reg = PtrAdd.getOperand(2).getReg();
  3775. if (MRI.hasOneNonDBGUse(Src1Reg))
  3776. return false;
  3777. auto C1 = getIConstantVRegVal(Src1Def->getOperand(2).getReg(), MRI);
  3778. if (!C1)
  3779. return false;
  3780. auto C2 = getIConstantVRegVal(Src2Reg, MRI);
  3781. if (!C2)
  3782. return false;
  3783. const APInt &C1APIntVal = *C1;
  3784. const APInt &C2APIntVal = *C2;
  3785. const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
  3786. for (auto &UseMI : MRI.use_nodbg_instructions(Src1Reg)) {
  3787. // This combine may end up running before ptrtoint/inttoptr combines
  3788. // manage to eliminate redundant conversions, so try to look through them.
  3789. MachineInstr *ConvUseMI = &UseMI;
  3790. unsigned ConvUseOpc = ConvUseMI->getOpcode();
  3791. while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
  3792. ConvUseOpc == TargetOpcode::G_PTRTOINT) {
  3793. Register DefReg = ConvUseMI->getOperand(0).getReg();
  3794. if (!MRI.hasOneNonDBGUse(DefReg))
  3795. break;
  3796. ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
  3797. ConvUseOpc = ConvUseMI->getOpcode();
  3798. }
  3799. auto LoadStore = ConvUseOpc == TargetOpcode::G_LOAD ||
  3800. ConvUseOpc == TargetOpcode::G_STORE;
  3801. if (!LoadStore)
  3802. continue;
  3803. // Is x[offset2] already not a legal addressing mode? If so then
  3804. // reassociating the constants breaks nothing (we test offset2 because
  3805. // that's the one we hope to fold into the load or store).
  3806. TargetLoweringBase::AddrMode AM;
  3807. AM.HasBaseReg = true;
  3808. AM.BaseOffs = C2APIntVal.getSExtValue();
  3809. unsigned AS =
  3810. MRI.getType(ConvUseMI->getOperand(1).getReg()).getAddressSpace();
  3811. Type *AccessTy =
  3812. getTypeForLLT(MRI.getType(ConvUseMI->getOperand(0).getReg()),
  3813. PtrAdd.getMF()->getFunction().getContext());
  3814. const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
  3815. if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
  3816. AccessTy, AS))
  3817. continue;
  3818. // Would x[offset1+offset2] still be a legal addressing mode?
  3819. AM.BaseOffs = CombinedValue;
  3820. if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
  3821. AccessTy, AS))
  3822. return true;
  3823. }
  3824. return false;
  3825. }
  3826. bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI,
  3827. MachineInstr *RHS,
  3828. BuildFnTy &MatchInfo) {
  3829. // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
  3830. Register Src1Reg = MI.getOperand(1).getReg();
  3831. if (RHS->getOpcode() != TargetOpcode::G_ADD)
  3832. return false;
  3833. auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
  3834. if (!C2)
  3835. return false;
  3836. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  3837. LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
  3838. auto NewBase =
  3839. Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg());
  3840. Observer.changingInstr(MI);
  3841. MI.getOperand(1).setReg(NewBase.getReg(0));
  3842. MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
  3843. Observer.changedInstr(MI);
  3844. };
  3845. return !reassociationCanBreakAddressingModePattern(MI);
  3846. }
  3847. bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI,
  3848. MachineInstr *LHS,
  3849. MachineInstr *RHS,
  3850. BuildFnTy &MatchInfo) {
  3851. // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
  3852. // if and only if (G_PTR_ADD X, C) has one use.
  3853. Register LHSBase;
  3854. Optional<ValueAndVReg> LHSCstOff;
  3855. if (!mi_match(MI.getBaseReg(), MRI,
  3856. m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
  3857. return false;
  3858. auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
  3859. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  3860. // When we change LHSPtrAdd's offset register we might cause it to use a reg
  3861. // before its def. Sink the instruction so the outer PTR_ADD to ensure this
  3862. // doesn't happen.
  3863. LHSPtrAdd->moveBefore(&MI);
  3864. Register RHSReg = MI.getOffsetReg();
  3865. Observer.changingInstr(MI);
  3866. MI.getOperand(2).setReg(LHSCstOff->VReg);
  3867. Observer.changedInstr(MI);
  3868. Observer.changingInstr(*LHSPtrAdd);
  3869. LHSPtrAdd->getOperand(2).setReg(RHSReg);
  3870. Observer.changedInstr(*LHSPtrAdd);
  3871. };
  3872. return !reassociationCanBreakAddressingModePattern(MI);
  3873. }
  3874. bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI,
  3875. MachineInstr *LHS,
  3876. MachineInstr *RHS,
  3877. BuildFnTy &MatchInfo) {
  3878. // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
  3879. auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
  3880. if (!LHSPtrAdd)
  3881. return false;
  3882. Register Src2Reg = MI.getOperand(2).getReg();
  3883. Register LHSSrc1 = LHSPtrAdd->getBaseReg();
  3884. Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
  3885. auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
  3886. if (!C1)
  3887. return false;
  3888. auto C2 = getIConstantVRegVal(Src2Reg, MRI);
  3889. if (!C2)
  3890. return false;
  3891. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  3892. auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
  3893. Observer.changingInstr(MI);
  3894. MI.getOperand(1).setReg(LHSSrc1);
  3895. MI.getOperand(2).setReg(NewCst.getReg(0));
  3896. Observer.changedInstr(MI);
  3897. };
  3898. return !reassociationCanBreakAddressingModePattern(MI);
  3899. }
  3900. bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI,
  3901. BuildFnTy &MatchInfo) {
  3902. auto &PtrAdd = cast<GPtrAdd>(MI);
  3903. // We're trying to match a few pointer computation patterns here for
  3904. // re-association opportunities.
  3905. // 1) Isolating a constant operand to be on the RHS, e.g.:
  3906. // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
  3907. //
  3908. // 2) Folding two constants in each sub-tree as long as such folding
  3909. // doesn't break a legal addressing mode.
  3910. // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
  3911. //
  3912. // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
  3913. // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
  3914. // iif (G_PTR_ADD X, C) has one use.
  3915. MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg());
  3916. MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg());
  3917. // Try to match example 2.
  3918. if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
  3919. return true;
  3920. // Try to match example 3.
  3921. if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
  3922. return true;
  3923. // Try to match example 1.
  3924. if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
  3925. return true;
  3926. return false;
  3927. }
  3928. bool CombinerHelper::matchConstantFold(MachineInstr &MI, APInt &MatchInfo) {
  3929. Register Op1 = MI.getOperand(1).getReg();
  3930. Register Op2 = MI.getOperand(2).getReg();
  3931. auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
  3932. if (!MaybeCst)
  3933. return false;
  3934. MatchInfo = *MaybeCst;
  3935. return true;
  3936. }
  3937. bool CombinerHelper::matchNarrowBinopFeedingAnd(
  3938. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  3939. // Look for a binop feeding into an AND with a mask:
  3940. //
  3941. // %add = G_ADD %lhs, %rhs
  3942. // %and = G_AND %add, 000...11111111
  3943. //
  3944. // Check if it's possible to perform the binop at a narrower width and zext
  3945. // back to the original width like so:
  3946. //
  3947. // %narrow_lhs = G_TRUNC %lhs
  3948. // %narrow_rhs = G_TRUNC %rhs
  3949. // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
  3950. // %new_add = G_ZEXT %narrow_add
  3951. // %and = G_AND %new_add, 000...11111111
  3952. //
  3953. // This can allow later combines to eliminate the G_AND if it turns out
  3954. // that the mask is irrelevant.
  3955. assert(MI.getOpcode() == TargetOpcode::G_AND);
  3956. Register Dst = MI.getOperand(0).getReg();
  3957. Register AndLHS = MI.getOperand(1).getReg();
  3958. Register AndRHS = MI.getOperand(2).getReg();
  3959. LLT WideTy = MRI.getType(Dst);
  3960. // If the potential binop has more than one use, then it's possible that one
  3961. // of those uses will need its full width.
  3962. if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
  3963. return false;
  3964. // Check if the LHS feeding the AND is impacted by the high bits that we're
  3965. // masking out.
  3966. //
  3967. // e.g. for 64-bit x, y:
  3968. //
  3969. // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
  3970. MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
  3971. if (!LHSInst)
  3972. return false;
  3973. unsigned LHSOpc = LHSInst->getOpcode();
  3974. switch (LHSOpc) {
  3975. default:
  3976. return false;
  3977. case TargetOpcode::G_ADD:
  3978. case TargetOpcode::G_SUB:
  3979. case TargetOpcode::G_MUL:
  3980. case TargetOpcode::G_AND:
  3981. case TargetOpcode::G_OR:
  3982. case TargetOpcode::G_XOR:
  3983. break;
  3984. }
  3985. // Find the mask on the RHS.
  3986. auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
  3987. if (!Cst)
  3988. return false;
  3989. auto Mask = Cst->Value;
  3990. if (!Mask.isMask())
  3991. return false;
  3992. // No point in combining if there's nothing to truncate.
  3993. unsigned NarrowWidth = Mask.countTrailingOnes();
  3994. if (NarrowWidth == WideTy.getSizeInBits())
  3995. return false;
  3996. LLT NarrowTy = LLT::scalar(NarrowWidth);
  3997. // Check if adding the zext + truncates could be harmful.
  3998. auto &MF = *MI.getMF();
  3999. const auto &TLI = getTargetLowering();
  4000. LLVMContext &Ctx = MF.getFunction().getContext();
  4001. auto &DL = MF.getDataLayout();
  4002. if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) ||
  4003. !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx))
  4004. return false;
  4005. if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
  4006. !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
  4007. return false;
  4008. Register BinOpLHS = LHSInst->getOperand(1).getReg();
  4009. Register BinOpRHS = LHSInst->getOperand(2).getReg();
  4010. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4011. auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
  4012. auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
  4013. auto NarrowBinOp =
  4014. Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
  4015. auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
  4016. Observer.changingInstr(MI);
  4017. MI.getOperand(1).setReg(Ext.getReg(0));
  4018. Observer.changedInstr(MI);
  4019. };
  4020. return true;
  4021. }
  4022. bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) {
  4023. unsigned Opc = MI.getOpcode();
  4024. assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO);
  4025. if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(2)))
  4026. return false;
  4027. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4028. Observer.changingInstr(MI);
  4029. unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO
  4030. : TargetOpcode::G_SADDO;
  4031. MI.setDesc(Builder.getTII().get(NewOpc));
  4032. MI.getOperand(3).setReg(MI.getOperand(2).getReg());
  4033. Observer.changedInstr(MI);
  4034. };
  4035. return true;
  4036. }
  4037. MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) {
  4038. assert(MI.getOpcode() == TargetOpcode::G_UDIV);
  4039. auto &UDiv = cast<GenericMachineInstr>(MI);
  4040. Register Dst = UDiv.getReg(0);
  4041. Register LHS = UDiv.getReg(1);
  4042. Register RHS = UDiv.getReg(2);
  4043. LLT Ty = MRI.getType(Dst);
  4044. LLT ScalarTy = Ty.getScalarType();
  4045. const unsigned EltBits = ScalarTy.getScalarSizeInBits();
  4046. LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  4047. LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
  4048. auto &MIB = Builder;
  4049. MIB.setInstrAndDebugLoc(MI);
  4050. bool UseNPQ = false;
  4051. SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
  4052. auto BuildUDIVPattern = [&](const Constant *C) {
  4053. auto *CI = cast<ConstantInt>(C);
  4054. const APInt &Divisor = CI->getValue();
  4055. UnsignedDivisonByConstantInfo magics =
  4056. UnsignedDivisonByConstantInfo::get(Divisor);
  4057. unsigned PreShift = 0, PostShift = 0;
  4058. // If the divisor is even, we can avoid using the expensive fixup by
  4059. // shifting the divided value upfront.
  4060. if (magics.IsAdd != 0 && !Divisor[0]) {
  4061. PreShift = Divisor.countTrailingZeros();
  4062. // Get magic number for the shifted divisor.
  4063. magics =
  4064. UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
  4065. assert(magics.IsAdd == 0 && "Should use cheap fixup now");
  4066. }
  4067. APInt Magic = magics.Magic;
  4068. unsigned SelNPQ;
  4069. if (magics.IsAdd == 0 || Divisor.isOneValue()) {
  4070. assert(magics.ShiftAmount < Divisor.getBitWidth() &&
  4071. "We shouldn't generate an undefined shift!");
  4072. PostShift = magics.ShiftAmount;
  4073. SelNPQ = false;
  4074. } else {
  4075. PostShift = magics.ShiftAmount - 1;
  4076. SelNPQ = true;
  4077. }
  4078. PreShifts.push_back(
  4079. MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
  4080. MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
  4081. NPQFactors.push_back(
  4082. MIB.buildConstant(ScalarTy,
  4083. SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
  4084. : APInt::getZero(EltBits))
  4085. .getReg(0));
  4086. PostShifts.push_back(
  4087. MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
  4088. UseNPQ |= SelNPQ;
  4089. return true;
  4090. };
  4091. // Collect the shifts/magic values from each element.
  4092. bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
  4093. (void)Matched;
  4094. assert(Matched && "Expected unary predicate match to succeed");
  4095. Register PreShift, PostShift, MagicFactor, NPQFactor;
  4096. auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
  4097. if (RHSDef) {
  4098. PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
  4099. MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
  4100. NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
  4101. PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
  4102. } else {
  4103. assert(MRI.getType(RHS).isScalar() &&
  4104. "Non-build_vector operation should have been a scalar");
  4105. PreShift = PreShifts[0];
  4106. MagicFactor = MagicFactors[0];
  4107. PostShift = PostShifts[0];
  4108. }
  4109. Register Q = LHS;
  4110. Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
  4111. // Multiply the numerator (operand 0) by the magic value.
  4112. Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
  4113. if (UseNPQ) {
  4114. Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
  4115. // For vectors we might have a mix of non-NPQ/NPQ paths, so use
  4116. // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
  4117. if (Ty.isVector())
  4118. NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
  4119. else
  4120. NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
  4121. Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
  4122. }
  4123. Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
  4124. auto One = MIB.buildConstant(Ty, 1);
  4125. auto IsOne = MIB.buildICmp(
  4126. CmpInst::Predicate::ICMP_EQ,
  4127. Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One);
  4128. return MIB.buildSelect(Ty, IsOne, LHS, Q);
  4129. }
  4130. bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
  4131. assert(MI.getOpcode() == TargetOpcode::G_UDIV);
  4132. Register Dst = MI.getOperand(0).getReg();
  4133. Register RHS = MI.getOperand(2).getReg();
  4134. LLT DstTy = MRI.getType(Dst);
  4135. auto *RHSDef = MRI.getVRegDef(RHS);
  4136. if (!isConstantOrConstantVector(*RHSDef, MRI))
  4137. return false;
  4138. auto &MF = *MI.getMF();
  4139. AttributeList Attr = MF.getFunction().getAttributes();
  4140. const auto &TLI = getTargetLowering();
  4141. LLVMContext &Ctx = MF.getFunction().getContext();
  4142. auto &DL = MF.getDataLayout();
  4143. if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
  4144. return false;
  4145. // Don't do this for minsize because the instruction sequence is usually
  4146. // larger.
  4147. if (MF.getFunction().hasMinSize())
  4148. return false;
  4149. // Don't do this if the types are not going to be legal.
  4150. if (LI) {
  4151. if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
  4152. return false;
  4153. if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
  4154. return false;
  4155. if (!isLegalOrBeforeLegalizer(
  4156. {TargetOpcode::G_ICMP,
  4157. {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
  4158. DstTy}}))
  4159. return false;
  4160. }
  4161. auto CheckEltValue = [&](const Constant *C) {
  4162. if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
  4163. return !CI->isZero();
  4164. return false;
  4165. };
  4166. return matchUnaryPredicate(MRI, RHS, CheckEltValue);
  4167. }
  4168. void CombinerHelper::applyUDivByConst(MachineInstr &MI) {
  4169. auto *NewMI = buildUDivUsingMul(MI);
  4170. replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
  4171. }
  4172. bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) {
  4173. assert(MI.getOpcode() == TargetOpcode::G_UMULH);
  4174. Register RHS = MI.getOperand(2).getReg();
  4175. Register Dst = MI.getOperand(0).getReg();
  4176. LLT Ty = MRI.getType(Dst);
  4177. LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  4178. auto MatchPow2ExceptOne = [&](const Constant *C) {
  4179. if (auto *CI = dyn_cast<ConstantInt>(C))
  4180. return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
  4181. return false;
  4182. };
  4183. if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
  4184. return false;
  4185. return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}});
  4186. }
  4187. void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) {
  4188. Register LHS = MI.getOperand(1).getReg();
  4189. Register RHS = MI.getOperand(2).getReg();
  4190. Register Dst = MI.getOperand(0).getReg();
  4191. LLT Ty = MRI.getType(Dst);
  4192. LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
  4193. unsigned NumEltBits = Ty.getScalarSizeInBits();
  4194. Builder.setInstrAndDebugLoc(MI);
  4195. auto LogBase2 = buildLogBase2(RHS, Builder);
  4196. auto ShiftAmt =
  4197. Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
  4198. auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
  4199. Builder.buildLShr(Dst, LHS, Trunc);
  4200. MI.eraseFromParent();
  4201. }
  4202. bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI,
  4203. BuildFnTy &MatchInfo) {
  4204. unsigned Opc = MI.getOpcode();
  4205. assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB ||
  4206. Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
  4207. Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA);
  4208. Register Dst = MI.getOperand(0).getReg();
  4209. Register X = MI.getOperand(1).getReg();
  4210. Register Y = MI.getOperand(2).getReg();
  4211. LLT Type = MRI.getType(Dst);
  4212. // fold (fadd x, fneg(y)) -> (fsub x, y)
  4213. // fold (fadd fneg(y), x) -> (fsub x, y)
  4214. // G_ADD is commutative so both cases are checked by m_GFAdd
  4215. if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
  4216. isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) {
  4217. Opc = TargetOpcode::G_FSUB;
  4218. }
  4219. /// fold (fsub x, fneg(y)) -> (fadd x, y)
  4220. else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
  4221. isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) {
  4222. Opc = TargetOpcode::G_FADD;
  4223. }
  4224. // fold (fmul fneg(x), fneg(y)) -> (fmul x, y)
  4225. // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y)
  4226. // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z)
  4227. // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z)
  4228. else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
  4229. Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) &&
  4230. mi_match(X, MRI, m_GFNeg(m_Reg(X))) &&
  4231. mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) {
  4232. // no opcode change
  4233. } else
  4234. return false;
  4235. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4236. Observer.changingInstr(MI);
  4237. MI.setDesc(B.getTII().get(Opc));
  4238. MI.getOperand(1).setReg(X);
  4239. MI.getOperand(2).setReg(Y);
  4240. Observer.changedInstr(MI);
  4241. };
  4242. return true;
  4243. }
  4244. /// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
  4245. /// due to global flags or MachineInstr flags.
  4246. static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
  4247. if (MI.getOpcode() != TargetOpcode::G_FMUL)
  4248. return false;
  4249. return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
  4250. }
  4251. static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
  4252. const MachineRegisterInfo &MRI) {
  4253. return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
  4254. MRI.use_instr_nodbg_end()) >
  4255. std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
  4256. MRI.use_instr_nodbg_end());
  4257. }
  4258. bool CombinerHelper::canCombineFMadOrFMA(MachineInstr &MI,
  4259. bool &AllowFusionGlobally,
  4260. bool &HasFMAD, bool &Aggressive,
  4261. bool CanReassociate) {
  4262. auto *MF = MI.getMF();
  4263. const auto &TLI = *MF->getSubtarget().getTargetLowering();
  4264. const TargetOptions &Options = MF->getTarget().Options;
  4265. LLT DstType = MRI.getType(MI.getOperand(0).getReg());
  4266. if (CanReassociate &&
  4267. !(Options.UnsafeFPMath || MI.getFlag(MachineInstr::MIFlag::FmReassoc)))
  4268. return false;
  4269. // Floating-point multiply-add with intermediate rounding.
  4270. HasFMAD = (LI && TLI.isFMADLegal(MI, DstType));
  4271. // Floating-point multiply-add without intermediate rounding.
  4272. bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
  4273. isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
  4274. // No valid opcode, do not combine.
  4275. if (!HasFMAD && !HasFMA)
  4276. return false;
  4277. AllowFusionGlobally = Options.AllowFPOpFusion == FPOpFusion::Fast ||
  4278. Options.UnsafeFPMath || HasFMAD;
  4279. // If the addition is not contractable, do not combine.
  4280. if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
  4281. return false;
  4282. Aggressive = TLI.enableAggressiveFMAFusion(DstType);
  4283. return true;
  4284. }
  4285. bool CombinerHelper::matchCombineFAddFMulToFMadOrFMA(
  4286. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4287. assert(MI.getOpcode() == TargetOpcode::G_FADD);
  4288. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4289. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4290. return false;
  4291. Register Op1 = MI.getOperand(1).getReg();
  4292. Register Op2 = MI.getOperand(2).getReg();
  4293. DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
  4294. DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
  4295. unsigned PreferredFusedOpcode =
  4296. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4297. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  4298. // prefer to fold the multiply with fewer uses.
  4299. if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4300. isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
  4301. if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
  4302. std::swap(LHS, RHS);
  4303. }
  4304. // fold (fadd (fmul x, y), z) -> (fma x, y, z)
  4305. if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4306. (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
  4307. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4308. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4309. {LHS.MI->getOperand(1).getReg(),
  4310. LHS.MI->getOperand(2).getReg(), RHS.Reg});
  4311. };
  4312. return true;
  4313. }
  4314. // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
  4315. if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
  4316. (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
  4317. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4318. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4319. {RHS.MI->getOperand(1).getReg(),
  4320. RHS.MI->getOperand(2).getReg(), LHS.Reg});
  4321. };
  4322. return true;
  4323. }
  4324. return false;
  4325. }
  4326. bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA(
  4327. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4328. assert(MI.getOpcode() == TargetOpcode::G_FADD);
  4329. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4330. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4331. return false;
  4332. const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
  4333. Register Op1 = MI.getOperand(1).getReg();
  4334. Register Op2 = MI.getOperand(2).getReg();
  4335. DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
  4336. DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
  4337. LLT DstType = MRI.getType(MI.getOperand(0).getReg());
  4338. unsigned PreferredFusedOpcode =
  4339. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4340. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  4341. // prefer to fold the multiply with fewer uses.
  4342. if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4343. isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
  4344. if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
  4345. std::swap(LHS, RHS);
  4346. }
  4347. // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
  4348. MachineInstr *FpExtSrc;
  4349. if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
  4350. isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
  4351. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
  4352. MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
  4353. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4354. auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
  4355. auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
  4356. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4357. {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg});
  4358. };
  4359. return true;
  4360. }
  4361. // fold (fadd z, (fpext (fmul x, y))) -> (fma (fpext x), (fpext y), z)
  4362. // Note: Commutes FADD operands.
  4363. if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
  4364. isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
  4365. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
  4366. MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
  4367. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4368. auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
  4369. auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
  4370. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4371. {FpExtX.getReg(0), FpExtY.getReg(0), LHS.Reg});
  4372. };
  4373. return true;
  4374. }
  4375. return false;
  4376. }
  4377. bool CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA(
  4378. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4379. assert(MI.getOpcode() == TargetOpcode::G_FADD);
  4380. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4381. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
  4382. return false;
  4383. Register Op1 = MI.getOperand(1).getReg();
  4384. Register Op2 = MI.getOperand(2).getReg();
  4385. DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
  4386. DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
  4387. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  4388. unsigned PreferredFusedOpcode =
  4389. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4390. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  4391. // prefer to fold the multiply with fewer uses.
  4392. if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4393. isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
  4394. if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
  4395. std::swap(LHS, RHS);
  4396. }
  4397. MachineInstr *FMA = nullptr;
  4398. Register Z;
  4399. // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
  4400. if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
  4401. (MRI.getVRegDef(LHS.MI->getOperand(3).getReg())->getOpcode() ==
  4402. TargetOpcode::G_FMUL) &&
  4403. MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
  4404. MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
  4405. FMA = LHS.MI;
  4406. Z = RHS.Reg;
  4407. }
  4408. // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
  4409. else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
  4410. (MRI.getVRegDef(RHS.MI->getOperand(3).getReg())->getOpcode() ==
  4411. TargetOpcode::G_FMUL) &&
  4412. MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
  4413. MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
  4414. Z = LHS.Reg;
  4415. FMA = RHS.MI;
  4416. }
  4417. if (FMA) {
  4418. MachineInstr *FMulMI = MRI.getVRegDef(FMA->getOperand(3).getReg());
  4419. Register X = FMA->getOperand(1).getReg();
  4420. Register Y = FMA->getOperand(2).getReg();
  4421. Register U = FMulMI->getOperand(1).getReg();
  4422. Register V = FMulMI->getOperand(2).getReg();
  4423. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4424. Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
  4425. B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z});
  4426. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4427. {X, Y, InnerFMA});
  4428. };
  4429. return true;
  4430. }
  4431. return false;
  4432. }
  4433. bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
  4434. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4435. assert(MI.getOpcode() == TargetOpcode::G_FADD);
  4436. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4437. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4438. return false;
  4439. if (!Aggressive)
  4440. return false;
  4441. const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
  4442. LLT DstType = MRI.getType(MI.getOperand(0).getReg());
  4443. Register Op1 = MI.getOperand(1).getReg();
  4444. Register Op2 = MI.getOperand(2).getReg();
  4445. DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
  4446. DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
  4447. unsigned PreferredFusedOpcode =
  4448. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4449. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  4450. // prefer to fold the multiply with fewer uses.
  4451. if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4452. isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
  4453. if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
  4454. std::swap(LHS, RHS);
  4455. }
  4456. // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
  4457. auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
  4458. Register Y, MachineIRBuilder &B) {
  4459. Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
  4460. Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
  4461. Register InnerFMA =
  4462. B.buildInstr(PreferredFusedOpcode, {DstType}, {FpExtU, FpExtV, Z})
  4463. .getReg(0);
  4464. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4465. {X, Y, InnerFMA});
  4466. };
  4467. MachineInstr *FMulMI, *FMAMI;
  4468. // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
  4469. // -> (fma x, y, (fma (fpext u), (fpext v), z))
  4470. if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
  4471. mi_match(LHS.MI->getOperand(3).getReg(), MRI,
  4472. m_GFPExt(m_MInstr(FMulMI))) &&
  4473. isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4474. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
  4475. MRI.getType(FMulMI->getOperand(0).getReg()))) {
  4476. MatchInfo = [=](MachineIRBuilder &B) {
  4477. buildMatchInfo(FMulMI->getOperand(1).getReg(),
  4478. FMulMI->getOperand(2).getReg(), RHS.Reg,
  4479. LHS.MI->getOperand(1).getReg(),
  4480. LHS.MI->getOperand(2).getReg(), B);
  4481. };
  4482. return true;
  4483. }
  4484. // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
  4485. // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
  4486. // FIXME: This turns two single-precision and one double-precision
  4487. // operation into two double-precision operations, which might not be
  4488. // interesting for all targets, especially GPUs.
  4489. if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
  4490. FMAMI->getOpcode() == PreferredFusedOpcode) {
  4491. MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
  4492. if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4493. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
  4494. MRI.getType(FMAMI->getOperand(0).getReg()))) {
  4495. MatchInfo = [=](MachineIRBuilder &B) {
  4496. Register X = FMAMI->getOperand(1).getReg();
  4497. Register Y = FMAMI->getOperand(2).getReg();
  4498. X = B.buildFPExt(DstType, X).getReg(0);
  4499. Y = B.buildFPExt(DstType, Y).getReg(0);
  4500. buildMatchInfo(FMulMI->getOperand(1).getReg(),
  4501. FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y, B);
  4502. };
  4503. return true;
  4504. }
  4505. }
  4506. // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
  4507. // -> (fma x, y, (fma (fpext u), (fpext v), z))
  4508. if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
  4509. mi_match(RHS.MI->getOperand(3).getReg(), MRI,
  4510. m_GFPExt(m_MInstr(FMulMI))) &&
  4511. isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4512. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
  4513. MRI.getType(FMulMI->getOperand(0).getReg()))) {
  4514. MatchInfo = [=](MachineIRBuilder &B) {
  4515. buildMatchInfo(FMulMI->getOperand(1).getReg(),
  4516. FMulMI->getOperand(2).getReg(), LHS.Reg,
  4517. RHS.MI->getOperand(1).getReg(),
  4518. RHS.MI->getOperand(2).getReg(), B);
  4519. };
  4520. return true;
  4521. }
  4522. // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
  4523. // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
  4524. // FIXME: This turns two single-precision and one double-precision
  4525. // operation into two double-precision operations, which might not be
  4526. // interesting for all targets, especially GPUs.
  4527. if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
  4528. FMAMI->getOpcode() == PreferredFusedOpcode) {
  4529. MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
  4530. if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4531. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
  4532. MRI.getType(FMAMI->getOperand(0).getReg()))) {
  4533. MatchInfo = [=](MachineIRBuilder &B) {
  4534. Register X = FMAMI->getOperand(1).getReg();
  4535. Register Y = FMAMI->getOperand(2).getReg();
  4536. X = B.buildFPExt(DstType, X).getReg(0);
  4537. Y = B.buildFPExt(DstType, Y).getReg(0);
  4538. buildMatchInfo(FMulMI->getOperand(1).getReg(),
  4539. FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y, B);
  4540. };
  4541. return true;
  4542. }
  4543. }
  4544. return false;
  4545. }
  4546. bool CombinerHelper::matchCombineFSubFMulToFMadOrFMA(
  4547. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4548. assert(MI.getOpcode() == TargetOpcode::G_FSUB);
  4549. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4550. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4551. return false;
  4552. Register Op1 = MI.getOperand(1).getReg();
  4553. Register Op2 = MI.getOperand(2).getReg();
  4554. DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
  4555. DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
  4556. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  4557. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  4558. // prefer to fold the multiply with fewer uses.
  4559. int FirstMulHasFewerUses = true;
  4560. if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4561. isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
  4562. hasMoreUses(*LHS.MI, *RHS.MI, MRI))
  4563. FirstMulHasFewerUses = false;
  4564. unsigned PreferredFusedOpcode =
  4565. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4566. // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
  4567. if (FirstMulHasFewerUses &&
  4568. (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
  4569. (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
  4570. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4571. Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
  4572. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4573. {LHS.MI->getOperand(1).getReg(),
  4574. LHS.MI->getOperand(2).getReg(), NegZ});
  4575. };
  4576. return true;
  4577. }
  4578. // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
  4579. else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
  4580. (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
  4581. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4582. Register NegY =
  4583. B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
  4584. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4585. {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg});
  4586. };
  4587. return true;
  4588. }
  4589. return false;
  4590. }
  4591. bool CombinerHelper::matchCombineFSubFNegFMulToFMadOrFMA(
  4592. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4593. assert(MI.getOpcode() == TargetOpcode::G_FSUB);
  4594. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4595. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4596. return false;
  4597. Register LHSReg = MI.getOperand(1).getReg();
  4598. Register RHSReg = MI.getOperand(2).getReg();
  4599. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  4600. unsigned PreferredFusedOpcode =
  4601. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4602. MachineInstr *FMulMI;
  4603. // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
  4604. if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
  4605. (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
  4606. MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
  4607. isContractableFMul(*FMulMI, AllowFusionGlobally)) {
  4608. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4609. Register NegX =
  4610. B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
  4611. Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
  4612. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4613. {NegX, FMulMI->getOperand(2).getReg(), NegZ});
  4614. };
  4615. return true;
  4616. }
  4617. // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
  4618. if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
  4619. (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
  4620. MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
  4621. isContractableFMul(*FMulMI, AllowFusionGlobally)) {
  4622. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4623. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4624. {FMulMI->getOperand(1).getReg(),
  4625. FMulMI->getOperand(2).getReg(), LHSReg});
  4626. };
  4627. return true;
  4628. }
  4629. return false;
  4630. }
  4631. bool CombinerHelper::matchCombineFSubFpExtFMulToFMadOrFMA(
  4632. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4633. assert(MI.getOpcode() == TargetOpcode::G_FSUB);
  4634. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4635. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4636. return false;
  4637. Register LHSReg = MI.getOperand(1).getReg();
  4638. Register RHSReg = MI.getOperand(2).getReg();
  4639. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  4640. unsigned PreferredFusedOpcode =
  4641. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4642. MachineInstr *FMulMI;
  4643. // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
  4644. if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
  4645. isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4646. (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
  4647. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4648. Register FpExtX =
  4649. B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
  4650. Register FpExtY =
  4651. B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
  4652. Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
  4653. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4654. {FpExtX, FpExtY, NegZ});
  4655. };
  4656. return true;
  4657. }
  4658. // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
  4659. if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
  4660. isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4661. (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
  4662. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4663. Register FpExtY =
  4664. B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
  4665. Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
  4666. Register FpExtZ =
  4667. B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
  4668. B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
  4669. {NegY, FpExtZ, LHSReg});
  4670. };
  4671. return true;
  4672. }
  4673. return false;
  4674. }
  4675. bool CombinerHelper::matchCombineFSubFpExtFNegFMulToFMadOrFMA(
  4676. MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
  4677. assert(MI.getOpcode() == TargetOpcode::G_FSUB);
  4678. bool AllowFusionGlobally, HasFMAD, Aggressive;
  4679. if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
  4680. return false;
  4681. const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
  4682. LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
  4683. Register LHSReg = MI.getOperand(1).getReg();
  4684. Register RHSReg = MI.getOperand(2).getReg();
  4685. unsigned PreferredFusedOpcode =
  4686. HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
  4687. auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
  4688. MachineIRBuilder &B) {
  4689. Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
  4690. Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
  4691. B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z});
  4692. };
  4693. MachineInstr *FMulMI;
  4694. // fold (fsub (fpext (fneg (fmul x, y))), z) ->
  4695. // (fneg (fma (fpext x), (fpext y), z))
  4696. // fold (fsub (fneg (fpext (fmul x, y))), z) ->
  4697. // (fneg (fma (fpext x), (fpext y), z))
  4698. if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
  4699. mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
  4700. isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4701. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
  4702. MRI.getType(FMulMI->getOperand(0).getReg()))) {
  4703. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4704. Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
  4705. buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
  4706. FMulMI->getOperand(2).getReg(), RHSReg, B);
  4707. B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
  4708. };
  4709. return true;
  4710. }
  4711. // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
  4712. // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
  4713. if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
  4714. mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
  4715. isContractableFMul(*FMulMI, AllowFusionGlobally) &&
  4716. TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
  4717. MRI.getType(FMulMI->getOperand(0).getReg()))) {
  4718. MatchInfo = [=, &MI](MachineIRBuilder &B) {
  4719. buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
  4720. FMulMI->getOperand(2).getReg(), LHSReg, B);
  4721. };
  4722. return true;
  4723. }
  4724. return false;
  4725. }
  4726. bool CombinerHelper::tryCombine(MachineInstr &MI) {
  4727. if (tryCombineCopy(MI))
  4728. return true;
  4729. if (tryCombineExtendingLoads(MI))
  4730. return true;
  4731. if (tryCombineIndexedLoadStore(MI))
  4732. return true;
  4733. return false;
  4734. }