ARMBaseInstrInfo.cpp 228 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525
  1. //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the Base ARM implementation of the TargetInstrInfo class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ARMBaseInstrInfo.h"
  13. #include "ARMBaseRegisterInfo.h"
  14. #include "ARMConstantPoolValue.h"
  15. #include "ARMFeatures.h"
  16. #include "ARMHazardRecognizer.h"
  17. #include "ARMMachineFunctionInfo.h"
  18. #include "ARMSubtarget.h"
  19. #include "MCTargetDesc/ARMAddressingModes.h"
  20. #include "MCTargetDesc/ARMBaseInfo.h"
  21. #include "MVETailPredUtils.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/CodeGen/LiveVariables.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineConstantPool.h"
  30. #include "llvm/CodeGen/MachineFrameInfo.h"
  31. #include "llvm/CodeGen/MachineFunction.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineMemOperand.h"
  35. #include "llvm/CodeGen/MachineModuleInfo.h"
  36. #include "llvm/CodeGen/MachineOperand.h"
  37. #include "llvm/CodeGen/MachineRegisterInfo.h"
  38. #include "llvm/CodeGen/MachineScheduler.h"
  39. #include "llvm/CodeGen/MultiHazardRecognizer.h"
  40. #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
  41. #include "llvm/CodeGen/SelectionDAGNodes.h"
  42. #include "llvm/CodeGen/TargetInstrInfo.h"
  43. #include "llvm/CodeGen/TargetRegisterInfo.h"
  44. #include "llvm/CodeGen/TargetSchedule.h"
  45. #include "llvm/IR/Attributes.h"
  46. #include "llvm/IR/Constants.h"
  47. #include "llvm/IR/DebugLoc.h"
  48. #include "llvm/IR/Function.h"
  49. #include "llvm/IR/GlobalValue.h"
  50. #include "llvm/MC/MCAsmInfo.h"
  51. #include "llvm/MC/MCInstrDesc.h"
  52. #include "llvm/MC/MCInstrItineraries.h"
  53. #include "llvm/Support/BranchProbability.h"
  54. #include "llvm/Support/Casting.h"
  55. #include "llvm/Support/CommandLine.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/Debug.h"
  58. #include "llvm/Support/ErrorHandling.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include "llvm/Target/TargetMachine.h"
  61. #include <algorithm>
  62. #include <cassert>
  63. #include <cstdint>
  64. #include <iterator>
  65. #include <new>
  66. #include <utility>
  67. #include <vector>
  68. using namespace llvm;
  69. #define DEBUG_TYPE "arm-instrinfo"
  70. #define GET_INSTRINFO_CTOR_DTOR
  71. #include "ARMGenInstrInfo.inc"
  72. static cl::opt<bool>
  73. EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
  74. cl::desc("Enable ARM 2-addr to 3-addr conv"));
  75. /// ARM_MLxEntry - Record information about MLA / MLS instructions.
  76. struct ARM_MLxEntry {
  77. uint16_t MLxOpc; // MLA / MLS opcode
  78. uint16_t MulOpc; // Expanded multiplication opcode
  79. uint16_t AddSubOpc; // Expanded add / sub opcode
  80. bool NegAcc; // True if the acc is negated before the add / sub.
  81. bool HasLane; // True if instruction has an extra "lane" operand.
  82. };
  83. static const ARM_MLxEntry ARM_MLxTable[] = {
  84. // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane
  85. // fp scalar ops
  86. { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false },
  87. { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false },
  88. { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false },
  89. { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false },
  90. { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false },
  91. { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false },
  92. { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false },
  93. { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false },
  94. // fp SIMD ops
  95. { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false },
  96. { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false },
  97. { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false },
  98. { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false },
  99. { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true },
  100. { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true },
  101. { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true },
  102. { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true },
  103. };
  104. ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
  105. : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
  106. Subtarget(STI) {
  107. for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
  108. if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
  109. llvm_unreachable("Duplicated entries?");
  110. MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
  111. MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
  112. }
  113. }
  114. // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
  115. // currently defaults to no prepass hazard recognizer.
  116. ScheduleHazardRecognizer *
  117. ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
  118. const ScheduleDAG *DAG) const {
  119. if (usePreRAHazardRecognizer()) {
  120. const InstrItineraryData *II =
  121. static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
  122. return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
  123. }
  124. return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
  125. }
  126. // Called during:
  127. // - pre-RA scheduling
  128. // - post-RA scheduling when FeatureUseMISched is set
  129. ScheduleHazardRecognizer *ARMBaseInstrInfo::CreateTargetMIHazardRecognizer(
  130. const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
  131. MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
  132. // We would like to restrict this hazard recognizer to only
  133. // post-RA scheduling; we can tell that we're post-RA because we don't
  134. // track VRegLiveness.
  135. // Cortex-M7: TRM indicates that there is a single ITCM bank and two DTCM
  136. // banks banked on bit 2. Assume that TCMs are in use.
  137. if (Subtarget.isCortexM7() && !DAG->hasVRegLiveness())
  138. MHR->AddHazardRecognizer(
  139. std::make_unique<ARMBankConflictHazardRecognizer>(DAG, 0x4, true));
  140. // Not inserting ARMHazardRecognizerFPMLx because that would change
  141. // legacy behavior
  142. auto BHR = TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
  143. MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
  144. return MHR;
  145. }
  146. // Called during post-RA scheduling when FeatureUseMISched is not set
  147. ScheduleHazardRecognizer *ARMBaseInstrInfo::
  148. CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
  149. const ScheduleDAG *DAG) const {
  150. MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
  151. if (Subtarget.isThumb2() || Subtarget.hasVFP2Base())
  152. MHR->AddHazardRecognizer(std::make_unique<ARMHazardRecognizerFPMLx>());
  153. auto BHR = TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
  154. if (BHR)
  155. MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
  156. return MHR;
  157. }
  158. MachineInstr *ARMBaseInstrInfo::convertToThreeAddress(
  159. MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const {
  160. // FIXME: Thumb2 support.
  161. if (!EnableARM3Addr)
  162. return nullptr;
  163. MachineFunction &MF = *MI.getParent()->getParent();
  164. uint64_t TSFlags = MI.getDesc().TSFlags;
  165. bool isPre = false;
  166. switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
  167. default: return nullptr;
  168. case ARMII::IndexModePre:
  169. isPre = true;
  170. break;
  171. case ARMII::IndexModePost:
  172. break;
  173. }
  174. // Try splitting an indexed load/store to an un-indexed one plus an add/sub
  175. // operation.
  176. unsigned MemOpc = getUnindexedOpcode(MI.getOpcode());
  177. if (MemOpc == 0)
  178. return nullptr;
  179. MachineInstr *UpdateMI = nullptr;
  180. MachineInstr *MemMI = nullptr;
  181. unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
  182. const MCInstrDesc &MCID = MI.getDesc();
  183. unsigned NumOps = MCID.getNumOperands();
  184. bool isLoad = !MI.mayStore();
  185. const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0);
  186. const MachineOperand &Base = MI.getOperand(2);
  187. const MachineOperand &Offset = MI.getOperand(NumOps - 3);
  188. Register WBReg = WB.getReg();
  189. Register BaseReg = Base.getReg();
  190. Register OffReg = Offset.getReg();
  191. unsigned OffImm = MI.getOperand(NumOps - 2).getImm();
  192. ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm();
  193. switch (AddrMode) {
  194. default: llvm_unreachable("Unknown indexed op!");
  195. case ARMII::AddrMode2: {
  196. bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
  197. unsigned Amt = ARM_AM::getAM2Offset(OffImm);
  198. if (OffReg == 0) {
  199. if (ARM_AM::getSOImmVal(Amt) == -1)
  200. // Can't encode it in a so_imm operand. This transformation will
  201. // add more than 1 instruction. Abandon!
  202. return nullptr;
  203. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  204. get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
  205. .addReg(BaseReg)
  206. .addImm(Amt)
  207. .add(predOps(Pred))
  208. .add(condCodeOp());
  209. } else if (Amt != 0) {
  210. ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
  211. unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
  212. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  213. get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
  214. .addReg(BaseReg)
  215. .addReg(OffReg)
  216. .addReg(0)
  217. .addImm(SOOpc)
  218. .add(predOps(Pred))
  219. .add(condCodeOp());
  220. } else
  221. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  222. get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
  223. .addReg(BaseReg)
  224. .addReg(OffReg)
  225. .add(predOps(Pred))
  226. .add(condCodeOp());
  227. break;
  228. }
  229. case ARMII::AddrMode3 : {
  230. bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
  231. unsigned Amt = ARM_AM::getAM3Offset(OffImm);
  232. if (OffReg == 0)
  233. // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
  234. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  235. get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
  236. .addReg(BaseReg)
  237. .addImm(Amt)
  238. .add(predOps(Pred))
  239. .add(condCodeOp());
  240. else
  241. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  242. get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
  243. .addReg(BaseReg)
  244. .addReg(OffReg)
  245. .add(predOps(Pred))
  246. .add(condCodeOp());
  247. break;
  248. }
  249. }
  250. std::vector<MachineInstr*> NewMIs;
  251. if (isPre) {
  252. if (isLoad)
  253. MemMI =
  254. BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
  255. .addReg(WBReg)
  256. .addImm(0)
  257. .addImm(Pred);
  258. else
  259. MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
  260. .addReg(MI.getOperand(1).getReg())
  261. .addReg(WBReg)
  262. .addReg(0)
  263. .addImm(0)
  264. .addImm(Pred);
  265. NewMIs.push_back(MemMI);
  266. NewMIs.push_back(UpdateMI);
  267. } else {
  268. if (isLoad)
  269. MemMI =
  270. BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
  271. .addReg(BaseReg)
  272. .addImm(0)
  273. .addImm(Pred);
  274. else
  275. MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
  276. .addReg(MI.getOperand(1).getReg())
  277. .addReg(BaseReg)
  278. .addReg(0)
  279. .addImm(0)
  280. .addImm(Pred);
  281. if (WB.isDead())
  282. UpdateMI->getOperand(0).setIsDead();
  283. NewMIs.push_back(UpdateMI);
  284. NewMIs.push_back(MemMI);
  285. }
  286. // Transfer LiveVariables states, kill / dead info.
  287. if (LV) {
  288. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  289. MachineOperand &MO = MI.getOperand(i);
  290. if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) {
  291. Register Reg = MO.getReg();
  292. LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
  293. if (MO.isDef()) {
  294. MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
  295. if (MO.isDead())
  296. LV->addVirtualRegisterDead(Reg, *NewMI);
  297. }
  298. if (MO.isUse() && MO.isKill()) {
  299. for (unsigned j = 0; j < 2; ++j) {
  300. // Look at the two new MI's in reverse order.
  301. MachineInstr *NewMI = NewMIs[j];
  302. if (!NewMI->readsRegister(Reg))
  303. continue;
  304. LV->addVirtualRegisterKilled(Reg, *NewMI);
  305. if (VI.removeKill(MI))
  306. VI.Kills.push_back(NewMI);
  307. break;
  308. }
  309. }
  310. }
  311. }
  312. }
  313. MachineBasicBlock::iterator MBBI = MI.getIterator();
  314. MFI->insert(MBBI, NewMIs[1]);
  315. MFI->insert(MBBI, NewMIs[0]);
  316. return NewMIs[0];
  317. }
  318. // Branch analysis.
  319. bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
  320. MachineBasicBlock *&TBB,
  321. MachineBasicBlock *&FBB,
  322. SmallVectorImpl<MachineOperand> &Cond,
  323. bool AllowModify) const {
  324. TBB = nullptr;
  325. FBB = nullptr;
  326. MachineBasicBlock::instr_iterator I = MBB.instr_end();
  327. if (I == MBB.instr_begin())
  328. return false; // Empty blocks are easy.
  329. --I;
  330. // Walk backwards from the end of the basic block until the branch is
  331. // analyzed or we give up.
  332. while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) {
  333. // Flag to be raised on unanalyzeable instructions. This is useful in cases
  334. // where we want to clean up on the end of the basic block before we bail
  335. // out.
  336. bool CantAnalyze = false;
  337. // Skip over DEBUG values, predicated nonterminators and speculation
  338. // barrier terminators.
  339. while (I->isDebugInstr() || !I->isTerminator() ||
  340. isSpeculationBarrierEndBBOpcode(I->getOpcode()) ||
  341. I->getOpcode() == ARM::t2DoLoopStartTP){
  342. if (I == MBB.instr_begin())
  343. return false;
  344. --I;
  345. }
  346. if (isIndirectBranchOpcode(I->getOpcode()) ||
  347. isJumpTableBranchOpcode(I->getOpcode())) {
  348. // Indirect branches and jump tables can't be analyzed, but we still want
  349. // to clean up any instructions at the tail of the basic block.
  350. CantAnalyze = true;
  351. } else if (isUncondBranchOpcode(I->getOpcode())) {
  352. TBB = I->getOperand(0).getMBB();
  353. } else if (isCondBranchOpcode(I->getOpcode())) {
  354. // Bail out if we encounter multiple conditional branches.
  355. if (!Cond.empty())
  356. return true;
  357. assert(!FBB && "FBB should have been null.");
  358. FBB = TBB;
  359. TBB = I->getOperand(0).getMBB();
  360. Cond.push_back(I->getOperand(1));
  361. Cond.push_back(I->getOperand(2));
  362. } else if (I->isReturn()) {
  363. // Returns can't be analyzed, but we should run cleanup.
  364. CantAnalyze = true;
  365. } else {
  366. // We encountered other unrecognized terminator. Bail out immediately.
  367. return true;
  368. }
  369. // Cleanup code - to be run for unpredicated unconditional branches and
  370. // returns.
  371. if (!isPredicated(*I) &&
  372. (isUncondBranchOpcode(I->getOpcode()) ||
  373. isIndirectBranchOpcode(I->getOpcode()) ||
  374. isJumpTableBranchOpcode(I->getOpcode()) ||
  375. I->isReturn())) {
  376. // Forget any previous condition branch information - it no longer applies.
  377. Cond.clear();
  378. FBB = nullptr;
  379. // If we can modify the function, delete everything below this
  380. // unconditional branch.
  381. if (AllowModify) {
  382. MachineBasicBlock::iterator DI = std::next(I);
  383. while (DI != MBB.instr_end()) {
  384. MachineInstr &InstToDelete = *DI;
  385. ++DI;
  386. // Speculation barriers must not be deleted.
  387. if (isSpeculationBarrierEndBBOpcode(InstToDelete.getOpcode()))
  388. continue;
  389. InstToDelete.eraseFromParent();
  390. }
  391. }
  392. }
  393. if (CantAnalyze) {
  394. // We may not be able to analyze the block, but we could still have
  395. // an unconditional branch as the last instruction in the block, which
  396. // just branches to layout successor. If this is the case, then just
  397. // remove it if we're allowed to make modifications.
  398. if (AllowModify && !isPredicated(MBB.back()) &&
  399. isUncondBranchOpcode(MBB.back().getOpcode()) &&
  400. TBB && MBB.isLayoutSuccessor(TBB))
  401. removeBranch(MBB);
  402. return true;
  403. }
  404. if (I == MBB.instr_begin())
  405. return false;
  406. --I;
  407. }
  408. // We made it past the terminators without bailing out - we must have
  409. // analyzed this branch successfully.
  410. return false;
  411. }
  412. unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB,
  413. int *BytesRemoved) const {
  414. assert(!BytesRemoved && "code size not handled");
  415. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  416. if (I == MBB.end())
  417. return 0;
  418. if (!isUncondBranchOpcode(I->getOpcode()) &&
  419. !isCondBranchOpcode(I->getOpcode()))
  420. return 0;
  421. // Remove the branch.
  422. I->eraseFromParent();
  423. I = MBB.end();
  424. if (I == MBB.begin()) return 1;
  425. --I;
  426. if (!isCondBranchOpcode(I->getOpcode()))
  427. return 1;
  428. // Remove the branch.
  429. I->eraseFromParent();
  430. return 2;
  431. }
  432. unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB,
  433. MachineBasicBlock *TBB,
  434. MachineBasicBlock *FBB,
  435. ArrayRef<MachineOperand> Cond,
  436. const DebugLoc &DL,
  437. int *BytesAdded) const {
  438. assert(!BytesAdded && "code size not handled");
  439. ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
  440. int BOpc = !AFI->isThumbFunction()
  441. ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
  442. int BccOpc = !AFI->isThumbFunction()
  443. ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
  444. bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
  445. // Shouldn't be a fall through.
  446. assert(TBB && "insertBranch must not be told to insert a fallthrough");
  447. assert((Cond.size() == 2 || Cond.size() == 0) &&
  448. "ARM branch conditions have two components!");
  449. // For conditional branches, we use addOperand to preserve CPSR flags.
  450. if (!FBB) {
  451. if (Cond.empty()) { // Unconditional branch?
  452. if (isThumb)
  453. BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL));
  454. else
  455. BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
  456. } else
  457. BuildMI(&MBB, DL, get(BccOpc))
  458. .addMBB(TBB)
  459. .addImm(Cond[0].getImm())
  460. .add(Cond[1]);
  461. return 1;
  462. }
  463. // Two-way conditional branch.
  464. BuildMI(&MBB, DL, get(BccOpc))
  465. .addMBB(TBB)
  466. .addImm(Cond[0].getImm())
  467. .add(Cond[1]);
  468. if (isThumb)
  469. BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL));
  470. else
  471. BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
  472. return 2;
  473. }
  474. bool ARMBaseInstrInfo::
  475. reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
  476. ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
  477. Cond[0].setImm(ARMCC::getOppositeCondition(CC));
  478. return false;
  479. }
  480. bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const {
  481. if (MI.isBundle()) {
  482. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  483. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  484. while (++I != E && I->isInsideBundle()) {
  485. int PIdx = I->findFirstPredOperandIdx();
  486. if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
  487. return true;
  488. }
  489. return false;
  490. }
  491. int PIdx = MI.findFirstPredOperandIdx();
  492. return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL;
  493. }
  494. std::string ARMBaseInstrInfo::createMIROperandComment(
  495. const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
  496. const TargetRegisterInfo *TRI) const {
  497. // First, let's see if there is a generic comment for this operand
  498. std::string GenericComment =
  499. TargetInstrInfo::createMIROperandComment(MI, Op, OpIdx, TRI);
  500. if (!GenericComment.empty())
  501. return GenericComment;
  502. // If not, check if we have an immediate operand.
  503. if (Op.getType() != MachineOperand::MO_Immediate)
  504. return std::string();
  505. // And print its corresponding condition code if the immediate is a
  506. // predicate.
  507. int FirstPredOp = MI.findFirstPredOperandIdx();
  508. if (FirstPredOp != (int) OpIdx)
  509. return std::string();
  510. std::string CC = "CC::";
  511. CC += ARMCondCodeToString((ARMCC::CondCodes)Op.getImm());
  512. return CC;
  513. }
  514. bool ARMBaseInstrInfo::PredicateInstruction(
  515. MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
  516. unsigned Opc = MI.getOpcode();
  517. if (isUncondBranchOpcode(Opc)) {
  518. MI.setDesc(get(getMatchingCondBranchOpcode(Opc)));
  519. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  520. .addImm(Pred[0].getImm())
  521. .addReg(Pred[1].getReg());
  522. return true;
  523. }
  524. int PIdx = MI.findFirstPredOperandIdx();
  525. if (PIdx != -1) {
  526. MachineOperand &PMO = MI.getOperand(PIdx);
  527. PMO.setImm(Pred[0].getImm());
  528. MI.getOperand(PIdx+1).setReg(Pred[1].getReg());
  529. // Thumb 1 arithmetic instructions do not set CPSR when executed inside an
  530. // IT block. This affects how they are printed.
  531. const MCInstrDesc &MCID = MI.getDesc();
  532. if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
  533. assert(MCID.OpInfo[1].isOptionalDef() && "CPSR def isn't expected operand");
  534. assert((MI.getOperand(1).isDead() ||
  535. MI.getOperand(1).getReg() != ARM::CPSR) &&
  536. "if conversion tried to stop defining used CPSR");
  537. MI.getOperand(1).setReg(ARM::NoRegister);
  538. }
  539. return true;
  540. }
  541. return false;
  542. }
  543. bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
  544. ArrayRef<MachineOperand> Pred2) const {
  545. if (Pred1.size() > 2 || Pred2.size() > 2)
  546. return false;
  547. ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
  548. ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
  549. if (CC1 == CC2)
  550. return true;
  551. switch (CC1) {
  552. default:
  553. return false;
  554. case ARMCC::AL:
  555. return true;
  556. case ARMCC::HS:
  557. return CC2 == ARMCC::HI;
  558. case ARMCC::LS:
  559. return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
  560. case ARMCC::GE:
  561. return CC2 == ARMCC::GT;
  562. case ARMCC::LE:
  563. return CC2 == ARMCC::LT;
  564. }
  565. }
  566. bool ARMBaseInstrInfo::ClobbersPredicate(MachineInstr &MI,
  567. std::vector<MachineOperand> &Pred,
  568. bool SkipDead) const {
  569. bool Found = false;
  570. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  571. const MachineOperand &MO = MI.getOperand(i);
  572. bool ClobbersCPSR = MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR);
  573. bool IsCPSR = MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR;
  574. if (ClobbersCPSR || IsCPSR) {
  575. // Filter out T1 instructions that have a dead CPSR,
  576. // allowing IT blocks to be generated containing T1 instructions
  577. const MCInstrDesc &MCID = MI.getDesc();
  578. if (MCID.TSFlags & ARMII::ThumbArithFlagSetting && MO.isDead() &&
  579. SkipDead)
  580. continue;
  581. Pred.push_back(MO);
  582. Found = true;
  583. }
  584. }
  585. return Found;
  586. }
  587. bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) {
  588. for (const auto &MO : MI.operands())
  589. if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead())
  590. return true;
  591. return false;
  592. }
  593. static bool isEligibleForITBlock(const MachineInstr *MI) {
  594. switch (MI->getOpcode()) {
  595. default: return true;
  596. case ARM::tADC: // ADC (register) T1
  597. case ARM::tADDi3: // ADD (immediate) T1
  598. case ARM::tADDi8: // ADD (immediate) T2
  599. case ARM::tADDrr: // ADD (register) T1
  600. case ARM::tAND: // AND (register) T1
  601. case ARM::tASRri: // ASR (immediate) T1
  602. case ARM::tASRrr: // ASR (register) T1
  603. case ARM::tBIC: // BIC (register) T1
  604. case ARM::tEOR: // EOR (register) T1
  605. case ARM::tLSLri: // LSL (immediate) T1
  606. case ARM::tLSLrr: // LSL (register) T1
  607. case ARM::tLSRri: // LSR (immediate) T1
  608. case ARM::tLSRrr: // LSR (register) T1
  609. case ARM::tMUL: // MUL T1
  610. case ARM::tMVN: // MVN (register) T1
  611. case ARM::tORR: // ORR (register) T1
  612. case ARM::tROR: // ROR (register) T1
  613. case ARM::tRSB: // RSB (immediate) T1
  614. case ARM::tSBC: // SBC (register) T1
  615. case ARM::tSUBi3: // SUB (immediate) T1
  616. case ARM::tSUBi8: // SUB (immediate) T2
  617. case ARM::tSUBrr: // SUB (register) T1
  618. return !ARMBaseInstrInfo::isCPSRDefined(*MI);
  619. }
  620. }
  621. /// isPredicable - Return true if the specified instruction can be predicated.
  622. /// By default, this returns true for every instruction with a
  623. /// PredicateOperand.
  624. bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const {
  625. if (!MI.isPredicable())
  626. return false;
  627. if (MI.isBundle())
  628. return false;
  629. if (!isEligibleForITBlock(&MI))
  630. return false;
  631. const MachineFunction *MF = MI.getParent()->getParent();
  632. const ARMFunctionInfo *AFI =
  633. MF->getInfo<ARMFunctionInfo>();
  634. // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM.
  635. // In their ARM encoding, they can't be encoded in a conditional form.
  636. if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
  637. return false;
  638. // Make indirect control flow changes unpredicable when SLS mitigation is
  639. // enabled.
  640. const ARMSubtarget &ST = MF->getSubtarget<ARMSubtarget>();
  641. if (ST.hardenSlsRetBr() && isIndirectControlFlowNotComingBack(MI))
  642. return false;
  643. if (ST.hardenSlsBlr() && isIndirectCall(MI))
  644. return false;
  645. if (AFI->isThumb2Function()) {
  646. if (getSubtarget().restrictIT())
  647. return isV8EligibleForIT(&MI);
  648. }
  649. return true;
  650. }
  651. namespace llvm {
  652. template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) {
  653. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  654. const MachineOperand &MO = MI->getOperand(i);
  655. if (!MO.isReg() || MO.isUndef() || MO.isUse())
  656. continue;
  657. if (MO.getReg() != ARM::CPSR)
  658. continue;
  659. if (!MO.isDead())
  660. return false;
  661. }
  662. // all definitions of CPSR are dead
  663. return true;
  664. }
  665. } // end namespace llvm
  666. /// GetInstSize - Return the size of the specified MachineInstr.
  667. ///
  668. unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
  669. const MachineBasicBlock &MBB = *MI.getParent();
  670. const MachineFunction *MF = MBB.getParent();
  671. const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
  672. const MCInstrDesc &MCID = MI.getDesc();
  673. if (MCID.getSize())
  674. return MCID.getSize();
  675. switch (MI.getOpcode()) {
  676. default:
  677. // pseudo-instruction sizes are zero.
  678. return 0;
  679. case TargetOpcode::BUNDLE:
  680. return getInstBundleLength(MI);
  681. case ARM::MOVi16_ga_pcrel:
  682. case ARM::MOVTi16_ga_pcrel:
  683. case ARM::t2MOVi16_ga_pcrel:
  684. case ARM::t2MOVTi16_ga_pcrel:
  685. return 4;
  686. case ARM::MOVi32imm:
  687. case ARM::t2MOVi32imm:
  688. return 8;
  689. case ARM::CONSTPOOL_ENTRY:
  690. case ARM::JUMPTABLE_INSTS:
  691. case ARM::JUMPTABLE_ADDRS:
  692. case ARM::JUMPTABLE_TBB:
  693. case ARM::JUMPTABLE_TBH:
  694. // If this machine instr is a constant pool entry, its size is recorded as
  695. // operand #2.
  696. return MI.getOperand(2).getImm();
  697. case ARM::Int_eh_sjlj_longjmp:
  698. return 16;
  699. case ARM::tInt_eh_sjlj_longjmp:
  700. return 10;
  701. case ARM::tInt_WIN_eh_sjlj_longjmp:
  702. return 12;
  703. case ARM::Int_eh_sjlj_setjmp:
  704. case ARM::Int_eh_sjlj_setjmp_nofp:
  705. return 20;
  706. case ARM::tInt_eh_sjlj_setjmp:
  707. case ARM::t2Int_eh_sjlj_setjmp:
  708. case ARM::t2Int_eh_sjlj_setjmp_nofp:
  709. return 12;
  710. case ARM::SPACE:
  711. return MI.getOperand(1).getImm();
  712. case ARM::INLINEASM:
  713. case ARM::INLINEASM_BR: {
  714. // If this machine instr is an inline asm, measure it.
  715. unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
  716. if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction())
  717. Size = alignTo(Size, 4);
  718. return Size;
  719. }
  720. case ARM::SpeculationBarrierISBDSBEndBB:
  721. case ARM::t2SpeculationBarrierISBDSBEndBB:
  722. // This gets lowered to 2 4-byte instructions.
  723. return 8;
  724. case ARM::SpeculationBarrierSBEndBB:
  725. case ARM::t2SpeculationBarrierSBEndBB:
  726. // This gets lowered to 1 4-byte instructions.
  727. return 4;
  728. }
  729. }
  730. unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const {
  731. unsigned Size = 0;
  732. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  733. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  734. while (++I != E && I->isInsideBundle()) {
  735. assert(!I->isBundle() && "No nested bundle!");
  736. Size += getInstSizeInBytes(*I);
  737. }
  738. return Size;
  739. }
  740. void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB,
  741. MachineBasicBlock::iterator I,
  742. unsigned DestReg, bool KillSrc,
  743. const ARMSubtarget &Subtarget) const {
  744. unsigned Opc = Subtarget.isThumb()
  745. ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR)
  746. : ARM::MRS;
  747. MachineInstrBuilder MIB =
  748. BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg);
  749. // There is only 1 A/R class MRS instruction, and it always refers to
  750. // APSR. However, there are lots of other possibilities on M-class cores.
  751. if (Subtarget.isMClass())
  752. MIB.addImm(0x800);
  753. MIB.add(predOps(ARMCC::AL))
  754. .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc));
  755. }
  756. void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB,
  757. MachineBasicBlock::iterator I,
  758. unsigned SrcReg, bool KillSrc,
  759. const ARMSubtarget &Subtarget) const {
  760. unsigned Opc = Subtarget.isThumb()
  761. ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR)
  762. : ARM::MSR;
  763. MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
  764. if (Subtarget.isMClass())
  765. MIB.addImm(0x800);
  766. else
  767. MIB.addImm(8);
  768. MIB.addReg(SrcReg, getKillRegState(KillSrc))
  769. .add(predOps(ARMCC::AL))
  770. .addReg(ARM::CPSR, RegState::Implicit | RegState::Define);
  771. }
  772. void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) {
  773. MIB.addImm(ARMVCC::None);
  774. MIB.addReg(0);
  775. }
  776. void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB,
  777. Register DestReg) {
  778. addUnpredicatedMveVpredNOp(MIB);
  779. MIB.addReg(DestReg, RegState::Undef);
  780. }
  781. void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) {
  782. MIB.addImm(Cond);
  783. MIB.addReg(ARM::VPR, RegState::Implicit);
  784. }
  785. void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB,
  786. unsigned Cond, unsigned Inactive) {
  787. addPredicatedMveVpredNOp(MIB, Cond);
  788. MIB.addReg(Inactive);
  789. }
  790. void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
  791. MachineBasicBlock::iterator I,
  792. const DebugLoc &DL, MCRegister DestReg,
  793. MCRegister SrcReg, bool KillSrc) const {
  794. bool GPRDest = ARM::GPRRegClass.contains(DestReg);
  795. bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
  796. if (GPRDest && GPRSrc) {
  797. BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
  798. .addReg(SrcReg, getKillRegState(KillSrc))
  799. .add(predOps(ARMCC::AL))
  800. .add(condCodeOp());
  801. return;
  802. }
  803. bool SPRDest = ARM::SPRRegClass.contains(DestReg);
  804. bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
  805. unsigned Opc = 0;
  806. if (SPRDest && SPRSrc)
  807. Opc = ARM::VMOVS;
  808. else if (GPRDest && SPRSrc)
  809. Opc = ARM::VMOVRS;
  810. else if (SPRDest && GPRSrc)
  811. Opc = ARM::VMOVSR;
  812. else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64())
  813. Opc = ARM::VMOVD;
  814. else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
  815. Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
  816. if (Opc) {
  817. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
  818. MIB.addReg(SrcReg, getKillRegState(KillSrc));
  819. if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR)
  820. MIB.addReg(SrcReg, getKillRegState(KillSrc));
  821. if (Opc == ARM::MVE_VORR)
  822. addUnpredicatedMveVpredROp(MIB, DestReg);
  823. else
  824. MIB.add(predOps(ARMCC::AL));
  825. return;
  826. }
  827. // Handle register classes that require multiple instructions.
  828. unsigned BeginIdx = 0;
  829. unsigned SubRegs = 0;
  830. int Spacing = 1;
  831. // Use VORRq when possible.
  832. if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
  833. Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
  834. BeginIdx = ARM::qsub_0;
  835. SubRegs = 2;
  836. } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
  837. Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
  838. BeginIdx = ARM::qsub_0;
  839. SubRegs = 4;
  840. // Fall back to VMOVD.
  841. } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
  842. Opc = ARM::VMOVD;
  843. BeginIdx = ARM::dsub_0;
  844. SubRegs = 2;
  845. } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
  846. Opc = ARM::VMOVD;
  847. BeginIdx = ARM::dsub_0;
  848. SubRegs = 3;
  849. } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
  850. Opc = ARM::VMOVD;
  851. BeginIdx = ARM::dsub_0;
  852. SubRegs = 4;
  853. } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
  854. Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
  855. BeginIdx = ARM::gsub_0;
  856. SubRegs = 2;
  857. } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
  858. Opc = ARM::VMOVD;
  859. BeginIdx = ARM::dsub_0;
  860. SubRegs = 2;
  861. Spacing = 2;
  862. } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
  863. Opc = ARM::VMOVD;
  864. BeginIdx = ARM::dsub_0;
  865. SubRegs = 3;
  866. Spacing = 2;
  867. } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
  868. Opc = ARM::VMOVD;
  869. BeginIdx = ARM::dsub_0;
  870. SubRegs = 4;
  871. Spacing = 2;
  872. } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) &&
  873. !Subtarget.hasFP64()) {
  874. Opc = ARM::VMOVS;
  875. BeginIdx = ARM::ssub_0;
  876. SubRegs = 2;
  877. } else if (SrcReg == ARM::CPSR) {
  878. copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget);
  879. return;
  880. } else if (DestReg == ARM::CPSR) {
  881. copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget);
  882. return;
  883. } else if (DestReg == ARM::VPR) {
  884. assert(ARM::GPRRegClass.contains(SrcReg));
  885. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg)
  886. .addReg(SrcReg, getKillRegState(KillSrc))
  887. .add(predOps(ARMCC::AL));
  888. return;
  889. } else if (SrcReg == ARM::VPR) {
  890. assert(ARM::GPRRegClass.contains(DestReg));
  891. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg)
  892. .addReg(SrcReg, getKillRegState(KillSrc))
  893. .add(predOps(ARMCC::AL));
  894. return;
  895. } else if (DestReg == ARM::FPSCR_NZCV) {
  896. assert(ARM::GPRRegClass.contains(SrcReg));
  897. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg)
  898. .addReg(SrcReg, getKillRegState(KillSrc))
  899. .add(predOps(ARMCC::AL));
  900. return;
  901. } else if (SrcReg == ARM::FPSCR_NZCV) {
  902. assert(ARM::GPRRegClass.contains(DestReg));
  903. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg)
  904. .addReg(SrcReg, getKillRegState(KillSrc))
  905. .add(predOps(ARMCC::AL));
  906. return;
  907. }
  908. assert(Opc && "Impossible reg-to-reg copy");
  909. const TargetRegisterInfo *TRI = &getRegisterInfo();
  910. MachineInstrBuilder Mov;
  911. // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
  912. if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
  913. BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
  914. Spacing = -Spacing;
  915. }
  916. #ifndef NDEBUG
  917. SmallSet<unsigned, 4> DstRegs;
  918. #endif
  919. for (unsigned i = 0; i != SubRegs; ++i) {
  920. Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
  921. Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
  922. assert(Dst && Src && "Bad sub-register");
  923. #ifndef NDEBUG
  924. assert(!DstRegs.count(Src) && "destructive vector copy");
  925. DstRegs.insert(Dst);
  926. #endif
  927. Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
  928. // VORR (NEON or MVE) takes two source operands.
  929. if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) {
  930. Mov.addReg(Src);
  931. }
  932. // MVE VORR takes predicate operands in place of an ordinary condition.
  933. if (Opc == ARM::MVE_VORR)
  934. addUnpredicatedMveVpredROp(Mov, Dst);
  935. else
  936. Mov = Mov.add(predOps(ARMCC::AL));
  937. // MOVr can set CC.
  938. if (Opc == ARM::MOVr)
  939. Mov = Mov.add(condCodeOp());
  940. }
  941. // Add implicit super-register defs and kills to the last instruction.
  942. Mov->addRegisterDefined(DestReg, TRI);
  943. if (KillSrc)
  944. Mov->addRegisterKilled(SrcReg, TRI);
  945. }
  946. Optional<DestSourcePair>
  947. ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
  948. // VMOVRRD is also a copy instruction but it requires
  949. // special way of handling. It is more complex copy version
  950. // and since that we are not considering it. For recognition
  951. // of such instruction isExtractSubregLike MI interface fuction
  952. // could be used.
  953. // VORRq is considered as a move only if two inputs are
  954. // the same register.
  955. if (!MI.isMoveReg() ||
  956. (MI.getOpcode() == ARM::VORRq &&
  957. MI.getOperand(1).getReg() != MI.getOperand(2).getReg()))
  958. return None;
  959. return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
  960. }
  961. Optional<ParamLoadedValue>
  962. ARMBaseInstrInfo::describeLoadedValue(const MachineInstr &MI,
  963. Register Reg) const {
  964. if (auto DstSrcPair = isCopyInstrImpl(MI)) {
  965. Register DstReg = DstSrcPair->Destination->getReg();
  966. // TODO: We don't handle cases where the forwarding reg is narrower/wider
  967. // than the copy registers. Consider for example:
  968. //
  969. // s16 = VMOVS s0
  970. // s17 = VMOVS s1
  971. // call @callee(d0)
  972. //
  973. // We'd like to describe the call site value of d0 as d8, but this requires
  974. // gathering and merging the descriptions for the two VMOVS instructions.
  975. //
  976. // We also don't handle the reverse situation, where the forwarding reg is
  977. // narrower than the copy destination:
  978. //
  979. // d8 = VMOVD d0
  980. // call @callee(s1)
  981. //
  982. // We need to produce a fragment description (the call site value of s1 is
  983. // /not/ just d8).
  984. if (DstReg != Reg)
  985. return None;
  986. }
  987. return TargetInstrInfo::describeLoadedValue(MI, Reg);
  988. }
  989. const MachineInstrBuilder &
  990. ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
  991. unsigned SubIdx, unsigned State,
  992. const TargetRegisterInfo *TRI) const {
  993. if (!SubIdx)
  994. return MIB.addReg(Reg, State);
  995. if (Register::isPhysicalRegister(Reg))
  996. return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
  997. return MIB.addReg(Reg, State, SubIdx);
  998. }
  999. void ARMBaseInstrInfo::
  1000. storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
  1001. Register SrcReg, bool isKill, int FI,
  1002. const TargetRegisterClass *RC,
  1003. const TargetRegisterInfo *TRI) const {
  1004. MachineFunction &MF = *MBB.getParent();
  1005. MachineFrameInfo &MFI = MF.getFrameInfo();
  1006. Align Alignment = MFI.getObjectAlign(FI);
  1007. MachineMemOperand *MMO = MF.getMachineMemOperand(
  1008. MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
  1009. MFI.getObjectSize(FI), Alignment);
  1010. switch (TRI->getSpillSize(*RC)) {
  1011. case 2:
  1012. if (ARM::HPRRegClass.hasSubClassEq(RC)) {
  1013. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH))
  1014. .addReg(SrcReg, getKillRegState(isKill))
  1015. .addFrameIndex(FI)
  1016. .addImm(0)
  1017. .addMemOperand(MMO)
  1018. .add(predOps(ARMCC::AL));
  1019. } else
  1020. llvm_unreachable("Unknown reg class!");
  1021. break;
  1022. case 4:
  1023. if (ARM::GPRRegClass.hasSubClassEq(RC)) {
  1024. BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12))
  1025. .addReg(SrcReg, getKillRegState(isKill))
  1026. .addFrameIndex(FI)
  1027. .addImm(0)
  1028. .addMemOperand(MMO)
  1029. .add(predOps(ARMCC::AL));
  1030. } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
  1031. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS))
  1032. .addReg(SrcReg, getKillRegState(isKill))
  1033. .addFrameIndex(FI)
  1034. .addImm(0)
  1035. .addMemOperand(MMO)
  1036. .add(predOps(ARMCC::AL));
  1037. } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
  1038. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off))
  1039. .addReg(SrcReg, getKillRegState(isKill))
  1040. .addFrameIndex(FI)
  1041. .addImm(0)
  1042. .addMemOperand(MMO)
  1043. .add(predOps(ARMCC::AL));
  1044. } else
  1045. llvm_unreachable("Unknown reg class!");
  1046. break;
  1047. case 8:
  1048. if (ARM::DPRRegClass.hasSubClassEq(RC)) {
  1049. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD))
  1050. .addReg(SrcReg, getKillRegState(isKill))
  1051. .addFrameIndex(FI)
  1052. .addImm(0)
  1053. .addMemOperand(MMO)
  1054. .add(predOps(ARMCC::AL));
  1055. } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
  1056. if (Subtarget.hasV5TEOps()) {
  1057. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD));
  1058. AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
  1059. AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
  1060. MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
  1061. .add(predOps(ARMCC::AL));
  1062. } else {
  1063. // Fallback to STM instruction, which has existed since the dawn of
  1064. // time.
  1065. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA))
  1066. .addFrameIndex(FI)
  1067. .addMemOperand(MMO)
  1068. .add(predOps(ARMCC::AL));
  1069. AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
  1070. AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
  1071. }
  1072. } else
  1073. llvm_unreachable("Unknown reg class!");
  1074. break;
  1075. case 16:
  1076. if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
  1077. // Use aligned spills if the stack can be realigned.
  1078. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
  1079. BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64))
  1080. .addFrameIndex(FI)
  1081. .addImm(16)
  1082. .addReg(SrcReg, getKillRegState(isKill))
  1083. .addMemOperand(MMO)
  1084. .add(predOps(ARMCC::AL));
  1085. } else {
  1086. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA))
  1087. .addReg(SrcReg, getKillRegState(isKill))
  1088. .addFrameIndex(FI)
  1089. .addMemOperand(MMO)
  1090. .add(predOps(ARMCC::AL));
  1091. }
  1092. } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
  1093. Subtarget.hasMVEIntegerOps()) {
  1094. auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32));
  1095. MIB.addReg(SrcReg, getKillRegState(isKill))
  1096. .addFrameIndex(FI)
  1097. .addImm(0)
  1098. .addMemOperand(MMO);
  1099. addUnpredicatedMveVpredNOp(MIB);
  1100. } else
  1101. llvm_unreachable("Unknown reg class!");
  1102. break;
  1103. case 24:
  1104. if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
  1105. // Use aligned spills if the stack can be realigned.
  1106. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1107. Subtarget.hasNEON()) {
  1108. BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo))
  1109. .addFrameIndex(FI)
  1110. .addImm(16)
  1111. .addReg(SrcReg, getKillRegState(isKill))
  1112. .addMemOperand(MMO)
  1113. .add(predOps(ARMCC::AL));
  1114. } else {
  1115. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
  1116. get(ARM::VSTMDIA))
  1117. .addFrameIndex(FI)
  1118. .add(predOps(ARMCC::AL))
  1119. .addMemOperand(MMO);
  1120. MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
  1121. MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
  1122. AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
  1123. }
  1124. } else
  1125. llvm_unreachable("Unknown reg class!");
  1126. break;
  1127. case 32:
  1128. if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
  1129. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1130. Subtarget.hasNEON()) {
  1131. // FIXME: It's possible to only store part of the QQ register if the
  1132. // spilled def has a sub-register index.
  1133. BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo))
  1134. .addFrameIndex(FI)
  1135. .addImm(16)
  1136. .addReg(SrcReg, getKillRegState(isKill))
  1137. .addMemOperand(MMO)
  1138. .add(predOps(ARMCC::AL));
  1139. } else {
  1140. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
  1141. get(ARM::VSTMDIA))
  1142. .addFrameIndex(FI)
  1143. .add(predOps(ARMCC::AL))
  1144. .addMemOperand(MMO);
  1145. MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
  1146. MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
  1147. MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
  1148. AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
  1149. }
  1150. } else
  1151. llvm_unreachable("Unknown reg class!");
  1152. break;
  1153. case 64:
  1154. if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
  1155. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA))
  1156. .addFrameIndex(FI)
  1157. .add(predOps(ARMCC::AL))
  1158. .addMemOperand(MMO);
  1159. MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
  1160. MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
  1161. MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
  1162. MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
  1163. MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
  1164. MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
  1165. MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
  1166. AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
  1167. } else
  1168. llvm_unreachable("Unknown reg class!");
  1169. break;
  1170. default:
  1171. llvm_unreachable("Unknown reg class!");
  1172. }
  1173. }
  1174. unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
  1175. int &FrameIndex) const {
  1176. switch (MI.getOpcode()) {
  1177. default: break;
  1178. case ARM::STRrs:
  1179. case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
  1180. if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
  1181. MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
  1182. MI.getOperand(3).getImm() == 0) {
  1183. FrameIndex = MI.getOperand(1).getIndex();
  1184. return MI.getOperand(0).getReg();
  1185. }
  1186. break;
  1187. case ARM::STRi12:
  1188. case ARM::t2STRi12:
  1189. case ARM::tSTRspi:
  1190. case ARM::VSTRD:
  1191. case ARM::VSTRS:
  1192. if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
  1193. MI.getOperand(2).getImm() == 0) {
  1194. FrameIndex = MI.getOperand(1).getIndex();
  1195. return MI.getOperand(0).getReg();
  1196. }
  1197. break;
  1198. case ARM::VSTR_P0_off:
  1199. if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
  1200. MI.getOperand(1).getImm() == 0) {
  1201. FrameIndex = MI.getOperand(0).getIndex();
  1202. return ARM::P0;
  1203. }
  1204. break;
  1205. case ARM::VST1q64:
  1206. case ARM::VST1d64TPseudo:
  1207. case ARM::VST1d64QPseudo:
  1208. if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) {
  1209. FrameIndex = MI.getOperand(0).getIndex();
  1210. return MI.getOperand(2).getReg();
  1211. }
  1212. break;
  1213. case ARM::VSTMQIA:
  1214. if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
  1215. FrameIndex = MI.getOperand(1).getIndex();
  1216. return MI.getOperand(0).getReg();
  1217. }
  1218. break;
  1219. }
  1220. return 0;
  1221. }
  1222. unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
  1223. int &FrameIndex) const {
  1224. SmallVector<const MachineMemOperand *, 1> Accesses;
  1225. if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) &&
  1226. Accesses.size() == 1) {
  1227. FrameIndex =
  1228. cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
  1229. ->getFrameIndex();
  1230. return true;
  1231. }
  1232. return false;
  1233. }
  1234. void ARMBaseInstrInfo::
  1235. loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
  1236. Register DestReg, int FI,
  1237. const TargetRegisterClass *RC,
  1238. const TargetRegisterInfo *TRI) const {
  1239. DebugLoc DL;
  1240. if (I != MBB.end()) DL = I->getDebugLoc();
  1241. MachineFunction &MF = *MBB.getParent();
  1242. MachineFrameInfo &MFI = MF.getFrameInfo();
  1243. const Align Alignment = MFI.getObjectAlign(FI);
  1244. MachineMemOperand *MMO = MF.getMachineMemOperand(
  1245. MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
  1246. MFI.getObjectSize(FI), Alignment);
  1247. switch (TRI->getSpillSize(*RC)) {
  1248. case 2:
  1249. if (ARM::HPRRegClass.hasSubClassEq(RC)) {
  1250. BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg)
  1251. .addFrameIndex(FI)
  1252. .addImm(0)
  1253. .addMemOperand(MMO)
  1254. .add(predOps(ARMCC::AL));
  1255. } else
  1256. llvm_unreachable("Unknown reg class!");
  1257. break;
  1258. case 4:
  1259. if (ARM::GPRRegClass.hasSubClassEq(RC)) {
  1260. BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
  1261. .addFrameIndex(FI)
  1262. .addImm(0)
  1263. .addMemOperand(MMO)
  1264. .add(predOps(ARMCC::AL));
  1265. } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
  1266. BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
  1267. .addFrameIndex(FI)
  1268. .addImm(0)
  1269. .addMemOperand(MMO)
  1270. .add(predOps(ARMCC::AL));
  1271. } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
  1272. BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg)
  1273. .addFrameIndex(FI)
  1274. .addImm(0)
  1275. .addMemOperand(MMO)
  1276. .add(predOps(ARMCC::AL));
  1277. } else
  1278. llvm_unreachable("Unknown reg class!");
  1279. break;
  1280. case 8:
  1281. if (ARM::DPRRegClass.hasSubClassEq(RC)) {
  1282. BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
  1283. .addFrameIndex(FI)
  1284. .addImm(0)
  1285. .addMemOperand(MMO)
  1286. .add(predOps(ARMCC::AL));
  1287. } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
  1288. MachineInstrBuilder MIB;
  1289. if (Subtarget.hasV5TEOps()) {
  1290. MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
  1291. AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
  1292. AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
  1293. MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
  1294. .add(predOps(ARMCC::AL));
  1295. } else {
  1296. // Fallback to LDM instruction, which has existed since the dawn of
  1297. // time.
  1298. MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA))
  1299. .addFrameIndex(FI)
  1300. .addMemOperand(MMO)
  1301. .add(predOps(ARMCC::AL));
  1302. MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
  1303. MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
  1304. }
  1305. if (Register::isPhysicalRegister(DestReg))
  1306. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1307. } else
  1308. llvm_unreachable("Unknown reg class!");
  1309. break;
  1310. case 16:
  1311. if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
  1312. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
  1313. BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
  1314. .addFrameIndex(FI)
  1315. .addImm(16)
  1316. .addMemOperand(MMO)
  1317. .add(predOps(ARMCC::AL));
  1318. } else {
  1319. BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
  1320. .addFrameIndex(FI)
  1321. .addMemOperand(MMO)
  1322. .add(predOps(ARMCC::AL));
  1323. }
  1324. } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
  1325. Subtarget.hasMVEIntegerOps()) {
  1326. auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg);
  1327. MIB.addFrameIndex(FI)
  1328. .addImm(0)
  1329. .addMemOperand(MMO);
  1330. addUnpredicatedMveVpredNOp(MIB);
  1331. } else
  1332. llvm_unreachable("Unknown reg class!");
  1333. break;
  1334. case 24:
  1335. if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
  1336. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1337. Subtarget.hasNEON()) {
  1338. BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
  1339. .addFrameIndex(FI)
  1340. .addImm(16)
  1341. .addMemOperand(MMO)
  1342. .add(predOps(ARMCC::AL));
  1343. } else {
  1344. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
  1345. .addFrameIndex(FI)
  1346. .addMemOperand(MMO)
  1347. .add(predOps(ARMCC::AL));
  1348. MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
  1349. MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
  1350. MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
  1351. if (Register::isPhysicalRegister(DestReg))
  1352. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1353. }
  1354. } else
  1355. llvm_unreachable("Unknown reg class!");
  1356. break;
  1357. case 32:
  1358. if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
  1359. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1360. Subtarget.hasNEON()) {
  1361. BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
  1362. .addFrameIndex(FI)
  1363. .addImm(16)
  1364. .addMemOperand(MMO)
  1365. .add(predOps(ARMCC::AL));
  1366. } else {
  1367. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
  1368. .addFrameIndex(FI)
  1369. .add(predOps(ARMCC::AL))
  1370. .addMemOperand(MMO);
  1371. MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
  1372. MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
  1373. MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
  1374. MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
  1375. if (Register::isPhysicalRegister(DestReg))
  1376. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1377. }
  1378. } else
  1379. llvm_unreachable("Unknown reg class!");
  1380. break;
  1381. case 64:
  1382. if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
  1383. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
  1384. .addFrameIndex(FI)
  1385. .add(predOps(ARMCC::AL))
  1386. .addMemOperand(MMO);
  1387. MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
  1388. MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
  1389. MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
  1390. MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
  1391. MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
  1392. MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
  1393. MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
  1394. MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
  1395. if (Register::isPhysicalRegister(DestReg))
  1396. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1397. } else
  1398. llvm_unreachable("Unknown reg class!");
  1399. break;
  1400. default:
  1401. llvm_unreachable("Unknown regclass!");
  1402. }
  1403. }
  1404. unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
  1405. int &FrameIndex) const {
  1406. switch (MI.getOpcode()) {
  1407. default: break;
  1408. case ARM::LDRrs:
  1409. case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame.
  1410. if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
  1411. MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
  1412. MI.getOperand(3).getImm() == 0) {
  1413. FrameIndex = MI.getOperand(1).getIndex();
  1414. return MI.getOperand(0).getReg();
  1415. }
  1416. break;
  1417. case ARM::LDRi12:
  1418. case ARM::t2LDRi12:
  1419. case ARM::tLDRspi:
  1420. case ARM::VLDRD:
  1421. case ARM::VLDRS:
  1422. if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
  1423. MI.getOperand(2).getImm() == 0) {
  1424. FrameIndex = MI.getOperand(1).getIndex();
  1425. return MI.getOperand(0).getReg();
  1426. }
  1427. break;
  1428. case ARM::VLDR_P0_off:
  1429. if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
  1430. MI.getOperand(1).getImm() == 0) {
  1431. FrameIndex = MI.getOperand(0).getIndex();
  1432. return ARM::P0;
  1433. }
  1434. break;
  1435. case ARM::VLD1q64:
  1436. case ARM::VLD1d8TPseudo:
  1437. case ARM::VLD1d16TPseudo:
  1438. case ARM::VLD1d32TPseudo:
  1439. case ARM::VLD1d64TPseudo:
  1440. case ARM::VLD1d8QPseudo:
  1441. case ARM::VLD1d16QPseudo:
  1442. case ARM::VLD1d32QPseudo:
  1443. case ARM::VLD1d64QPseudo:
  1444. if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
  1445. FrameIndex = MI.getOperand(1).getIndex();
  1446. return MI.getOperand(0).getReg();
  1447. }
  1448. break;
  1449. case ARM::VLDMQIA:
  1450. if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
  1451. FrameIndex = MI.getOperand(1).getIndex();
  1452. return MI.getOperand(0).getReg();
  1453. }
  1454. break;
  1455. }
  1456. return 0;
  1457. }
  1458. unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
  1459. int &FrameIndex) const {
  1460. SmallVector<const MachineMemOperand *, 1> Accesses;
  1461. if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) &&
  1462. Accesses.size() == 1) {
  1463. FrameIndex =
  1464. cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
  1465. ->getFrameIndex();
  1466. return true;
  1467. }
  1468. return false;
  1469. }
  1470. /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD
  1471. /// depending on whether the result is used.
  1472. void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const {
  1473. bool isThumb1 = Subtarget.isThumb1Only();
  1474. bool isThumb2 = Subtarget.isThumb2();
  1475. const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo();
  1476. DebugLoc dl = MI->getDebugLoc();
  1477. MachineBasicBlock *BB = MI->getParent();
  1478. MachineInstrBuilder LDM, STM;
  1479. if (isThumb1 || !MI->getOperand(1).isDead()) {
  1480. MachineOperand LDWb(MI->getOperand(1));
  1481. LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
  1482. : isThumb1 ? ARM::tLDMIA_UPD
  1483. : ARM::LDMIA_UPD))
  1484. .add(LDWb);
  1485. } else {
  1486. LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
  1487. }
  1488. if (isThumb1 || !MI->getOperand(0).isDead()) {
  1489. MachineOperand STWb(MI->getOperand(0));
  1490. STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
  1491. : isThumb1 ? ARM::tSTMIA_UPD
  1492. : ARM::STMIA_UPD))
  1493. .add(STWb);
  1494. } else {
  1495. STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
  1496. }
  1497. MachineOperand LDBase(MI->getOperand(3));
  1498. LDM.add(LDBase).add(predOps(ARMCC::AL));
  1499. MachineOperand STBase(MI->getOperand(2));
  1500. STM.add(STBase).add(predOps(ARMCC::AL));
  1501. // Sort the scratch registers into ascending order.
  1502. const TargetRegisterInfo &TRI = getRegisterInfo();
  1503. SmallVector<unsigned, 6> ScratchRegs;
  1504. for(unsigned I = 5; I < MI->getNumOperands(); ++I)
  1505. ScratchRegs.push_back(MI->getOperand(I).getReg());
  1506. llvm::sort(ScratchRegs,
  1507. [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool {
  1508. return TRI.getEncodingValue(Reg1) <
  1509. TRI.getEncodingValue(Reg2);
  1510. });
  1511. for (const auto &Reg : ScratchRegs) {
  1512. LDM.addReg(Reg, RegState::Define);
  1513. STM.addReg(Reg, RegState::Kill);
  1514. }
  1515. BB->erase(MI);
  1516. }
  1517. bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
  1518. if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
  1519. assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() &&
  1520. "LOAD_STACK_GUARD currently supported only for MachO.");
  1521. expandLoadStackGuard(MI);
  1522. MI.getParent()->erase(MI);
  1523. return true;
  1524. }
  1525. if (MI.getOpcode() == ARM::MEMCPY) {
  1526. expandMEMCPY(MI);
  1527. return true;
  1528. }
  1529. // This hook gets to expand COPY instructions before they become
  1530. // copyPhysReg() calls. Look for VMOVS instructions that can legally be
  1531. // widened to VMOVD. We prefer the VMOVD when possible because it may be
  1532. // changed into a VORR that can go down the NEON pipeline.
  1533. if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64())
  1534. return false;
  1535. // Look for a copy between even S-registers. That is where we keep floats
  1536. // when using NEON v2f32 instructions for f32 arithmetic.
  1537. Register DstRegS = MI.getOperand(0).getReg();
  1538. Register SrcRegS = MI.getOperand(1).getReg();
  1539. if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
  1540. return false;
  1541. const TargetRegisterInfo *TRI = &getRegisterInfo();
  1542. unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
  1543. &ARM::DPRRegClass);
  1544. unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
  1545. &ARM::DPRRegClass);
  1546. if (!DstRegD || !SrcRegD)
  1547. return false;
  1548. // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only
  1549. // legal if the COPY already defines the full DstRegD, and it isn't a
  1550. // sub-register insertion.
  1551. if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI))
  1552. return false;
  1553. // A dead copy shouldn't show up here, but reject it just in case.
  1554. if (MI.getOperand(0).isDead())
  1555. return false;
  1556. // All clear, widen the COPY.
  1557. LLVM_DEBUG(dbgs() << "widening: " << MI);
  1558. MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
  1559. // Get rid of the old implicit-def of DstRegD. Leave it if it defines a Q-reg
  1560. // or some other super-register.
  1561. int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD);
  1562. if (ImpDefIdx != -1)
  1563. MI.RemoveOperand(ImpDefIdx);
  1564. // Change the opcode and operands.
  1565. MI.setDesc(get(ARM::VMOVD));
  1566. MI.getOperand(0).setReg(DstRegD);
  1567. MI.getOperand(1).setReg(SrcRegD);
  1568. MIB.add(predOps(ARMCC::AL));
  1569. // We are now reading SrcRegD instead of SrcRegS. This may upset the
  1570. // register scavenger and machine verifier, so we need to indicate that we
  1571. // are reading an undefined value from SrcRegD, but a proper value from
  1572. // SrcRegS.
  1573. MI.getOperand(1).setIsUndef();
  1574. MIB.addReg(SrcRegS, RegState::Implicit);
  1575. // SrcRegD may actually contain an unrelated value in the ssub_1
  1576. // sub-register. Don't kill it. Only kill the ssub_0 sub-register.
  1577. if (MI.getOperand(1).isKill()) {
  1578. MI.getOperand(1).setIsKill(false);
  1579. MI.addRegisterKilled(SrcRegS, TRI, true);
  1580. }
  1581. LLVM_DEBUG(dbgs() << "replaced by: " << MI);
  1582. return true;
  1583. }
  1584. /// Create a copy of a const pool value. Update CPI to the new index and return
  1585. /// the label UID.
  1586. static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
  1587. MachineConstantPool *MCP = MF.getConstantPool();
  1588. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1589. const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
  1590. assert(MCPE.isMachineConstantPoolEntry() &&
  1591. "Expecting a machine constantpool entry!");
  1592. ARMConstantPoolValue *ACPV =
  1593. static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
  1594. unsigned PCLabelId = AFI->createPICLabelUId();
  1595. ARMConstantPoolValue *NewCPV = nullptr;
  1596. // FIXME: The below assumes PIC relocation model and that the function
  1597. // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
  1598. // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
  1599. // instructions, so that's probably OK, but is PIC always correct when
  1600. // we get here?
  1601. if (ACPV->isGlobalValue())
  1602. NewCPV = ARMConstantPoolConstant::Create(
  1603. cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue,
  1604. 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress());
  1605. else if (ACPV->isExtSymbol())
  1606. NewCPV = ARMConstantPoolSymbol::
  1607. Create(MF.getFunction().getContext(),
  1608. cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
  1609. else if (ACPV->isBlockAddress())
  1610. NewCPV = ARMConstantPoolConstant::
  1611. Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
  1612. ARMCP::CPBlockAddress, 4);
  1613. else if (ACPV->isLSDA())
  1614. NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId,
  1615. ARMCP::CPLSDA, 4);
  1616. else if (ACPV->isMachineBasicBlock())
  1617. NewCPV = ARMConstantPoolMBB::
  1618. Create(MF.getFunction().getContext(),
  1619. cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
  1620. else
  1621. llvm_unreachable("Unexpected ARM constantpool value type!!");
  1622. CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlign());
  1623. return PCLabelId;
  1624. }
  1625. void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB,
  1626. MachineBasicBlock::iterator I,
  1627. Register DestReg, unsigned SubIdx,
  1628. const MachineInstr &Orig,
  1629. const TargetRegisterInfo &TRI) const {
  1630. unsigned Opcode = Orig.getOpcode();
  1631. switch (Opcode) {
  1632. default: {
  1633. MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
  1634. MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
  1635. MBB.insert(I, MI);
  1636. break;
  1637. }
  1638. case ARM::tLDRpci_pic:
  1639. case ARM::t2LDRpci_pic: {
  1640. MachineFunction &MF = *MBB.getParent();
  1641. unsigned CPI = Orig.getOperand(1).getIndex();
  1642. unsigned PCLabelId = duplicateCPV(MF, CPI);
  1643. BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg)
  1644. .addConstantPoolIndex(CPI)
  1645. .addImm(PCLabelId)
  1646. .cloneMemRefs(Orig);
  1647. break;
  1648. }
  1649. }
  1650. }
  1651. MachineInstr &
  1652. ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB,
  1653. MachineBasicBlock::iterator InsertBefore,
  1654. const MachineInstr &Orig) const {
  1655. MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig);
  1656. MachineBasicBlock::instr_iterator I = Cloned.getIterator();
  1657. for (;;) {
  1658. switch (I->getOpcode()) {
  1659. case ARM::tLDRpci_pic:
  1660. case ARM::t2LDRpci_pic: {
  1661. MachineFunction &MF = *MBB.getParent();
  1662. unsigned CPI = I->getOperand(1).getIndex();
  1663. unsigned PCLabelId = duplicateCPV(MF, CPI);
  1664. I->getOperand(1).setIndex(CPI);
  1665. I->getOperand(2).setImm(PCLabelId);
  1666. break;
  1667. }
  1668. }
  1669. if (!I->isBundledWithSucc())
  1670. break;
  1671. ++I;
  1672. }
  1673. return Cloned;
  1674. }
  1675. bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0,
  1676. const MachineInstr &MI1,
  1677. const MachineRegisterInfo *MRI) const {
  1678. unsigned Opcode = MI0.getOpcode();
  1679. if (Opcode == ARM::t2LDRpci ||
  1680. Opcode == ARM::t2LDRpci_pic ||
  1681. Opcode == ARM::tLDRpci ||
  1682. Opcode == ARM::tLDRpci_pic ||
  1683. Opcode == ARM::LDRLIT_ga_pcrel ||
  1684. Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
  1685. Opcode == ARM::tLDRLIT_ga_pcrel ||
  1686. Opcode == ARM::MOV_ga_pcrel ||
  1687. Opcode == ARM::MOV_ga_pcrel_ldr ||
  1688. Opcode == ARM::t2MOV_ga_pcrel) {
  1689. if (MI1.getOpcode() != Opcode)
  1690. return false;
  1691. if (MI0.getNumOperands() != MI1.getNumOperands())
  1692. return false;
  1693. const MachineOperand &MO0 = MI0.getOperand(1);
  1694. const MachineOperand &MO1 = MI1.getOperand(1);
  1695. if (MO0.getOffset() != MO1.getOffset())
  1696. return false;
  1697. if (Opcode == ARM::LDRLIT_ga_pcrel ||
  1698. Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
  1699. Opcode == ARM::tLDRLIT_ga_pcrel ||
  1700. Opcode == ARM::MOV_ga_pcrel ||
  1701. Opcode == ARM::MOV_ga_pcrel_ldr ||
  1702. Opcode == ARM::t2MOV_ga_pcrel)
  1703. // Ignore the PC labels.
  1704. return MO0.getGlobal() == MO1.getGlobal();
  1705. const MachineFunction *MF = MI0.getParent()->getParent();
  1706. const MachineConstantPool *MCP = MF->getConstantPool();
  1707. int CPI0 = MO0.getIndex();
  1708. int CPI1 = MO1.getIndex();
  1709. const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
  1710. const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
  1711. bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
  1712. bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
  1713. if (isARMCP0 && isARMCP1) {
  1714. ARMConstantPoolValue *ACPV0 =
  1715. static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
  1716. ARMConstantPoolValue *ACPV1 =
  1717. static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
  1718. return ACPV0->hasSameValue(ACPV1);
  1719. } else if (!isARMCP0 && !isARMCP1) {
  1720. return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
  1721. }
  1722. return false;
  1723. } else if (Opcode == ARM::PICLDR) {
  1724. if (MI1.getOpcode() != Opcode)
  1725. return false;
  1726. if (MI0.getNumOperands() != MI1.getNumOperands())
  1727. return false;
  1728. Register Addr0 = MI0.getOperand(1).getReg();
  1729. Register Addr1 = MI1.getOperand(1).getReg();
  1730. if (Addr0 != Addr1) {
  1731. if (!MRI || !Register::isVirtualRegister(Addr0) ||
  1732. !Register::isVirtualRegister(Addr1))
  1733. return false;
  1734. // This assumes SSA form.
  1735. MachineInstr *Def0 = MRI->getVRegDef(Addr0);
  1736. MachineInstr *Def1 = MRI->getVRegDef(Addr1);
  1737. // Check if the loaded value, e.g. a constantpool of a global address, are
  1738. // the same.
  1739. if (!produceSameValue(*Def0, *Def1, MRI))
  1740. return false;
  1741. }
  1742. for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) {
  1743. // %12 = PICLDR %11, 0, 14, %noreg
  1744. const MachineOperand &MO0 = MI0.getOperand(i);
  1745. const MachineOperand &MO1 = MI1.getOperand(i);
  1746. if (!MO0.isIdenticalTo(MO1))
  1747. return false;
  1748. }
  1749. return true;
  1750. }
  1751. return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
  1752. }
  1753. /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
  1754. /// determine if two loads are loading from the same base address. It should
  1755. /// only return true if the base pointers are the same and the only differences
  1756. /// between the two addresses is the offset. It also returns the offsets by
  1757. /// reference.
  1758. ///
  1759. /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
  1760. /// is permanently disabled.
  1761. bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
  1762. int64_t &Offset1,
  1763. int64_t &Offset2) const {
  1764. // Don't worry about Thumb: just ARM and Thumb2.
  1765. if (Subtarget.isThumb1Only()) return false;
  1766. if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
  1767. return false;
  1768. switch (Load1->getMachineOpcode()) {
  1769. default:
  1770. return false;
  1771. case ARM::LDRi12:
  1772. case ARM::LDRBi12:
  1773. case ARM::LDRD:
  1774. case ARM::LDRH:
  1775. case ARM::LDRSB:
  1776. case ARM::LDRSH:
  1777. case ARM::VLDRD:
  1778. case ARM::VLDRS:
  1779. case ARM::t2LDRi8:
  1780. case ARM::t2LDRBi8:
  1781. case ARM::t2LDRDi8:
  1782. case ARM::t2LDRSHi8:
  1783. case ARM::t2LDRi12:
  1784. case ARM::t2LDRBi12:
  1785. case ARM::t2LDRSHi12:
  1786. break;
  1787. }
  1788. switch (Load2->getMachineOpcode()) {
  1789. default:
  1790. return false;
  1791. case ARM::LDRi12:
  1792. case ARM::LDRBi12:
  1793. case ARM::LDRD:
  1794. case ARM::LDRH:
  1795. case ARM::LDRSB:
  1796. case ARM::LDRSH:
  1797. case ARM::VLDRD:
  1798. case ARM::VLDRS:
  1799. case ARM::t2LDRi8:
  1800. case ARM::t2LDRBi8:
  1801. case ARM::t2LDRSHi8:
  1802. case ARM::t2LDRi12:
  1803. case ARM::t2LDRBi12:
  1804. case ARM::t2LDRSHi12:
  1805. break;
  1806. }
  1807. // Check if base addresses and chain operands match.
  1808. if (Load1->getOperand(0) != Load2->getOperand(0) ||
  1809. Load1->getOperand(4) != Load2->getOperand(4))
  1810. return false;
  1811. // Index should be Reg0.
  1812. if (Load1->getOperand(3) != Load2->getOperand(3))
  1813. return false;
  1814. // Determine the offsets.
  1815. if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
  1816. isa<ConstantSDNode>(Load2->getOperand(1))) {
  1817. Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
  1818. Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
  1819. return true;
  1820. }
  1821. return false;
  1822. }
  1823. /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
  1824. /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
  1825. /// be scheduled togther. On some targets if two loads are loading from
  1826. /// addresses in the same cache line, it's better if they are scheduled
  1827. /// together. This function takes two integers that represent the load offsets
  1828. /// from the common base address. It returns true if it decides it's desirable
  1829. /// to schedule the two loads together. "NumLoads" is the number of loads that
  1830. /// have already been scheduled after Load1.
  1831. ///
  1832. /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
  1833. /// is permanently disabled.
  1834. bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
  1835. int64_t Offset1, int64_t Offset2,
  1836. unsigned NumLoads) const {
  1837. // Don't worry about Thumb: just ARM and Thumb2.
  1838. if (Subtarget.isThumb1Only()) return false;
  1839. assert(Offset2 > Offset1);
  1840. if ((Offset2 - Offset1) / 8 > 64)
  1841. return false;
  1842. // Check if the machine opcodes are different. If they are different
  1843. // then we consider them to not be of the same base address,
  1844. // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
  1845. // In this case, they are considered to be the same because they are different
  1846. // encoding forms of the same basic instruction.
  1847. if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
  1848. !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
  1849. Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
  1850. (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
  1851. Load2->getMachineOpcode() == ARM::t2LDRBi8)))
  1852. return false; // FIXME: overly conservative?
  1853. // Four loads in a row should be sufficient.
  1854. if (NumLoads >= 3)
  1855. return false;
  1856. return true;
  1857. }
  1858. bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
  1859. const MachineBasicBlock *MBB,
  1860. const MachineFunction &MF) const {
  1861. // Debug info is never a scheduling boundary. It's necessary to be explicit
  1862. // due to the special treatment of IT instructions below, otherwise a
  1863. // dbg_value followed by an IT will result in the IT instruction being
  1864. // considered a scheduling hazard, which is wrong. It should be the actual
  1865. // instruction preceding the dbg_value instruction(s), just like it is
  1866. // when debug info is not present.
  1867. if (MI.isDebugInstr())
  1868. return false;
  1869. // Terminators and labels can't be scheduled around.
  1870. if (MI.isTerminator() || MI.isPosition())
  1871. return true;
  1872. // INLINEASM_BR can jump to another block
  1873. if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
  1874. return true;
  1875. // Treat the start of the IT block as a scheduling boundary, but schedule
  1876. // t2IT along with all instructions following it.
  1877. // FIXME: This is a big hammer. But the alternative is to add all potential
  1878. // true and anti dependencies to IT block instructions as implicit operands
  1879. // to the t2IT instruction. The added compile time and complexity does not
  1880. // seem worth it.
  1881. MachineBasicBlock::const_iterator I = MI;
  1882. // Make sure to skip any debug instructions
  1883. while (++I != MBB->end() && I->isDebugInstr())
  1884. ;
  1885. if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
  1886. return true;
  1887. // Don't attempt to schedule around any instruction that defines
  1888. // a stack-oriented pointer, as it's unlikely to be profitable. This
  1889. // saves compile time, because it doesn't require every single
  1890. // stack slot reference to depend on the instruction that does the
  1891. // modification.
  1892. // Calls don't actually change the stack pointer, even if they have imp-defs.
  1893. // No ARM calling conventions change the stack pointer. (X86 calling
  1894. // conventions sometimes do).
  1895. if (!MI.isCall() && MI.definesRegister(ARM::SP))
  1896. return true;
  1897. return false;
  1898. }
  1899. bool ARMBaseInstrInfo::
  1900. isProfitableToIfCvt(MachineBasicBlock &MBB,
  1901. unsigned NumCycles, unsigned ExtraPredCycles,
  1902. BranchProbability Probability) const {
  1903. if (!NumCycles)
  1904. return false;
  1905. // If we are optimizing for size, see if the branch in the predecessor can be
  1906. // lowered to cbn?z by the constant island lowering pass, and return false if
  1907. // so. This results in a shorter instruction sequence.
  1908. if (MBB.getParent()->getFunction().hasOptSize()) {
  1909. MachineBasicBlock *Pred = *MBB.pred_begin();
  1910. if (!Pred->empty()) {
  1911. MachineInstr *LastMI = &*Pred->rbegin();
  1912. if (LastMI->getOpcode() == ARM::t2Bcc) {
  1913. const TargetRegisterInfo *TRI = &getRegisterInfo();
  1914. MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI);
  1915. if (CmpMI)
  1916. return false;
  1917. }
  1918. }
  1919. }
  1920. return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles,
  1921. MBB, 0, 0, Probability);
  1922. }
  1923. bool ARMBaseInstrInfo::
  1924. isProfitableToIfCvt(MachineBasicBlock &TBB,
  1925. unsigned TCycles, unsigned TExtra,
  1926. MachineBasicBlock &FBB,
  1927. unsigned FCycles, unsigned FExtra,
  1928. BranchProbability Probability) const {
  1929. if (!TCycles)
  1930. return false;
  1931. // In thumb code we often end up trading one branch for a IT block, and
  1932. // if we are cloning the instruction can increase code size. Prevent
  1933. // blocks with multiple predecesors from being ifcvted to prevent this
  1934. // cloning.
  1935. if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) {
  1936. if (TBB.pred_size() != 1 || FBB.pred_size() != 1)
  1937. return false;
  1938. }
  1939. // Attempt to estimate the relative costs of predication versus branching.
  1940. // Here we scale up each component of UnpredCost to avoid precision issue when
  1941. // scaling TCycles/FCycles by Probability.
  1942. const unsigned ScalingUpFactor = 1024;
  1943. unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor;
  1944. unsigned UnpredCost;
  1945. if (!Subtarget.hasBranchPredictor()) {
  1946. // When we don't have a branch predictor it's always cheaper to not take a
  1947. // branch than take it, so we have to take that into account.
  1948. unsigned NotTakenBranchCost = 1;
  1949. unsigned TakenBranchCost = Subtarget.getMispredictionPenalty();
  1950. unsigned TUnpredCycles, FUnpredCycles;
  1951. if (!FCycles) {
  1952. // Triangle: TBB is the fallthrough
  1953. TUnpredCycles = TCycles + NotTakenBranchCost;
  1954. FUnpredCycles = TakenBranchCost;
  1955. } else {
  1956. // Diamond: TBB is the block that is branched to, FBB is the fallthrough
  1957. TUnpredCycles = TCycles + TakenBranchCost;
  1958. FUnpredCycles = FCycles + NotTakenBranchCost;
  1959. // The branch at the end of FBB will disappear when it's predicated, so
  1960. // discount it from PredCost.
  1961. PredCost -= 1 * ScalingUpFactor;
  1962. }
  1963. // The total cost is the cost of each path scaled by their probabilites
  1964. unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor);
  1965. unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor);
  1966. UnpredCost = TUnpredCost + FUnpredCost;
  1967. // When predicating assume that the first IT can be folded away but later
  1968. // ones cost one cycle each
  1969. if (Subtarget.isThumb2() && TCycles + FCycles > 4) {
  1970. PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor;
  1971. }
  1972. } else {
  1973. unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor);
  1974. unsigned FUnpredCost =
  1975. Probability.getCompl().scale(FCycles * ScalingUpFactor);
  1976. UnpredCost = TUnpredCost + FUnpredCost;
  1977. UnpredCost += 1 * ScalingUpFactor; // The branch itself
  1978. UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10;
  1979. }
  1980. return PredCost <= UnpredCost;
  1981. }
  1982. unsigned
  1983. ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF,
  1984. unsigned NumInsts) const {
  1985. // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions.
  1986. // ARM has a condition code field in every predicable instruction, using it
  1987. // doesn't change code size.
  1988. if (!Subtarget.isThumb2())
  1989. return 0;
  1990. // It's possible that the size of the IT is restricted to a single block.
  1991. unsigned MaxInsts = Subtarget.restrictIT() ? 1 : 4;
  1992. return divideCeil(NumInsts, MaxInsts) * 2;
  1993. }
  1994. unsigned
  1995. ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const {
  1996. // If this branch is likely to be folded into the comparison to form a
  1997. // CB(N)Z, then removing it won't reduce code size at all, because that will
  1998. // just replace the CB(N)Z with a CMP.
  1999. if (MI.getOpcode() == ARM::t2Bcc &&
  2000. findCMPToFoldIntoCBZ(&MI, &getRegisterInfo()))
  2001. return 0;
  2002. unsigned Size = getInstSizeInBytes(MI);
  2003. // For Thumb2, all branches are 32-bit instructions during the if conversion
  2004. // pass, but may be replaced with 16-bit instructions during size reduction.
  2005. // Since the branches considered by if conversion tend to be forward branches
  2006. // over small basic blocks, they are very likely to be in range for the
  2007. // narrow instructions, so we assume the final code size will be half what it
  2008. // currently is.
  2009. if (Subtarget.isThumb2())
  2010. Size /= 2;
  2011. return Size;
  2012. }
  2013. bool
  2014. ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
  2015. MachineBasicBlock &FMBB) const {
  2016. // Reduce false anti-dependencies to let the target's out-of-order execution
  2017. // engine do its thing.
  2018. return Subtarget.isProfitableToUnpredicate();
  2019. }
  2020. /// getInstrPredicate - If instruction is predicated, returns its predicate
  2021. /// condition, otherwise returns AL. It also returns the condition code
  2022. /// register by reference.
  2023. ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI,
  2024. Register &PredReg) {
  2025. int PIdx = MI.findFirstPredOperandIdx();
  2026. if (PIdx == -1) {
  2027. PredReg = 0;
  2028. return ARMCC::AL;
  2029. }
  2030. PredReg = MI.getOperand(PIdx+1).getReg();
  2031. return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
  2032. }
  2033. unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) {
  2034. if (Opc == ARM::B)
  2035. return ARM::Bcc;
  2036. if (Opc == ARM::tB)
  2037. return ARM::tBcc;
  2038. if (Opc == ARM::t2B)
  2039. return ARM::t2Bcc;
  2040. llvm_unreachable("Unknown unconditional branch opcode!");
  2041. }
  2042. MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI,
  2043. bool NewMI,
  2044. unsigned OpIdx1,
  2045. unsigned OpIdx2) const {
  2046. switch (MI.getOpcode()) {
  2047. case ARM::MOVCCr:
  2048. case ARM::t2MOVCCr: {
  2049. // MOVCC can be commuted by inverting the condition.
  2050. Register PredReg;
  2051. ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
  2052. // MOVCC AL can't be inverted. Shouldn't happen.
  2053. if (CC == ARMCC::AL || PredReg != ARM::CPSR)
  2054. return nullptr;
  2055. MachineInstr *CommutedMI =
  2056. TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
  2057. if (!CommutedMI)
  2058. return nullptr;
  2059. // After swapping the MOVCC operands, also invert the condition.
  2060. CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx())
  2061. .setImm(ARMCC::getOppositeCondition(CC));
  2062. return CommutedMI;
  2063. }
  2064. }
  2065. return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
  2066. }
  2067. /// Identify instructions that can be folded into a MOVCC instruction, and
  2068. /// return the defining instruction.
  2069. MachineInstr *
  2070. ARMBaseInstrInfo::canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI,
  2071. const TargetInstrInfo *TII) const {
  2072. if (!Reg.isVirtual())
  2073. return nullptr;
  2074. if (!MRI.hasOneNonDBGUse(Reg))
  2075. return nullptr;
  2076. MachineInstr *MI = MRI.getVRegDef(Reg);
  2077. if (!MI)
  2078. return nullptr;
  2079. // Check if MI can be predicated and folded into the MOVCC.
  2080. if (!isPredicable(*MI))
  2081. return nullptr;
  2082. // Check if MI has any non-dead defs or physreg uses. This also detects
  2083. // predicated instructions which will be reading CPSR.
  2084. for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
  2085. const MachineOperand &MO = MI->getOperand(i);
  2086. // Reject frame index operands, PEI can't handle the predicated pseudos.
  2087. if (MO.isFI() || MO.isCPI() || MO.isJTI())
  2088. return nullptr;
  2089. if (!MO.isReg())
  2090. continue;
  2091. // MI can't have any tied operands, that would conflict with predication.
  2092. if (MO.isTied())
  2093. return nullptr;
  2094. if (Register::isPhysicalRegister(MO.getReg()))
  2095. return nullptr;
  2096. if (MO.isDef() && !MO.isDead())
  2097. return nullptr;
  2098. }
  2099. bool DontMoveAcrossStores = true;
  2100. if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores))
  2101. return nullptr;
  2102. return MI;
  2103. }
  2104. bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI,
  2105. SmallVectorImpl<MachineOperand> &Cond,
  2106. unsigned &TrueOp, unsigned &FalseOp,
  2107. bool &Optimizable) const {
  2108. assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
  2109. "Unknown select instruction");
  2110. // MOVCC operands:
  2111. // 0: Def.
  2112. // 1: True use.
  2113. // 2: False use.
  2114. // 3: Condition code.
  2115. // 4: CPSR use.
  2116. TrueOp = 1;
  2117. FalseOp = 2;
  2118. Cond.push_back(MI.getOperand(3));
  2119. Cond.push_back(MI.getOperand(4));
  2120. // We can always fold a def.
  2121. Optimizable = true;
  2122. return false;
  2123. }
  2124. MachineInstr *
  2125. ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI,
  2126. SmallPtrSetImpl<MachineInstr *> &SeenMIs,
  2127. bool PreferFalse) const {
  2128. assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
  2129. "Unknown select instruction");
  2130. MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  2131. MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this);
  2132. bool Invert = !DefMI;
  2133. if (!DefMI)
  2134. DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this);
  2135. if (!DefMI)
  2136. return nullptr;
  2137. // Find new register class to use.
  2138. MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1);
  2139. Register DestReg = MI.getOperand(0).getReg();
  2140. const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
  2141. if (!MRI.constrainRegClass(DestReg, PreviousClass))
  2142. return nullptr;
  2143. // Create a new predicated version of DefMI.
  2144. // Rfalse is the first use.
  2145. MachineInstrBuilder NewMI =
  2146. BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);
  2147. // Copy all the DefMI operands, excluding its (null) predicate.
  2148. const MCInstrDesc &DefDesc = DefMI->getDesc();
  2149. for (unsigned i = 1, e = DefDesc.getNumOperands();
  2150. i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
  2151. NewMI.add(DefMI->getOperand(i));
  2152. unsigned CondCode = MI.getOperand(3).getImm();
  2153. if (Invert)
  2154. NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
  2155. else
  2156. NewMI.addImm(CondCode);
  2157. NewMI.add(MI.getOperand(4));
  2158. // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
  2159. if (NewMI->hasOptionalDef())
  2160. NewMI.add(condCodeOp());
  2161. // The output register value when the predicate is false is an implicit
  2162. // register operand tied to the first def.
  2163. // The tie makes the register allocator ensure the FalseReg is allocated the
  2164. // same register as operand 0.
  2165. FalseReg.setImplicit();
  2166. NewMI.add(FalseReg);
  2167. NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
  2168. // Update SeenMIs set: register newly created MI and erase removed DefMI.
  2169. SeenMIs.insert(NewMI);
  2170. SeenMIs.erase(DefMI);
  2171. // If MI is inside a loop, and DefMI is outside the loop, then kill flags on
  2172. // DefMI would be invalid when tranferred inside the loop. Checking for a
  2173. // loop is expensive, but at least remove kill flags if they are in different
  2174. // BBs.
  2175. if (DefMI->getParent() != MI.getParent())
  2176. NewMI->clearKillInfo();
  2177. // The caller will erase MI, but not DefMI.
  2178. DefMI->eraseFromParent();
  2179. return NewMI;
  2180. }
  2181. /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
  2182. /// instruction is encoded with an 'S' bit is determined by the optional CPSR
  2183. /// def operand.
  2184. ///
  2185. /// This will go away once we can teach tblgen how to set the optional CPSR def
  2186. /// operand itself.
  2187. struct AddSubFlagsOpcodePair {
  2188. uint16_t PseudoOpc;
  2189. uint16_t MachineOpc;
  2190. };
  2191. static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
  2192. {ARM::ADDSri, ARM::ADDri},
  2193. {ARM::ADDSrr, ARM::ADDrr},
  2194. {ARM::ADDSrsi, ARM::ADDrsi},
  2195. {ARM::ADDSrsr, ARM::ADDrsr},
  2196. {ARM::SUBSri, ARM::SUBri},
  2197. {ARM::SUBSrr, ARM::SUBrr},
  2198. {ARM::SUBSrsi, ARM::SUBrsi},
  2199. {ARM::SUBSrsr, ARM::SUBrsr},
  2200. {ARM::RSBSri, ARM::RSBri},
  2201. {ARM::RSBSrsi, ARM::RSBrsi},
  2202. {ARM::RSBSrsr, ARM::RSBrsr},
  2203. {ARM::tADDSi3, ARM::tADDi3},
  2204. {ARM::tADDSi8, ARM::tADDi8},
  2205. {ARM::tADDSrr, ARM::tADDrr},
  2206. {ARM::tADCS, ARM::tADC},
  2207. {ARM::tSUBSi3, ARM::tSUBi3},
  2208. {ARM::tSUBSi8, ARM::tSUBi8},
  2209. {ARM::tSUBSrr, ARM::tSUBrr},
  2210. {ARM::tSBCS, ARM::tSBC},
  2211. {ARM::tRSBS, ARM::tRSB},
  2212. {ARM::tLSLSri, ARM::tLSLri},
  2213. {ARM::t2ADDSri, ARM::t2ADDri},
  2214. {ARM::t2ADDSrr, ARM::t2ADDrr},
  2215. {ARM::t2ADDSrs, ARM::t2ADDrs},
  2216. {ARM::t2SUBSri, ARM::t2SUBri},
  2217. {ARM::t2SUBSrr, ARM::t2SUBrr},
  2218. {ARM::t2SUBSrs, ARM::t2SUBrs},
  2219. {ARM::t2RSBSri, ARM::t2RSBri},
  2220. {ARM::t2RSBSrs, ARM::t2RSBrs},
  2221. };
  2222. unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
  2223. for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
  2224. if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
  2225. return AddSubFlagsOpcodeMap[i].MachineOpc;
  2226. return 0;
  2227. }
  2228. void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
  2229. MachineBasicBlock::iterator &MBBI,
  2230. const DebugLoc &dl, Register DestReg,
  2231. Register BaseReg, int NumBytes,
  2232. ARMCC::CondCodes Pred, Register PredReg,
  2233. const ARMBaseInstrInfo &TII,
  2234. unsigned MIFlags) {
  2235. if (NumBytes == 0 && DestReg != BaseReg) {
  2236. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
  2237. .addReg(BaseReg, RegState::Kill)
  2238. .add(predOps(Pred, PredReg))
  2239. .add(condCodeOp())
  2240. .setMIFlags(MIFlags);
  2241. return;
  2242. }
  2243. bool isSub = NumBytes < 0;
  2244. if (isSub) NumBytes = -NumBytes;
  2245. while (NumBytes) {
  2246. unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
  2247. unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
  2248. assert(ThisVal && "Didn't extract field correctly");
  2249. // We will handle these bits from offset, clear them.
  2250. NumBytes &= ~ThisVal;
  2251. assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
  2252. // Build the new ADD / SUB.
  2253. unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
  2254. BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
  2255. .addReg(BaseReg, RegState::Kill)
  2256. .addImm(ThisVal)
  2257. .add(predOps(Pred, PredReg))
  2258. .add(condCodeOp())
  2259. .setMIFlags(MIFlags);
  2260. BaseReg = DestReg;
  2261. }
  2262. }
  2263. bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
  2264. MachineFunction &MF, MachineInstr *MI,
  2265. unsigned NumBytes) {
  2266. // This optimisation potentially adds lots of load and store
  2267. // micro-operations, it's only really a great benefit to code-size.
  2268. if (!Subtarget.hasMinSize())
  2269. return false;
  2270. // If only one register is pushed/popped, LLVM can use an LDR/STR
  2271. // instead. We can't modify those so make sure we're dealing with an
  2272. // instruction we understand.
  2273. bool IsPop = isPopOpcode(MI->getOpcode());
  2274. bool IsPush = isPushOpcode(MI->getOpcode());
  2275. if (!IsPush && !IsPop)
  2276. return false;
  2277. bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
  2278. MI->getOpcode() == ARM::VLDMDIA_UPD;
  2279. bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
  2280. MI->getOpcode() == ARM::tPOP ||
  2281. MI->getOpcode() == ARM::tPOP_RET;
  2282. assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
  2283. MI->getOperand(1).getReg() == ARM::SP)) &&
  2284. "trying to fold sp update into non-sp-updating push/pop");
  2285. // The VFP push & pop act on D-registers, so we can only fold an adjustment
  2286. // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
  2287. // if this is violated.
  2288. if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
  2289. return false;
  2290. // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
  2291. // pred) so the list starts at 4. Thumb1 starts after the predicate.
  2292. int RegListIdx = IsT1PushPop ? 2 : 4;
  2293. // Calculate the space we'll need in terms of registers.
  2294. unsigned RegsNeeded;
  2295. const TargetRegisterClass *RegClass;
  2296. if (IsVFPPushPop) {
  2297. RegsNeeded = NumBytes / 8;
  2298. RegClass = &ARM::DPRRegClass;
  2299. } else {
  2300. RegsNeeded = NumBytes / 4;
  2301. RegClass = &ARM::GPRRegClass;
  2302. }
  2303. // We're going to have to strip all list operands off before
  2304. // re-adding them since the order matters, so save the existing ones
  2305. // for later.
  2306. SmallVector<MachineOperand, 4> RegList;
  2307. // We're also going to need the first register transferred by this
  2308. // instruction, which won't necessarily be the first register in the list.
  2309. unsigned FirstRegEnc = -1;
  2310. const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
  2311. for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) {
  2312. MachineOperand &MO = MI->getOperand(i);
  2313. RegList.push_back(MO);
  2314. if (MO.isReg() && !MO.isImplicit() &&
  2315. TRI->getEncodingValue(MO.getReg()) < FirstRegEnc)
  2316. FirstRegEnc = TRI->getEncodingValue(MO.getReg());
  2317. }
  2318. const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
  2319. // Now try to find enough space in the reglist to allocate NumBytes.
  2320. for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded;
  2321. --CurRegEnc) {
  2322. unsigned CurReg = RegClass->getRegister(CurRegEnc);
  2323. if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7))
  2324. continue;
  2325. if (!IsPop) {
  2326. // Pushing any register is completely harmless, mark the register involved
  2327. // as undef since we don't care about its value and must not restore it
  2328. // during stack unwinding.
  2329. RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
  2330. false, false, true));
  2331. --RegsNeeded;
  2332. continue;
  2333. }
  2334. // However, we can only pop an extra register if it's not live. For
  2335. // registers live within the function we might clobber a return value
  2336. // register; the other way a register can be live here is if it's
  2337. // callee-saved.
  2338. if (isCalleeSavedRegister(CurReg, CSRegs) ||
  2339. MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) !=
  2340. MachineBasicBlock::LQR_Dead) {
  2341. // VFP pops don't allow holes in the register list, so any skip is fatal
  2342. // for our transformation. GPR pops do, so we should just keep looking.
  2343. if (IsVFPPushPop)
  2344. return false;
  2345. else
  2346. continue;
  2347. }
  2348. // Mark the unimportant registers as <def,dead> in the POP.
  2349. RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
  2350. true));
  2351. --RegsNeeded;
  2352. }
  2353. if (RegsNeeded > 0)
  2354. return false;
  2355. // Finally we know we can profitably perform the optimisation so go
  2356. // ahead: strip all existing registers off and add them back again
  2357. // in the right order.
  2358. for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
  2359. MI->RemoveOperand(i);
  2360. // Add the complete list back in.
  2361. MachineInstrBuilder MIB(MF, &*MI);
  2362. for (int i = RegList.size() - 1; i >= 0; --i)
  2363. MIB.add(RegList[i]);
  2364. return true;
  2365. }
  2366. bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
  2367. Register FrameReg, int &Offset,
  2368. const ARMBaseInstrInfo &TII) {
  2369. unsigned Opcode = MI.getOpcode();
  2370. const MCInstrDesc &Desc = MI.getDesc();
  2371. unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
  2372. bool isSub = false;
  2373. // Memory operands in inline assembly always use AddrMode2.
  2374. if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR)
  2375. AddrMode = ARMII::AddrMode2;
  2376. if (Opcode == ARM::ADDri) {
  2377. Offset += MI.getOperand(FrameRegIdx+1).getImm();
  2378. if (Offset == 0) {
  2379. // Turn it into a move.
  2380. MI.setDesc(TII.get(ARM::MOVr));
  2381. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  2382. MI.RemoveOperand(FrameRegIdx+1);
  2383. Offset = 0;
  2384. return true;
  2385. } else if (Offset < 0) {
  2386. Offset = -Offset;
  2387. isSub = true;
  2388. MI.setDesc(TII.get(ARM::SUBri));
  2389. }
  2390. // Common case: small offset, fits into instruction.
  2391. if (ARM_AM::getSOImmVal(Offset) != -1) {
  2392. // Replace the FrameIndex with sp / fp
  2393. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  2394. MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
  2395. Offset = 0;
  2396. return true;
  2397. }
  2398. // Otherwise, pull as much of the immedidate into this ADDri/SUBri
  2399. // as possible.
  2400. unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
  2401. unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
  2402. // We will handle these bits from offset, clear them.
  2403. Offset &= ~ThisImmVal;
  2404. // Get the properly encoded SOImmVal field.
  2405. assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
  2406. "Bit extraction didn't work?");
  2407. MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
  2408. } else {
  2409. unsigned ImmIdx = 0;
  2410. int InstrOffs = 0;
  2411. unsigned NumBits = 0;
  2412. unsigned Scale = 1;
  2413. switch (AddrMode) {
  2414. case ARMII::AddrMode_i12:
  2415. ImmIdx = FrameRegIdx + 1;
  2416. InstrOffs = MI.getOperand(ImmIdx).getImm();
  2417. NumBits = 12;
  2418. break;
  2419. case ARMII::AddrMode2:
  2420. ImmIdx = FrameRegIdx+2;
  2421. InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
  2422. if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2423. InstrOffs *= -1;
  2424. NumBits = 12;
  2425. break;
  2426. case ARMII::AddrMode3:
  2427. ImmIdx = FrameRegIdx+2;
  2428. InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
  2429. if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2430. InstrOffs *= -1;
  2431. NumBits = 8;
  2432. break;
  2433. case ARMII::AddrMode4:
  2434. case ARMII::AddrMode6:
  2435. // Can't fold any offset even if it's zero.
  2436. return false;
  2437. case ARMII::AddrMode5:
  2438. ImmIdx = FrameRegIdx+1;
  2439. InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
  2440. if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2441. InstrOffs *= -1;
  2442. NumBits = 8;
  2443. Scale = 4;
  2444. break;
  2445. case ARMII::AddrMode5FP16:
  2446. ImmIdx = FrameRegIdx+1;
  2447. InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
  2448. if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2449. InstrOffs *= -1;
  2450. NumBits = 8;
  2451. Scale = 2;
  2452. break;
  2453. case ARMII::AddrModeT2_i7:
  2454. case ARMII::AddrModeT2_i7s2:
  2455. case ARMII::AddrModeT2_i7s4:
  2456. ImmIdx = FrameRegIdx+1;
  2457. InstrOffs = MI.getOperand(ImmIdx).getImm();
  2458. NumBits = 7;
  2459. Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 :
  2460. AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1);
  2461. break;
  2462. default:
  2463. llvm_unreachable("Unsupported addressing mode!");
  2464. }
  2465. Offset += InstrOffs * Scale;
  2466. assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
  2467. if (Offset < 0) {
  2468. Offset = -Offset;
  2469. isSub = true;
  2470. }
  2471. // Attempt to fold address comp. if opcode has offset bits
  2472. if (NumBits > 0) {
  2473. // Common case: small offset, fits into instruction.
  2474. MachineOperand &ImmOp = MI.getOperand(ImmIdx);
  2475. int ImmedOffset = Offset / Scale;
  2476. unsigned Mask = (1 << NumBits) - 1;
  2477. if ((unsigned)Offset <= Mask * Scale) {
  2478. // Replace the FrameIndex with sp
  2479. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  2480. // FIXME: When addrmode2 goes away, this will simplify (like the
  2481. // T2 version), as the LDR.i12 versions don't need the encoding
  2482. // tricks for the offset value.
  2483. if (isSub) {
  2484. if (AddrMode == ARMII::AddrMode_i12)
  2485. ImmedOffset = -ImmedOffset;
  2486. else
  2487. ImmedOffset |= 1 << NumBits;
  2488. }
  2489. ImmOp.ChangeToImmediate(ImmedOffset);
  2490. Offset = 0;
  2491. return true;
  2492. }
  2493. // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
  2494. ImmedOffset = ImmedOffset & Mask;
  2495. if (isSub) {
  2496. if (AddrMode == ARMII::AddrMode_i12)
  2497. ImmedOffset = -ImmedOffset;
  2498. else
  2499. ImmedOffset |= 1 << NumBits;
  2500. }
  2501. ImmOp.ChangeToImmediate(ImmedOffset);
  2502. Offset &= ~(Mask*Scale);
  2503. }
  2504. }
  2505. Offset = (isSub) ? -Offset : Offset;
  2506. return Offset == 0;
  2507. }
  2508. /// analyzeCompare - For a comparison instruction, return the source registers
  2509. /// in SrcReg and SrcReg2 if having two register operands, and the value it
  2510. /// compares against in CmpValue. Return true if the comparison instruction
  2511. /// can be analyzed.
  2512. bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
  2513. Register &SrcReg2, int &CmpMask,
  2514. int &CmpValue) const {
  2515. switch (MI.getOpcode()) {
  2516. default: break;
  2517. case ARM::CMPri:
  2518. case ARM::t2CMPri:
  2519. case ARM::tCMPi8:
  2520. SrcReg = MI.getOperand(0).getReg();
  2521. SrcReg2 = 0;
  2522. CmpMask = ~0;
  2523. CmpValue = MI.getOperand(1).getImm();
  2524. return true;
  2525. case ARM::CMPrr:
  2526. case ARM::t2CMPrr:
  2527. case ARM::tCMPr:
  2528. SrcReg = MI.getOperand(0).getReg();
  2529. SrcReg2 = MI.getOperand(1).getReg();
  2530. CmpMask = ~0;
  2531. CmpValue = 0;
  2532. return true;
  2533. case ARM::TSTri:
  2534. case ARM::t2TSTri:
  2535. SrcReg = MI.getOperand(0).getReg();
  2536. SrcReg2 = 0;
  2537. CmpMask = MI.getOperand(1).getImm();
  2538. CmpValue = 0;
  2539. return true;
  2540. }
  2541. return false;
  2542. }
  2543. /// isSuitableForMask - Identify a suitable 'and' instruction that
  2544. /// operates on the given source register and applies the same mask
  2545. /// as a 'tst' instruction. Provide a limited look-through for copies.
  2546. /// When successful, MI will hold the found instruction.
  2547. static bool isSuitableForMask(MachineInstr *&MI, Register SrcReg,
  2548. int CmpMask, bool CommonUse) {
  2549. switch (MI->getOpcode()) {
  2550. case ARM::ANDri:
  2551. case ARM::t2ANDri:
  2552. if (CmpMask != MI->getOperand(2).getImm())
  2553. return false;
  2554. if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
  2555. return true;
  2556. break;
  2557. }
  2558. return false;
  2559. }
  2560. /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return
  2561. /// the condition code if we modify the instructions such that flags are
  2562. /// set by ADD(a,b,X).
  2563. inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) {
  2564. switch (CC) {
  2565. default: return ARMCC::AL;
  2566. case ARMCC::HS: return ARMCC::LO;
  2567. case ARMCC::LO: return ARMCC::HS;
  2568. case ARMCC::VS: return ARMCC::VS;
  2569. case ARMCC::VC: return ARMCC::VC;
  2570. }
  2571. }
  2572. /// isRedundantFlagInstr - check whether the first instruction, whose only
  2573. /// purpose is to update flags, can be made redundant.
  2574. /// CMPrr can be made redundant by SUBrr if the operands are the same.
  2575. /// CMPri can be made redundant by SUBri if the operands are the same.
  2576. /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X).
  2577. /// This function can be extended later on.
  2578. inline static bool isRedundantFlagInstr(const MachineInstr *CmpI,
  2579. Register SrcReg, Register SrcReg2,
  2580. int ImmValue, const MachineInstr *OI,
  2581. bool &IsThumb1) {
  2582. if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
  2583. (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) &&
  2584. ((OI->getOperand(1).getReg() == SrcReg &&
  2585. OI->getOperand(2).getReg() == SrcReg2) ||
  2586. (OI->getOperand(1).getReg() == SrcReg2 &&
  2587. OI->getOperand(2).getReg() == SrcReg))) {
  2588. IsThumb1 = false;
  2589. return true;
  2590. }
  2591. if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr &&
  2592. ((OI->getOperand(2).getReg() == SrcReg &&
  2593. OI->getOperand(3).getReg() == SrcReg2) ||
  2594. (OI->getOperand(2).getReg() == SrcReg2 &&
  2595. OI->getOperand(3).getReg() == SrcReg))) {
  2596. IsThumb1 = true;
  2597. return true;
  2598. }
  2599. if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) &&
  2600. (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) &&
  2601. OI->getOperand(1).getReg() == SrcReg &&
  2602. OI->getOperand(2).getImm() == ImmValue) {
  2603. IsThumb1 = false;
  2604. return true;
  2605. }
  2606. if (CmpI->getOpcode() == ARM::tCMPi8 &&
  2607. (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) &&
  2608. OI->getOperand(2).getReg() == SrcReg &&
  2609. OI->getOperand(3).getImm() == ImmValue) {
  2610. IsThumb1 = true;
  2611. return true;
  2612. }
  2613. if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
  2614. (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr ||
  2615. OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) &&
  2616. OI->getOperand(0).isReg() && OI->getOperand(1).isReg() &&
  2617. OI->getOperand(0).getReg() == SrcReg &&
  2618. OI->getOperand(1).getReg() == SrcReg2) {
  2619. IsThumb1 = false;
  2620. return true;
  2621. }
  2622. if (CmpI->getOpcode() == ARM::tCMPr &&
  2623. (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 ||
  2624. OI->getOpcode() == ARM::tADDrr) &&
  2625. OI->getOperand(0).getReg() == SrcReg &&
  2626. OI->getOperand(2).getReg() == SrcReg2) {
  2627. IsThumb1 = true;
  2628. return true;
  2629. }
  2630. return false;
  2631. }
  2632. static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) {
  2633. switch (MI->getOpcode()) {
  2634. default: return false;
  2635. case ARM::tLSLri:
  2636. case ARM::tLSRri:
  2637. case ARM::tLSLrr:
  2638. case ARM::tLSRrr:
  2639. case ARM::tSUBrr:
  2640. case ARM::tADDrr:
  2641. case ARM::tADDi3:
  2642. case ARM::tADDi8:
  2643. case ARM::tSUBi3:
  2644. case ARM::tSUBi8:
  2645. case ARM::tMUL:
  2646. case ARM::tADC:
  2647. case ARM::tSBC:
  2648. case ARM::tRSB:
  2649. case ARM::tAND:
  2650. case ARM::tORR:
  2651. case ARM::tEOR:
  2652. case ARM::tBIC:
  2653. case ARM::tMVN:
  2654. case ARM::tASRri:
  2655. case ARM::tASRrr:
  2656. case ARM::tROR:
  2657. IsThumb1 = true;
  2658. LLVM_FALLTHROUGH;
  2659. case ARM::RSBrr:
  2660. case ARM::RSBri:
  2661. case ARM::RSCrr:
  2662. case ARM::RSCri:
  2663. case ARM::ADDrr:
  2664. case ARM::ADDri:
  2665. case ARM::ADCrr:
  2666. case ARM::ADCri:
  2667. case ARM::SUBrr:
  2668. case ARM::SUBri:
  2669. case ARM::SBCrr:
  2670. case ARM::SBCri:
  2671. case ARM::t2RSBri:
  2672. case ARM::t2ADDrr:
  2673. case ARM::t2ADDri:
  2674. case ARM::t2ADCrr:
  2675. case ARM::t2ADCri:
  2676. case ARM::t2SUBrr:
  2677. case ARM::t2SUBri:
  2678. case ARM::t2SBCrr:
  2679. case ARM::t2SBCri:
  2680. case ARM::ANDrr:
  2681. case ARM::ANDri:
  2682. case ARM::t2ANDrr:
  2683. case ARM::t2ANDri:
  2684. case ARM::ORRrr:
  2685. case ARM::ORRri:
  2686. case ARM::t2ORRrr:
  2687. case ARM::t2ORRri:
  2688. case ARM::EORrr:
  2689. case ARM::EORri:
  2690. case ARM::t2EORrr:
  2691. case ARM::t2EORri:
  2692. case ARM::t2LSRri:
  2693. case ARM::t2LSRrr:
  2694. case ARM::t2LSLri:
  2695. case ARM::t2LSLrr:
  2696. return true;
  2697. }
  2698. }
  2699. /// optimizeCompareInstr - Convert the instruction supplying the argument to the
  2700. /// comparison into one that sets the zero bit in the flags register;
  2701. /// Remove a redundant Compare instruction if an earlier instruction can set the
  2702. /// flags in the same way as Compare.
  2703. /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
  2704. /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
  2705. /// condition code of instructions which use the flags.
  2706. bool ARMBaseInstrInfo::optimizeCompareInstr(
  2707. MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int CmpMask,
  2708. int CmpValue, const MachineRegisterInfo *MRI) const {
  2709. // Get the unique definition of SrcReg.
  2710. MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
  2711. if (!MI) return false;
  2712. // Masked compares sometimes use the same register as the corresponding 'and'.
  2713. if (CmpMask != ~0) {
  2714. if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) {
  2715. MI = nullptr;
  2716. for (MachineRegisterInfo::use_instr_iterator
  2717. UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
  2718. UI != UE; ++UI) {
  2719. if (UI->getParent() != CmpInstr.getParent())
  2720. continue;
  2721. MachineInstr *PotentialAND = &*UI;
  2722. if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
  2723. isPredicated(*PotentialAND))
  2724. continue;
  2725. MI = PotentialAND;
  2726. break;
  2727. }
  2728. if (!MI) return false;
  2729. }
  2730. }
  2731. // Get ready to iterate backward from CmpInstr.
  2732. MachineBasicBlock::iterator I = CmpInstr, E = MI,
  2733. B = CmpInstr.getParent()->begin();
  2734. // Early exit if CmpInstr is at the beginning of the BB.
  2735. if (I == B) return false;
  2736. // There are two possible candidates which can be changed to set CPSR:
  2737. // One is MI, the other is a SUB or ADD instruction.
  2738. // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or
  2739. // ADDr[ri](r1, r2, X).
  2740. // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
  2741. MachineInstr *SubAdd = nullptr;
  2742. if (SrcReg2 != 0)
  2743. // MI is not a candidate for CMPrr.
  2744. MI = nullptr;
  2745. else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {
  2746. // Conservatively refuse to convert an instruction which isn't in the same
  2747. // BB as the comparison.
  2748. // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate.
  2749. // Thus we cannot return here.
  2750. if (CmpInstr.getOpcode() == ARM::CMPri ||
  2751. CmpInstr.getOpcode() == ARM::t2CMPri ||
  2752. CmpInstr.getOpcode() == ARM::tCMPi8)
  2753. MI = nullptr;
  2754. else
  2755. return false;
  2756. }
  2757. bool IsThumb1 = false;
  2758. if (MI && !isOptimizeCompareCandidate(MI, IsThumb1))
  2759. return false;
  2760. // We also want to do this peephole for cases like this: if (a*b == 0),
  2761. // and optimise away the CMP instruction from the generated code sequence:
  2762. // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values
  2763. // resulting from the select instruction, but these MOVS instructions for
  2764. // Thumb1 (V6M) are flag setting and are thus preventing this optimisation.
  2765. // However, if we only have MOVS instructions in between the CMP and the
  2766. // other instruction (the MULS in this example), then the CPSR is dead so we
  2767. // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this
  2768. // reordering and then continue the analysis hoping we can eliminate the
  2769. // CMP. This peephole works on the vregs, so is still in SSA form. As a
  2770. // consequence, the movs won't redefine/kill the MUL operands which would
  2771. // make this reordering illegal.
  2772. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2773. if (MI && IsThumb1) {
  2774. --I;
  2775. if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) {
  2776. bool CanReorder = true;
  2777. for (; I != E; --I) {
  2778. if (I->getOpcode() != ARM::tMOVi8) {
  2779. CanReorder = false;
  2780. break;
  2781. }
  2782. }
  2783. if (CanReorder) {
  2784. MI = MI->removeFromParent();
  2785. E = CmpInstr;
  2786. CmpInstr.getParent()->insert(E, MI);
  2787. }
  2788. }
  2789. I = CmpInstr;
  2790. E = MI;
  2791. }
  2792. // Check that CPSR isn't set between the comparison instruction and the one we
  2793. // want to change. At the same time, search for SubAdd.
  2794. bool SubAddIsThumb1 = false;
  2795. do {
  2796. const MachineInstr &Instr = *--I;
  2797. // Check whether CmpInstr can be made redundant by the current instruction.
  2798. if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr,
  2799. SubAddIsThumb1)) {
  2800. SubAdd = &*I;
  2801. break;
  2802. }
  2803. // Allow E (which was initially MI) to be SubAdd but do not search before E.
  2804. if (I == E)
  2805. break;
  2806. if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
  2807. Instr.readsRegister(ARM::CPSR, TRI))
  2808. // This instruction modifies or uses CPSR after the one we want to
  2809. // change. We can't do this transformation.
  2810. return false;
  2811. if (I == B) {
  2812. // In some cases, we scan the use-list of an instruction for an AND;
  2813. // that AND is in the same BB, but may not be scheduled before the
  2814. // corresponding TST. In that case, bail out.
  2815. //
  2816. // FIXME: We could try to reschedule the AND.
  2817. return false;
  2818. }
  2819. } while (true);
  2820. // Return false if no candidates exist.
  2821. if (!MI && !SubAdd)
  2822. return false;
  2823. // If we found a SubAdd, use it as it will be closer to the CMP
  2824. if (SubAdd) {
  2825. MI = SubAdd;
  2826. IsThumb1 = SubAddIsThumb1;
  2827. }
  2828. // We can't use a predicated instruction - it doesn't always write the flags.
  2829. if (isPredicated(*MI))
  2830. return false;
  2831. // Scan forward for the use of CPSR
  2832. // When checking against MI: if it's a conditional code that requires
  2833. // checking of the V bit or C bit, then this is not safe to do.
  2834. // It is safe to remove CmpInstr if CPSR is redefined or killed.
  2835. // If we are done with the basic block, we need to check whether CPSR is
  2836. // live-out.
  2837. SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
  2838. OperandsToUpdate;
  2839. bool isSafe = false;
  2840. I = CmpInstr;
  2841. E = CmpInstr.getParent()->end();
  2842. while (!isSafe && ++I != E) {
  2843. const MachineInstr &Instr = *I;
  2844. for (unsigned IO = 0, EO = Instr.getNumOperands();
  2845. !isSafe && IO != EO; ++IO) {
  2846. const MachineOperand &MO = Instr.getOperand(IO);
  2847. if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
  2848. isSafe = true;
  2849. break;
  2850. }
  2851. if (!MO.isReg() || MO.getReg() != ARM::CPSR)
  2852. continue;
  2853. if (MO.isDef()) {
  2854. isSafe = true;
  2855. break;
  2856. }
  2857. // Condition code is after the operand before CPSR except for VSELs.
  2858. ARMCC::CondCodes CC;
  2859. bool IsInstrVSel = true;
  2860. switch (Instr.getOpcode()) {
  2861. default:
  2862. IsInstrVSel = false;
  2863. CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
  2864. break;
  2865. case ARM::VSELEQD:
  2866. case ARM::VSELEQS:
  2867. case ARM::VSELEQH:
  2868. CC = ARMCC::EQ;
  2869. break;
  2870. case ARM::VSELGTD:
  2871. case ARM::VSELGTS:
  2872. case ARM::VSELGTH:
  2873. CC = ARMCC::GT;
  2874. break;
  2875. case ARM::VSELGED:
  2876. case ARM::VSELGES:
  2877. case ARM::VSELGEH:
  2878. CC = ARMCC::GE;
  2879. break;
  2880. case ARM::VSELVSD:
  2881. case ARM::VSELVSS:
  2882. case ARM::VSELVSH:
  2883. CC = ARMCC::VS;
  2884. break;
  2885. }
  2886. if (SubAdd) {
  2887. // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
  2888. // on CMP needs to be updated to be based on SUB.
  2889. // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also
  2890. // needs to be modified.
  2891. // Push the condition code operands to OperandsToUpdate.
  2892. // If it is safe to remove CmpInstr, the condition code of these
  2893. // operands will be modified.
  2894. unsigned Opc = SubAdd->getOpcode();
  2895. bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr ||
  2896. Opc == ARM::SUBri || Opc == ARM::t2SUBri ||
  2897. Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 ||
  2898. Opc == ARM::tSUBi8;
  2899. unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2;
  2900. if (!IsSub ||
  2901. (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 &&
  2902. SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) {
  2903. // VSel doesn't support condition code update.
  2904. if (IsInstrVSel)
  2905. return false;
  2906. // Ensure we can swap the condition.
  2907. ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC));
  2908. if (NewCC == ARMCC::AL)
  2909. return false;
  2910. OperandsToUpdate.push_back(
  2911. std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
  2912. }
  2913. } else {
  2914. // No SubAdd, so this is x = <op> y, z; cmp x, 0.
  2915. switch (CC) {
  2916. case ARMCC::EQ: // Z
  2917. case ARMCC::NE: // Z
  2918. case ARMCC::MI: // N
  2919. case ARMCC::PL: // N
  2920. case ARMCC::AL: // none
  2921. // CPSR can be used multiple times, we should continue.
  2922. break;
  2923. case ARMCC::HS: // C
  2924. case ARMCC::LO: // C
  2925. case ARMCC::VS: // V
  2926. case ARMCC::VC: // V
  2927. case ARMCC::HI: // C Z
  2928. case ARMCC::LS: // C Z
  2929. case ARMCC::GE: // N V
  2930. case ARMCC::LT: // N V
  2931. case ARMCC::GT: // Z N V
  2932. case ARMCC::LE: // Z N V
  2933. // The instruction uses the V bit or C bit which is not safe.
  2934. return false;
  2935. }
  2936. }
  2937. }
  2938. }
  2939. // If CPSR is not killed nor re-defined, we should check whether it is
  2940. // live-out. If it is live-out, do not optimize.
  2941. if (!isSafe) {
  2942. MachineBasicBlock *MBB = CmpInstr.getParent();
  2943. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
  2944. SE = MBB->succ_end(); SI != SE; ++SI)
  2945. if ((*SI)->isLiveIn(ARM::CPSR))
  2946. return false;
  2947. }
  2948. // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always
  2949. // set CPSR so this is represented as an explicit output)
  2950. if (!IsThumb1) {
  2951. MI->getOperand(5).setReg(ARM::CPSR);
  2952. MI->getOperand(5).setIsDef(true);
  2953. }
  2954. assert(!isPredicated(*MI) && "Can't use flags from predicated instruction");
  2955. CmpInstr.eraseFromParent();
  2956. // Modify the condition code of operands in OperandsToUpdate.
  2957. // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
  2958. // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
  2959. for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
  2960. OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
  2961. MI->clearRegisterDeads(ARM::CPSR);
  2962. return true;
  2963. }
  2964. bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const {
  2965. // Do not sink MI if it might be used to optimize a redundant compare.
  2966. // We heuristically only look at the instruction immediately following MI to
  2967. // avoid potentially searching the entire basic block.
  2968. if (isPredicated(MI))
  2969. return true;
  2970. MachineBasicBlock::const_iterator Next = &MI;
  2971. ++Next;
  2972. Register SrcReg, SrcReg2;
  2973. int CmpMask, CmpValue;
  2974. bool IsThumb1;
  2975. if (Next != MI.getParent()->end() &&
  2976. analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) &&
  2977. isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1))
  2978. return false;
  2979. return true;
  2980. }
  2981. bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
  2982. Register Reg,
  2983. MachineRegisterInfo *MRI) const {
  2984. // Fold large immediates into add, sub, or, xor.
  2985. unsigned DefOpc = DefMI.getOpcode();
  2986. if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
  2987. return false;
  2988. if (!DefMI.getOperand(1).isImm())
  2989. // Could be t2MOVi32imm @xx
  2990. return false;
  2991. if (!MRI->hasOneNonDBGUse(Reg))
  2992. return false;
  2993. const MCInstrDesc &DefMCID = DefMI.getDesc();
  2994. if (DefMCID.hasOptionalDef()) {
  2995. unsigned NumOps = DefMCID.getNumOperands();
  2996. const MachineOperand &MO = DefMI.getOperand(NumOps - 1);
  2997. if (MO.getReg() == ARM::CPSR && !MO.isDead())
  2998. // If DefMI defines CPSR and it is not dead, it's obviously not safe
  2999. // to delete DefMI.
  3000. return false;
  3001. }
  3002. const MCInstrDesc &UseMCID = UseMI.getDesc();
  3003. if (UseMCID.hasOptionalDef()) {
  3004. unsigned NumOps = UseMCID.getNumOperands();
  3005. if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR)
  3006. // If the instruction sets the flag, do not attempt this optimization
  3007. // since it may change the semantics of the code.
  3008. return false;
  3009. }
  3010. unsigned UseOpc = UseMI.getOpcode();
  3011. unsigned NewUseOpc = 0;
  3012. uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm();
  3013. uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
  3014. bool Commute = false;
  3015. switch (UseOpc) {
  3016. default: return false;
  3017. case ARM::SUBrr:
  3018. case ARM::ADDrr:
  3019. case ARM::ORRrr:
  3020. case ARM::EORrr:
  3021. case ARM::t2SUBrr:
  3022. case ARM::t2ADDrr:
  3023. case ARM::t2ORRrr:
  3024. case ARM::t2EORrr: {
  3025. Commute = UseMI.getOperand(2).getReg() != Reg;
  3026. switch (UseOpc) {
  3027. default: break;
  3028. case ARM::ADDrr:
  3029. case ARM::SUBrr:
  3030. if (UseOpc == ARM::SUBrr && Commute)
  3031. return false;
  3032. // ADD/SUB are special because they're essentially the same operation, so
  3033. // we can handle a larger range of immediates.
  3034. if (ARM_AM::isSOImmTwoPartVal(ImmVal))
  3035. NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri;
  3036. else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) {
  3037. ImmVal = -ImmVal;
  3038. NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri;
  3039. } else
  3040. return false;
  3041. SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
  3042. SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
  3043. break;
  3044. case ARM::ORRrr:
  3045. case ARM::EORrr:
  3046. if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
  3047. return false;
  3048. SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
  3049. SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
  3050. switch (UseOpc) {
  3051. default: break;
  3052. case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
  3053. case ARM::EORrr: NewUseOpc = ARM::EORri; break;
  3054. }
  3055. break;
  3056. case ARM::t2ADDrr:
  3057. case ARM::t2SUBrr: {
  3058. if (UseOpc == ARM::t2SUBrr && Commute)
  3059. return false;
  3060. // ADD/SUB are special because they're essentially the same operation, so
  3061. // we can handle a larger range of immediates.
  3062. const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP;
  3063. const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri;
  3064. const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri;
  3065. if (ARM_AM::isT2SOImmTwoPartVal(ImmVal))
  3066. NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB;
  3067. else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) {
  3068. ImmVal = -ImmVal;
  3069. NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD;
  3070. } else
  3071. return false;
  3072. SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
  3073. SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
  3074. break;
  3075. }
  3076. case ARM::t2ORRrr:
  3077. case ARM::t2EORrr:
  3078. if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
  3079. return false;
  3080. SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
  3081. SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
  3082. switch (UseOpc) {
  3083. default: break;
  3084. case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
  3085. case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
  3086. }
  3087. break;
  3088. }
  3089. }
  3090. }
  3091. unsigned OpIdx = Commute ? 2 : 1;
  3092. Register Reg1 = UseMI.getOperand(OpIdx).getReg();
  3093. bool isKill = UseMI.getOperand(OpIdx).isKill();
  3094. const TargetRegisterClass *TRC = MRI->getRegClass(Reg);
  3095. Register NewReg = MRI->createVirtualRegister(TRC);
  3096. BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc),
  3097. NewReg)
  3098. .addReg(Reg1, getKillRegState(isKill))
  3099. .addImm(SOImmValV1)
  3100. .add(predOps(ARMCC::AL))
  3101. .add(condCodeOp());
  3102. UseMI.setDesc(get(NewUseOpc));
  3103. UseMI.getOperand(1).setReg(NewReg);
  3104. UseMI.getOperand(1).setIsKill();
  3105. UseMI.getOperand(2).ChangeToImmediate(SOImmValV2);
  3106. DefMI.eraseFromParent();
  3107. // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP.
  3108. // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm].
  3109. // Then the below code will not be needed, as the input/output register
  3110. // classes will be rgpr or gprSP.
  3111. // For now, we fix the UseMI operand explicitly here:
  3112. switch(NewUseOpc){
  3113. case ARM::t2ADDspImm:
  3114. case ARM::t2SUBspImm:
  3115. case ARM::t2ADDri:
  3116. case ARM::t2SUBri:
  3117. MRI->constrainRegClass(UseMI.getOperand(0).getReg(), TRC);
  3118. }
  3119. return true;
  3120. }
  3121. static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
  3122. const MachineInstr &MI) {
  3123. switch (MI.getOpcode()) {
  3124. default: {
  3125. const MCInstrDesc &Desc = MI.getDesc();
  3126. int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
  3127. assert(UOps >= 0 && "bad # UOps");
  3128. return UOps;
  3129. }
  3130. case ARM::LDRrs:
  3131. case ARM::LDRBrs:
  3132. case ARM::STRrs:
  3133. case ARM::STRBrs: {
  3134. unsigned ShOpVal = MI.getOperand(3).getImm();
  3135. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3136. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3137. if (!isSub &&
  3138. (ShImm == 0 ||
  3139. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3140. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3141. return 1;
  3142. return 2;
  3143. }
  3144. case ARM::LDRH:
  3145. case ARM::STRH: {
  3146. if (!MI.getOperand(2).getReg())
  3147. return 1;
  3148. unsigned ShOpVal = MI.getOperand(3).getImm();
  3149. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3150. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3151. if (!isSub &&
  3152. (ShImm == 0 ||
  3153. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3154. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3155. return 1;
  3156. return 2;
  3157. }
  3158. case ARM::LDRSB:
  3159. case ARM::LDRSH:
  3160. return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2;
  3161. case ARM::LDRSB_POST:
  3162. case ARM::LDRSH_POST: {
  3163. Register Rt = MI.getOperand(0).getReg();
  3164. Register Rm = MI.getOperand(3).getReg();
  3165. return (Rt == Rm) ? 4 : 3;
  3166. }
  3167. case ARM::LDR_PRE_REG:
  3168. case ARM::LDRB_PRE_REG: {
  3169. Register Rt = MI.getOperand(0).getReg();
  3170. Register Rm = MI.getOperand(3).getReg();
  3171. if (Rt == Rm)
  3172. return 3;
  3173. unsigned ShOpVal = MI.getOperand(4).getImm();
  3174. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3175. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3176. if (!isSub &&
  3177. (ShImm == 0 ||
  3178. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3179. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3180. return 2;
  3181. return 3;
  3182. }
  3183. case ARM::STR_PRE_REG:
  3184. case ARM::STRB_PRE_REG: {
  3185. unsigned ShOpVal = MI.getOperand(4).getImm();
  3186. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3187. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3188. if (!isSub &&
  3189. (ShImm == 0 ||
  3190. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3191. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3192. return 2;
  3193. return 3;
  3194. }
  3195. case ARM::LDRH_PRE:
  3196. case ARM::STRH_PRE: {
  3197. Register Rt = MI.getOperand(0).getReg();
  3198. Register Rm = MI.getOperand(3).getReg();
  3199. if (!Rm)
  3200. return 2;
  3201. if (Rt == Rm)
  3202. return 3;
  3203. return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2;
  3204. }
  3205. case ARM::LDR_POST_REG:
  3206. case ARM::LDRB_POST_REG:
  3207. case ARM::LDRH_POST: {
  3208. Register Rt = MI.getOperand(0).getReg();
  3209. Register Rm = MI.getOperand(3).getReg();
  3210. return (Rt == Rm) ? 3 : 2;
  3211. }
  3212. case ARM::LDR_PRE_IMM:
  3213. case ARM::LDRB_PRE_IMM:
  3214. case ARM::LDR_POST_IMM:
  3215. case ARM::LDRB_POST_IMM:
  3216. case ARM::STRB_POST_IMM:
  3217. case ARM::STRB_POST_REG:
  3218. case ARM::STRB_PRE_IMM:
  3219. case ARM::STRH_POST:
  3220. case ARM::STR_POST_IMM:
  3221. case ARM::STR_POST_REG:
  3222. case ARM::STR_PRE_IMM:
  3223. return 2;
  3224. case ARM::LDRSB_PRE:
  3225. case ARM::LDRSH_PRE: {
  3226. Register Rm = MI.getOperand(3).getReg();
  3227. if (Rm == 0)
  3228. return 3;
  3229. Register Rt = MI.getOperand(0).getReg();
  3230. if (Rt == Rm)
  3231. return 4;
  3232. unsigned ShOpVal = MI.getOperand(4).getImm();
  3233. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3234. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3235. if (!isSub &&
  3236. (ShImm == 0 ||
  3237. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3238. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3239. return 3;
  3240. return 4;
  3241. }
  3242. case ARM::LDRD: {
  3243. Register Rt = MI.getOperand(0).getReg();
  3244. Register Rn = MI.getOperand(2).getReg();
  3245. Register Rm = MI.getOperand(3).getReg();
  3246. if (Rm)
  3247. return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
  3248. : 3;
  3249. return (Rt == Rn) ? 3 : 2;
  3250. }
  3251. case ARM::STRD: {
  3252. Register Rm = MI.getOperand(3).getReg();
  3253. if (Rm)
  3254. return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
  3255. : 3;
  3256. return 2;
  3257. }
  3258. case ARM::LDRD_POST:
  3259. case ARM::t2LDRD_POST:
  3260. return 3;
  3261. case ARM::STRD_POST:
  3262. case ARM::t2STRD_POST:
  3263. return 4;
  3264. case ARM::LDRD_PRE: {
  3265. Register Rt = MI.getOperand(0).getReg();
  3266. Register Rn = MI.getOperand(3).getReg();
  3267. Register Rm = MI.getOperand(4).getReg();
  3268. if (Rm)
  3269. return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
  3270. : 4;
  3271. return (Rt == Rn) ? 4 : 3;
  3272. }
  3273. case ARM::t2LDRD_PRE: {
  3274. Register Rt = MI.getOperand(0).getReg();
  3275. Register Rn = MI.getOperand(3).getReg();
  3276. return (Rt == Rn) ? 4 : 3;
  3277. }
  3278. case ARM::STRD_PRE: {
  3279. Register Rm = MI.getOperand(4).getReg();
  3280. if (Rm)
  3281. return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
  3282. : 4;
  3283. return 3;
  3284. }
  3285. case ARM::t2STRD_PRE:
  3286. return 3;
  3287. case ARM::t2LDR_POST:
  3288. case ARM::t2LDRB_POST:
  3289. case ARM::t2LDRB_PRE:
  3290. case ARM::t2LDRSBi12:
  3291. case ARM::t2LDRSBi8:
  3292. case ARM::t2LDRSBpci:
  3293. case ARM::t2LDRSBs:
  3294. case ARM::t2LDRH_POST:
  3295. case ARM::t2LDRH_PRE:
  3296. case ARM::t2LDRSBT:
  3297. case ARM::t2LDRSB_POST:
  3298. case ARM::t2LDRSB_PRE:
  3299. case ARM::t2LDRSH_POST:
  3300. case ARM::t2LDRSH_PRE:
  3301. case ARM::t2LDRSHi12:
  3302. case ARM::t2LDRSHi8:
  3303. case ARM::t2LDRSHpci:
  3304. case ARM::t2LDRSHs:
  3305. return 2;
  3306. case ARM::t2LDRDi8: {
  3307. Register Rt = MI.getOperand(0).getReg();
  3308. Register Rn = MI.getOperand(2).getReg();
  3309. return (Rt == Rn) ? 3 : 2;
  3310. }
  3311. case ARM::t2STRB_POST:
  3312. case ARM::t2STRB_PRE:
  3313. case ARM::t2STRBs:
  3314. case ARM::t2STRDi8:
  3315. case ARM::t2STRH_POST:
  3316. case ARM::t2STRH_PRE:
  3317. case ARM::t2STRHs:
  3318. case ARM::t2STR_POST:
  3319. case ARM::t2STR_PRE:
  3320. case ARM::t2STRs:
  3321. return 2;
  3322. }
  3323. }
  3324. // Return the number of 32-bit words loaded by LDM or stored by STM. If this
  3325. // can't be easily determined return 0 (missing MachineMemOperand).
  3326. //
  3327. // FIXME: The current MachineInstr design does not support relying on machine
  3328. // mem operands to determine the width of a memory access. Instead, we expect
  3329. // the target to provide this information based on the instruction opcode and
  3330. // operands. However, using MachineMemOperand is the best solution now for
  3331. // two reasons:
  3332. //
  3333. // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
  3334. // operands. This is much more dangerous than using the MachineMemOperand
  3335. // sizes because CodeGen passes can insert/remove optional machine operands. In
  3336. // fact, it's totally incorrect for preRA passes and appears to be wrong for
  3337. // postRA passes as well.
  3338. //
  3339. // 2) getNumLDMAddresses is only used by the scheduling machine model and any
  3340. // machine model that calls this should handle the unknown (zero size) case.
  3341. //
  3342. // Long term, we should require a target hook that verifies MachineMemOperand
  3343. // sizes during MC lowering. That target hook should be local to MC lowering
  3344. // because we can't ensure that it is aware of other MI forms. Doing this will
  3345. // ensure that MachineMemOperands are correctly propagated through all passes.
  3346. unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const {
  3347. unsigned Size = 0;
  3348. for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
  3349. E = MI.memoperands_end();
  3350. I != E; ++I) {
  3351. Size += (*I)->getSize();
  3352. }
  3353. // FIXME: The scheduler currently can't handle values larger than 16. But
  3354. // the values can actually go up to 32 for floating-point load/store
  3355. // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory
  3356. // operations isn't right; we could end up with "extra" memory operands for
  3357. // various reasons, like tail merge merging two memory operations.
  3358. return std::min(Size / 4, 16U);
  3359. }
  3360. static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,
  3361. unsigned NumRegs) {
  3362. unsigned UOps = 1 + NumRegs; // 1 for address computation.
  3363. switch (Opc) {
  3364. default:
  3365. break;
  3366. case ARM::VLDMDIA_UPD:
  3367. case ARM::VLDMDDB_UPD:
  3368. case ARM::VLDMSIA_UPD:
  3369. case ARM::VLDMSDB_UPD:
  3370. case ARM::VSTMDIA_UPD:
  3371. case ARM::VSTMDDB_UPD:
  3372. case ARM::VSTMSIA_UPD:
  3373. case ARM::VSTMSDB_UPD:
  3374. case ARM::LDMIA_UPD:
  3375. case ARM::LDMDA_UPD:
  3376. case ARM::LDMDB_UPD:
  3377. case ARM::LDMIB_UPD:
  3378. case ARM::STMIA_UPD:
  3379. case ARM::STMDA_UPD:
  3380. case ARM::STMDB_UPD:
  3381. case ARM::STMIB_UPD:
  3382. case ARM::tLDMIA_UPD:
  3383. case ARM::tSTMIA_UPD:
  3384. case ARM::t2LDMIA_UPD:
  3385. case ARM::t2LDMDB_UPD:
  3386. case ARM::t2STMIA_UPD:
  3387. case ARM::t2STMDB_UPD:
  3388. ++UOps; // One for base register writeback.
  3389. break;
  3390. case ARM::LDMIA_RET:
  3391. case ARM::tPOP_RET:
  3392. case ARM::t2LDMIA_RET:
  3393. UOps += 2; // One for base reg wb, one for write to pc.
  3394. break;
  3395. }
  3396. return UOps;
  3397. }
  3398. unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
  3399. const MachineInstr &MI) const {
  3400. if (!ItinData || ItinData->isEmpty())
  3401. return 1;
  3402. const MCInstrDesc &Desc = MI.getDesc();
  3403. unsigned Class = Desc.getSchedClass();
  3404. int ItinUOps = ItinData->getNumMicroOps(Class);
  3405. if (ItinUOps >= 0) {
  3406. if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
  3407. return getNumMicroOpsSwiftLdSt(ItinData, MI);
  3408. return ItinUOps;
  3409. }
  3410. unsigned Opc = MI.getOpcode();
  3411. switch (Opc) {
  3412. default:
  3413. llvm_unreachable("Unexpected multi-uops instruction!");
  3414. case ARM::VLDMQIA:
  3415. case ARM::VSTMQIA:
  3416. return 2;
  3417. // The number of uOps for load / store multiple are determined by the number
  3418. // registers.
  3419. //
  3420. // On Cortex-A8, each pair of register loads / stores can be scheduled on the
  3421. // same cycle. The scheduling for the first load / store must be done
  3422. // separately by assuming the address is not 64-bit aligned.
  3423. //
  3424. // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
  3425. // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON
  3426. // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
  3427. case ARM::VLDMDIA:
  3428. case ARM::VLDMDIA_UPD:
  3429. case ARM::VLDMDDB_UPD:
  3430. case ARM::VLDMSIA:
  3431. case ARM::VLDMSIA_UPD:
  3432. case ARM::VLDMSDB_UPD:
  3433. case ARM::VSTMDIA:
  3434. case ARM::VSTMDIA_UPD:
  3435. case ARM::VSTMDDB_UPD:
  3436. case ARM::VSTMSIA:
  3437. case ARM::VSTMSIA_UPD:
  3438. case ARM::VSTMSDB_UPD: {
  3439. unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands();
  3440. return (NumRegs / 2) + (NumRegs % 2) + 1;
  3441. }
  3442. case ARM::LDMIA_RET:
  3443. case ARM::LDMIA:
  3444. case ARM::LDMDA:
  3445. case ARM::LDMDB:
  3446. case ARM::LDMIB:
  3447. case ARM::LDMIA_UPD:
  3448. case ARM::LDMDA_UPD:
  3449. case ARM::LDMDB_UPD:
  3450. case ARM::LDMIB_UPD:
  3451. case ARM::STMIA:
  3452. case ARM::STMDA:
  3453. case ARM::STMDB:
  3454. case ARM::STMIB:
  3455. case ARM::STMIA_UPD:
  3456. case ARM::STMDA_UPD:
  3457. case ARM::STMDB_UPD:
  3458. case ARM::STMIB_UPD:
  3459. case ARM::tLDMIA:
  3460. case ARM::tLDMIA_UPD:
  3461. case ARM::tSTMIA_UPD:
  3462. case ARM::tPOP_RET:
  3463. case ARM::tPOP:
  3464. case ARM::tPUSH:
  3465. case ARM::t2LDMIA_RET:
  3466. case ARM::t2LDMIA:
  3467. case ARM::t2LDMDB:
  3468. case ARM::t2LDMIA_UPD:
  3469. case ARM::t2LDMDB_UPD:
  3470. case ARM::t2STMIA:
  3471. case ARM::t2STMDB:
  3472. case ARM::t2STMIA_UPD:
  3473. case ARM::t2STMDB_UPD: {
  3474. unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1;
  3475. switch (Subtarget.getLdStMultipleTiming()) {
  3476. case ARMSubtarget::SingleIssuePlusExtras:
  3477. return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs);
  3478. case ARMSubtarget::SingleIssue:
  3479. // Assume the worst.
  3480. return NumRegs;
  3481. case ARMSubtarget::DoubleIssue: {
  3482. if (NumRegs < 4)
  3483. return 2;
  3484. // 4 registers would be issued: 2, 2.
  3485. // 5 registers would be issued: 2, 2, 1.
  3486. unsigned UOps = (NumRegs / 2);
  3487. if (NumRegs % 2)
  3488. ++UOps;
  3489. return UOps;
  3490. }
  3491. case ARMSubtarget::DoubleIssueCheckUnalignedAccess: {
  3492. unsigned UOps = (NumRegs / 2);
  3493. // If there are odd number of registers or if it's not 64-bit aligned,
  3494. // then it takes an extra AGU (Address Generation Unit) cycle.
  3495. if ((NumRegs % 2) || !MI.hasOneMemOperand() ||
  3496. (*MI.memoperands_begin())->getAlign() < Align(8))
  3497. ++UOps;
  3498. return UOps;
  3499. }
  3500. }
  3501. }
  3502. }
  3503. llvm_unreachable("Didn't find the number of microops");
  3504. }
  3505. int
  3506. ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
  3507. const MCInstrDesc &DefMCID,
  3508. unsigned DefClass,
  3509. unsigned DefIdx, unsigned DefAlign) const {
  3510. int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
  3511. if (RegNo <= 0)
  3512. // Def is the address writeback.
  3513. return ItinData->getOperandCycle(DefClass, DefIdx);
  3514. int DefCycle;
  3515. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3516. // (regno / 2) + (regno % 2) + 1
  3517. DefCycle = RegNo / 2 + 1;
  3518. if (RegNo % 2)
  3519. ++DefCycle;
  3520. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3521. DefCycle = RegNo;
  3522. bool isSLoad = false;
  3523. switch (DefMCID.getOpcode()) {
  3524. default: break;
  3525. case ARM::VLDMSIA:
  3526. case ARM::VLDMSIA_UPD:
  3527. case ARM::VLDMSDB_UPD:
  3528. isSLoad = true;
  3529. break;
  3530. }
  3531. // If there are odd number of 'S' registers or if it's not 64-bit aligned,
  3532. // then it takes an extra cycle.
  3533. if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
  3534. ++DefCycle;
  3535. } else {
  3536. // Assume the worst.
  3537. DefCycle = RegNo + 2;
  3538. }
  3539. return DefCycle;
  3540. }
  3541. int
  3542. ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
  3543. const MCInstrDesc &DefMCID,
  3544. unsigned DefClass,
  3545. unsigned DefIdx, unsigned DefAlign) const {
  3546. int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
  3547. if (RegNo <= 0)
  3548. // Def is the address writeback.
  3549. return ItinData->getOperandCycle(DefClass, DefIdx);
  3550. int DefCycle;
  3551. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3552. // 4 registers would be issued: 1, 2, 1.
  3553. // 5 registers would be issued: 1, 2, 2.
  3554. DefCycle = RegNo / 2;
  3555. if (DefCycle < 1)
  3556. DefCycle = 1;
  3557. // Result latency is issue cycle + 2: E2.
  3558. DefCycle += 2;
  3559. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3560. DefCycle = (RegNo / 2);
  3561. // If there are odd number of registers or if it's not 64-bit aligned,
  3562. // then it takes an extra AGU (Address Generation Unit) cycle.
  3563. if ((RegNo % 2) || DefAlign < 8)
  3564. ++DefCycle;
  3565. // Result latency is AGU cycles + 2.
  3566. DefCycle += 2;
  3567. } else {
  3568. // Assume the worst.
  3569. DefCycle = RegNo + 2;
  3570. }
  3571. return DefCycle;
  3572. }
  3573. int
  3574. ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
  3575. const MCInstrDesc &UseMCID,
  3576. unsigned UseClass,
  3577. unsigned UseIdx, unsigned UseAlign) const {
  3578. int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
  3579. if (RegNo <= 0)
  3580. return ItinData->getOperandCycle(UseClass, UseIdx);
  3581. int UseCycle;
  3582. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3583. // (regno / 2) + (regno % 2) + 1
  3584. UseCycle = RegNo / 2 + 1;
  3585. if (RegNo % 2)
  3586. ++UseCycle;
  3587. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3588. UseCycle = RegNo;
  3589. bool isSStore = false;
  3590. switch (UseMCID.getOpcode()) {
  3591. default: break;
  3592. case ARM::VSTMSIA:
  3593. case ARM::VSTMSIA_UPD:
  3594. case ARM::VSTMSDB_UPD:
  3595. isSStore = true;
  3596. break;
  3597. }
  3598. // If there are odd number of 'S' registers or if it's not 64-bit aligned,
  3599. // then it takes an extra cycle.
  3600. if ((isSStore && (RegNo % 2)) || UseAlign < 8)
  3601. ++UseCycle;
  3602. } else {
  3603. // Assume the worst.
  3604. UseCycle = RegNo + 2;
  3605. }
  3606. return UseCycle;
  3607. }
  3608. int
  3609. ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
  3610. const MCInstrDesc &UseMCID,
  3611. unsigned UseClass,
  3612. unsigned UseIdx, unsigned UseAlign) const {
  3613. int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
  3614. if (RegNo <= 0)
  3615. return ItinData->getOperandCycle(UseClass, UseIdx);
  3616. int UseCycle;
  3617. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3618. UseCycle = RegNo / 2;
  3619. if (UseCycle < 2)
  3620. UseCycle = 2;
  3621. // Read in E3.
  3622. UseCycle += 2;
  3623. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3624. UseCycle = (RegNo / 2);
  3625. // If there are odd number of registers or if it's not 64-bit aligned,
  3626. // then it takes an extra AGU (Address Generation Unit) cycle.
  3627. if ((RegNo % 2) || UseAlign < 8)
  3628. ++UseCycle;
  3629. } else {
  3630. // Assume the worst.
  3631. UseCycle = 1;
  3632. }
  3633. return UseCycle;
  3634. }
  3635. int
  3636. ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  3637. const MCInstrDesc &DefMCID,
  3638. unsigned DefIdx, unsigned DefAlign,
  3639. const MCInstrDesc &UseMCID,
  3640. unsigned UseIdx, unsigned UseAlign) const {
  3641. unsigned DefClass = DefMCID.getSchedClass();
  3642. unsigned UseClass = UseMCID.getSchedClass();
  3643. if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
  3644. return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
  3645. // This may be a def / use of a variable_ops instruction, the operand
  3646. // latency might be determinable dynamically. Let the target try to
  3647. // figure it out.
  3648. int DefCycle = -1;
  3649. bool LdmBypass = false;
  3650. switch (DefMCID.getOpcode()) {
  3651. default:
  3652. DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
  3653. break;
  3654. case ARM::VLDMDIA:
  3655. case ARM::VLDMDIA_UPD:
  3656. case ARM::VLDMDDB_UPD:
  3657. case ARM::VLDMSIA:
  3658. case ARM::VLDMSIA_UPD:
  3659. case ARM::VLDMSDB_UPD:
  3660. DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
  3661. break;
  3662. case ARM::LDMIA_RET:
  3663. case ARM::LDMIA:
  3664. case ARM::LDMDA:
  3665. case ARM::LDMDB:
  3666. case ARM::LDMIB:
  3667. case ARM::LDMIA_UPD:
  3668. case ARM::LDMDA_UPD:
  3669. case ARM::LDMDB_UPD:
  3670. case ARM::LDMIB_UPD:
  3671. case ARM::tLDMIA:
  3672. case ARM::tLDMIA_UPD:
  3673. case ARM::tPUSH:
  3674. case ARM::t2LDMIA_RET:
  3675. case ARM::t2LDMIA:
  3676. case ARM::t2LDMDB:
  3677. case ARM::t2LDMIA_UPD:
  3678. case ARM::t2LDMDB_UPD:
  3679. LdmBypass = true;
  3680. DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
  3681. break;
  3682. }
  3683. if (DefCycle == -1)
  3684. // We can't seem to determine the result latency of the def, assume it's 2.
  3685. DefCycle = 2;
  3686. int UseCycle = -1;
  3687. switch (UseMCID.getOpcode()) {
  3688. default:
  3689. UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
  3690. break;
  3691. case ARM::VSTMDIA:
  3692. case ARM::VSTMDIA_UPD:
  3693. case ARM::VSTMDDB_UPD:
  3694. case ARM::VSTMSIA:
  3695. case ARM::VSTMSIA_UPD:
  3696. case ARM::VSTMSDB_UPD:
  3697. UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
  3698. break;
  3699. case ARM::STMIA:
  3700. case ARM::STMDA:
  3701. case ARM::STMDB:
  3702. case ARM::STMIB:
  3703. case ARM::STMIA_UPD:
  3704. case ARM::STMDA_UPD:
  3705. case ARM::STMDB_UPD:
  3706. case ARM::STMIB_UPD:
  3707. case ARM::tSTMIA_UPD:
  3708. case ARM::tPOP_RET:
  3709. case ARM::tPOP:
  3710. case ARM::t2STMIA:
  3711. case ARM::t2STMDB:
  3712. case ARM::t2STMIA_UPD:
  3713. case ARM::t2STMDB_UPD:
  3714. UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
  3715. break;
  3716. }
  3717. if (UseCycle == -1)
  3718. // Assume it's read in the first stage.
  3719. UseCycle = 1;
  3720. UseCycle = DefCycle - UseCycle + 1;
  3721. if (UseCycle > 0) {
  3722. if (LdmBypass) {
  3723. // It's a variable_ops instruction so we can't use DefIdx here. Just use
  3724. // first def operand.
  3725. if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
  3726. UseClass, UseIdx))
  3727. --UseCycle;
  3728. } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
  3729. UseClass, UseIdx)) {
  3730. --UseCycle;
  3731. }
  3732. }
  3733. return UseCycle;
  3734. }
  3735. static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
  3736. const MachineInstr *MI, unsigned Reg,
  3737. unsigned &DefIdx, unsigned &Dist) {
  3738. Dist = 0;
  3739. MachineBasicBlock::const_iterator I = MI; ++I;
  3740. MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
  3741. assert(II->isInsideBundle() && "Empty bundle?");
  3742. int Idx = -1;
  3743. while (II->isInsideBundle()) {
  3744. Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
  3745. if (Idx != -1)
  3746. break;
  3747. --II;
  3748. ++Dist;
  3749. }
  3750. assert(Idx != -1 && "Cannot find bundled definition!");
  3751. DefIdx = Idx;
  3752. return &*II;
  3753. }
  3754. static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
  3755. const MachineInstr &MI, unsigned Reg,
  3756. unsigned &UseIdx, unsigned &Dist) {
  3757. Dist = 0;
  3758. MachineBasicBlock::const_instr_iterator II = ++MI.getIterator();
  3759. assert(II->isInsideBundle() && "Empty bundle?");
  3760. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  3761. // FIXME: This doesn't properly handle multiple uses.
  3762. int Idx = -1;
  3763. while (II != E && II->isInsideBundle()) {
  3764. Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
  3765. if (Idx != -1)
  3766. break;
  3767. if (II->getOpcode() != ARM::t2IT)
  3768. ++Dist;
  3769. ++II;
  3770. }
  3771. if (Idx == -1) {
  3772. Dist = 0;
  3773. return nullptr;
  3774. }
  3775. UseIdx = Idx;
  3776. return &*II;
  3777. }
  3778. /// Return the number of cycles to add to (or subtract from) the static
  3779. /// itinerary based on the def opcode and alignment. The caller will ensure that
  3780. /// adjusted latency is at least one cycle.
  3781. static int adjustDefLatency(const ARMSubtarget &Subtarget,
  3782. const MachineInstr &DefMI,
  3783. const MCInstrDesc &DefMCID, unsigned DefAlign) {
  3784. int Adjust = 0;
  3785. if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
  3786. // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
  3787. // variants are one cycle cheaper.
  3788. switch (DefMCID.getOpcode()) {
  3789. default: break;
  3790. case ARM::LDRrs:
  3791. case ARM::LDRBrs: {
  3792. unsigned ShOpVal = DefMI.getOperand(3).getImm();
  3793. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3794. if (ShImm == 0 ||
  3795. (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
  3796. --Adjust;
  3797. break;
  3798. }
  3799. case ARM::t2LDRs:
  3800. case ARM::t2LDRBs:
  3801. case ARM::t2LDRHs:
  3802. case ARM::t2LDRSHs: {
  3803. // Thumb2 mode: lsl only.
  3804. unsigned ShAmt = DefMI.getOperand(3).getImm();
  3805. if (ShAmt == 0 || ShAmt == 2)
  3806. --Adjust;
  3807. break;
  3808. }
  3809. }
  3810. } else if (Subtarget.isSwift()) {
  3811. // FIXME: Properly handle all of the latency adjustments for address
  3812. // writeback.
  3813. switch (DefMCID.getOpcode()) {
  3814. default: break;
  3815. case ARM::LDRrs:
  3816. case ARM::LDRBrs: {
  3817. unsigned ShOpVal = DefMI.getOperand(3).getImm();
  3818. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3819. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3820. if (!isSub &&
  3821. (ShImm == 0 ||
  3822. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3823. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3824. Adjust -= 2;
  3825. else if (!isSub &&
  3826. ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
  3827. --Adjust;
  3828. break;
  3829. }
  3830. case ARM::t2LDRs:
  3831. case ARM::t2LDRBs:
  3832. case ARM::t2LDRHs:
  3833. case ARM::t2LDRSHs: {
  3834. // Thumb2 mode: lsl only.
  3835. unsigned ShAmt = DefMI.getOperand(3).getImm();
  3836. if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
  3837. Adjust -= 2;
  3838. break;
  3839. }
  3840. }
  3841. }
  3842. if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) {
  3843. switch (DefMCID.getOpcode()) {
  3844. default: break;
  3845. case ARM::VLD1q8:
  3846. case ARM::VLD1q16:
  3847. case ARM::VLD1q32:
  3848. case ARM::VLD1q64:
  3849. case ARM::VLD1q8wb_fixed:
  3850. case ARM::VLD1q16wb_fixed:
  3851. case ARM::VLD1q32wb_fixed:
  3852. case ARM::VLD1q64wb_fixed:
  3853. case ARM::VLD1q8wb_register:
  3854. case ARM::VLD1q16wb_register:
  3855. case ARM::VLD1q32wb_register:
  3856. case ARM::VLD1q64wb_register:
  3857. case ARM::VLD2d8:
  3858. case ARM::VLD2d16:
  3859. case ARM::VLD2d32:
  3860. case ARM::VLD2q8:
  3861. case ARM::VLD2q16:
  3862. case ARM::VLD2q32:
  3863. case ARM::VLD2d8wb_fixed:
  3864. case ARM::VLD2d16wb_fixed:
  3865. case ARM::VLD2d32wb_fixed:
  3866. case ARM::VLD2q8wb_fixed:
  3867. case ARM::VLD2q16wb_fixed:
  3868. case ARM::VLD2q32wb_fixed:
  3869. case ARM::VLD2d8wb_register:
  3870. case ARM::VLD2d16wb_register:
  3871. case ARM::VLD2d32wb_register:
  3872. case ARM::VLD2q8wb_register:
  3873. case ARM::VLD2q16wb_register:
  3874. case ARM::VLD2q32wb_register:
  3875. case ARM::VLD3d8:
  3876. case ARM::VLD3d16:
  3877. case ARM::VLD3d32:
  3878. case ARM::VLD1d64T:
  3879. case ARM::VLD3d8_UPD:
  3880. case ARM::VLD3d16_UPD:
  3881. case ARM::VLD3d32_UPD:
  3882. case ARM::VLD1d64Twb_fixed:
  3883. case ARM::VLD1d64Twb_register:
  3884. case ARM::VLD3q8_UPD:
  3885. case ARM::VLD3q16_UPD:
  3886. case ARM::VLD3q32_UPD:
  3887. case ARM::VLD4d8:
  3888. case ARM::VLD4d16:
  3889. case ARM::VLD4d32:
  3890. case ARM::VLD1d64Q:
  3891. case ARM::VLD4d8_UPD:
  3892. case ARM::VLD4d16_UPD:
  3893. case ARM::VLD4d32_UPD:
  3894. case ARM::VLD1d64Qwb_fixed:
  3895. case ARM::VLD1d64Qwb_register:
  3896. case ARM::VLD4q8_UPD:
  3897. case ARM::VLD4q16_UPD:
  3898. case ARM::VLD4q32_UPD:
  3899. case ARM::VLD1DUPq8:
  3900. case ARM::VLD1DUPq16:
  3901. case ARM::VLD1DUPq32:
  3902. case ARM::VLD1DUPq8wb_fixed:
  3903. case ARM::VLD1DUPq16wb_fixed:
  3904. case ARM::VLD1DUPq32wb_fixed:
  3905. case ARM::VLD1DUPq8wb_register:
  3906. case ARM::VLD1DUPq16wb_register:
  3907. case ARM::VLD1DUPq32wb_register:
  3908. case ARM::VLD2DUPd8:
  3909. case ARM::VLD2DUPd16:
  3910. case ARM::VLD2DUPd32:
  3911. case ARM::VLD2DUPd8wb_fixed:
  3912. case ARM::VLD2DUPd16wb_fixed:
  3913. case ARM::VLD2DUPd32wb_fixed:
  3914. case ARM::VLD2DUPd8wb_register:
  3915. case ARM::VLD2DUPd16wb_register:
  3916. case ARM::VLD2DUPd32wb_register:
  3917. case ARM::VLD4DUPd8:
  3918. case ARM::VLD4DUPd16:
  3919. case ARM::VLD4DUPd32:
  3920. case ARM::VLD4DUPd8_UPD:
  3921. case ARM::VLD4DUPd16_UPD:
  3922. case ARM::VLD4DUPd32_UPD:
  3923. case ARM::VLD1LNd8:
  3924. case ARM::VLD1LNd16:
  3925. case ARM::VLD1LNd32:
  3926. case ARM::VLD1LNd8_UPD:
  3927. case ARM::VLD1LNd16_UPD:
  3928. case ARM::VLD1LNd32_UPD:
  3929. case ARM::VLD2LNd8:
  3930. case ARM::VLD2LNd16:
  3931. case ARM::VLD2LNd32:
  3932. case ARM::VLD2LNq16:
  3933. case ARM::VLD2LNq32:
  3934. case ARM::VLD2LNd8_UPD:
  3935. case ARM::VLD2LNd16_UPD:
  3936. case ARM::VLD2LNd32_UPD:
  3937. case ARM::VLD2LNq16_UPD:
  3938. case ARM::VLD2LNq32_UPD:
  3939. case ARM::VLD4LNd8:
  3940. case ARM::VLD4LNd16:
  3941. case ARM::VLD4LNd32:
  3942. case ARM::VLD4LNq16:
  3943. case ARM::VLD4LNq32:
  3944. case ARM::VLD4LNd8_UPD:
  3945. case ARM::VLD4LNd16_UPD:
  3946. case ARM::VLD4LNd32_UPD:
  3947. case ARM::VLD4LNq16_UPD:
  3948. case ARM::VLD4LNq32_UPD:
  3949. // If the address is not 64-bit aligned, the latencies of these
  3950. // instructions increases by one.
  3951. ++Adjust;
  3952. break;
  3953. }
  3954. }
  3955. return Adjust;
  3956. }
  3957. int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  3958. const MachineInstr &DefMI,
  3959. unsigned DefIdx,
  3960. const MachineInstr &UseMI,
  3961. unsigned UseIdx) const {
  3962. // No operand latency. The caller may fall back to getInstrLatency.
  3963. if (!ItinData || ItinData->isEmpty())
  3964. return -1;
  3965. const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
  3966. Register Reg = DefMO.getReg();
  3967. const MachineInstr *ResolvedDefMI = &DefMI;
  3968. unsigned DefAdj = 0;
  3969. if (DefMI.isBundle())
  3970. ResolvedDefMI =
  3971. getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj);
  3972. if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() ||
  3973. ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) {
  3974. return 1;
  3975. }
  3976. const MachineInstr *ResolvedUseMI = &UseMI;
  3977. unsigned UseAdj = 0;
  3978. if (UseMI.isBundle()) {
  3979. ResolvedUseMI =
  3980. getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj);
  3981. if (!ResolvedUseMI)
  3982. return -1;
  3983. }
  3984. return getOperandLatencyImpl(
  3985. ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO,
  3986. Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj);
  3987. }
  3988. int ARMBaseInstrInfo::getOperandLatencyImpl(
  3989. const InstrItineraryData *ItinData, const MachineInstr &DefMI,
  3990. unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj,
  3991. const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI,
  3992. unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const {
  3993. if (Reg == ARM::CPSR) {
  3994. if (DefMI.getOpcode() == ARM::FMSTAT) {
  3995. // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
  3996. return Subtarget.isLikeA9() ? 1 : 20;
  3997. }
  3998. // CPSR set and branch can be paired in the same cycle.
  3999. if (UseMI.isBranch())
  4000. return 0;
  4001. // Otherwise it takes the instruction latency (generally one).
  4002. unsigned Latency = getInstrLatency(ItinData, DefMI);
  4003. // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
  4004. // its uses. Instructions which are otherwise scheduled between them may
  4005. // incur a code size penalty (not able to use the CPSR setting 16-bit
  4006. // instructions).
  4007. if (Latency > 0 && Subtarget.isThumb2()) {
  4008. const MachineFunction *MF = DefMI.getParent()->getParent();
  4009. // FIXME: Use Function::hasOptSize().
  4010. if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize))
  4011. --Latency;
  4012. }
  4013. return Latency;
  4014. }
  4015. if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit())
  4016. return -1;
  4017. unsigned DefAlign = DefMI.hasOneMemOperand()
  4018. ? (*DefMI.memoperands_begin())->getAlign().value()
  4019. : 0;
  4020. unsigned UseAlign = UseMI.hasOneMemOperand()
  4021. ? (*UseMI.memoperands_begin())->getAlign().value()
  4022. : 0;
  4023. // Get the itinerary's latency if possible, and handle variable_ops.
  4024. int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID,
  4025. UseIdx, UseAlign);
  4026. // Unable to find operand latency. The caller may resort to getInstrLatency.
  4027. if (Latency < 0)
  4028. return Latency;
  4029. // Adjust for IT block position.
  4030. int Adj = DefAdj + UseAdj;
  4031. // Adjust for dynamic def-side opcode variants not captured by the itinerary.
  4032. Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
  4033. if (Adj >= 0 || (int)Latency > -Adj) {
  4034. return Latency + Adj;
  4035. }
  4036. // Return the itinerary latency, which may be zero but not less than zero.
  4037. return Latency;
  4038. }
  4039. int
  4040. ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  4041. SDNode *DefNode, unsigned DefIdx,
  4042. SDNode *UseNode, unsigned UseIdx) const {
  4043. if (!DefNode->isMachineOpcode())
  4044. return 1;
  4045. const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
  4046. if (isZeroCost(DefMCID.Opcode))
  4047. return 0;
  4048. if (!ItinData || ItinData->isEmpty())
  4049. return DefMCID.mayLoad() ? 3 : 1;
  4050. if (!UseNode->isMachineOpcode()) {
  4051. int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
  4052. int Adj = Subtarget.getPreISelOperandLatencyAdjustment();
  4053. int Threshold = 1 + Adj;
  4054. return Latency <= Threshold ? 1 : Latency - Adj;
  4055. }
  4056. const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
  4057. auto *DefMN = cast<MachineSDNode>(DefNode);
  4058. unsigned DefAlign = !DefMN->memoperands_empty()
  4059. ? (*DefMN->memoperands_begin())->getAlign().value()
  4060. : 0;
  4061. auto *UseMN = cast<MachineSDNode>(UseNode);
  4062. unsigned UseAlign = !UseMN->memoperands_empty()
  4063. ? (*UseMN->memoperands_begin())->getAlign().value()
  4064. : 0;
  4065. int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
  4066. UseMCID, UseIdx, UseAlign);
  4067. if (Latency > 1 &&
  4068. (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
  4069. Subtarget.isCortexA7())) {
  4070. // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
  4071. // variants are one cycle cheaper.
  4072. switch (DefMCID.getOpcode()) {
  4073. default: break;
  4074. case ARM::LDRrs:
  4075. case ARM::LDRBrs: {
  4076. unsigned ShOpVal =
  4077. cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
  4078. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  4079. if (ShImm == 0 ||
  4080. (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
  4081. --Latency;
  4082. break;
  4083. }
  4084. case ARM::t2LDRs:
  4085. case ARM::t2LDRBs:
  4086. case ARM::t2LDRHs:
  4087. case ARM::t2LDRSHs: {
  4088. // Thumb2 mode: lsl only.
  4089. unsigned ShAmt =
  4090. cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
  4091. if (ShAmt == 0 || ShAmt == 2)
  4092. --Latency;
  4093. break;
  4094. }
  4095. }
  4096. } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
  4097. // FIXME: Properly handle all of the latency adjustments for address
  4098. // writeback.
  4099. switch (DefMCID.getOpcode()) {
  4100. default: break;
  4101. case ARM::LDRrs:
  4102. case ARM::LDRBrs: {
  4103. unsigned ShOpVal =
  4104. cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
  4105. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  4106. if (ShImm == 0 ||
  4107. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  4108. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
  4109. Latency -= 2;
  4110. else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
  4111. --Latency;
  4112. break;
  4113. }
  4114. case ARM::t2LDRs:
  4115. case ARM::t2LDRBs:
  4116. case ARM::t2LDRHs:
  4117. case ARM::t2LDRSHs:
  4118. // Thumb2 mode: lsl 0-3 only.
  4119. Latency -= 2;
  4120. break;
  4121. }
  4122. }
  4123. if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment())
  4124. switch (DefMCID.getOpcode()) {
  4125. default: break;
  4126. case ARM::VLD1q8:
  4127. case ARM::VLD1q16:
  4128. case ARM::VLD1q32:
  4129. case ARM::VLD1q64:
  4130. case ARM::VLD1q8wb_register:
  4131. case ARM::VLD1q16wb_register:
  4132. case ARM::VLD1q32wb_register:
  4133. case ARM::VLD1q64wb_register:
  4134. case ARM::VLD1q8wb_fixed:
  4135. case ARM::VLD1q16wb_fixed:
  4136. case ARM::VLD1q32wb_fixed:
  4137. case ARM::VLD1q64wb_fixed:
  4138. case ARM::VLD2d8:
  4139. case ARM::VLD2d16:
  4140. case ARM::VLD2d32:
  4141. case ARM::VLD2q8Pseudo:
  4142. case ARM::VLD2q16Pseudo:
  4143. case ARM::VLD2q32Pseudo:
  4144. case ARM::VLD2d8wb_fixed:
  4145. case ARM::VLD2d16wb_fixed:
  4146. case ARM::VLD2d32wb_fixed:
  4147. case ARM::VLD2q8PseudoWB_fixed:
  4148. case ARM::VLD2q16PseudoWB_fixed:
  4149. case ARM::VLD2q32PseudoWB_fixed:
  4150. case ARM::VLD2d8wb_register:
  4151. case ARM::VLD2d16wb_register:
  4152. case ARM::VLD2d32wb_register:
  4153. case ARM::VLD2q8PseudoWB_register:
  4154. case ARM::VLD2q16PseudoWB_register:
  4155. case ARM::VLD2q32PseudoWB_register:
  4156. case ARM::VLD3d8Pseudo:
  4157. case ARM::VLD3d16Pseudo:
  4158. case ARM::VLD3d32Pseudo:
  4159. case ARM::VLD1d8TPseudo:
  4160. case ARM::VLD1d16TPseudo:
  4161. case ARM::VLD1d32TPseudo:
  4162. case ARM::VLD1d64TPseudo:
  4163. case ARM::VLD1d64TPseudoWB_fixed:
  4164. case ARM::VLD1d64TPseudoWB_register:
  4165. case ARM::VLD3d8Pseudo_UPD:
  4166. case ARM::VLD3d16Pseudo_UPD:
  4167. case ARM::VLD3d32Pseudo_UPD:
  4168. case ARM::VLD3q8Pseudo_UPD:
  4169. case ARM::VLD3q16Pseudo_UPD:
  4170. case ARM::VLD3q32Pseudo_UPD:
  4171. case ARM::VLD3q8oddPseudo:
  4172. case ARM::VLD3q16oddPseudo:
  4173. case ARM::VLD3q32oddPseudo:
  4174. case ARM::VLD3q8oddPseudo_UPD:
  4175. case ARM::VLD3q16oddPseudo_UPD:
  4176. case ARM::VLD3q32oddPseudo_UPD:
  4177. case ARM::VLD4d8Pseudo:
  4178. case ARM::VLD4d16Pseudo:
  4179. case ARM::VLD4d32Pseudo:
  4180. case ARM::VLD1d8QPseudo:
  4181. case ARM::VLD1d16QPseudo:
  4182. case ARM::VLD1d32QPseudo:
  4183. case ARM::VLD1d64QPseudo:
  4184. case ARM::VLD1d64QPseudoWB_fixed:
  4185. case ARM::VLD1d64QPseudoWB_register:
  4186. case ARM::VLD1q8HighQPseudo:
  4187. case ARM::VLD1q8LowQPseudo_UPD:
  4188. case ARM::VLD1q8HighTPseudo:
  4189. case ARM::VLD1q8LowTPseudo_UPD:
  4190. case ARM::VLD1q16HighQPseudo:
  4191. case ARM::VLD1q16LowQPseudo_UPD:
  4192. case ARM::VLD1q16HighTPseudo:
  4193. case ARM::VLD1q16LowTPseudo_UPD:
  4194. case ARM::VLD1q32HighQPseudo:
  4195. case ARM::VLD1q32LowQPseudo_UPD:
  4196. case ARM::VLD1q32HighTPseudo:
  4197. case ARM::VLD1q32LowTPseudo_UPD:
  4198. case ARM::VLD1q64HighQPseudo:
  4199. case ARM::VLD1q64LowQPseudo_UPD:
  4200. case ARM::VLD1q64HighTPseudo:
  4201. case ARM::VLD1q64LowTPseudo_UPD:
  4202. case ARM::VLD4d8Pseudo_UPD:
  4203. case ARM::VLD4d16Pseudo_UPD:
  4204. case ARM::VLD4d32Pseudo_UPD:
  4205. case ARM::VLD4q8Pseudo_UPD:
  4206. case ARM::VLD4q16Pseudo_UPD:
  4207. case ARM::VLD4q32Pseudo_UPD:
  4208. case ARM::VLD4q8oddPseudo:
  4209. case ARM::VLD4q16oddPseudo:
  4210. case ARM::VLD4q32oddPseudo:
  4211. case ARM::VLD4q8oddPseudo_UPD:
  4212. case ARM::VLD4q16oddPseudo_UPD:
  4213. case ARM::VLD4q32oddPseudo_UPD:
  4214. case ARM::VLD1DUPq8:
  4215. case ARM::VLD1DUPq16:
  4216. case ARM::VLD1DUPq32:
  4217. case ARM::VLD1DUPq8wb_fixed:
  4218. case ARM::VLD1DUPq16wb_fixed:
  4219. case ARM::VLD1DUPq32wb_fixed:
  4220. case ARM::VLD1DUPq8wb_register:
  4221. case ARM::VLD1DUPq16wb_register:
  4222. case ARM::VLD1DUPq32wb_register:
  4223. case ARM::VLD2DUPd8:
  4224. case ARM::VLD2DUPd16:
  4225. case ARM::VLD2DUPd32:
  4226. case ARM::VLD2DUPd8wb_fixed:
  4227. case ARM::VLD2DUPd16wb_fixed:
  4228. case ARM::VLD2DUPd32wb_fixed:
  4229. case ARM::VLD2DUPd8wb_register:
  4230. case ARM::VLD2DUPd16wb_register:
  4231. case ARM::VLD2DUPd32wb_register:
  4232. case ARM::VLD2DUPq8EvenPseudo:
  4233. case ARM::VLD2DUPq8OddPseudo:
  4234. case ARM::VLD2DUPq16EvenPseudo:
  4235. case ARM::VLD2DUPq16OddPseudo:
  4236. case ARM::VLD2DUPq32EvenPseudo:
  4237. case ARM::VLD2DUPq32OddPseudo:
  4238. case ARM::VLD3DUPq8EvenPseudo:
  4239. case ARM::VLD3DUPq8OddPseudo:
  4240. case ARM::VLD3DUPq16EvenPseudo:
  4241. case ARM::VLD3DUPq16OddPseudo:
  4242. case ARM::VLD3DUPq32EvenPseudo:
  4243. case ARM::VLD3DUPq32OddPseudo:
  4244. case ARM::VLD4DUPd8Pseudo:
  4245. case ARM::VLD4DUPd16Pseudo:
  4246. case ARM::VLD4DUPd32Pseudo:
  4247. case ARM::VLD4DUPd8Pseudo_UPD:
  4248. case ARM::VLD4DUPd16Pseudo_UPD:
  4249. case ARM::VLD4DUPd32Pseudo_UPD:
  4250. case ARM::VLD4DUPq8EvenPseudo:
  4251. case ARM::VLD4DUPq8OddPseudo:
  4252. case ARM::VLD4DUPq16EvenPseudo:
  4253. case ARM::VLD4DUPq16OddPseudo:
  4254. case ARM::VLD4DUPq32EvenPseudo:
  4255. case ARM::VLD4DUPq32OddPseudo:
  4256. case ARM::VLD1LNq8Pseudo:
  4257. case ARM::VLD1LNq16Pseudo:
  4258. case ARM::VLD1LNq32Pseudo:
  4259. case ARM::VLD1LNq8Pseudo_UPD:
  4260. case ARM::VLD1LNq16Pseudo_UPD:
  4261. case ARM::VLD1LNq32Pseudo_UPD:
  4262. case ARM::VLD2LNd8Pseudo:
  4263. case ARM::VLD2LNd16Pseudo:
  4264. case ARM::VLD2LNd32Pseudo:
  4265. case ARM::VLD2LNq16Pseudo:
  4266. case ARM::VLD2LNq32Pseudo:
  4267. case ARM::VLD2LNd8Pseudo_UPD:
  4268. case ARM::VLD2LNd16Pseudo_UPD:
  4269. case ARM::VLD2LNd32Pseudo_UPD:
  4270. case ARM::VLD2LNq16Pseudo_UPD:
  4271. case ARM::VLD2LNq32Pseudo_UPD:
  4272. case ARM::VLD4LNd8Pseudo:
  4273. case ARM::VLD4LNd16Pseudo:
  4274. case ARM::VLD4LNd32Pseudo:
  4275. case ARM::VLD4LNq16Pseudo:
  4276. case ARM::VLD4LNq32Pseudo:
  4277. case ARM::VLD4LNd8Pseudo_UPD:
  4278. case ARM::VLD4LNd16Pseudo_UPD:
  4279. case ARM::VLD4LNd32Pseudo_UPD:
  4280. case ARM::VLD4LNq16Pseudo_UPD:
  4281. case ARM::VLD4LNq32Pseudo_UPD:
  4282. // If the address is not 64-bit aligned, the latencies of these
  4283. // instructions increases by one.
  4284. ++Latency;
  4285. break;
  4286. }
  4287. return Latency;
  4288. }
  4289. unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const {
  4290. if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
  4291. MI.isImplicitDef())
  4292. return 0;
  4293. if (MI.isBundle())
  4294. return 0;
  4295. const MCInstrDesc &MCID = MI.getDesc();
  4296. if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
  4297. !Subtarget.cheapPredicableCPSRDef())) {
  4298. // When predicated, CPSR is an additional source operand for CPSR updating
  4299. // instructions, this apparently increases their latencies.
  4300. return 1;
  4301. }
  4302. return 0;
  4303. }
  4304. unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
  4305. const MachineInstr &MI,
  4306. unsigned *PredCost) const {
  4307. if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
  4308. MI.isImplicitDef())
  4309. return 1;
  4310. // An instruction scheduler typically runs on unbundled instructions, however
  4311. // other passes may query the latency of a bundled instruction.
  4312. if (MI.isBundle()) {
  4313. unsigned Latency = 0;
  4314. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  4315. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  4316. while (++I != E && I->isInsideBundle()) {
  4317. if (I->getOpcode() != ARM::t2IT)
  4318. Latency += getInstrLatency(ItinData, *I, PredCost);
  4319. }
  4320. return Latency;
  4321. }
  4322. const MCInstrDesc &MCID = MI.getDesc();
  4323. if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
  4324. !Subtarget.cheapPredicableCPSRDef()))) {
  4325. // When predicated, CPSR is an additional source operand for CPSR updating
  4326. // instructions, this apparently increases their latencies.
  4327. *PredCost = 1;
  4328. }
  4329. // Be sure to call getStageLatency for an empty itinerary in case it has a
  4330. // valid MinLatency property.
  4331. if (!ItinData)
  4332. return MI.mayLoad() ? 3 : 1;
  4333. unsigned Class = MCID.getSchedClass();
  4334. // For instructions with variable uops, use uops as latency.
  4335. if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
  4336. return getNumMicroOps(ItinData, MI);
  4337. // For the common case, fall back on the itinerary's latency.
  4338. unsigned Latency = ItinData->getStageLatency(Class);
  4339. // Adjust for dynamic def-side opcode variants not captured by the itinerary.
  4340. unsigned DefAlign =
  4341. MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlign().value() : 0;
  4342. int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign);
  4343. if (Adj >= 0 || (int)Latency > -Adj) {
  4344. return Latency + Adj;
  4345. }
  4346. return Latency;
  4347. }
  4348. int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
  4349. SDNode *Node) const {
  4350. if (!Node->isMachineOpcode())
  4351. return 1;
  4352. if (!ItinData || ItinData->isEmpty())
  4353. return 1;
  4354. unsigned Opcode = Node->getMachineOpcode();
  4355. switch (Opcode) {
  4356. default:
  4357. return ItinData->getStageLatency(get(Opcode).getSchedClass());
  4358. case ARM::VLDMQIA:
  4359. case ARM::VSTMQIA:
  4360. return 2;
  4361. }
  4362. }
  4363. bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
  4364. const MachineRegisterInfo *MRI,
  4365. const MachineInstr &DefMI,
  4366. unsigned DefIdx,
  4367. const MachineInstr &UseMI,
  4368. unsigned UseIdx) const {
  4369. unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
  4370. unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask;
  4371. if (Subtarget.nonpipelinedVFP() &&
  4372. (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
  4373. return true;
  4374. // Hoist VFP / NEON instructions with 4 or higher latency.
  4375. unsigned Latency =
  4376. SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx);
  4377. if (Latency <= 3)
  4378. return false;
  4379. return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
  4380. UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
  4381. }
  4382. bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
  4383. const MachineInstr &DefMI,
  4384. unsigned DefIdx) const {
  4385. const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
  4386. if (!ItinData || ItinData->isEmpty())
  4387. return false;
  4388. unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
  4389. if (DDomain == ARMII::DomainGeneral) {
  4390. unsigned DefClass = DefMI.getDesc().getSchedClass();
  4391. int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
  4392. return (DefCycle != -1 && DefCycle <= 2);
  4393. }
  4394. return false;
  4395. }
  4396. bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI,
  4397. StringRef &ErrInfo) const {
  4398. if (convertAddSubFlagsOpcode(MI.getOpcode())) {
  4399. ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
  4400. return false;
  4401. }
  4402. if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) {
  4403. // Make sure we don't generate a lo-lo mov that isn't supported.
  4404. if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) &&
  4405. !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) {
  4406. ErrInfo = "Non-flag-setting Thumb1 mov is v6-only";
  4407. return false;
  4408. }
  4409. }
  4410. if (MI.getOpcode() == ARM::tPUSH ||
  4411. MI.getOpcode() == ARM::tPOP ||
  4412. MI.getOpcode() == ARM::tPOP_RET) {
  4413. for (int i = 2, e = MI.getNumOperands(); i < e; ++i) {
  4414. if (MI.getOperand(i).isImplicit() ||
  4415. !MI.getOperand(i).isReg())
  4416. continue;
  4417. Register Reg = MI.getOperand(i).getReg();
  4418. if (Reg < ARM::R0 || Reg > ARM::R7) {
  4419. if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) &&
  4420. !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) {
  4421. ErrInfo = "Unsupported register in Thumb1 push/pop";
  4422. return false;
  4423. }
  4424. }
  4425. }
  4426. }
  4427. if (MI.getOpcode() == ARM::MVE_VMOV_q_rr) {
  4428. assert(MI.getOperand(4).isImm() && MI.getOperand(5).isImm());
  4429. if ((MI.getOperand(4).getImm() != 2 && MI.getOperand(4).getImm() != 3) ||
  4430. MI.getOperand(4).getImm() != MI.getOperand(5).getImm() + 2) {
  4431. ErrInfo = "Incorrect array index for MVE_VMOV_q_rr";
  4432. return false;
  4433. }
  4434. }
  4435. return true;
  4436. }
  4437. // LoadStackGuard has so far only been implemented for MachO. Different code
  4438. // sequence is needed for other targets.
  4439. void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
  4440. unsigned LoadImmOpc,
  4441. unsigned LoadOpc) const {
  4442. assert(!Subtarget.isROPI() && !Subtarget.isRWPI() &&
  4443. "ROPI/RWPI not currently supported with stack guard");
  4444. MachineBasicBlock &MBB = *MI->getParent();
  4445. DebugLoc DL = MI->getDebugLoc();
  4446. Register Reg = MI->getOperand(0).getReg();
  4447. const GlobalValue *GV =
  4448. cast<GlobalValue>((*MI->memoperands_begin())->getValue());
  4449. MachineInstrBuilder MIB;
  4450. BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
  4451. .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY);
  4452. if (Subtarget.isGVIndirectSymbol(GV)) {
  4453. MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
  4454. MIB.addReg(Reg, RegState::Kill).addImm(0);
  4455. auto Flags = MachineMemOperand::MOLoad |
  4456. MachineMemOperand::MODereferenceable |
  4457. MachineMemOperand::MOInvariant;
  4458. MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
  4459. MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, Align(4));
  4460. MIB.addMemOperand(MMO).add(predOps(ARMCC::AL));
  4461. }
  4462. MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
  4463. MIB.addReg(Reg, RegState::Kill)
  4464. .addImm(0)
  4465. .cloneMemRefs(*MI)
  4466. .add(predOps(ARMCC::AL));
  4467. }
  4468. bool
  4469. ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
  4470. unsigned &AddSubOpc,
  4471. bool &NegAcc, bool &HasLane) const {
  4472. DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
  4473. if (I == MLxEntryMap.end())
  4474. return false;
  4475. const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
  4476. MulOpc = Entry.MulOpc;
  4477. AddSubOpc = Entry.AddSubOpc;
  4478. NegAcc = Entry.NegAcc;
  4479. HasLane = Entry.HasLane;
  4480. return true;
  4481. }
  4482. //===----------------------------------------------------------------------===//
  4483. // Execution domains.
  4484. //===----------------------------------------------------------------------===//
  4485. //
  4486. // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
  4487. // and some can go down both. The vmov instructions go down the VFP pipeline,
  4488. // but they can be changed to vorr equivalents that are executed by the NEON
  4489. // pipeline.
  4490. //
  4491. // We use the following execution domain numbering:
  4492. //
  4493. enum ARMExeDomain {
  4494. ExeGeneric = 0,
  4495. ExeVFP = 1,
  4496. ExeNEON = 2
  4497. };
  4498. //
  4499. // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
  4500. //
  4501. std::pair<uint16_t, uint16_t>
  4502. ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const {
  4503. // If we don't have access to NEON instructions then we won't be able
  4504. // to swizzle anything to the NEON domain. Check to make sure.
  4505. if (Subtarget.hasNEON()) {
  4506. // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
  4507. // if they are not predicated.
  4508. if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI))
  4509. return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
  4510. // CortexA9 is particularly picky about mixing the two and wants these
  4511. // converted.
  4512. if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) &&
  4513. (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR ||
  4514. MI.getOpcode() == ARM::VMOVS))
  4515. return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
  4516. }
  4517. // No other instructions can be swizzled, so just determine their domain.
  4518. unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask;
  4519. if (Domain & ARMII::DomainNEON)
  4520. return std::make_pair(ExeNEON, 0);
  4521. // Certain instructions can go either way on Cortex-A8.
  4522. // Treat them as NEON instructions.
  4523. if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
  4524. return std::make_pair(ExeNEON, 0);
  4525. if (Domain & ARMII::DomainVFP)
  4526. return std::make_pair(ExeVFP, 0);
  4527. return std::make_pair(ExeGeneric, 0);
  4528. }
  4529. static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
  4530. unsigned SReg, unsigned &Lane) {
  4531. unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
  4532. Lane = 0;
  4533. if (DReg != ARM::NoRegister)
  4534. return DReg;
  4535. Lane = 1;
  4536. DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
  4537. assert(DReg && "S-register with no D super-register?");
  4538. return DReg;
  4539. }
  4540. /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
  4541. /// set ImplicitSReg to a register number that must be marked as implicit-use or
  4542. /// zero if no register needs to be defined as implicit-use.
  4543. ///
  4544. /// If the function cannot determine if an SPR should be marked implicit use or
  4545. /// not, it returns false.
  4546. ///
  4547. /// This function handles cases where an instruction is being modified from taking
  4548. /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
  4549. /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
  4550. /// lane of the DPR).
  4551. ///
  4552. /// If the other SPR is defined, an implicit-use of it should be added. Else,
  4553. /// (including the case where the DPR itself is defined), it should not.
  4554. ///
  4555. static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
  4556. MachineInstr &MI, unsigned DReg,
  4557. unsigned Lane, unsigned &ImplicitSReg) {
  4558. // If the DPR is defined or used already, the other SPR lane will be chained
  4559. // correctly, so there is nothing to be done.
  4560. if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) {
  4561. ImplicitSReg = 0;
  4562. return true;
  4563. }
  4564. // Otherwise we need to go searching to see if the SPR is set explicitly.
  4565. ImplicitSReg = TRI->getSubReg(DReg,
  4566. (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
  4567. MachineBasicBlock::LivenessQueryResult LQR =
  4568. MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
  4569. if (LQR == MachineBasicBlock::LQR_Live)
  4570. return true;
  4571. else if (LQR == MachineBasicBlock::LQR_Unknown)
  4572. return false;
  4573. // If the register is known not to be live, there is no need to add an
  4574. // implicit-use.
  4575. ImplicitSReg = 0;
  4576. return true;
  4577. }
  4578. void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI,
  4579. unsigned Domain) const {
  4580. unsigned DstReg, SrcReg, DReg;
  4581. unsigned Lane;
  4582. MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
  4583. const TargetRegisterInfo *TRI = &getRegisterInfo();
  4584. switch (MI.getOpcode()) {
  4585. default:
  4586. llvm_unreachable("cannot handle opcode!");
  4587. break;
  4588. case ARM::VMOVD:
  4589. if (Domain != ExeNEON)
  4590. break;
  4591. // Zap the predicate operands.
  4592. assert(!isPredicated(MI) && "Cannot predicate a VORRd");
  4593. // Make sure we've got NEON instructions.
  4594. assert(Subtarget.hasNEON() && "VORRd requires NEON");
  4595. // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
  4596. DstReg = MI.getOperand(0).getReg();
  4597. SrcReg = MI.getOperand(1).getReg();
  4598. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4599. MI.RemoveOperand(i - 1);
  4600. // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
  4601. MI.setDesc(get(ARM::VORRd));
  4602. MIB.addReg(DstReg, RegState::Define)
  4603. .addReg(SrcReg)
  4604. .addReg(SrcReg)
  4605. .add(predOps(ARMCC::AL));
  4606. break;
  4607. case ARM::VMOVRS:
  4608. if (Domain != ExeNEON)
  4609. break;
  4610. assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
  4611. // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
  4612. DstReg = MI.getOperand(0).getReg();
  4613. SrcReg = MI.getOperand(1).getReg();
  4614. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4615. MI.RemoveOperand(i - 1);
  4616. DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
  4617. // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
  4618. // Note that DSrc has been widened and the other lane may be undef, which
  4619. // contaminates the entire register.
  4620. MI.setDesc(get(ARM::VGETLNi32));
  4621. MIB.addReg(DstReg, RegState::Define)
  4622. .addReg(DReg, RegState::Undef)
  4623. .addImm(Lane)
  4624. .add(predOps(ARMCC::AL));
  4625. // The old source should be an implicit use, otherwise we might think it
  4626. // was dead before here.
  4627. MIB.addReg(SrcReg, RegState::Implicit);
  4628. break;
  4629. case ARM::VMOVSR: {
  4630. if (Domain != ExeNEON)
  4631. break;
  4632. assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
  4633. // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
  4634. DstReg = MI.getOperand(0).getReg();
  4635. SrcReg = MI.getOperand(1).getReg();
  4636. DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
  4637. unsigned ImplicitSReg;
  4638. if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
  4639. break;
  4640. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4641. MI.RemoveOperand(i - 1);
  4642. // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
  4643. // Again DDst may be undefined at the beginning of this instruction.
  4644. MI.setDesc(get(ARM::VSETLNi32));
  4645. MIB.addReg(DReg, RegState::Define)
  4646. .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI)))
  4647. .addReg(SrcReg)
  4648. .addImm(Lane)
  4649. .add(predOps(ARMCC::AL));
  4650. // The narrower destination must be marked as set to keep previous chains
  4651. // in place.
  4652. MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
  4653. if (ImplicitSReg != 0)
  4654. MIB.addReg(ImplicitSReg, RegState::Implicit);
  4655. break;
  4656. }
  4657. case ARM::VMOVS: {
  4658. if (Domain != ExeNEON)
  4659. break;
  4660. // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
  4661. DstReg = MI.getOperand(0).getReg();
  4662. SrcReg = MI.getOperand(1).getReg();
  4663. unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
  4664. DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
  4665. DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
  4666. unsigned ImplicitSReg;
  4667. if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
  4668. break;
  4669. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4670. MI.RemoveOperand(i - 1);
  4671. if (DSrc == DDst) {
  4672. // Destination can be:
  4673. // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
  4674. MI.setDesc(get(ARM::VDUPLN32d));
  4675. MIB.addReg(DDst, RegState::Define)
  4676. .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI)))
  4677. .addImm(SrcLane)
  4678. .add(predOps(ARMCC::AL));
  4679. // Neither the source or the destination are naturally represented any
  4680. // more, so add them in manually.
  4681. MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
  4682. MIB.addReg(SrcReg, RegState::Implicit);
  4683. if (ImplicitSReg != 0)
  4684. MIB.addReg(ImplicitSReg, RegState::Implicit);
  4685. break;
  4686. }
  4687. // In general there's no single instruction that can perform an S <-> S
  4688. // move in NEON space, but a pair of VEXT instructions *can* do the
  4689. // job. It turns out that the VEXTs needed will only use DSrc once, with
  4690. // the position based purely on the combination of lane-0 and lane-1
  4691. // involved. For example
  4692. // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1
  4693. // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1
  4694. // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1
  4695. // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1
  4696. //
  4697. // Pattern of the MachineInstrs is:
  4698. // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
  4699. MachineInstrBuilder NewMIB;
  4700. NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32),
  4701. DDst);
  4702. // On the first instruction, both DSrc and DDst may be undef if present.
  4703. // Specifically when the original instruction didn't have them as an
  4704. // <imp-use>.
  4705. unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
  4706. bool CurUndef = !MI.readsRegister(CurReg, TRI);
  4707. NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
  4708. CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
  4709. CurUndef = !MI.readsRegister(CurReg, TRI);
  4710. NewMIB.addReg(CurReg, getUndefRegState(CurUndef))
  4711. .addImm(1)
  4712. .add(predOps(ARMCC::AL));
  4713. if (SrcLane == DstLane)
  4714. NewMIB.addReg(SrcReg, RegState::Implicit);
  4715. MI.setDesc(get(ARM::VEXTd32));
  4716. MIB.addReg(DDst, RegState::Define);
  4717. // On the second instruction, DDst has definitely been defined above, so
  4718. // it is not undef. DSrc, if present, can be undef as above.
  4719. CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
  4720. CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
  4721. MIB.addReg(CurReg, getUndefRegState(CurUndef));
  4722. CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
  4723. CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
  4724. MIB.addReg(CurReg, getUndefRegState(CurUndef))
  4725. .addImm(1)
  4726. .add(predOps(ARMCC::AL));
  4727. if (SrcLane != DstLane)
  4728. MIB.addReg(SrcReg, RegState::Implicit);
  4729. // As before, the original destination is no longer represented, add it
  4730. // implicitly.
  4731. MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
  4732. if (ImplicitSReg != 0)
  4733. MIB.addReg(ImplicitSReg, RegState::Implicit);
  4734. break;
  4735. }
  4736. }
  4737. }
  4738. //===----------------------------------------------------------------------===//
  4739. // Partial register updates
  4740. //===----------------------------------------------------------------------===//
  4741. //
  4742. // Swift renames NEON registers with 64-bit granularity. That means any
  4743. // instruction writing an S-reg implicitly reads the containing D-reg. The
  4744. // problem is mostly avoided by translating f32 operations to v2f32 operations
  4745. // on D-registers, but f32 loads are still a problem.
  4746. //
  4747. // These instructions can load an f32 into a NEON register:
  4748. //
  4749. // VLDRS - Only writes S, partial D update.
  4750. // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
  4751. // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
  4752. //
  4753. // FCONSTD can be used as a dependency-breaking instruction.
  4754. unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance(
  4755. const MachineInstr &MI, unsigned OpNum,
  4756. const TargetRegisterInfo *TRI) const {
  4757. auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance();
  4758. if (!PartialUpdateClearance)
  4759. return 0;
  4760. assert(TRI && "Need TRI instance");
  4761. const MachineOperand &MO = MI.getOperand(OpNum);
  4762. if (MO.readsReg())
  4763. return 0;
  4764. Register Reg = MO.getReg();
  4765. int UseOp = -1;
  4766. switch (MI.getOpcode()) {
  4767. // Normal instructions writing only an S-register.
  4768. case ARM::VLDRS:
  4769. case ARM::FCONSTS:
  4770. case ARM::VMOVSR:
  4771. case ARM::VMOVv8i8:
  4772. case ARM::VMOVv4i16:
  4773. case ARM::VMOVv2i32:
  4774. case ARM::VMOVv2f32:
  4775. case ARM::VMOVv1i64:
  4776. UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI);
  4777. break;
  4778. // Explicitly reads the dependency.
  4779. case ARM::VLD1LNd32:
  4780. UseOp = 3;
  4781. break;
  4782. default:
  4783. return 0;
  4784. }
  4785. // If this instruction actually reads a value from Reg, there is no unwanted
  4786. // dependency.
  4787. if (UseOp != -1 && MI.getOperand(UseOp).readsReg())
  4788. return 0;
  4789. // We must be able to clobber the whole D-reg.
  4790. if (Register::isVirtualRegister(Reg)) {
  4791. // Virtual register must be a def undef foo:ssub_0 operand.
  4792. if (!MO.getSubReg() || MI.readsVirtualRegister(Reg))
  4793. return 0;
  4794. } else if (ARM::SPRRegClass.contains(Reg)) {
  4795. // Physical register: MI must define the full D-reg.
  4796. unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
  4797. &ARM::DPRRegClass);
  4798. if (!DReg || !MI.definesRegister(DReg, TRI))
  4799. return 0;
  4800. }
  4801. // MI has an unwanted D-register dependency.
  4802. // Avoid defs in the previous N instructrions.
  4803. return PartialUpdateClearance;
  4804. }
  4805. // Break a partial register dependency after getPartialRegUpdateClearance
  4806. // returned non-zero.
  4807. void ARMBaseInstrInfo::breakPartialRegDependency(
  4808. MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
  4809. assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def");
  4810. assert(TRI && "Need TRI instance");
  4811. const MachineOperand &MO = MI.getOperand(OpNum);
  4812. Register Reg = MO.getReg();
  4813. assert(Register::isPhysicalRegister(Reg) &&
  4814. "Can't break virtual register dependencies.");
  4815. unsigned DReg = Reg;
  4816. // If MI defines an S-reg, find the corresponding D super-register.
  4817. if (ARM::SPRRegClass.contains(Reg)) {
  4818. DReg = ARM::D0 + (Reg - ARM::S0) / 2;
  4819. assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
  4820. }
  4821. assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
  4822. assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
  4823. // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
  4824. // the full D-register by loading the same value to both lanes. The
  4825. // instruction is micro-coded with 2 uops, so don't do this until we can
  4826. // properly schedule micro-coded instructions. The dispatcher stalls cause
  4827. // too big regressions.
  4828. // Insert the dependency-breaking FCONSTD before MI.
  4829. // 96 is the encoding of 0.5, but the actual value doesn't matter here.
  4830. BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg)
  4831. .addImm(96)
  4832. .add(predOps(ARMCC::AL));
  4833. MI.addRegisterKilled(DReg, TRI, true);
  4834. }
  4835. bool ARMBaseInstrInfo::hasNOP() const {
  4836. return Subtarget.getFeatureBits()[ARM::HasV6KOps];
  4837. }
  4838. bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
  4839. if (MI->getNumOperands() < 4)
  4840. return true;
  4841. unsigned ShOpVal = MI->getOperand(3).getImm();
  4842. unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
  4843. // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
  4844. if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
  4845. ((ShImm == 1 || ShImm == 2) &&
  4846. ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
  4847. return true;
  4848. return false;
  4849. }
  4850. bool ARMBaseInstrInfo::getRegSequenceLikeInputs(
  4851. const MachineInstr &MI, unsigned DefIdx,
  4852. SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
  4853. assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
  4854. assert(MI.isRegSequenceLike() && "Invalid kind of instruction");
  4855. switch (MI.getOpcode()) {
  4856. case ARM::VMOVDRR:
  4857. // dX = VMOVDRR rY, rZ
  4858. // is the same as:
  4859. // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1
  4860. // Populate the InputRegs accordingly.
  4861. // rY
  4862. const MachineOperand *MOReg = &MI.getOperand(1);
  4863. if (!MOReg->isUndef())
  4864. InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
  4865. MOReg->getSubReg(), ARM::ssub_0));
  4866. // rZ
  4867. MOReg = &MI.getOperand(2);
  4868. if (!MOReg->isUndef())
  4869. InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
  4870. MOReg->getSubReg(), ARM::ssub_1));
  4871. return true;
  4872. }
  4873. llvm_unreachable("Target dependent opcode missing");
  4874. }
  4875. bool ARMBaseInstrInfo::getExtractSubregLikeInputs(
  4876. const MachineInstr &MI, unsigned DefIdx,
  4877. RegSubRegPairAndIdx &InputReg) const {
  4878. assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
  4879. assert(MI.isExtractSubregLike() && "Invalid kind of instruction");
  4880. switch (MI.getOpcode()) {
  4881. case ARM::VMOVRRD:
  4882. // rX, rY = VMOVRRD dZ
  4883. // is the same as:
  4884. // rX = EXTRACT_SUBREG dZ, ssub_0
  4885. // rY = EXTRACT_SUBREG dZ, ssub_1
  4886. const MachineOperand &MOReg = MI.getOperand(2);
  4887. if (MOReg.isUndef())
  4888. return false;
  4889. InputReg.Reg = MOReg.getReg();
  4890. InputReg.SubReg = MOReg.getSubReg();
  4891. InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1;
  4892. return true;
  4893. }
  4894. llvm_unreachable("Target dependent opcode missing");
  4895. }
  4896. bool ARMBaseInstrInfo::getInsertSubregLikeInputs(
  4897. const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg,
  4898. RegSubRegPairAndIdx &InsertedReg) const {
  4899. assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
  4900. assert(MI.isInsertSubregLike() && "Invalid kind of instruction");
  4901. switch (MI.getOpcode()) {
  4902. case ARM::VSETLNi32:
  4903. // dX = VSETLNi32 dY, rZ, imm
  4904. const MachineOperand &MOBaseReg = MI.getOperand(1);
  4905. const MachineOperand &MOInsertedReg = MI.getOperand(2);
  4906. if (MOInsertedReg.isUndef())
  4907. return false;
  4908. const MachineOperand &MOIndex = MI.getOperand(3);
  4909. BaseReg.Reg = MOBaseReg.getReg();
  4910. BaseReg.SubReg = MOBaseReg.getSubReg();
  4911. InsertedReg.Reg = MOInsertedReg.getReg();
  4912. InsertedReg.SubReg = MOInsertedReg.getSubReg();
  4913. InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1;
  4914. return true;
  4915. }
  4916. llvm_unreachable("Target dependent opcode missing");
  4917. }
  4918. std::pair<unsigned, unsigned>
  4919. ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
  4920. const unsigned Mask = ARMII::MO_OPTION_MASK;
  4921. return std::make_pair(TF & Mask, TF & ~Mask);
  4922. }
  4923. ArrayRef<std::pair<unsigned, const char *>>
  4924. ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
  4925. using namespace ARMII;
  4926. static const std::pair<unsigned, const char *> TargetFlags[] = {
  4927. {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}};
  4928. return makeArrayRef(TargetFlags);
  4929. }
  4930. ArrayRef<std::pair<unsigned, const char *>>
  4931. ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
  4932. using namespace ARMII;
  4933. static const std::pair<unsigned, const char *> TargetFlags[] = {
  4934. {MO_COFFSTUB, "arm-coffstub"},
  4935. {MO_GOT, "arm-got"},
  4936. {MO_SBREL, "arm-sbrel"},
  4937. {MO_DLLIMPORT, "arm-dllimport"},
  4938. {MO_SECREL, "arm-secrel"},
  4939. {MO_NONLAZY, "arm-nonlazy"}};
  4940. return makeArrayRef(TargetFlags);
  4941. }
  4942. Optional<RegImmPair> ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI,
  4943. Register Reg) const {
  4944. int Sign = 1;
  4945. unsigned Opcode = MI.getOpcode();
  4946. int64_t Offset = 0;
  4947. // TODO: Handle cases where Reg is a super- or sub-register of the
  4948. // destination register.
  4949. const MachineOperand &Op0 = MI.getOperand(0);
  4950. if (!Op0.isReg() || Reg != Op0.getReg())
  4951. return None;
  4952. // We describe SUBri or ADDri instructions.
  4953. if (Opcode == ARM::SUBri)
  4954. Sign = -1;
  4955. else if (Opcode != ARM::ADDri)
  4956. return None;
  4957. // TODO: Third operand can be global address (usually some string). Since
  4958. // strings can be relocated we cannot calculate their offsets for
  4959. // now.
  4960. if (!MI.getOperand(1).isReg() || !MI.getOperand(2).isImm())
  4961. return None;
  4962. Offset = MI.getOperand(2).getImm() * Sign;
  4963. return RegImmPair{MI.getOperand(1).getReg(), Offset};
  4964. }
  4965. bool llvm::registerDefinedBetween(unsigned Reg,
  4966. MachineBasicBlock::iterator From,
  4967. MachineBasicBlock::iterator To,
  4968. const TargetRegisterInfo *TRI) {
  4969. for (auto I = From; I != To; ++I)
  4970. if (I->modifiesRegister(Reg, TRI))
  4971. return true;
  4972. return false;
  4973. }
  4974. MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br,
  4975. const TargetRegisterInfo *TRI) {
  4976. // Search backwards to the instruction that defines CSPR. This may or not
  4977. // be a CMP, we check that after this loop. If we find another instruction
  4978. // that reads cpsr, we return nullptr.
  4979. MachineBasicBlock::iterator CmpMI = Br;
  4980. while (CmpMI != Br->getParent()->begin()) {
  4981. --CmpMI;
  4982. if (CmpMI->modifiesRegister(ARM::CPSR, TRI))
  4983. break;
  4984. if (CmpMI->readsRegister(ARM::CPSR, TRI))
  4985. break;
  4986. }
  4987. // Check that this inst is a CMP r[0-7], #0 and that the register
  4988. // is not redefined between the cmp and the br.
  4989. if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri)
  4990. return nullptr;
  4991. Register Reg = CmpMI->getOperand(0).getReg();
  4992. Register PredReg;
  4993. ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg);
  4994. if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0)
  4995. return nullptr;
  4996. if (!isARMLowRegister(Reg))
  4997. return nullptr;
  4998. if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI))
  4999. return nullptr;
  5000. return &*CmpMI;
  5001. }
  5002. unsigned llvm::ConstantMaterializationCost(unsigned Val,
  5003. const ARMSubtarget *Subtarget,
  5004. bool ForCodesize) {
  5005. if (Subtarget->isThumb()) {
  5006. if (Val <= 255) // MOV
  5007. return ForCodesize ? 2 : 1;
  5008. if (Subtarget->hasV6T2Ops() && (Val <= 0xffff || // MOV
  5009. ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW
  5010. ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN
  5011. return ForCodesize ? 4 : 1;
  5012. if (Val <= 510) // MOV + ADDi8
  5013. return ForCodesize ? 4 : 2;
  5014. if (~Val <= 255) // MOV + MVN
  5015. return ForCodesize ? 4 : 2;
  5016. if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL
  5017. return ForCodesize ? 4 : 2;
  5018. } else {
  5019. if (ARM_AM::getSOImmVal(Val) != -1) // MOV
  5020. return ForCodesize ? 4 : 1;
  5021. if (ARM_AM::getSOImmVal(~Val) != -1) // MVN
  5022. return ForCodesize ? 4 : 1;
  5023. if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW
  5024. return ForCodesize ? 4 : 1;
  5025. if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs
  5026. return ForCodesize ? 8 : 2;
  5027. if (ARM_AM::isSOImmTwoPartValNeg(Val)) // two instrs
  5028. return ForCodesize ? 8 : 2;
  5029. }
  5030. if (Subtarget->useMovt()) // MOVW + MOVT
  5031. return ForCodesize ? 8 : 2;
  5032. return ForCodesize ? 8 : 3; // Literal pool load
  5033. }
  5034. bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2,
  5035. const ARMSubtarget *Subtarget,
  5036. bool ForCodesize) {
  5037. // Check with ForCodesize
  5038. unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize);
  5039. unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize);
  5040. if (Cost1 < Cost2)
  5041. return true;
  5042. if (Cost1 > Cost2)
  5043. return false;
  5044. // If they are equal, try with !ForCodesize
  5045. return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) <
  5046. ConstantMaterializationCost(Val2, Subtarget, !ForCodesize);
  5047. }
  5048. /// Constants defining how certain sequences should be outlined.
  5049. /// This encompasses how an outlined function should be called, and what kind of
  5050. /// frame should be emitted for that outlined function.
  5051. ///
  5052. /// \p MachineOutlinerTailCall implies that the function is being created from
  5053. /// a sequence of instructions ending in a return.
  5054. ///
  5055. /// That is,
  5056. ///
  5057. /// I1 OUTLINED_FUNCTION:
  5058. /// I2 --> B OUTLINED_FUNCTION I1
  5059. /// BX LR I2
  5060. /// BX LR
  5061. ///
  5062. /// +-------------------------+--------+-----+
  5063. /// | | Thumb2 | ARM |
  5064. /// +-------------------------+--------+-----+
  5065. /// | Call overhead in Bytes | 4 | 4 |
  5066. /// | Frame overhead in Bytes | 0 | 0 |
  5067. /// | Stack fixup required | No | No |
  5068. /// +-------------------------+--------+-----+
  5069. ///
  5070. /// \p MachineOutlinerThunk implies that the function is being created from
  5071. /// a sequence of instructions ending in a call. The outlined function is
  5072. /// called with a BL instruction, and the outlined function tail-calls the
  5073. /// original call destination.
  5074. ///
  5075. /// That is,
  5076. ///
  5077. /// I1 OUTLINED_FUNCTION:
  5078. /// I2 --> BL OUTLINED_FUNCTION I1
  5079. /// BL f I2
  5080. /// B f
  5081. ///
  5082. /// +-------------------------+--------+-----+
  5083. /// | | Thumb2 | ARM |
  5084. /// +-------------------------+--------+-----+
  5085. /// | Call overhead in Bytes | 4 | 4 |
  5086. /// | Frame overhead in Bytes | 0 | 0 |
  5087. /// | Stack fixup required | No | No |
  5088. /// +-------------------------+--------+-----+
  5089. ///
  5090. /// \p MachineOutlinerNoLRSave implies that the function should be called using
  5091. /// a BL instruction, but doesn't require LR to be saved and restored. This
  5092. /// happens when LR is known to be dead.
  5093. ///
  5094. /// That is,
  5095. ///
  5096. /// I1 OUTLINED_FUNCTION:
  5097. /// I2 --> BL OUTLINED_FUNCTION I1
  5098. /// I3 I2
  5099. /// I3
  5100. /// BX LR
  5101. ///
  5102. /// +-------------------------+--------+-----+
  5103. /// | | Thumb2 | ARM |
  5104. /// +-------------------------+--------+-----+
  5105. /// | Call overhead in Bytes | 4 | 4 |
  5106. /// | Frame overhead in Bytes | 4 | 4 |
  5107. /// | Stack fixup required | No | No |
  5108. /// +-------------------------+--------+-----+
  5109. ///
  5110. /// \p MachineOutlinerRegSave implies that the function should be called with a
  5111. /// save and restore of LR to an available register. This allows us to avoid
  5112. /// stack fixups. Note that this outlining variant is compatible with the
  5113. /// NoLRSave case.
  5114. ///
  5115. /// That is,
  5116. ///
  5117. /// I1 Save LR OUTLINED_FUNCTION:
  5118. /// I2 --> BL OUTLINED_FUNCTION I1
  5119. /// I3 Restore LR I2
  5120. /// I3
  5121. /// BX LR
  5122. ///
  5123. /// +-------------------------+--------+-----+
  5124. /// | | Thumb2 | ARM |
  5125. /// +-------------------------+--------+-----+
  5126. /// | Call overhead in Bytes | 8 | 12 |
  5127. /// | Frame overhead in Bytes | 2 | 4 |
  5128. /// | Stack fixup required | No | No |
  5129. /// +-------------------------+--------+-----+
  5130. ///
  5131. /// \p MachineOutlinerDefault implies that the function should be called with
  5132. /// a save and restore of LR to the stack.
  5133. ///
  5134. /// That is,
  5135. ///
  5136. /// I1 Save LR OUTLINED_FUNCTION:
  5137. /// I2 --> BL OUTLINED_FUNCTION I1
  5138. /// I3 Restore LR I2
  5139. /// I3
  5140. /// BX LR
  5141. ///
  5142. /// +-------------------------+--------+-----+
  5143. /// | | Thumb2 | ARM |
  5144. /// +-------------------------+--------+-----+
  5145. /// | Call overhead in Bytes | 8 | 12 |
  5146. /// | Frame overhead in Bytes | 2 | 4 |
  5147. /// | Stack fixup required | Yes | Yes |
  5148. /// +-------------------------+--------+-----+
  5149. enum MachineOutlinerClass {
  5150. MachineOutlinerTailCall,
  5151. MachineOutlinerThunk,
  5152. MachineOutlinerNoLRSave,
  5153. MachineOutlinerRegSave,
  5154. MachineOutlinerDefault
  5155. };
  5156. enum MachineOutlinerMBBFlags {
  5157. LRUnavailableSomewhere = 0x2,
  5158. HasCalls = 0x4,
  5159. UnsafeRegsDead = 0x8
  5160. };
  5161. struct OutlinerCosts {
  5162. const int CallTailCall;
  5163. const int FrameTailCall;
  5164. const int CallThunk;
  5165. const int FrameThunk;
  5166. const int CallNoLRSave;
  5167. const int FrameNoLRSave;
  5168. const int CallRegSave;
  5169. const int FrameRegSave;
  5170. const int CallDefault;
  5171. const int FrameDefault;
  5172. const int SaveRestoreLROnStack;
  5173. OutlinerCosts(const ARMSubtarget &target)
  5174. : CallTailCall(target.isThumb() ? 4 : 4),
  5175. FrameTailCall(target.isThumb() ? 0 : 0),
  5176. CallThunk(target.isThumb() ? 4 : 4),
  5177. FrameThunk(target.isThumb() ? 0 : 0),
  5178. CallNoLRSave(target.isThumb() ? 4 : 4),
  5179. FrameNoLRSave(target.isThumb() ? 4 : 4),
  5180. CallRegSave(target.isThumb() ? 8 : 12),
  5181. FrameRegSave(target.isThumb() ? 2 : 4),
  5182. CallDefault(target.isThumb() ? 8 : 12),
  5183. FrameDefault(target.isThumb() ? 2 : 4),
  5184. SaveRestoreLROnStack(target.isThumb() ? 8 : 8) {}
  5185. };
  5186. unsigned
  5187. ARMBaseInstrInfo::findRegisterToSaveLRTo(const outliner::Candidate &C) const {
  5188. assert(C.LRUWasSet && "LRU wasn't set?");
  5189. MachineFunction *MF = C.getMF();
  5190. const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo *>(
  5191. MF->getSubtarget().getRegisterInfo());
  5192. BitVector regsReserved = ARI->getReservedRegs(*MF);
  5193. // Check if there is an available register across the sequence that we can
  5194. // use.
  5195. for (unsigned Reg : ARM::rGPRRegClass) {
  5196. if (!(Reg < regsReserved.size() && regsReserved.test(Reg)) &&
  5197. Reg != ARM::LR && // LR is not reserved, but don't use it.
  5198. Reg != ARM::R12 && // R12 is not guaranteed to be preserved.
  5199. C.LRU.available(Reg) && C.UsedInSequence.available(Reg))
  5200. return Reg;
  5201. }
  5202. // No suitable register. Return 0.
  5203. return 0u;
  5204. }
  5205. // Compute liveness of LR at the point after the interval [I, E), which
  5206. // denotes a *backward* iteration through instructions. Used only for return
  5207. // basic blocks, which do not end with a tail call.
  5208. static bool isLRAvailable(const TargetRegisterInfo &TRI,
  5209. MachineBasicBlock::reverse_iterator I,
  5210. MachineBasicBlock::reverse_iterator E) {
  5211. // At the end of the function LR dead.
  5212. bool Live = false;
  5213. for (; I != E; ++I) {
  5214. const MachineInstr &MI = *I;
  5215. // Check defs of LR.
  5216. if (MI.modifiesRegister(ARM::LR, &TRI))
  5217. Live = false;
  5218. // Check uses of LR.
  5219. unsigned Opcode = MI.getOpcode();
  5220. if (Opcode == ARM::BX_RET || Opcode == ARM::MOVPCLR ||
  5221. Opcode == ARM::SUBS_PC_LR || Opcode == ARM::tBX_RET ||
  5222. Opcode == ARM::tBXNS_RET) {
  5223. // These instructions use LR, but it's not an (explicit or implicit)
  5224. // operand.
  5225. Live = true;
  5226. continue;
  5227. }
  5228. if (MI.readsRegister(ARM::LR, &TRI))
  5229. Live = true;
  5230. }
  5231. return !Live;
  5232. }
  5233. outliner::OutlinedFunction ARMBaseInstrInfo::getOutliningCandidateInfo(
  5234. std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
  5235. outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
  5236. unsigned SequenceSize =
  5237. std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
  5238. [this](unsigned Sum, const MachineInstr &MI) {
  5239. return Sum + getInstSizeInBytes(MI);
  5240. });
  5241. // Properties about candidate MBBs that hold for all of them.
  5242. unsigned FlagsSetInAll = 0xF;
  5243. // Compute liveness information for each candidate, and set FlagsSetInAll.
  5244. const TargetRegisterInfo &TRI = getRegisterInfo();
  5245. std::for_each(
  5246. RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
  5247. [&FlagsSetInAll](outliner::Candidate &C) { FlagsSetInAll &= C.Flags; });
  5248. // According to the ARM Procedure Call Standard, the following are
  5249. // undefined on entry/exit from a function call:
  5250. //
  5251. // * Register R12(IP),
  5252. // * Condition codes (and thus the CPSR register)
  5253. //
  5254. // Since we control the instructions which are part of the outlined regions
  5255. // we don't need to be fully compliant with the AAPCS, but we have to
  5256. // guarantee that if a veneer is inserted at link time the code is still
  5257. // correct. Because of this, we can't outline any sequence of instructions
  5258. // where one of these registers is live into/across it. Thus, we need to
  5259. // delete those candidates.
  5260. auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
  5261. // If the unsafe registers in this block are all dead, then we don't need
  5262. // to compute liveness here.
  5263. if (C.Flags & UnsafeRegsDead)
  5264. return false;
  5265. C.initLRU(TRI);
  5266. LiveRegUnits LRU = C.LRU;
  5267. return (!LRU.available(ARM::R12) || !LRU.available(ARM::CPSR));
  5268. };
  5269. // Are there any candidates where those registers are live?
  5270. if (!(FlagsSetInAll & UnsafeRegsDead)) {
  5271. // Erase every candidate that violates the restrictions above. (It could be
  5272. // true that we have viable candidates, so it's not worth bailing out in
  5273. // the case that, say, 1 out of 20 candidates violate the restructions.)
  5274. llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall);
  5275. // If the sequence doesn't have enough candidates left, then we're done.
  5276. if (RepeatedSequenceLocs.size() < 2)
  5277. return outliner::OutlinedFunction();
  5278. }
  5279. // At this point, we have only "safe" candidates to outline. Figure out
  5280. // frame + call instruction information.
  5281. unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
  5282. // Helper lambda which sets call information for every candidate.
  5283. auto SetCandidateCallInfo =
  5284. [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
  5285. for (outliner::Candidate &C : RepeatedSequenceLocs)
  5286. C.setCallInfo(CallID, NumBytesForCall);
  5287. };
  5288. OutlinerCosts Costs(Subtarget);
  5289. unsigned FrameID = MachineOutlinerDefault;
  5290. unsigned NumBytesToCreateFrame = Costs.FrameDefault;
  5291. // If the last instruction in any candidate is a terminator, then we should
  5292. // tail call all of the candidates.
  5293. if (RepeatedSequenceLocs[0].back()->isTerminator()) {
  5294. FrameID = MachineOutlinerTailCall;
  5295. NumBytesToCreateFrame = Costs.FrameTailCall;
  5296. SetCandidateCallInfo(MachineOutlinerTailCall, Costs.CallTailCall);
  5297. } else if (LastInstrOpcode == ARM::BL || LastInstrOpcode == ARM::BLX ||
  5298. LastInstrOpcode == ARM::BLX_noip || LastInstrOpcode == ARM::tBL ||
  5299. LastInstrOpcode == ARM::tBLXr ||
  5300. LastInstrOpcode == ARM::tBLXr_noip ||
  5301. LastInstrOpcode == ARM::tBLXi) {
  5302. FrameID = MachineOutlinerThunk;
  5303. NumBytesToCreateFrame = Costs.FrameThunk;
  5304. SetCandidateCallInfo(MachineOutlinerThunk, Costs.CallThunk);
  5305. } else {
  5306. // We need to decide how to emit calls + frames. We can always emit the same
  5307. // frame if we don't need to save to the stack. If we have to save to the
  5308. // stack, then we need a different frame.
  5309. unsigned NumBytesNoStackCalls = 0;
  5310. std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
  5311. for (outliner::Candidate &C : RepeatedSequenceLocs) {
  5312. C.initLRU(TRI);
  5313. // LR liveness is overestimated in return blocks, unless they end with a
  5314. // tail call.
  5315. const auto Last = C.getMBB()->rbegin();
  5316. const bool LRIsAvailable =
  5317. C.getMBB()->isReturnBlock() && !Last->isCall()
  5318. ? isLRAvailable(TRI, Last,
  5319. (MachineBasicBlock::reverse_iterator)C.front())
  5320. : C.LRU.available(ARM::LR);
  5321. if (LRIsAvailable) {
  5322. FrameID = MachineOutlinerNoLRSave;
  5323. NumBytesNoStackCalls += Costs.CallNoLRSave;
  5324. C.setCallInfo(MachineOutlinerNoLRSave, Costs.CallNoLRSave);
  5325. CandidatesWithoutStackFixups.push_back(C);
  5326. }
  5327. // Is an unused register available? If so, we won't modify the stack, so
  5328. // we can outline with the same frame type as those that don't save LR.
  5329. else if (findRegisterToSaveLRTo(C)) {
  5330. FrameID = MachineOutlinerRegSave;
  5331. NumBytesNoStackCalls += Costs.CallRegSave;
  5332. C.setCallInfo(MachineOutlinerRegSave, Costs.CallRegSave);
  5333. CandidatesWithoutStackFixups.push_back(C);
  5334. }
  5335. // Is SP used in the sequence at all? If not, we don't have to modify
  5336. // the stack, so we are guaranteed to get the same frame.
  5337. else if (C.UsedInSequence.available(ARM::SP)) {
  5338. NumBytesNoStackCalls += Costs.CallDefault;
  5339. C.setCallInfo(MachineOutlinerDefault, Costs.CallDefault);
  5340. CandidatesWithoutStackFixups.push_back(C);
  5341. }
  5342. // If we outline this, we need to modify the stack. Pretend we don't
  5343. // outline this by saving all of its bytes.
  5344. else
  5345. NumBytesNoStackCalls += SequenceSize;
  5346. }
  5347. // If there are no places where we have to save LR, then note that we don't
  5348. // have to update the stack. Otherwise, give every candidate the default
  5349. // call type
  5350. if (NumBytesNoStackCalls <=
  5351. RepeatedSequenceLocs.size() * Costs.CallDefault) {
  5352. RepeatedSequenceLocs = CandidatesWithoutStackFixups;
  5353. FrameID = MachineOutlinerNoLRSave;
  5354. } else
  5355. SetCandidateCallInfo(MachineOutlinerDefault, Costs.CallDefault);
  5356. }
  5357. // Does every candidate's MBB contain a call? If so, then we might have a
  5358. // call in the range.
  5359. if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
  5360. // check if the range contains a call. These require a save + restore of
  5361. // the link register.
  5362. if (std::any_of(FirstCand.front(), FirstCand.back(),
  5363. [](const MachineInstr &MI) { return MI.isCall(); }))
  5364. NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
  5365. // Handle the last instruction separately. If it is tail call, then the
  5366. // last instruction is a call, we don't want to save + restore in this
  5367. // case. However, it could be possible that the last instruction is a
  5368. // call without it being valid to tail call this sequence. We should
  5369. // consider this as well.
  5370. else if (FrameID != MachineOutlinerThunk &&
  5371. FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
  5372. NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
  5373. }
  5374. return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
  5375. NumBytesToCreateFrame, FrameID);
  5376. }
  5377. bool ARMBaseInstrInfo::checkAndUpdateStackOffset(MachineInstr *MI,
  5378. int64_t Fixup,
  5379. bool Updt) const {
  5380. int SPIdx = MI->findRegisterUseOperandIdx(ARM::SP);
  5381. unsigned AddrMode = (MI->getDesc().TSFlags & ARMII::AddrModeMask);
  5382. if (SPIdx < 0)
  5383. // No SP operand
  5384. return true;
  5385. else if (SPIdx != 1 && (AddrMode != ARMII::AddrModeT2_i8s4 || SPIdx != 2))
  5386. // If SP is not the base register we can't do much
  5387. return false;
  5388. // Stack might be involved but addressing mode doesn't handle any offset.
  5389. // Rq: AddrModeT1_[1|2|4] don't operate on SP
  5390. if (AddrMode == ARMII::AddrMode1 // Arithmetic instructions
  5391. || AddrMode == ARMII::AddrMode4 // Load/Store Multiple
  5392. || AddrMode == ARMII::AddrMode6 // Neon Load/Store Multiple
  5393. || AddrMode == ARMII::AddrModeT2_so // SP can't be used as based register
  5394. || AddrMode == ARMII::AddrModeT2_pc // PCrel access
  5395. || AddrMode == ARMII::AddrMode2 // Used by PRE and POST indexed LD/ST
  5396. || AddrMode == ARMII::AddrModeT2_i7 // v8.1-M MVE
  5397. || AddrMode == ARMII::AddrModeT2_i7s2 // v8.1-M MVE
  5398. || AddrMode == ARMII::AddrModeT2_i7s4 // v8.1-M sys regs VLDR/VSTR
  5399. || AddrMode == ARMII::AddrModeNone)
  5400. return false;
  5401. unsigned NumOps = MI->getDesc().getNumOperands();
  5402. unsigned ImmIdx = NumOps - 3;
  5403. const MachineOperand &Offset = MI->getOperand(ImmIdx);
  5404. assert(Offset.isImm() && "Is not an immediate");
  5405. int64_t OffVal = Offset.getImm();
  5406. if (OffVal < 0)
  5407. // Don't override data if the are below SP.
  5408. return false;
  5409. unsigned NumBits = 0;
  5410. unsigned Scale = 1;
  5411. switch (AddrMode) {
  5412. case ARMII::AddrMode3:
  5413. if (ARM_AM::getAM3Op(OffVal) == ARM_AM::sub)
  5414. return false;
  5415. OffVal = ARM_AM::getAM3Offset(OffVal);
  5416. NumBits = 8;
  5417. break;
  5418. case ARMII::AddrMode5:
  5419. if (ARM_AM::getAM5Op(OffVal) == ARM_AM::sub)
  5420. return false;
  5421. OffVal = ARM_AM::getAM5Offset(OffVal);
  5422. NumBits = 8;
  5423. Scale = 4;
  5424. break;
  5425. case ARMII::AddrMode5FP16:
  5426. if (ARM_AM::getAM5FP16Op(OffVal) == ARM_AM::sub)
  5427. return false;
  5428. OffVal = ARM_AM::getAM5FP16Offset(OffVal);
  5429. NumBits = 8;
  5430. Scale = 2;
  5431. break;
  5432. case ARMII::AddrModeT2_i8:
  5433. NumBits = 8;
  5434. break;
  5435. case ARMII::AddrModeT2_i8s4:
  5436. // FIXME: Values are already scaled in this addressing mode.
  5437. assert((Fixup & 3) == 0 && "Can't encode this offset!");
  5438. NumBits = 10;
  5439. break;
  5440. case ARMII::AddrModeT2_ldrex:
  5441. NumBits = 8;
  5442. Scale = 4;
  5443. break;
  5444. case ARMII::AddrModeT2_i12:
  5445. case ARMII::AddrMode_i12:
  5446. NumBits = 12;
  5447. break;
  5448. case ARMII::AddrModeT1_s: // SP-relative LD/ST
  5449. NumBits = 8;
  5450. Scale = 4;
  5451. break;
  5452. default:
  5453. llvm_unreachable("Unsupported addressing mode!");
  5454. }
  5455. // Make sure the offset is encodable for instructions that scale the
  5456. // immediate.
  5457. assert(((OffVal * Scale + Fixup) & (Scale - 1)) == 0 &&
  5458. "Can't encode this offset!");
  5459. OffVal += Fixup / Scale;
  5460. unsigned Mask = (1 << NumBits) - 1;
  5461. if (OffVal <= Mask) {
  5462. if (Updt)
  5463. MI->getOperand(ImmIdx).setImm(OffVal);
  5464. return true;
  5465. }
  5466. return false;
  5467. }
  5468. bool ARMBaseInstrInfo::isFunctionSafeToOutlineFrom(
  5469. MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
  5470. const Function &F = MF.getFunction();
  5471. // Can F be deduplicated by the linker? If it can, don't outline from it.
  5472. if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
  5473. return false;
  5474. // Don't outline from functions with section markings; the program could
  5475. // expect that all the code is in the named section.
  5476. // FIXME: Allow outlining from multiple functions with the same section
  5477. // marking.
  5478. if (F.hasSection())
  5479. return false;
  5480. // FIXME: Thumb1 outlining is not handled
  5481. if (MF.getInfo<ARMFunctionInfo>()->isThumb1OnlyFunction())
  5482. return false;
  5483. // It's safe to outline from MF.
  5484. return true;
  5485. }
  5486. bool ARMBaseInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
  5487. unsigned &Flags) const {
  5488. // Check if LR is available through all of the MBB. If it's not, then set
  5489. // a flag.
  5490. assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
  5491. "Suitable Machine Function for outlining must track liveness");
  5492. LiveRegUnits LRU(getRegisterInfo());
  5493. std::for_each(MBB.rbegin(), MBB.rend(),
  5494. [&LRU](MachineInstr &MI) { LRU.accumulate(MI); });
  5495. // Check if each of the unsafe registers are available...
  5496. bool R12AvailableInBlock = LRU.available(ARM::R12);
  5497. bool CPSRAvailableInBlock = LRU.available(ARM::CPSR);
  5498. // If all of these are dead (and not live out), we know we don't have to check
  5499. // them later.
  5500. if (R12AvailableInBlock && CPSRAvailableInBlock)
  5501. Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
  5502. // Now, add the live outs to the set.
  5503. LRU.addLiveOuts(MBB);
  5504. // If any of these registers is available in the MBB, but also a live out of
  5505. // the block, then we know outlining is unsafe.
  5506. if (R12AvailableInBlock && !LRU.available(ARM::R12))
  5507. return false;
  5508. if (CPSRAvailableInBlock && !LRU.available(ARM::CPSR))
  5509. return false;
  5510. // Check if there's a call inside this MachineBasicBlock. If there is, then
  5511. // set a flag.
  5512. if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
  5513. Flags |= MachineOutlinerMBBFlags::HasCalls;
  5514. // LR liveness is overestimated in return blocks.
  5515. bool LRIsAvailable =
  5516. MBB.isReturnBlock() && !MBB.back().isCall()
  5517. ? isLRAvailable(getRegisterInfo(), MBB.rbegin(), MBB.rend())
  5518. : LRU.available(ARM::LR);
  5519. if (!LRIsAvailable)
  5520. Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
  5521. return true;
  5522. }
  5523. outliner::InstrType
  5524. ARMBaseInstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
  5525. unsigned Flags) const {
  5526. MachineInstr &MI = *MIT;
  5527. const TargetRegisterInfo *TRI = &getRegisterInfo();
  5528. // Be conservative with inline ASM
  5529. if (MI.isInlineAsm())
  5530. return outliner::InstrType::Illegal;
  5531. // Don't allow debug values to impact outlining type.
  5532. if (MI.isDebugInstr() || MI.isIndirectDebugValue())
  5533. return outliner::InstrType::Invisible;
  5534. // At this point, KILL or IMPLICIT_DEF instructions don't really tell us much
  5535. // so we can go ahead and skip over them.
  5536. if (MI.isKill() || MI.isImplicitDef())
  5537. return outliner::InstrType::Invisible;
  5538. // PIC instructions contain labels, outlining them would break offset
  5539. // computing. unsigned Opc = MI.getOpcode();
  5540. unsigned Opc = MI.getOpcode();
  5541. if (Opc == ARM::tPICADD || Opc == ARM::PICADD || Opc == ARM::PICSTR ||
  5542. Opc == ARM::PICSTRB || Opc == ARM::PICSTRH || Opc == ARM::PICLDR ||
  5543. Opc == ARM::PICLDRB || Opc == ARM::PICLDRH || Opc == ARM::PICLDRSB ||
  5544. Opc == ARM::PICLDRSH || Opc == ARM::t2LDRpci_pic ||
  5545. Opc == ARM::t2MOVi16_ga_pcrel || Opc == ARM::t2MOVTi16_ga_pcrel ||
  5546. Opc == ARM::t2MOV_ga_pcrel)
  5547. return outliner::InstrType::Illegal;
  5548. // Be conservative with ARMv8.1 MVE instructions.
  5549. if (Opc == ARM::t2BF_LabelPseudo || Opc == ARM::t2DoLoopStart ||
  5550. Opc == ARM::t2DoLoopStartTP || Opc == ARM::t2WhileLoopStart ||
  5551. Opc == ARM::t2LoopDec || Opc == ARM::t2LoopEnd ||
  5552. Opc == ARM::t2LoopEndDec)
  5553. return outliner::InstrType::Illegal;
  5554. const MCInstrDesc &MCID = MI.getDesc();
  5555. uint64_t MIFlags = MCID.TSFlags;
  5556. if ((MIFlags & ARMII::DomainMask) == ARMII::DomainMVE)
  5557. return outliner::InstrType::Illegal;
  5558. // Is this a terminator for a basic block?
  5559. if (MI.isTerminator()) {
  5560. // Don't outline if the branch is not unconditional.
  5561. if (isPredicated(MI))
  5562. return outliner::InstrType::Illegal;
  5563. // Is this the end of a function?
  5564. if (MI.getParent()->succ_empty())
  5565. return outliner::InstrType::Legal;
  5566. // It's not, so don't outline it.
  5567. return outliner::InstrType::Illegal;
  5568. }
  5569. // Make sure none of the operands are un-outlinable.
  5570. for (const MachineOperand &MOP : MI.operands()) {
  5571. if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
  5572. MOP.isTargetIndex())
  5573. return outliner::InstrType::Illegal;
  5574. }
  5575. // Don't outline if link register or program counter value are used.
  5576. if (MI.readsRegister(ARM::LR, TRI) || MI.readsRegister(ARM::PC, TRI))
  5577. return outliner::InstrType::Illegal;
  5578. if (MI.isCall()) {
  5579. // Get the function associated with the call. Look at each operand and find
  5580. // the one that represents the calle and get its name.
  5581. const Function *Callee = nullptr;
  5582. for (const MachineOperand &MOP : MI.operands()) {
  5583. if (MOP.isGlobal()) {
  5584. Callee = dyn_cast<Function>(MOP.getGlobal());
  5585. break;
  5586. }
  5587. }
  5588. // Dont't outline calls to "mcount" like functions, in particular Linux
  5589. // kernel function tracing relies on it.
  5590. if (Callee &&
  5591. (Callee->getName() == "\01__gnu_mcount_nc" ||
  5592. Callee->getName() == "\01mcount" || Callee->getName() == "__mcount"))
  5593. return outliner::InstrType::Illegal;
  5594. // If we don't know anything about the callee, assume it depends on the
  5595. // stack layout of the caller. In that case, it's only legal to outline
  5596. // as a tail-call. Explicitly list the call instructions we know about so
  5597. // we don't get unexpected results with call pseudo-instructions.
  5598. auto UnknownCallOutlineType = outliner::InstrType::Illegal;
  5599. if (Opc == ARM::BL || Opc == ARM::tBL || Opc == ARM::BLX ||
  5600. Opc == ARM::BLX_noip || Opc == ARM::tBLXr || Opc == ARM::tBLXr_noip ||
  5601. Opc == ARM::tBLXi)
  5602. UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
  5603. if (!Callee)
  5604. return UnknownCallOutlineType;
  5605. // We have a function we have information about. Check if it's something we
  5606. // can safely outline.
  5607. MachineFunction *MF = MI.getParent()->getParent();
  5608. MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
  5609. // We don't know what's going on with the callee at all. Don't touch it.
  5610. if (!CalleeMF)
  5611. return UnknownCallOutlineType;
  5612. // Check if we know anything about the callee saves on the function. If we
  5613. // don't, then don't touch it, since that implies that we haven't computed
  5614. // anything about its stack frame yet.
  5615. MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
  5616. if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
  5617. MFI.getNumObjects() > 0)
  5618. return UnknownCallOutlineType;
  5619. // At this point, we can say that CalleeMF ought to not pass anything on the
  5620. // stack. Therefore, we can outline it.
  5621. return outliner::InstrType::Legal;
  5622. }
  5623. // Since calls are handled, don't touch LR or PC
  5624. if (MI.modifiesRegister(ARM::LR, TRI) || MI.modifiesRegister(ARM::PC, TRI))
  5625. return outliner::InstrType::Illegal;
  5626. // Does this use the stack?
  5627. if (MI.modifiesRegister(ARM::SP, TRI) || MI.readsRegister(ARM::SP, TRI)) {
  5628. // True if there is no chance that any outlined candidate from this range
  5629. // could require stack fixups. That is, both
  5630. // * LR is available in the range (No save/restore around call)
  5631. // * The range doesn't include calls (No save/restore in outlined frame)
  5632. // are true.
  5633. // FIXME: This is very restrictive; the flags check the whole block,
  5634. // not just the bit we will try to outline.
  5635. bool MightNeedStackFixUp =
  5636. (Flags & (MachineOutlinerMBBFlags::LRUnavailableSomewhere |
  5637. MachineOutlinerMBBFlags::HasCalls));
  5638. if (!MightNeedStackFixUp)
  5639. return outliner::InstrType::Legal;
  5640. // Any modification of SP will break our code to save/restore LR.
  5641. // FIXME: We could handle some instructions which add a constant offset to
  5642. // SP, with a bit more work.
  5643. if (MI.modifiesRegister(ARM::SP, TRI))
  5644. return outliner::InstrType::Illegal;
  5645. // At this point, we have a stack instruction that we might need to fix up.
  5646. // up. We'll handle it if it's a load or store.
  5647. if (checkAndUpdateStackOffset(&MI, Subtarget.getStackAlignment().value(),
  5648. false))
  5649. return outliner::InstrType::Legal;
  5650. // We can't fix it up, so don't outline it.
  5651. return outliner::InstrType::Illegal;
  5652. }
  5653. // Be conservative with IT blocks.
  5654. if (MI.readsRegister(ARM::ITSTATE, TRI) ||
  5655. MI.modifiesRegister(ARM::ITSTATE, TRI))
  5656. return outliner::InstrType::Illegal;
  5657. // Don't outline positions.
  5658. if (MI.isPosition())
  5659. return outliner::InstrType::Illegal;
  5660. return outliner::InstrType::Legal;
  5661. }
  5662. void ARMBaseInstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
  5663. for (MachineInstr &MI : MBB) {
  5664. checkAndUpdateStackOffset(&MI, Subtarget.getStackAlignment().value(), true);
  5665. }
  5666. }
  5667. void ARMBaseInstrInfo::saveLROnStack(MachineBasicBlock &MBB,
  5668. MachineBasicBlock::iterator It) const {
  5669. unsigned Opc = Subtarget.isThumb() ? ARM::t2STR_PRE : ARM::STR_PRE_IMM;
  5670. int Align = -Subtarget.getStackAlignment().value();
  5671. BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::SP)
  5672. .addReg(ARM::LR, RegState::Kill)
  5673. .addReg(ARM::SP)
  5674. .addImm(Align)
  5675. .add(predOps(ARMCC::AL));
  5676. }
  5677. void ARMBaseInstrInfo::emitCFIForLRSaveOnStack(
  5678. MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
  5679. MachineFunction &MF = *MBB.getParent();
  5680. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5681. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5682. int Align = Subtarget.getStackAlignment().value();
  5683. // Add a CFI saying the stack was moved down.
  5684. int64_t StackPosEntry =
  5685. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Align));
  5686. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5687. .addCFIIndex(StackPosEntry)
  5688. .setMIFlags(MachineInstr::FrameSetup);
  5689. // Add a CFI saying that the LR that we want to find is now higher than
  5690. // before.
  5691. int64_t LRPosEntry =
  5692. MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfLR, -Align));
  5693. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5694. .addCFIIndex(LRPosEntry)
  5695. .setMIFlags(MachineInstr::FrameSetup);
  5696. }
  5697. void ARMBaseInstrInfo::emitCFIForLRSaveToReg(MachineBasicBlock &MBB,
  5698. MachineBasicBlock::iterator It,
  5699. Register Reg) const {
  5700. MachineFunction &MF = *MBB.getParent();
  5701. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5702. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5703. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  5704. int64_t LRPosEntry = MF.addFrameInst(
  5705. MCCFIInstruction::createRegister(nullptr, DwarfLR, DwarfReg));
  5706. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5707. .addCFIIndex(LRPosEntry)
  5708. .setMIFlags(MachineInstr::FrameSetup);
  5709. }
  5710. void ARMBaseInstrInfo::restoreLRFromStack(
  5711. MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
  5712. unsigned Opc = Subtarget.isThumb() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
  5713. MachineInstrBuilder MIB = BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::LR)
  5714. .addReg(ARM::SP, RegState::Define)
  5715. .addReg(ARM::SP);
  5716. if (!Subtarget.isThumb())
  5717. MIB.addReg(0);
  5718. MIB.addImm(Subtarget.getStackAlignment().value()).add(predOps(ARMCC::AL));
  5719. }
  5720. void ARMBaseInstrInfo::emitCFIForLRRestoreFromStack(
  5721. MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
  5722. // Now stack has moved back up...
  5723. MachineFunction &MF = *MBB.getParent();
  5724. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5725. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5726. int64_t StackPosEntry =
  5727. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
  5728. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5729. .addCFIIndex(StackPosEntry)
  5730. .setMIFlags(MachineInstr::FrameDestroy);
  5731. // ... and we have restored LR.
  5732. int64_t LRPosEntry =
  5733. MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
  5734. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5735. .addCFIIndex(LRPosEntry)
  5736. .setMIFlags(MachineInstr::FrameDestroy);
  5737. }
  5738. void ARMBaseInstrInfo::emitCFIForLRRestoreFromReg(
  5739. MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
  5740. MachineFunction &MF = *MBB.getParent();
  5741. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5742. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5743. int64_t LRPosEntry =
  5744. MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
  5745. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5746. .addCFIIndex(LRPosEntry)
  5747. .setMIFlags(MachineInstr::FrameDestroy);
  5748. }
  5749. void ARMBaseInstrInfo::buildOutlinedFrame(
  5750. MachineBasicBlock &MBB, MachineFunction &MF,
  5751. const outliner::OutlinedFunction &OF) const {
  5752. // For thunk outlining, rewrite the last instruction from a call to a
  5753. // tail-call.
  5754. if (OF.FrameConstructionID == MachineOutlinerThunk) {
  5755. MachineInstr *Call = &*--MBB.instr_end();
  5756. bool isThumb = Subtarget.isThumb();
  5757. unsigned FuncOp = isThumb ? 2 : 0;
  5758. unsigned Opc = Call->getOperand(FuncOp).isReg()
  5759. ? isThumb ? ARM::tTAILJMPr : ARM::TAILJMPr
  5760. : isThumb ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd
  5761. : ARM::tTAILJMPdND
  5762. : ARM::TAILJMPd;
  5763. MachineInstrBuilder MIB = BuildMI(MBB, MBB.end(), DebugLoc(), get(Opc))
  5764. .add(Call->getOperand(FuncOp));
  5765. if (isThumb && !Call->getOperand(FuncOp).isReg())
  5766. MIB.add(predOps(ARMCC::AL));
  5767. Call->eraseFromParent();
  5768. }
  5769. // Is there a call in the outlined range?
  5770. auto IsNonTailCall = [](MachineInstr &MI) {
  5771. return MI.isCall() && !MI.isReturn();
  5772. };
  5773. if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
  5774. MachineBasicBlock::iterator It = MBB.begin();
  5775. MachineBasicBlock::iterator Et = MBB.end();
  5776. if (OF.FrameConstructionID == MachineOutlinerTailCall ||
  5777. OF.FrameConstructionID == MachineOutlinerThunk)
  5778. Et = std::prev(MBB.end());
  5779. // We have to save and restore LR, we need to add it to the liveins if it
  5780. // is not already part of the set. This is suffient since outlined
  5781. // functions only have one block.
  5782. if (!MBB.isLiveIn(ARM::LR))
  5783. MBB.addLiveIn(ARM::LR);
  5784. // Insert a save before the outlined region
  5785. saveLROnStack(MBB, It);
  5786. emitCFIForLRSaveOnStack(MBB, It);
  5787. // Fix up the instructions in the range, since we're going to modify the
  5788. // stack.
  5789. assert(OF.FrameConstructionID != MachineOutlinerDefault &&
  5790. "Can only fix up stack references once");
  5791. fixupPostOutline(MBB);
  5792. // Insert a restore before the terminator for the function. Restore LR.
  5793. restoreLRFromStack(MBB, Et);
  5794. emitCFIForLRRestoreFromStack(MBB, Et);
  5795. }
  5796. // If this is a tail call outlined function, then there's already a return.
  5797. if (OF.FrameConstructionID == MachineOutlinerTailCall ||
  5798. OF.FrameConstructionID == MachineOutlinerThunk)
  5799. return;
  5800. // Here we have to insert the return ourselves. Get the correct opcode from
  5801. // current feature set.
  5802. BuildMI(MBB, MBB.end(), DebugLoc(), get(Subtarget.getReturnOpcode()))
  5803. .add(predOps(ARMCC::AL));
  5804. // Did we have to modify the stack by saving the link register?
  5805. if (OF.FrameConstructionID != MachineOutlinerDefault &&
  5806. OF.Candidates[0].CallConstructionID != MachineOutlinerDefault)
  5807. return;
  5808. // We modified the stack.
  5809. // Walk over the basic block and fix up all the stack accesses.
  5810. fixupPostOutline(MBB);
  5811. }
  5812. MachineBasicBlock::iterator ARMBaseInstrInfo::insertOutlinedCall(
  5813. Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
  5814. MachineFunction &MF, const outliner::Candidate &C) const {
  5815. MachineInstrBuilder MIB;
  5816. MachineBasicBlock::iterator CallPt;
  5817. unsigned Opc;
  5818. bool isThumb = Subtarget.isThumb();
  5819. // Are we tail calling?
  5820. if (C.CallConstructionID == MachineOutlinerTailCall) {
  5821. // If yes, then we can just branch to the label.
  5822. Opc = isThumb
  5823. ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND
  5824. : ARM::TAILJMPd;
  5825. MIB = BuildMI(MF, DebugLoc(), get(Opc))
  5826. .addGlobalAddress(M.getNamedValue(MF.getName()));
  5827. if (isThumb)
  5828. MIB.add(predOps(ARMCC::AL));
  5829. It = MBB.insert(It, MIB);
  5830. return It;
  5831. }
  5832. // Create the call instruction.
  5833. Opc = isThumb ? ARM::tBL : ARM::BL;
  5834. MachineInstrBuilder CallMIB = BuildMI(MF, DebugLoc(), get(Opc));
  5835. if (isThumb)
  5836. CallMIB.add(predOps(ARMCC::AL));
  5837. CallMIB.addGlobalAddress(M.getNamedValue(MF.getName()));
  5838. if (C.CallConstructionID == MachineOutlinerNoLRSave ||
  5839. C.CallConstructionID == MachineOutlinerThunk) {
  5840. // No, so just insert the call.
  5841. It = MBB.insert(It, CallMIB);
  5842. return It;
  5843. }
  5844. const ARMFunctionInfo &AFI = *C.getMF()->getInfo<ARMFunctionInfo>();
  5845. // Can we save to a register?
  5846. if (C.CallConstructionID == MachineOutlinerRegSave) {
  5847. unsigned Reg = findRegisterToSaveLRTo(C);
  5848. assert(Reg != 0 && "No callee-saved register available?");
  5849. // Save and restore LR from that register.
  5850. copyPhysReg(MBB, It, DebugLoc(), Reg, ARM::LR, true);
  5851. if (!AFI.isLRSpilled())
  5852. emitCFIForLRSaveToReg(MBB, It, Reg);
  5853. CallPt = MBB.insert(It, CallMIB);
  5854. copyPhysReg(MBB, It, DebugLoc(), ARM::LR, Reg, true);
  5855. if (!AFI.isLRSpilled())
  5856. emitCFIForLRRestoreFromReg(MBB, It);
  5857. It--;
  5858. return CallPt;
  5859. }
  5860. // We have the default case. Save and restore from SP.
  5861. if (!MBB.isLiveIn(ARM::LR))
  5862. MBB.addLiveIn(ARM::LR);
  5863. saveLROnStack(MBB, It);
  5864. if (!AFI.isLRSpilled())
  5865. emitCFIForLRSaveOnStack(MBB, It);
  5866. CallPt = MBB.insert(It, CallMIB);
  5867. restoreLRFromStack(MBB, It);
  5868. if (!AFI.isLRSpilled())
  5869. emitCFIForLRRestoreFromStack(MBB, It);
  5870. It--;
  5871. return CallPt;
  5872. }
  5873. bool ARMBaseInstrInfo::shouldOutlineFromFunctionByDefault(
  5874. MachineFunction &MF) const {
  5875. return Subtarget.isMClass() && MF.getFunction().hasMinSize();
  5876. }
  5877. bool ARMBaseInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
  5878. AAResults *AA) const {
  5879. // Try hard to rematerialize any VCTPs because if we spill P0, it will block
  5880. // the tail predication conversion. This means that the element count
  5881. // register has to be live for longer, but that has to be better than
  5882. // spill/restore and VPT predication.
  5883. return isVCTP(&MI) && !isPredicated(MI);
  5884. }
  5885. unsigned llvm::getBLXOpcode(const MachineFunction &MF) {
  5886. return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::BLX_noip
  5887. : ARM::BLX;
  5888. }
  5889. unsigned llvm::gettBLXrOpcode(const MachineFunction &MF) {
  5890. return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::tBLXr_noip
  5891. : ARM::tBLXr;
  5892. }
  5893. unsigned llvm::getBLXpredOpcode(const MachineFunction &MF) {
  5894. return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::BLX_pred_noip
  5895. : ARM::BLX_pred;
  5896. }