aoptx86.pas 758 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  126. function PrePeepholeOptSxx(var p : tai) : boolean;
  127. function PrePeepholeOptIMUL(var p : tai) : boolean;
  128. function PrePeepholeOptAND(var p : tai) : boolean;
  129. function OptPass1Test(var p: tai): boolean;
  130. function OptPass1Add(var p: tai): boolean;
  131. function OptPass1AND(var p : tai) : boolean;
  132. function OptPass1CMOVcc(var p: tai): Boolean;
  133. function OptPass1_V_MOVAP(var p : tai) : boolean;
  134. function OptPass1VOP(var p : tai) : boolean;
  135. function OptPass1MOV(var p : tai) : boolean;
  136. function OptPass1Movx(var p : tai) : boolean;
  137. function OptPass1MOVXX(var p : tai) : boolean;
  138. function OptPass1OP(var p : tai) : boolean;
  139. function OptPass1LEA(var p : tai) : boolean;
  140. function OptPass1Sub(var p : tai) : boolean;
  141. function OptPass1SHLSAL(var p : tai) : boolean;
  142. function OptPass1SHR(var p : tai) : boolean;
  143. function OptPass1FSTP(var p : tai) : boolean;
  144. function OptPass1FLD(var p : tai) : boolean;
  145. function OptPass1Cmp(var p : tai) : boolean;
  146. function OptPass1PXor(var p : tai) : boolean;
  147. function OptPass1VPXor(var p: tai): boolean;
  148. function OptPass1Imul(var p : tai) : boolean;
  149. function OptPass1Jcc(var p : tai) : boolean;
  150. function OptPass1SHXX(var p: tai): boolean;
  151. function OptPass1VMOVDQ(var p: tai): Boolean;
  152. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  153. function OptPass1STCCLC(var p: tai): Boolean;
  154. function OptPass2STCCLC(var p: tai): Boolean;
  155. function OptPass2CMOVcc(var p: tai): Boolean;
  156. function OptPass2Movx(var p : tai): Boolean;
  157. function OptPass2MOV(var p : tai) : boolean;
  158. function OptPass2Imul(var p : tai) : boolean;
  159. function OptPass2Jmp(var p : tai) : boolean;
  160. function OptPass2Jcc(var p : tai) : boolean;
  161. function OptPass2Lea(var p: tai): Boolean;
  162. function OptPass2SUB(var p: tai): Boolean;
  163. function OptPass2ADD(var p : tai): Boolean;
  164. function OptPass2SETcc(var p : tai) : boolean;
  165. function OptPass2Cmp(var p: tai): Boolean;
  166. function OptPass2Test(var p: tai): Boolean;
  167. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  168. function PostPeepholeOptMov(var p : tai) : Boolean;
  169. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  170. function PostPeepholeOptXor(var p : tai) : Boolean;
  171. function PostPeepholeOptAnd(var p : tai) : boolean;
  172. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  173. function PostPeepholeOptCmp(var p : tai) : Boolean;
  174. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  175. function PostPeepholeOptCall(var p : tai) : Boolean;
  176. function PostPeepholeOptLea(var p : tai) : Boolean;
  177. function PostPeepholeOptPush(var p: tai): Boolean;
  178. function PostPeepholeOptShr(var p : tai) : boolean;
  179. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  180. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  181. function PostPeepholeOptRET(var p: tai): Boolean;
  182. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  183. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  184. function TrySwapMovOp(var p, hp1: tai): Boolean;
  185. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  186. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  187. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  188. { Processor-dependent reference optimisation }
  189. class procedure OptimizeRefs(var p: taicpu); static;
  190. end;
  191. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  194. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  195. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  196. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  197. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  198. {$if max_operands>2}
  199. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  200. {$endif max_operands>2}
  201. function RefsEqual(const r1, r2: treference): boolean;
  202. { Like RefsEqual, but doesn't compare the offsets }
  203. function RefsAlmostEqual(const r1, r2: treference): boolean;
  204. { Note that Result is set to True if the references COULD overlap but the
  205. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  206. might still overlap because %reg2 could be equal to %reg1-4 }
  207. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  208. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  209. { returns true, if ref is a reference using only the registers passed as base and index
  210. and having an offset }
  211. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  212. implementation
  213. uses
  214. cutils,verbose,
  215. systems,
  216. globals,
  217. cpuinfo,
  218. procinfo,
  219. paramgr,
  220. aasmbase,
  221. aoptbase,aoptutils,
  222. symconst,symsym,
  223. cgx86,
  224. itcpugas;
  225. {$ifndef 8086}
  226. const
  227. MAX_CMOV_INSTRUCTIONS = 4;
  228. MAX_CMOV_REGISTERS = 8;
  229. type
  230. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  231. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  232. tsProcessed);
  233. { For OptPass2Jcc }
  234. TCMOVTracking = object
  235. private
  236. CMOVScore, ConstCount: LongInt;
  237. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  238. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  239. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  240. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  241. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  242. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  243. fOptimizer: TX86AsmOptimizer;
  244. fLabel: TAsmSymbol;
  245. fInsertionPoint,
  246. fCondition,
  247. fInitialJump,
  248. fFirstMovBlock,
  249. fFirstMovBlockStop,
  250. fSecondJump,
  251. fThirdJump,
  252. fSecondMovBlock,
  253. fSecondMovBlockStop,
  254. fMidLabel,
  255. fEndLabel,
  256. fAllocationRange: tai;
  257. fState: TCMovTrackingState;
  258. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  259. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  260. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  261. public
  262. RegisterTracking: TAllUsedRegs;
  263. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  264. destructor Done;
  265. procedure Process(out new_p: tai);
  266. property State: TCMovTrackingState read fState;
  267. end;
  268. PCMOVTracking = ^TCMOVTracking;
  269. {$endif 8086}
  270. {$ifdef DEBUG_AOPTCPU}
  271. const
  272. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  273. {$else DEBUG_AOPTCPU}
  274. { Empty strings help the optimizer to remove string concatenations that won't
  275. ever appear to the user on release builds. [Kit] }
  276. const
  277. SPeepholeOptimization = '';
  278. {$endif DEBUG_AOPTCPU}
  279. LIST_STEP_SIZE = 4;
  280. type
  281. TJumpTrackingItem = class(TLinkedListItem)
  282. private
  283. FSymbol: TAsmSymbol;
  284. FRefs: LongInt;
  285. public
  286. constructor Create(ASymbol: TAsmSymbol);
  287. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. property Symbol: TAsmSymbol read FSymbol;
  289. property Refs: LongInt read FRefs;
  290. end;
  291. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  292. begin
  293. inherited Create;
  294. FSymbol := ASymbol;
  295. FRefs := 0;
  296. end;
  297. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  298. begin
  299. Inc(FRefs);
  300. end;
  301. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  302. begin
  303. result :=
  304. (instr.typ = ait_instruction) and
  305. (taicpu(instr).opcode = op) and
  306. ((opsize = []) or (taicpu(instr).opsize in opsize));
  307. end;
  308. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  309. begin
  310. result :=
  311. (instr.typ = ait_instruction) and
  312. ((taicpu(instr).opcode = op1) or
  313. (taicpu(instr).opcode = op2)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  318. begin
  319. result :=
  320. (instr.typ = ait_instruction) and
  321. ((taicpu(instr).opcode = op1) or
  322. (taicpu(instr).opcode = op2) or
  323. (taicpu(instr).opcode = op3)
  324. ) and
  325. ((opsize = []) or (taicpu(instr).opsize in opsize));
  326. end;
  327. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  328. const opsize : topsizes) : boolean;
  329. var
  330. op : TAsmOp;
  331. begin
  332. result:=false;
  333. if (instr.typ <> ait_instruction) or
  334. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  335. exit;
  336. for op in ops do
  337. begin
  338. if taicpu(instr).opcode = op then
  339. begin
  340. result:=true;
  341. exit;
  342. end;
  343. end;
  344. end;
  345. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  346. begin
  347. result := (oper.typ = top_reg) and (oper.reg = reg);
  348. end;
  349. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  350. begin
  351. result := (oper.typ = top_const) and (oper.val = a);
  352. end;
  353. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  354. begin
  355. result := oper1.typ = oper2.typ;
  356. if result then
  357. case oper1.typ of
  358. top_const:
  359. Result:=oper1.val = oper2.val;
  360. top_reg:
  361. Result:=oper1.reg = oper2.reg;
  362. top_ref:
  363. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  364. else
  365. internalerror(2013102801);
  366. end
  367. end;
  368. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  369. begin
  370. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  371. if result then
  372. case oper1.typ of
  373. top_const:
  374. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  375. top_reg:
  376. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  377. top_ref:
  378. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  379. else
  380. internalerror(2020052401);
  381. end
  382. end;
  383. function RefsEqual(const r1, r2: treference): boolean;
  384. begin
  385. RefsEqual :=
  386. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  387. (r1.relsymbol = r2.relsymbol) and
  388. (r1.segment = r2.segment) and (r1.base = r2.base) and
  389. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  390. (r1.offset = r2.offset) and
  391. (r1.volatility + r2.volatility = []);
  392. end;
  393. function RefsAlmostEqual(const r1, r2: treference): boolean;
  394. begin
  395. RefsAlmostEqual :=
  396. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  397. (r1.relsymbol = r2.relsymbol) and
  398. (r1.segment = r2.segment) and (r1.base = r2.base) and
  399. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  400. { Don't compare the offsets }
  401. (r1.volatility + r2.volatility = []);
  402. end;
  403. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  404. begin
  405. if (r1.symbol<>r2.symbol) then
  406. { If the index registers are different, there's a chance one could
  407. be set so it equals the other symbol }
  408. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  409. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  410. (r1.relsymbol = r2.relsymbol) and
  411. (r1.segment = r2.segment) and (r1.base = r2.base) and
  412. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  413. (r1.volatility + r2.volatility = []) then
  414. { In this case, it all depends on the offsets }
  415. Exit(abs(r1.offset - r2.offset) < Range);
  416. { There's a chance things MIGHT overlap, so take no chances }
  417. Result := True;
  418. end;
  419. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  420. begin
  421. Result:=(ref.offset=0) and
  422. (ref.scalefactor in [0,1]) and
  423. (ref.segment=NR_NO) and
  424. (ref.symbol=nil) and
  425. (ref.relsymbol=nil) and
  426. ((base=NR_INVALID) or
  427. (ref.base=base)) and
  428. ((index=NR_INVALID) or
  429. (ref.index=index)) and
  430. (ref.volatility=[]);
  431. end;
  432. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  433. begin
  434. Result:=(ref.scalefactor in [0,1]) and
  435. (ref.segment=NR_NO) and
  436. (ref.symbol=nil) and
  437. (ref.relsymbol=nil) and
  438. ((base=NR_INVALID) or
  439. (ref.base=base)) and
  440. ((index=NR_INVALID) or
  441. (ref.index=index)) and
  442. (ref.volatility=[]);
  443. end;
  444. function InstrReadsFlags(p: tai): boolean;
  445. begin
  446. InstrReadsFlags := true;
  447. case p.typ of
  448. ait_instruction:
  449. if InsProp[taicpu(p).opcode].Ch*
  450. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  451. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  452. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  453. exit;
  454. ait_label:
  455. exit;
  456. else
  457. ;
  458. end;
  459. InstrReadsFlags := false;
  460. end;
  461. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  462. begin
  463. Next:=Current;
  464. repeat
  465. Result:=GetNextInstruction(Next,Next);
  466. until not (Result) or
  467. not(cs_opt_level3 in current_settings.optimizerswitches) or
  468. (Next.typ<>ait_instruction) or
  469. RegInInstruction(reg,Next) or
  470. is_calljmp(taicpu(Next).opcode);
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  473. var
  474. GetNextResult: Boolean;
  475. begin
  476. Result:=0;
  477. Next:=Current;
  478. repeat
  479. GetNextResult := GetNextInstruction(Next,Next);
  480. if GetNextResult then
  481. Inc(Result)
  482. else
  483. { Must return zero upon hitting the end of the linked list without a match }
  484. Result := 0;
  485. until not (GetNextResult) or
  486. not(cs_opt_level3 in current_settings.optimizerswitches) or
  487. (Next.typ<>ait_instruction) or
  488. RegInInstruction(reg,Next) or
  489. is_calljmp(taicpu(Next).opcode);
  490. end;
  491. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  492. procedure TrackJump(Symbol: TAsmSymbol);
  493. var
  494. Search: TJumpTrackingItem;
  495. begin
  496. { See if an entry already exists in our jump tracking list
  497. (faster to search backwards due to the higher chance of
  498. matching destinations) }
  499. Search := TJumpTrackingItem(JumpTracking.Last);
  500. while Assigned(Search) do
  501. begin
  502. if Search.Symbol = Symbol then
  503. begin
  504. { Found it - remove it so it can be pushed to the front }
  505. JumpTracking.Remove(Search);
  506. Break;
  507. end;
  508. Search := TJumpTrackingItem(Search.Previous);
  509. end;
  510. if not Assigned(Search) then
  511. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  512. JumpTracking.Concat(Search);
  513. Search.IncRefs;
  514. end;
  515. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  516. var
  517. Search: TJumpTrackingItem;
  518. begin
  519. Result := False;
  520. { See if this label appears in the tracking list }
  521. Search := TJumpTrackingItem(JumpTracking.Last);
  522. while Assigned(Search) do
  523. begin
  524. if Search.Symbol = Symbol then
  525. begin
  526. { Found it - let's see what we can discover }
  527. if Search.Symbol.getrefs = Search.Refs then
  528. begin
  529. { Success - all the references are accounted for }
  530. JumpTracking.Remove(Search);
  531. Search.Free;
  532. { It is logically impossible for CrossJump to be false here
  533. because we must have run into a conditional jump for
  534. this label at some point }
  535. if not CrossJump then
  536. InternalError(2022041710);
  537. if JumpTracking.First = nil then
  538. { Tracking list is now empty - no more cross jumps }
  539. CrossJump := False;
  540. Result := True;
  541. Exit;
  542. end;
  543. { If the references don't match, it's possible to enter
  544. this label through other means, so drop out }
  545. Exit;
  546. end;
  547. Search := TJumpTrackingItem(Search.Previous);
  548. end;
  549. end;
  550. var
  551. Next_Label: tai;
  552. begin
  553. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  554. Next := Current;
  555. repeat
  556. Result := GetNextInstruction(Next,Next);
  557. if not Result then
  558. Break;
  559. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  560. if is_calljmpuncondret(taicpu(Next).opcode) then
  561. begin
  562. if (taicpu(Next).opcode = A_JMP) and
  563. { Remove dead code now to save time }
  564. RemoveDeadCodeAfterJump(taicpu(Next)) then
  565. { A jump was removed, but not the current instruction, and
  566. Result doesn't necessarily translate into an optimisation
  567. routine's Result, so use the "Force New Iteration" flag so
  568. mark a new pass }
  569. Include(OptsToCheck, aoc_ForceNewIteration);
  570. if not Assigned(JumpTracking) then
  571. begin
  572. { Cross-label optimisations often causes other optimisations
  573. to perform worse because they're not given the chance to
  574. optimise locally. In this case, don't do the cross-label
  575. optimisations yet, but flag them as a potential possibility
  576. for the next iteration of Pass 1 }
  577. if not NotFirstIteration then
  578. Include(OptsToCheck, aoc_ForceNewIteration);
  579. end
  580. else if IsJumpToLabel(taicpu(Next)) and
  581. GetNextInstruction(Next, Next_Label) then
  582. begin
  583. { If we have JMP .lbl, and the label after it has all of its
  584. references tracked, then this is probably an if-else style of
  585. block and we can keep tracking. If the label for this jump
  586. then appears later and is fully tracked, then it's the end
  587. of the if-else blocks and the code paths converge (thus
  588. marking the end of the cross-jump) }
  589. if (Next_Label.typ = ait_label) then
  590. begin
  591. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  592. begin
  593. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  594. Next := Next_Label;
  595. { CrossJump gets set to false by LabelAccountedFor if the
  596. list is completely emptied (as it indicates that all
  597. code paths have converged). We could avoid this nuance
  598. by moving the TrackJump call to before the
  599. LabelAccountedFor call, but this is slower in situations
  600. where LabelAccountedFor would return False due to the
  601. creation of a new object that is not used and destroyed
  602. soon after. }
  603. CrossJump := True;
  604. Continue;
  605. end;
  606. end
  607. else if (Next_Label.typ <> ait_marker) then
  608. { We just did a RemoveDeadCodeAfterJump, so either we find
  609. a label, the end of the procedure or some kind of marker}
  610. InternalError(2022041720);
  611. end;
  612. Result := False;
  613. Exit;
  614. end
  615. else
  616. begin
  617. if not Assigned(JumpTracking) then
  618. begin
  619. { Cross-label optimisations often causes other optimisations
  620. to perform worse because they're not given the chance to
  621. optimise locally. In this case, don't do the cross-label
  622. optimisations yet, but flag them as a potential possibility
  623. for the next iteration of Pass 1 }
  624. if not NotFirstIteration then
  625. Include(OptsToCheck, aoc_ForceNewIteration);
  626. end
  627. else if IsJumpToLabel(taicpu(Next)) then
  628. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  629. else
  630. { Conditional jumps should always be a jump to label }
  631. InternalError(2022041701);
  632. CrossJump := True;
  633. Continue;
  634. end;
  635. if Next.typ = ait_label then
  636. begin
  637. if not Assigned(JumpTracking) then
  638. begin
  639. { Cross-label optimisations often causes other optimisations
  640. to perform worse because they're not given the chance to
  641. optimise locally. In this case, don't do the cross-label
  642. optimisations yet, but flag them as a potential possibility
  643. for the next iteration of Pass 1 }
  644. if not NotFirstIteration then
  645. Include(OptsToCheck, aoc_ForceNewIteration);
  646. end
  647. else if LabelAccountedFor(tai_label(Next).labsym) then
  648. Continue;
  649. { If we reach here, we're at a label that hasn't been seen before
  650. (or JumpTracking was nil) }
  651. Break;
  652. end;
  653. until not Result or
  654. not (cs_opt_level3 in current_settings.optimizerswitches) or
  655. not (Next.typ in [ait_label, ait_instruction]) or
  656. RegInInstruction(reg,Next);
  657. end;
  658. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  659. begin
  660. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  661. begin
  662. Result:=GetNextInstruction(Current,Next);
  663. exit;
  664. end;
  665. Next:=tai(Current.Next);
  666. Result:=false;
  667. while assigned(Next) do
  668. begin
  669. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  670. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  671. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  672. exit
  673. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  674. begin
  675. Result:=true;
  676. exit;
  677. end;
  678. Next:=tai(Next.Next);
  679. end;
  680. end;
  681. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  682. begin
  683. Result:=RegReadByInstruction(reg,hp);
  684. end;
  685. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  686. var
  687. p: taicpu;
  688. opcount: longint;
  689. begin
  690. RegReadByInstruction := false;
  691. if hp.typ <> ait_instruction then
  692. exit;
  693. p := taicpu(hp);
  694. case p.opcode of
  695. A_CALL:
  696. regreadbyinstruction := true;
  697. A_IMUL:
  698. case p.ops of
  699. 1:
  700. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  701. (
  702. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  703. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  704. );
  705. 2,3:
  706. regReadByInstruction :=
  707. reginop(reg,p.oper[0]^) or
  708. reginop(reg,p.oper[1]^);
  709. else
  710. InternalError(2019112801);
  711. end;
  712. A_MUL:
  713. begin
  714. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  715. (
  716. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  717. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  718. );
  719. end;
  720. A_IDIV,A_DIV:
  721. begin
  722. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  723. (
  724. (getregtype(reg)=R_INTREGISTER) and
  725. (
  726. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  727. )
  728. );
  729. end;
  730. else
  731. begin
  732. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  733. begin
  734. RegReadByInstruction := false;
  735. exit;
  736. end;
  737. for opcount := 0 to p.ops-1 do
  738. if (p.oper[opCount]^.typ = top_ref) and
  739. RegInRef(reg,p.oper[opcount]^.ref^) then
  740. begin
  741. RegReadByInstruction := true;
  742. exit
  743. end;
  744. { special handling for SSE MOVSD }
  745. if (p.opcode=A_MOVSD) and (p.ops>0) then
  746. begin
  747. if p.ops<>2 then
  748. internalerror(2017042702);
  749. regReadByInstruction := reginop(reg,p.oper[0]^) or
  750. (
  751. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  752. );
  753. exit;
  754. end;
  755. with insprop[p.opcode] do
  756. begin
  757. case getregtype(reg) of
  758. R_INTREGISTER:
  759. begin
  760. case getsupreg(reg) of
  761. RS_EAX:
  762. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ECX:
  768. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EDX:
  774. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_EBX:
  780. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_ESP:
  786. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. RS_EBP:
  792. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. RS_ESI:
  798. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  799. begin
  800. RegReadByInstruction := true;
  801. exit
  802. end;
  803. RS_EDI:
  804. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  805. begin
  806. RegReadByInstruction := true;
  807. exit
  808. end;
  809. end;
  810. end;
  811. R_MMREGISTER:
  812. begin
  813. case getsupreg(reg) of
  814. RS_XMM0:
  815. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  816. begin
  817. RegReadByInstruction := true;
  818. exit
  819. end;
  820. end;
  821. end;
  822. else
  823. ;
  824. end;
  825. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  826. begin
  827. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  828. begin
  829. case p.condition of
  830. C_A,C_NBE, { CF=0 and ZF=0 }
  831. C_BE,C_NA: { CF=1 or ZF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  833. C_AE,C_NB,C_NC, { CF=0 }
  834. C_B,C_NAE,C_C: { CF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  836. C_NE,C_NZ, { ZF=0 }
  837. C_E,C_Z: { ZF=1 }
  838. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  839. C_G,C_NLE, { ZF=0 and SF=OF }
  840. C_LE,C_NG: { ZF=1 or SF<>OF }
  841. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  842. C_GE,C_NL, { SF=OF }
  843. C_L,C_NGE: { SF<>OF }
  844. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  845. C_NO, { OF=0 }
  846. C_O: { OF=1 }
  847. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  848. C_NP,C_PO, { PF=0 }
  849. C_P,C_PE: { PF=1 }
  850. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  851. C_NS, { SF=0 }
  852. C_S: { SF=1 }
  853. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  854. else
  855. internalerror(2017042701);
  856. end;
  857. if RegReadByInstruction then
  858. exit;
  859. end;
  860. case getsubreg(reg) of
  861. R_SUBW,R_SUBD,R_SUBQ:
  862. RegReadByInstruction :=
  863. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  864. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  865. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  866. R_SUBFLAGCARRY:
  867. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGPARITY:
  869. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGAUXILIARY:
  871. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGZERO:
  873. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGSIGN:
  875. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGOVERFLOW:
  877. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGINTERRUPT:
  879. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. R_SUBFLAGDIRECTION:
  881. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  882. else
  883. internalerror(2017042601);
  884. end;
  885. exit;
  886. end;
  887. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  888. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  889. (p.oper[0]^.reg=p.oper[1]^.reg) then
  890. exit;
  891. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  892. begin
  893. RegReadByInstruction := true;
  894. exit
  895. end;
  896. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  897. begin
  898. RegReadByInstruction := true;
  899. exit
  900. end;
  901. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  902. begin
  903. RegReadByInstruction := true;
  904. exit
  905. end;
  906. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  907. begin
  908. RegReadByInstruction := true;
  909. exit
  910. end;
  911. end;
  912. end;
  913. end;
  914. end;
  915. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  916. begin
  917. result:=false;
  918. if p1.typ<>ait_instruction then
  919. exit;
  920. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  921. exit(true);
  922. if (getregtype(reg)=R_INTREGISTER) and
  923. { change information for xmm movsd are not correct }
  924. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  925. begin
  926. { Handle instructions that behave differently depending on the size and operand count }
  927. case taicpu(p1).opcode of
  928. A_MUL, A_DIV, A_IDIV:
  929. if taicpu(p1).opsize = S_B then
  930. Result := (getsupreg(Reg) = RS_EAX)
  931. else
  932. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  933. A_IMUL:
  934. if taicpu(p1).ops = 1 then
  935. begin
  936. if taicpu(p1).opsize = S_B then
  937. Result := (getsupreg(Reg) = RS_EAX)
  938. else
  939. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  940. end;
  941. { If ops are greater than 1, call inherited method }
  942. else
  943. case getsupreg(reg) of
  944. { RS_EAX = RS_RAX on x86-64 }
  945. RS_EAX:
  946. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_ECX:
  948. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EDX:
  950. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_EBX:
  952. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_ESP:
  954. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_EBP:
  956. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_ESI:
  958. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. RS_EDI:
  960. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  961. else
  962. ;
  963. end;
  964. end;
  965. if result then
  966. exit;
  967. end
  968. else if getregtype(reg)=R_MMREGISTER then
  969. begin
  970. case getsupreg(reg) of
  971. RS_XMM0:
  972. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  973. else
  974. ;
  975. end;
  976. if result then
  977. exit;
  978. end
  979. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  980. begin
  981. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  982. exit(true);
  983. case getsubreg(reg) of
  984. R_SUBFLAGCARRY:
  985. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGPARITY:
  987. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGAUXILIARY:
  989. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGZERO:
  991. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGSIGN:
  993. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGOVERFLOW:
  995. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGINTERRUPT:
  997. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBFLAGDIRECTION:
  999. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1000. R_SUBW,R_SUBD,R_SUBQ:
  1001. { Everything except the direction bits }
  1002. Result:=
  1003. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1004. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1005. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1006. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1007. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1008. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1009. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1010. else
  1011. ;
  1012. end;
  1013. if result then
  1014. exit;
  1015. end
  1016. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1017. exit(true);
  1018. Result:=inherited RegInInstruction(Reg, p1);
  1019. end;
  1020. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1021. const
  1022. WriteOps: array[0..3] of set of TInsChange =
  1023. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1024. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1025. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1026. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1027. var
  1028. OperIdx: Integer;
  1029. begin
  1030. Result := False;
  1031. if p1.typ <> ait_instruction then
  1032. exit;
  1033. with insprop[taicpu(p1).opcode] do
  1034. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1035. begin
  1036. case getsubreg(reg) of
  1037. R_SUBW,R_SUBD,R_SUBQ:
  1038. Result :=
  1039. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1040. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1041. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1042. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1043. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1044. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGCARRY:
  1046. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGPARITY:
  1048. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGAUXILIARY:
  1050. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGZERO:
  1052. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGSIGN:
  1054. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGOVERFLOW:
  1056. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGINTERRUPT:
  1058. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. R_SUBFLAGDIRECTION:
  1060. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1061. else
  1062. internalerror(2017042602);
  1063. end;
  1064. exit;
  1065. end;
  1066. case taicpu(p1).opcode of
  1067. A_CALL:
  1068. { We could potentially set Result to False if the register in
  1069. question is non-volatile for the subroutine's calling convention,
  1070. but this would require detecting the calling convention in use and
  1071. also assuming that the routine doesn't contain malformed assembly
  1072. language, for example... so it could only be done under -O4 as it
  1073. would be considered a side-effect. [Kit] }
  1074. Result := True;
  1075. A_MOVSD:
  1076. { special handling for SSE MOVSD }
  1077. if (taicpu(p1).ops>0) then
  1078. begin
  1079. if taicpu(p1).ops<>2 then
  1080. internalerror(2017042703);
  1081. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1082. end;
  1083. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1084. so fix it here (FK)
  1085. }
  1086. A_VMOVSS,
  1087. A_VMOVSD:
  1088. begin
  1089. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1090. exit;
  1091. end;
  1092. A_MUL, A_DIV, A_IDIV:
  1093. begin
  1094. if taicpu(p1).opsize = S_B then
  1095. Result := (getsupreg(Reg) = RS_EAX)
  1096. else
  1097. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1098. end;
  1099. A_IMUL:
  1100. begin
  1101. if taicpu(p1).ops = 1 then
  1102. begin
  1103. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1104. end
  1105. else
  1106. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1107. Exit;
  1108. end;
  1109. else
  1110. ;
  1111. end;
  1112. if Result then
  1113. exit;
  1114. with insprop[taicpu(p1).opcode] do
  1115. begin
  1116. if getregtype(reg)=R_INTREGISTER then
  1117. begin
  1118. case getsupreg(reg) of
  1119. RS_EAX:
  1120. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ECX:
  1126. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EDX:
  1132. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_EBX:
  1138. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_ESP:
  1144. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. RS_EBP:
  1150. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1151. begin
  1152. Result := True;
  1153. exit
  1154. end;
  1155. RS_ESI:
  1156. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1157. begin
  1158. Result := True;
  1159. exit
  1160. end;
  1161. RS_EDI:
  1162. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1163. begin
  1164. Result := True;
  1165. exit
  1166. end;
  1167. end;
  1168. end;
  1169. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1170. if (WriteOps[OperIdx]*Ch<>[]) and
  1171. { The register doesn't get modified inside a reference }
  1172. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1173. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1174. begin
  1175. Result := true;
  1176. exit
  1177. end;
  1178. end;
  1179. end;
  1180. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1181. const
  1182. WriteOps: array[0..3] of set of TInsChange =
  1183. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1184. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1185. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1186. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1187. var
  1188. X: Integer;
  1189. CurrentP1Size: asizeint;
  1190. begin
  1191. Result := (
  1192. (Ref.base <> NR_NO) and
  1193. {$ifdef x86_64}
  1194. (Ref.base <> NR_RIP) and
  1195. {$endif x86_64}
  1196. RegModifiedBetween(Ref.base, p1, p2)
  1197. ) or
  1198. (
  1199. (Ref.index <> NR_NO) and
  1200. (Ref.index <> Ref.base) and
  1201. RegModifiedBetween(Ref.index, p1, p2)
  1202. );
  1203. { Now check to see if the memory itself is written to }
  1204. if not Result then
  1205. begin
  1206. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1207. if p1.typ = ait_instruction then
  1208. begin
  1209. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1210. with insprop[taicpu(p1).opcode] do
  1211. for X := 0 to taicpu(p1).ops - 1 do
  1212. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1213. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1214. { Catch any potential overlaps }
  1215. (
  1216. (RefSize = 0) or
  1217. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1218. ) and
  1219. (
  1220. (CurrentP1Size = 0) or
  1221. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1222. ) and
  1223. { Reference is used, but does the instruction write to it? }
  1224. (
  1225. (Ch_All in Ch) or
  1226. ((WriteOps[X] * Ch) <> [])
  1227. ) then
  1228. begin
  1229. Result := True;
  1230. Break;
  1231. end;
  1232. end;
  1233. end;
  1234. end;
  1235. {$ifdef DEBUG_AOPTCPU}
  1236. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1237. begin
  1238. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1239. end;
  1240. function debug_tostr(i: tcgint): string; inline;
  1241. begin
  1242. Result := tostr(i);
  1243. end;
  1244. function debug_hexstr(i: tcgint): string;
  1245. begin
  1246. Result := '0x';
  1247. case i of
  1248. 0..$FF:
  1249. Result := Result + hexstr(i, 2);
  1250. $100..$FFFF:
  1251. Result := Result + hexstr(i, 4);
  1252. $10000..$FFFFFF:
  1253. Result := Result + hexstr(i, 6);
  1254. $1000000..$FFFFFFFF:
  1255. Result := Result + hexstr(i, 8);
  1256. else
  1257. Result := Result + hexstr(i, 16);
  1258. end;
  1259. end;
  1260. function debug_regname(r: TRegister): string; inline;
  1261. begin
  1262. Result := '%' + std_regname(r);
  1263. end;
  1264. { Debug output function - creates a string representation of an operator }
  1265. function debug_operstr(oper: TOper): string;
  1266. begin
  1267. case oper.typ of
  1268. top_const:
  1269. Result := '$' + debug_tostr(oper.val);
  1270. top_reg:
  1271. Result := debug_regname(oper.reg);
  1272. top_ref:
  1273. begin
  1274. if oper.ref^.offset <> 0 then
  1275. Result := debug_tostr(oper.ref^.offset) + '('
  1276. else
  1277. Result := '(';
  1278. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1279. begin
  1280. Result := Result + debug_regname(oper.ref^.base);
  1281. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1282. Result := Result + ',' + debug_regname(oper.ref^.index);
  1283. end
  1284. else
  1285. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1286. Result := Result + debug_regname(oper.ref^.index);
  1287. if (oper.ref^.scalefactor > 1) then
  1288. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1289. else
  1290. Result := Result + ')';
  1291. end;
  1292. else
  1293. Result := '[UNKNOWN]';
  1294. end;
  1295. end;
  1296. function debug_op2str(opcode: tasmop): string; inline;
  1297. begin
  1298. Result := std_op2str[opcode];
  1299. end;
  1300. function debug_opsize2str(opsize: topsize): string; inline;
  1301. begin
  1302. Result := gas_opsize2str[opsize];
  1303. end;
  1304. {$else DEBUG_AOPTCPU}
  1305. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1306. begin
  1307. end;
  1308. function debug_tostr(i: tcgint): string; inline;
  1309. begin
  1310. Result := '';
  1311. end;
  1312. function debug_hexstr(i: tcgint): string; inline;
  1313. begin
  1314. Result := '';
  1315. end;
  1316. function debug_regname(r: TRegister): string; inline;
  1317. begin
  1318. Result := '';
  1319. end;
  1320. function debug_operstr(oper: TOper): string; inline;
  1321. begin
  1322. Result := '';
  1323. end;
  1324. function debug_op2str(opcode: tasmop): string; inline;
  1325. begin
  1326. Result := '';
  1327. end;
  1328. function debug_opsize2str(opsize: topsize): string; inline;
  1329. begin
  1330. Result := '';
  1331. end;
  1332. {$endif DEBUG_AOPTCPU}
  1333. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1334. begin
  1335. {$ifdef x86_64}
  1336. { Always fine on x86-64 }
  1337. Result := True;
  1338. {$else x86_64}
  1339. Result :=
  1340. {$ifdef i8086}
  1341. (current_settings.cputype >= cpu_386) and
  1342. {$endif i8086}
  1343. (
  1344. { Always accept if optimising for size }
  1345. (cs_opt_size in current_settings.optimizerswitches) or
  1346. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1347. (current_settings.optimizecputype >= cpu_Pentium2)
  1348. );
  1349. {$endif x86_64}
  1350. end;
  1351. { Attempts to allocate a volatile integer register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_int;
  1366. (*
  1367. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1368. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1369. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1370. *)
  1371. for CurrentSuperReg in RegSet do
  1372. begin
  1373. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1374. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1375. {$if defined(i386) or defined(i8086)}
  1376. { If the target size is 8-bit, make sure we can actually encode it }
  1377. and (
  1378. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1379. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1380. )
  1381. {$endif i386 or i8086}
  1382. then
  1383. begin
  1384. Currentp := p;
  1385. Breakout := False;
  1386. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1387. begin
  1388. case Currentp.typ of
  1389. ait_instruction:
  1390. begin
  1391. if RegInInstruction(CurrentReg, Currentp) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. { Cannot allocate across an unconditional jump }
  1397. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1398. Exit;
  1399. end;
  1400. ait_marker:
  1401. { Don't try anything more if a marker is hit }
  1402. Exit;
  1403. ait_regalloc:
  1404. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1405. begin
  1406. Breakout := True;
  1407. Break;
  1408. end;
  1409. else
  1410. ;
  1411. end;
  1412. end;
  1413. if Breakout then
  1414. { Try the next register }
  1415. Continue;
  1416. { We have a free register available }
  1417. Result := CurrentReg;
  1418. if not DontAlloc then
  1419. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1420. Exit;
  1421. end;
  1422. end;
  1423. end;
  1424. { Attempts to allocate a volatile MM register for use between p and hp,
  1425. using AUsedRegs for the current register usage information. Returns NR_NO
  1426. if no free register could be found }
  1427. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1428. var
  1429. RegSet: TCPURegisterSet;
  1430. CurrentSuperReg: Integer;
  1431. CurrentReg: TRegister;
  1432. Currentp: tai;
  1433. Breakout: Boolean;
  1434. begin
  1435. Result := NR_NO;
  1436. RegSet :=
  1437. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1438. current_procinfo.saved_regs_mm;
  1439. for CurrentSuperReg in RegSet do
  1440. begin
  1441. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1442. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1443. begin
  1444. Currentp := p;
  1445. Breakout := False;
  1446. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1447. begin
  1448. case Currentp.typ of
  1449. ait_instruction:
  1450. begin
  1451. if RegInInstruction(CurrentReg, Currentp) then
  1452. begin
  1453. Breakout := True;
  1454. Break;
  1455. end;
  1456. { Cannot allocate across an unconditional jump }
  1457. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1458. Exit;
  1459. end;
  1460. ait_marker:
  1461. { Don't try anything more if a marker is hit }
  1462. Exit;
  1463. ait_regalloc:
  1464. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1465. begin
  1466. Breakout := True;
  1467. Break;
  1468. end;
  1469. else
  1470. ;
  1471. end;
  1472. end;
  1473. if Breakout then
  1474. { Try the next register }
  1475. Continue;
  1476. { We have a free register available }
  1477. Result := CurrentReg;
  1478. if not DontAlloc then
  1479. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1480. Exit;
  1481. end;
  1482. end;
  1483. end;
  1484. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1485. begin
  1486. if not SuperRegistersEqual(reg1,reg2) then
  1487. exit(false);
  1488. if getregtype(reg1)<>R_INTREGISTER then
  1489. exit(true); {because SuperRegisterEqual is true}
  1490. case getsubreg(reg1) of
  1491. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1492. higher, it preserves the high bits, so the new value depends on
  1493. reg2's previous value. In other words, it is equivalent to doing:
  1494. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1495. R_SUBL:
  1496. exit(getsubreg(reg2)=R_SUBL);
  1497. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1498. higher, it actually does a:
  1499. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1500. R_SUBH:
  1501. exit(getsubreg(reg2)=R_SUBH);
  1502. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1503. bits of reg2:
  1504. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1505. R_SUBW:
  1506. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1507. { a write to R_SUBD always overwrites every other subregister,
  1508. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1509. R_SUBD,
  1510. R_SUBQ:
  1511. exit(true);
  1512. else
  1513. internalerror(2017042801);
  1514. end;
  1515. end;
  1516. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1517. begin
  1518. if not SuperRegistersEqual(reg1,reg2) then
  1519. exit(false);
  1520. if getregtype(reg1)<>R_INTREGISTER then
  1521. exit(true); {because SuperRegisterEqual is true}
  1522. case getsubreg(reg1) of
  1523. R_SUBL:
  1524. exit(getsubreg(reg2)<>R_SUBH);
  1525. R_SUBH:
  1526. exit(getsubreg(reg2)<>R_SUBL);
  1527. R_SUBW,
  1528. R_SUBD,
  1529. R_SUBQ:
  1530. exit(true);
  1531. else
  1532. internalerror(2017042802);
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1536. var
  1537. hp1 : tai;
  1538. l : TCGInt;
  1539. begin
  1540. result:=false;
  1541. if not(GetNextInstruction(p, hp1)) then
  1542. exit;
  1543. { changes the code sequence
  1544. shr/sar const1, x
  1545. shl const2, x
  1546. to
  1547. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1548. if (taicpu(p).oper[0]^.typ = top_const) and
  1549. MatchInstruction(hp1,A_SHL,[]) and
  1550. (taicpu(hp1).oper[0]^.typ = top_const) and
  1551. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1552. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1553. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1554. begin
  1555. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1556. not(cs_opt_size in current_settings.optimizerswitches)
  1557. {$ifdef x86_64}
  1558. and (
  1559. (taicpu(p).opsize <> S_Q) or
  1560. { 64-bit AND can only store signed 32-bit immediates }
  1561. (taicpu(p).oper[0]^.val < 32)
  1562. )
  1563. {$endif x86_64}
  1564. then
  1565. begin
  1566. { shr/sar const1, %reg
  1567. shl const2, %reg
  1568. with const1 > const2 }
  1569. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1570. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1571. taicpu(hp1).opcode := A_AND;
  1572. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1573. case taicpu(p).opsize Of
  1574. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1575. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1576. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1577. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1578. else
  1579. Internalerror(2017050703)
  1580. end;
  1581. end
  1582. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1583. not(cs_opt_size in current_settings.optimizerswitches)
  1584. {$ifdef x86_64}
  1585. and (
  1586. (taicpu(p).opsize <> S_Q) or
  1587. { 64-bit AND can only store signed 32-bit immediates }
  1588. (taicpu(p).oper[0]^.val < 32)
  1589. )
  1590. {$endif x86_64}
  1591. then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 < const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1597. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1598. taicpu(p).opcode := A_AND;
  1599. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1600. case taicpu(p).opsize Of
  1601. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1602. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1603. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1604. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1605. else
  1606. Internalerror(2017050702)
  1607. end;
  1608. end
  1609. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1610. {$ifdef x86_64}
  1611. and (
  1612. (taicpu(p).opsize <> S_Q) or
  1613. { 64-bit AND can only store signed 32-bit immediates }
  1614. (taicpu(p).oper[0]^.val < 32)
  1615. )
  1616. {$endif x86_64}
  1617. then
  1618. begin
  1619. { shr/sar const1, %reg
  1620. shl const2, %reg
  1621. with const1 = const2 }
  1622. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1623. taicpu(p).opcode := A_AND;
  1624. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1625. case taicpu(p).opsize Of
  1626. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1627. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1628. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1629. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1630. else
  1631. Internalerror(2017050701)
  1632. end;
  1633. RemoveInstruction(hp1);
  1634. end;
  1635. end;
  1636. end;
  1637. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1638. var
  1639. opsize : topsize;
  1640. hp1, hp2 : tai;
  1641. tmpref : treference;
  1642. ShiftValue : Cardinal;
  1643. BaseValue : TCGInt;
  1644. begin
  1645. result:=false;
  1646. opsize:=taicpu(p).opsize;
  1647. { changes certain "imul const, %reg"'s to lea sequences }
  1648. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1649. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1650. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1651. if (taicpu(p).oper[0]^.val = 1) then
  1652. if (taicpu(p).ops = 2) then
  1653. { remove "imul $1, reg" }
  1654. begin
  1655. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1656. Result := RemoveCurrentP(p);
  1657. end
  1658. else
  1659. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1660. begin
  1661. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1662. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1663. asml.InsertAfter(hp1, p);
  1664. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1665. RemoveCurrentP(p, hp1);
  1666. Result := True;
  1667. end
  1668. else if ((taicpu(p).ops <= 2) or
  1669. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1670. not(cs_opt_size in current_settings.optimizerswitches) and
  1671. (not(GetNextInstruction(p, hp1)) or
  1672. not((tai(hp1).typ = ait_instruction) and
  1673. ((taicpu(hp1).opcode=A_Jcc) and
  1674. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1675. begin
  1676. {
  1677. imul X, reg1, reg2 to
  1678. lea (reg1,reg1,Y), reg2
  1679. shl ZZ,reg2
  1680. imul XX, reg1 to
  1681. lea (reg1,reg1,YY), reg1
  1682. shl ZZ,reg2
  1683. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1684. it does not exist as a separate optimization target in FPC though.
  1685. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1686. at most two zeros
  1687. }
  1688. reference_reset(tmpref,1,[]);
  1689. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1690. begin
  1691. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1692. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1693. TmpRef.base := taicpu(p).oper[1]^.reg;
  1694. TmpRef.index := taicpu(p).oper[1]^.reg;
  1695. if not(BaseValue in [3,5,9]) then
  1696. Internalerror(2018110101);
  1697. TmpRef.ScaleFactor := BaseValue-1;
  1698. if (taicpu(p).ops = 2) then
  1699. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1700. else
  1701. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1702. AsmL.InsertAfter(hp1,p);
  1703. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1704. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1705. RemoveCurrentP(p, hp1);
  1706. if ShiftValue>0 then
  1707. begin
  1708. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1709. AsmL.InsertAfter(hp2,hp1);
  1710. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1711. end;
  1712. Result := True;
  1713. end;
  1714. end;
  1715. end;
  1716. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1717. begin
  1718. Result := False;
  1719. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1720. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1721. begin
  1722. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1723. taicpu(p).opcode := A_MOV;
  1724. Result := True;
  1725. end;
  1726. end;
  1727. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1728. var
  1729. p: taicpu absolute hp; { Implicit typecast }
  1730. i: Integer;
  1731. begin
  1732. Result := False;
  1733. if not assigned(hp) or
  1734. (hp.typ <> ait_instruction) then
  1735. Exit;
  1736. Prefetch(insprop[p.opcode]);
  1737. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1738. with insprop[p.opcode] do
  1739. begin
  1740. case getsubreg(reg) of
  1741. R_SUBW,R_SUBD,R_SUBQ:
  1742. Result:=
  1743. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1744. uncommon flags are checked first }
  1745. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1746. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1747. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1748. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1749. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1750. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1751. R_SUBFLAGCARRY:
  1752. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1753. R_SUBFLAGPARITY:
  1754. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1755. R_SUBFLAGAUXILIARY:
  1756. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1757. R_SUBFLAGZERO:
  1758. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1759. R_SUBFLAGSIGN:
  1760. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1761. R_SUBFLAGOVERFLOW:
  1762. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1763. R_SUBFLAGINTERRUPT:
  1764. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1765. R_SUBFLAGDIRECTION:
  1766. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1767. else
  1768. internalerror(2017050501);
  1769. end;
  1770. exit;
  1771. end;
  1772. { Handle special cases first }
  1773. case p.opcode of
  1774. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1775. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1776. begin
  1777. Result :=
  1778. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1779. (p.oper[1]^.typ = top_reg) and
  1780. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1781. (
  1782. (p.oper[0]^.typ = top_const) or
  1783. (
  1784. (p.oper[0]^.typ = top_reg) and
  1785. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1786. ) or (
  1787. (p.oper[0]^.typ = top_ref) and
  1788. not RegInRef(reg,p.oper[0]^.ref^)
  1789. )
  1790. );
  1791. end;
  1792. A_MUL, A_IMUL:
  1793. Result :=
  1794. (
  1795. (p.ops=3) and { IMUL only }
  1796. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1797. (
  1798. (
  1799. (p.oper[1]^.typ=top_reg) and
  1800. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1801. ) or (
  1802. (p.oper[1]^.typ=top_ref) and
  1803. not RegInRef(reg,p.oper[1]^.ref^)
  1804. )
  1805. )
  1806. ) or (
  1807. (
  1808. (p.ops=1) and
  1809. (
  1810. (
  1811. (
  1812. (p.oper[0]^.typ=top_reg) and
  1813. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1814. )
  1815. ) or (
  1816. (p.oper[0]^.typ=top_ref) and
  1817. not RegInRef(reg,p.oper[0]^.ref^)
  1818. )
  1819. ) and (
  1820. (
  1821. (p.opsize=S_B) and
  1822. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1823. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1824. ) or (
  1825. (p.opsize=S_W) and
  1826. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1827. ) or (
  1828. (p.opsize=S_L) and
  1829. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1830. {$ifdef x86_64}
  1831. ) or (
  1832. (p.opsize=S_Q) and
  1833. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1834. {$endif x86_64}
  1835. )
  1836. )
  1837. )
  1838. );
  1839. A_CBW:
  1840. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1841. {$ifndef x86_64}
  1842. A_LDS:
  1843. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1844. A_LES:
  1845. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1846. {$endif not x86_64}
  1847. A_LFS:
  1848. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1849. A_LGS:
  1850. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1851. A_LSS:
  1852. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1853. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1854. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1855. A_LODSB:
  1856. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1857. A_LODSW:
  1858. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1859. {$ifdef x86_64}
  1860. A_LODSQ:
  1861. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1862. {$endif x86_64}
  1863. A_LODSD:
  1864. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1865. A_FSTSW, A_FNSTSW:
  1866. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1867. else
  1868. begin
  1869. with insprop[p.opcode] do
  1870. begin
  1871. if (
  1872. { xor %reg,%reg etc. is classed as a new value }
  1873. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1874. MatchOpType(p, top_reg, top_reg) and
  1875. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1876. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1877. ) then
  1878. begin
  1879. Result := True;
  1880. Exit;
  1881. end;
  1882. { Make sure the entire register is overwritten }
  1883. if (getregtype(reg) = R_INTREGISTER) then
  1884. begin
  1885. if (p.ops > 0) then
  1886. begin
  1887. if RegInOp(reg, p.oper[0]^) then
  1888. begin
  1889. if (p.oper[0]^.typ = top_ref) then
  1890. begin
  1891. if RegInRef(reg, p.oper[0]^.ref^) then
  1892. begin
  1893. Result := False;
  1894. Exit;
  1895. end;
  1896. end
  1897. else if (p.oper[0]^.typ = top_reg) then
  1898. begin
  1899. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1900. begin
  1901. Result := False;
  1902. Exit;
  1903. end
  1904. else if ([Ch_WOp1]*Ch<>[]) then
  1905. begin
  1906. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1907. Result := True
  1908. else
  1909. begin
  1910. Result := False;
  1911. Exit;
  1912. end;
  1913. end;
  1914. end;
  1915. end;
  1916. if (p.ops > 1) then
  1917. begin
  1918. if RegInOp(reg, p.oper[1]^) then
  1919. begin
  1920. if (p.oper[1]^.typ = top_ref) then
  1921. begin
  1922. if RegInRef(reg, p.oper[1]^.ref^) then
  1923. begin
  1924. Result := False;
  1925. Exit;
  1926. end;
  1927. end
  1928. else if (p.oper[1]^.typ = top_reg) then
  1929. begin
  1930. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1931. begin
  1932. Result := False;
  1933. Exit;
  1934. end
  1935. else if ([Ch_WOp2]*Ch<>[]) then
  1936. begin
  1937. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1938. Result := True
  1939. else
  1940. begin
  1941. Result := False;
  1942. Exit;
  1943. end;
  1944. end;
  1945. end;
  1946. end;
  1947. if (p.ops > 2) then
  1948. begin
  1949. if RegInOp(reg, p.oper[2]^) then
  1950. begin
  1951. if (p.oper[2]^.typ = top_ref) then
  1952. begin
  1953. if RegInRef(reg, p.oper[2]^.ref^) then
  1954. begin
  1955. Result := False;
  1956. Exit;
  1957. end;
  1958. end
  1959. else if (p.oper[2]^.typ = top_reg) then
  1960. begin
  1961. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1962. begin
  1963. Result := False;
  1964. Exit;
  1965. end
  1966. else if ([Ch_WOp3]*Ch<>[]) then
  1967. begin
  1968. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1969. Result := True
  1970. else
  1971. begin
  1972. Result := False;
  1973. Exit;
  1974. end;
  1975. end;
  1976. end;
  1977. end;
  1978. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1979. begin
  1980. if (p.oper[3]^.typ = top_ref) then
  1981. begin
  1982. if RegInRef(reg, p.oper[3]^.ref^) then
  1983. begin
  1984. Result := False;
  1985. Exit;
  1986. end;
  1987. end
  1988. else if (p.oper[3]^.typ = top_reg) then
  1989. begin
  1990. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1991. begin
  1992. Result := False;
  1993. Exit;
  1994. end
  1995. else if ([Ch_WOp4]*Ch<>[]) then
  1996. begin
  1997. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1998. Result := True
  1999. else
  2000. begin
  2001. Result := False;
  2002. Exit;
  2003. end;
  2004. end;
  2005. end;
  2006. end;
  2007. end;
  2008. end;
  2009. end;
  2010. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2011. case getsupreg(reg) of
  2012. RS_EAX:
  2013. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2014. begin
  2015. Result := True;
  2016. Exit;
  2017. end;
  2018. RS_ECX:
  2019. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2020. begin
  2021. Result := True;
  2022. Exit;
  2023. end;
  2024. RS_EDX:
  2025. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2026. begin
  2027. Result := True;
  2028. Exit;
  2029. end;
  2030. RS_EBX:
  2031. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2032. begin
  2033. Result := True;
  2034. Exit;
  2035. end;
  2036. RS_ESP:
  2037. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2038. begin
  2039. Result := True;
  2040. Exit;
  2041. end;
  2042. RS_EBP:
  2043. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2044. begin
  2045. Result := True;
  2046. Exit;
  2047. end;
  2048. RS_ESI:
  2049. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2050. begin
  2051. Result := True;
  2052. Exit;
  2053. end;
  2054. RS_EDI:
  2055. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2056. begin
  2057. Result := True;
  2058. Exit;
  2059. end;
  2060. else
  2061. ;
  2062. end;
  2063. end;
  2064. end;
  2065. end;
  2066. end;
  2067. end;
  2068. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2069. var
  2070. hp2,hp3 : tai;
  2071. begin
  2072. { some x86-64 issue a NOP before the real exit code }
  2073. if MatchInstruction(p,A_NOP,[]) then
  2074. GetNextInstruction(p,p);
  2075. result:=assigned(p) and (p.typ=ait_instruction) and
  2076. ((taicpu(p).opcode = A_RET) or
  2077. ((taicpu(p).opcode=A_LEAVE) and
  2078. GetNextInstruction(p,hp2) and
  2079. MatchInstruction(hp2,A_RET,[S_NO])
  2080. ) or
  2081. (((taicpu(p).opcode=A_LEA) and
  2082. MatchOpType(taicpu(p),top_ref,top_reg) and
  2083. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2084. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2085. ) and
  2086. GetNextInstruction(p,hp2) and
  2087. MatchInstruction(hp2,A_RET,[S_NO])
  2088. ) or
  2089. ((((taicpu(p).opcode=A_MOV) and
  2090. MatchOpType(taicpu(p),top_reg,top_reg) and
  2091. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2092. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2093. ((taicpu(p).opcode=A_LEA) and
  2094. MatchOpType(taicpu(p),top_ref,top_reg) and
  2095. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2096. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2097. )
  2098. ) and
  2099. GetNextInstruction(p,hp2) and
  2100. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2101. MatchOpType(taicpu(hp2),top_reg) and
  2102. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2103. GetNextInstruction(hp2,hp3) and
  2104. MatchInstruction(hp3,A_RET,[S_NO])
  2105. )
  2106. );
  2107. end;
  2108. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2109. begin
  2110. isFoldableArithOp := False;
  2111. case hp1.opcode of
  2112. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2113. isFoldableArithOp :=
  2114. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2115. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2116. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2117. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2118. (taicpu(hp1).oper[1]^.reg = reg);
  2119. A_INC,A_DEC,A_NEG,A_NOT:
  2120. isFoldableArithOp :=
  2121. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2122. (taicpu(hp1).oper[0]^.reg = reg);
  2123. else
  2124. ;
  2125. end;
  2126. end;
  2127. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2128. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2129. var
  2130. hp2: tai;
  2131. begin
  2132. hp2 := p;
  2133. repeat
  2134. hp2 := tai(hp2.previous);
  2135. if assigned(hp2) and
  2136. (hp2.typ = ait_regalloc) and
  2137. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2138. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2139. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2140. begin
  2141. RemoveInstruction(hp2);
  2142. break;
  2143. end;
  2144. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2145. end;
  2146. begin
  2147. case current_procinfo.procdef.returndef.typ of
  2148. arraydef,recorddef,pointerdef,
  2149. stringdef,enumdef,procdef,objectdef,errordef,
  2150. filedef,setdef,procvardef,
  2151. classrefdef,forwarddef:
  2152. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2153. orddef:
  2154. if current_procinfo.procdef.returndef.size <> 0 then
  2155. begin
  2156. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2157. { for int64/qword }
  2158. if current_procinfo.procdef.returndef.size = 8 then
  2159. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2160. end;
  2161. else
  2162. ;
  2163. end;
  2164. end;
  2165. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2166. var
  2167. hp1: tai;
  2168. operswap: poper;
  2169. begin
  2170. Result := False;
  2171. { Optimise:
  2172. cmov(c) %reg1,%reg2
  2173. mov %reg2,%reg1
  2174. (%reg2 dealloc.)
  2175. To:
  2176. cmov(~c) %reg2,%reg1
  2177. }
  2178. if (taicpu(p).oper[0]^.typ = top_reg) then
  2179. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2180. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2181. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2182. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2183. begin
  2184. TransferUsedRegs(TmpUsedRegs);
  2185. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2186. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2187. begin
  2188. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2189. { Save time by swapping the pointers (they're both registers, so
  2190. we don't need to worry about reference counts) }
  2191. operswap := taicpu(p).oper[0];
  2192. taicpu(p).oper[0] := taicpu(p).oper[1];
  2193. taicpu(p).oper[1] := operswap;
  2194. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2195. RemoveInstruction(hp1);
  2196. { It's still a CMOV, so we can look further ahead }
  2197. Include(OptsToCheck, aoc_ForceNewIteration);
  2198. { But first, let's see if this will get optimised again
  2199. (probably won't happen, but best to be sure) }
  2200. Continue;
  2201. end;
  2202. Break;
  2203. end;
  2204. end;
  2205. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2206. var
  2207. hp1,hp2 : tai;
  2208. begin
  2209. result:=false;
  2210. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2211. begin
  2212. { vmova* reg1,reg1
  2213. =>
  2214. <nop> }
  2215. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2216. begin
  2217. RemoveCurrentP(p);
  2218. result:=true;
  2219. exit;
  2220. end;
  2221. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2222. (hp1.typ = ait_instruction) and
  2223. (
  2224. { Under -O2 and below, the instructions are always adjacent }
  2225. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2226. (taicpu(hp1).ops <= 1) or
  2227. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2228. { If reg1 = reg3, reg1 must not be modified in between }
  2229. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2230. ) then
  2231. begin
  2232. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2233. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2234. begin
  2235. { vmova* reg1,reg2
  2236. ...
  2237. vmova* reg2,reg3
  2238. dealloc reg2
  2239. =>
  2240. vmova* reg1,reg3 }
  2241. TransferUsedRegs(TmpUsedRegs);
  2242. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2243. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2244. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2245. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2246. begin
  2247. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2248. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2249. TransferUsedRegs(TmpUsedRegs);
  2250. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2251. RemoveInstruction(hp1);
  2252. result:=true;
  2253. exit;
  2254. end;
  2255. { special case:
  2256. vmova* reg1,<op>
  2257. ...
  2258. vmova* <op>,reg1
  2259. =>
  2260. vmova* reg1,<op> }
  2261. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2262. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2263. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2264. ) then
  2265. begin
  2266. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2267. RemoveInstruction(hp1);
  2268. result:=true;
  2269. exit;
  2270. end
  2271. end
  2272. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2273. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2274. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2275. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2276. ) and
  2277. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2278. begin
  2279. { vmova* reg1,reg2
  2280. ...
  2281. vmovs* reg2,<op>
  2282. dealloc reg2
  2283. =>
  2284. vmovs* reg1,<op> }
  2285. TransferUsedRegs(TmpUsedRegs);
  2286. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2287. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2288. begin
  2289. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2290. taicpu(p).opcode:=taicpu(hp1).opcode;
  2291. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2292. TransferUsedRegs(TmpUsedRegs);
  2293. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2294. RemoveInstruction(hp1);
  2295. result:=true;
  2296. exit;
  2297. end
  2298. end;
  2299. if MatchInstruction(hp1,[A_VFMADDPD,
  2300. A_VFMADD132PD,
  2301. A_VFMADD132PS,
  2302. A_VFMADD132SD,
  2303. A_VFMADD132SS,
  2304. A_VFMADD213PD,
  2305. A_VFMADD213PS,
  2306. A_VFMADD213SD,
  2307. A_VFMADD213SS,
  2308. A_VFMADD231PD,
  2309. A_VFMADD231PS,
  2310. A_VFMADD231SD,
  2311. A_VFMADD231SS,
  2312. A_VFMADDSUB132PD,
  2313. A_VFMADDSUB132PS,
  2314. A_VFMADDSUB213PD,
  2315. A_VFMADDSUB213PS,
  2316. A_VFMADDSUB231PD,
  2317. A_VFMADDSUB231PS,
  2318. A_VFMSUB132PD,
  2319. A_VFMSUB132PS,
  2320. A_VFMSUB132SD,
  2321. A_VFMSUB132SS,
  2322. A_VFMSUB213PD,
  2323. A_VFMSUB213PS,
  2324. A_VFMSUB213SD,
  2325. A_VFMSUB213SS,
  2326. A_VFMSUB231PD,
  2327. A_VFMSUB231PS,
  2328. A_VFMSUB231SD,
  2329. A_VFMSUB231SS,
  2330. A_VFMSUBADD132PD,
  2331. A_VFMSUBADD132PS,
  2332. A_VFMSUBADD213PD,
  2333. A_VFMSUBADD213PS,
  2334. A_VFMSUBADD231PD,
  2335. A_VFMSUBADD231PS,
  2336. A_VFNMADD132PD,
  2337. A_VFNMADD132PS,
  2338. A_VFNMADD132SD,
  2339. A_VFNMADD132SS,
  2340. A_VFNMADD213PD,
  2341. A_VFNMADD213PS,
  2342. A_VFNMADD213SD,
  2343. A_VFNMADD213SS,
  2344. A_VFNMADD231PD,
  2345. A_VFNMADD231PS,
  2346. A_VFNMADD231SD,
  2347. A_VFNMADD231SS,
  2348. A_VFNMSUB132PD,
  2349. A_VFNMSUB132PS,
  2350. A_VFNMSUB132SD,
  2351. A_VFNMSUB132SS,
  2352. A_VFNMSUB213PD,
  2353. A_VFNMSUB213PS,
  2354. A_VFNMSUB213SD,
  2355. A_VFNMSUB213SS,
  2356. A_VFNMSUB231PD,
  2357. A_VFNMSUB231PS,
  2358. A_VFNMSUB231SD,
  2359. A_VFNMSUB231SS],[S_NO]) and
  2360. { we mix single and double opperations here because we assume that the compiler
  2361. generates vmovapd only after double operations and vmovaps only after single operations }
  2362. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2363. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2364. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2365. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2366. begin
  2367. TransferUsedRegs(TmpUsedRegs);
  2368. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2369. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2370. begin
  2371. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2372. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2373. RemoveCurrentP(p)
  2374. else
  2375. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2376. RemoveInstruction(hp2);
  2377. end;
  2378. end
  2379. else if (hp1.typ = ait_instruction) and
  2380. (((taicpu(p).opcode=A_MOVAPS) and
  2381. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2382. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2383. ((taicpu(p).opcode=A_MOVAPD) and
  2384. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2385. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2386. ) and
  2387. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2388. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2389. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2390. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2391. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2392. { change
  2393. movapX reg,reg2
  2394. addsX/subsX/... reg3, reg2
  2395. movapX reg2,reg
  2396. to
  2397. addsX/subsX/... reg3,reg
  2398. }
  2399. begin
  2400. TransferUsedRegs(TmpUsedRegs);
  2401. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2402. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2403. begin
  2404. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2405. debug_op2str(taicpu(p).opcode)+' '+
  2406. debug_op2str(taicpu(hp1).opcode)+' '+
  2407. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2408. { we cannot eliminate the first move if
  2409. the operations uses the same register for source and dest }
  2410. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2411. { Remember that hp1 is not necessarily the immediate
  2412. next instruction }
  2413. RemoveCurrentP(p);
  2414. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2415. RemoveInstruction(hp2);
  2416. result:=true;
  2417. end;
  2418. end
  2419. else if (hp1.typ = ait_instruction) and
  2420. (((taicpu(p).opcode=A_VMOVAPD) and
  2421. (taicpu(hp1).opcode=A_VCOMISD)) or
  2422. ((taicpu(p).opcode=A_VMOVAPS) and
  2423. ((taicpu(hp1).opcode=A_VCOMISS))
  2424. )
  2425. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2426. { change
  2427. movapX reg,reg1
  2428. vcomisX reg1,reg1
  2429. to
  2430. vcomisX reg,reg
  2431. }
  2432. begin
  2433. TransferUsedRegs(TmpUsedRegs);
  2434. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2435. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2436. begin
  2437. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2438. debug_op2str(taicpu(p).opcode)+' '+
  2439. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2440. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2441. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2442. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2443. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2444. RemoveCurrentP(p);
  2445. result:=true;
  2446. exit;
  2447. end;
  2448. end
  2449. end;
  2450. end;
  2451. end;
  2452. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2453. var
  2454. hp1 : tai;
  2455. begin
  2456. result:=false;
  2457. { replace
  2458. V<Op>X %mreg1,%mreg2,%mreg3
  2459. VMovX %mreg3,%mreg4
  2460. dealloc %mreg3
  2461. by
  2462. V<Op>X %mreg1,%mreg2,%mreg4
  2463. ?
  2464. }
  2465. if GetNextInstruction(p,hp1) and
  2466. { we mix single and double operations here because we assume that the compiler
  2467. generates vmovapd only after double operations and vmovaps only after single operations }
  2468. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2469. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2470. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2471. begin
  2472. TransferUsedRegs(TmpUsedRegs);
  2473. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2474. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2475. begin
  2476. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2477. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2478. RemoveInstruction(hp1);
  2479. result:=true;
  2480. end;
  2481. end;
  2482. end;
  2483. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2484. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2485. begin
  2486. Result := False;
  2487. { For safety reasons, only check for exact register matches }
  2488. { Check base register }
  2489. if (ref.base = AOldReg) then
  2490. begin
  2491. ref.base := ANewReg;
  2492. Result := True;
  2493. end;
  2494. { Check index register }
  2495. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2496. begin
  2497. ref.index := ANewReg;
  2498. Result := True;
  2499. end;
  2500. end;
  2501. { Replaces all references to AOldReg in an operand to ANewReg }
  2502. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2503. var
  2504. OldSupReg, NewSupReg: TSuperRegister;
  2505. OldSubReg, NewSubReg: TSubRegister;
  2506. OldRegType: TRegisterType;
  2507. ThisOper: POper;
  2508. begin
  2509. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2510. Result := False;
  2511. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2512. InternalError(2020011801);
  2513. OldSupReg := getsupreg(AOldReg);
  2514. OldSubReg := getsubreg(AOldReg);
  2515. OldRegType := getregtype(AOldReg);
  2516. NewSupReg := getsupreg(ANewReg);
  2517. NewSubReg := getsubreg(ANewReg);
  2518. if OldRegType <> getregtype(ANewReg) then
  2519. InternalError(2020011802);
  2520. if OldSubReg <> NewSubReg then
  2521. InternalError(2020011803);
  2522. case ThisOper^.typ of
  2523. top_reg:
  2524. if (
  2525. (ThisOper^.reg = AOldReg) or
  2526. (
  2527. (OldRegType = R_INTREGISTER) and
  2528. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2529. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2530. (
  2531. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2532. {$ifndef x86_64}
  2533. and (
  2534. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2535. don't have an 8-bit representation }
  2536. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2537. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2538. )
  2539. {$endif x86_64}
  2540. )
  2541. )
  2542. ) then
  2543. begin
  2544. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2545. Result := True;
  2546. end;
  2547. top_ref:
  2548. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2549. Result := True;
  2550. else
  2551. ;
  2552. end;
  2553. end;
  2554. { Replaces all references to AOldReg in an instruction to ANewReg }
  2555. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2556. const
  2557. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2558. var
  2559. OperIdx: Integer;
  2560. begin
  2561. Result := False;
  2562. for OperIdx := 0 to p.ops - 1 do
  2563. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2564. begin
  2565. { The shift and rotate instructions can only use CL }
  2566. if not (
  2567. (OperIdx = 0) and
  2568. { This second condition just helps to avoid unnecessarily
  2569. calling MatchInstruction for 10 different opcodes }
  2570. (p.oper[0]^.reg = NR_CL) and
  2571. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2572. ) then
  2573. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2574. end
  2575. else if p.oper[OperIdx]^.typ = top_ref then
  2576. { It's okay to replace registers in references that get written to }
  2577. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2578. end;
  2579. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2580. begin
  2581. Result :=
  2582. (ref^.index = NR_NO) and
  2583. (
  2584. {$ifdef x86_64}
  2585. (
  2586. (ref^.base = NR_RIP) and
  2587. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2588. ) or
  2589. {$endif x86_64}
  2590. (ref^.refaddr = addr_full) or
  2591. (ref^.base = NR_STACK_POINTER_REG) or
  2592. (ref^.base = current_procinfo.framepointer)
  2593. );
  2594. end;
  2595. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2596. var
  2597. l: asizeint;
  2598. begin
  2599. Result := False;
  2600. { Should have been checked previously }
  2601. if p.opcode <> A_LEA then
  2602. InternalError(2020072501);
  2603. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2604. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2605. not(cs_opt_size in current_settings.optimizerswitches) then
  2606. exit;
  2607. with p.oper[0]^.ref^ do
  2608. begin
  2609. if (base <> p.oper[1]^.reg) or
  2610. (index <> NR_NO) or
  2611. assigned(symbol) then
  2612. exit;
  2613. l:=offset;
  2614. if (l=1) and UseIncDec then
  2615. begin
  2616. p.opcode:=A_INC;
  2617. p.loadreg(0,p.oper[1]^.reg);
  2618. p.ops:=1;
  2619. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2620. end
  2621. else if (l=-1) and UseIncDec then
  2622. begin
  2623. p.opcode:=A_DEC;
  2624. p.loadreg(0,p.oper[1]^.reg);
  2625. p.ops:=1;
  2626. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2627. end
  2628. else
  2629. begin
  2630. if (l<0) and (l<>-2147483648) then
  2631. begin
  2632. p.opcode:=A_SUB;
  2633. p.loadConst(0,-l);
  2634. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2635. end
  2636. else
  2637. begin
  2638. p.opcode:=A_ADD;
  2639. p.loadConst(0,l);
  2640. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2641. end;
  2642. end;
  2643. end;
  2644. Result := True;
  2645. end;
  2646. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2647. var
  2648. CurrentReg, ReplaceReg: TRegister;
  2649. begin
  2650. Result := False;
  2651. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2652. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2653. case hp.opcode of
  2654. A_FSTSW, A_FNSTSW,
  2655. A_IN, A_INS, A_OUT, A_OUTS,
  2656. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2657. { These routines have explicit operands, but they are restricted in
  2658. what they can be (e.g. IN and OUT can only read from AL, AX or
  2659. EAX. }
  2660. Exit;
  2661. A_IMUL:
  2662. begin
  2663. { The 1-operand version writes to implicit registers
  2664. The 2-operand version reads from the first operator, and reads
  2665. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2666. the 3-operand version reads from a register that it doesn't write to
  2667. }
  2668. case hp.ops of
  2669. 1:
  2670. if (
  2671. (
  2672. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2673. ) or
  2674. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2675. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2676. begin
  2677. Result := True;
  2678. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2679. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2680. end;
  2681. 2:
  2682. { Only modify the first parameter }
  2683. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2684. begin
  2685. Result := True;
  2686. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2687. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2688. end;
  2689. 3:
  2690. { Only modify the second parameter }
  2691. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2692. begin
  2693. Result := True;
  2694. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2695. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2696. end;
  2697. else
  2698. InternalError(2020012901);
  2699. end;
  2700. end;
  2701. else
  2702. if (hp.ops > 0) and
  2703. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2704. begin
  2705. Result := True;
  2706. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2707. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2708. end;
  2709. end;
  2710. end;
  2711. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2712. var
  2713. hp2, hp_regalloc: tai;
  2714. p_SourceReg, p_TargetReg: TRegister;
  2715. begin
  2716. Result := False;
  2717. { Backward optimisation. If we have:
  2718. func. %reg1,%reg2
  2719. mov %reg2,%reg3
  2720. (dealloc %reg2)
  2721. Change to:
  2722. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2723. Perform similar optimisations with 1, 3 and 4-operand instructions
  2724. that only have one output.
  2725. }
  2726. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2727. begin
  2728. p_SourceReg := taicpu(p).oper[0]^.reg;
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. TransferUsedRegs(TmpUsedRegs);
  2731. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2732. GetLastInstruction(p, hp2) and
  2733. (hp2.typ = ait_instruction) and
  2734. { Have to make sure it's an instruction that only reads from
  2735. the first operands and only writes (not reads or modifies) to
  2736. the last one; in essence, a pure function such as BSR, POPCNT
  2737. or ANDN }
  2738. (
  2739. (
  2740. (taicpu(hp2).ops = 1) and
  2741. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2742. ) or
  2743. (
  2744. (taicpu(hp2).ops = 2) and
  2745. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2746. ) or
  2747. (
  2748. (taicpu(hp2).ops = 3) and
  2749. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2750. ) or
  2751. (
  2752. (taicpu(hp2).ops = 4) and
  2753. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2754. )
  2755. ) and
  2756. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2757. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2758. begin
  2759. case taicpu(hp2).opcode of
  2760. A_FSTSW, A_FNSTSW,
  2761. A_IN, A_INS, A_OUT, A_OUTS,
  2762. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2763. { These routines have explicit operands, but they are restricted in
  2764. what they can be (e.g. IN and OUT can only read from AL, AX or
  2765. EAX. }
  2766. ;
  2767. else
  2768. begin
  2769. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2770. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2771. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2772. if Assigned(hp_regalloc) then
  2773. begin
  2774. Asml.Remove(hp_regalloc);
  2775. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2776. begin
  2777. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2778. hp_regalloc.Free;
  2779. end
  2780. else
  2781. { If the register is not explicitly deallocated, it's
  2782. being reused, so move the allocation to after func. }
  2783. AsmL.InsertAfter(hp_regalloc, hp2);
  2784. end;
  2785. if not RegInInstruction(p_TargetReg, hp2) then
  2786. begin
  2787. TransferUsedRegs(TmpUsedRegs);
  2788. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2789. end;
  2790. { Actually make the changes }
  2791. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2792. RemoveCurrentp(p, hp1);
  2793. { If the Func was another MOV instruction, we might get
  2794. "mov %reg,%reg" that doesn't get removed in Pass 2
  2795. otherwise, so deal with it here (also do something
  2796. similar with lea (%reg),%reg}
  2797. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2798. begin
  2799. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2800. if p = hp2 then
  2801. RemoveCurrentp(p)
  2802. else
  2803. RemoveInstruction(hp2);
  2804. end;
  2805. Result := True;
  2806. Exit;
  2807. end;
  2808. end;
  2809. end;
  2810. end;
  2811. end;
  2812. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2813. begin
  2814. Result := False;
  2815. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2816. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2817. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2818. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2819. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2820. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2821. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2822. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2823. begin
  2824. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2825. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2826. Result := True;
  2827. Include(OptsToCheck, aoc_ForceNewIteration);
  2828. end;
  2829. end;
  2830. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2831. var
  2832. hp1, hp2, hp3, hp4: tai;
  2833. DoOptimisation, TempBool: Boolean;
  2834. {$ifdef x86_64}
  2835. NewConst: TCGInt;
  2836. {$endif x86_64}
  2837. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2838. begin
  2839. if taicpu(hp1).opcode = signed_movop then
  2840. begin
  2841. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2842. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2843. end
  2844. else
  2845. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2846. end;
  2847. function TryConstMerge(var p1, p2: tai): Boolean;
  2848. var
  2849. ThisRef: TReference;
  2850. begin
  2851. Result := False;
  2852. ThisRef := taicpu(p2).oper[1]^.ref^;
  2853. { Only permit writes to the stack, since we can guarantee alignment with that }
  2854. if (ThisRef.index = NR_NO) and
  2855. (
  2856. (ThisRef.base = NR_STACK_POINTER_REG) or
  2857. (ThisRef.base = current_procinfo.framepointer)
  2858. ) then
  2859. begin
  2860. case taicpu(p).opsize of
  2861. S_B:
  2862. begin
  2863. { Word writes must be on a 2-byte boundary }
  2864. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2865. begin
  2866. { Reduce offset of second reference to see if it is sequential with the first }
  2867. Dec(ThisRef.offset, 1);
  2868. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2869. begin
  2870. { Make sure the constants aren't represented as a
  2871. negative number, as these won't merge properly }
  2872. taicpu(p1).opsize := S_W;
  2873. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2874. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2875. RemoveInstruction(p2);
  2876. Result := True;
  2877. end;
  2878. end;
  2879. end;
  2880. S_W:
  2881. begin
  2882. { Longword writes must be on a 4-byte boundary }
  2883. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2884. begin
  2885. { Reduce offset of second reference to see if it is sequential with the first }
  2886. Dec(ThisRef.offset, 2);
  2887. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2888. begin
  2889. { Make sure the constants aren't represented as a
  2890. negative number, as these won't merge properly }
  2891. taicpu(p1).opsize := S_L;
  2892. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2893. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2894. RemoveInstruction(p2);
  2895. Result := True;
  2896. end;
  2897. end;
  2898. end;
  2899. {$ifdef x86_64}
  2900. S_L:
  2901. begin
  2902. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2903. see if the constants can be encoded this way. }
  2904. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2905. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2906. { Quadword writes must be on an 8-byte boundary }
  2907. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2908. begin
  2909. { Reduce offset of second reference to see if it is sequential with the first }
  2910. Dec(ThisRef.offset, 4);
  2911. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2912. begin
  2913. { Make sure the constants aren't represented as a
  2914. negative number, as these won't merge properly }
  2915. taicpu(p1).opsize := S_Q;
  2916. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2917. taicpu(p1).oper[0]^.val := NewConst;
  2918. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2919. RemoveInstruction(p2);
  2920. Result := True;
  2921. end;
  2922. end;
  2923. end;
  2924. {$endif x86_64}
  2925. else
  2926. ;
  2927. end;
  2928. end;
  2929. end;
  2930. var
  2931. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2932. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2933. NewSize: topsize; NewOffset: asizeint;
  2934. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2935. SourceRef, TargetRef: TReference;
  2936. MovAligned, MovUnaligned: TAsmOp;
  2937. ThisRef: TReference;
  2938. JumpTracking: TLinkedList;
  2939. begin
  2940. Result:=false;
  2941. { remove mov reg1,reg1? }
  2942. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2943. then
  2944. begin
  2945. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2946. { take care of the register (de)allocs following p }
  2947. RemoveCurrentP(p);
  2948. Result := True;
  2949. exit;
  2950. end;
  2951. { Prevent compiler warnings }
  2952. p_SourceReg := NR_NO;
  2953. p_TargetReg := NR_NO;
  2954. if taicpu(p).oper[1]^.typ = top_reg then
  2955. begin
  2956. { Saves on a large number of dereferences }
  2957. p_TargetReg := taicpu(p).oper[1]^.reg;
  2958. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2959. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2960. else
  2961. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2962. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2963. while True do
  2964. begin
  2965. if (taicpu(hp1).opcode = A_AND) and
  2966. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2967. begin
  2968. { A change has occurred, just not in p }
  2969. Include(OptsToCheck, aoc_ForceNewIteration);
  2970. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2971. begin
  2972. case taicpu(p).opsize of
  2973. S_L:
  2974. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2975. begin
  2976. { Optimize out:
  2977. mov x, %reg
  2978. and ffffffffh, %reg
  2979. }
  2980. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2981. RemoveInstruction(hp1);
  2982. Result:=true;
  2983. exit;
  2984. end;
  2985. S_Q: { TODO: Confirm if this is even possible }
  2986. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2987. begin
  2988. { Optimize out:
  2989. mov x, %reg
  2990. and ffffffffffffffffh, %reg
  2991. }
  2992. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2993. RemoveInstruction(hp1);
  2994. Result:=true;
  2995. exit;
  2996. end;
  2997. else
  2998. ;
  2999. end;
  3000. if (
  3001. { Make sure that if a reference is used, its registers
  3002. are not modified in between }
  3003. (
  3004. (taicpu(p).oper[0]^.typ = top_reg) and
  3005. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3006. ) or
  3007. (
  3008. (taicpu(p).oper[0]^.typ = top_ref) and
  3009. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3010. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3011. )
  3012. ) and
  3013. GetNextInstruction(hp1,hp2) and
  3014. MatchInstruction(hp2,A_TEST,[]) and
  3015. (
  3016. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3017. (
  3018. { If the register being tested is smaller than the one
  3019. that received a bitwise AND, permit it if the constant
  3020. fits into the smaller size }
  3021. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3022. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3023. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3024. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3025. (
  3026. (
  3027. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3028. (taicpu(hp1).oper[0]^.val <= $FF)
  3029. ) or
  3030. (
  3031. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3032. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3033. {$ifdef x86_64}
  3034. ) or
  3035. (
  3036. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3037. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3038. {$endif x86_64}
  3039. )
  3040. )
  3041. )
  3042. ) and
  3043. (
  3044. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3045. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3046. ) and
  3047. GetNextInstruction(hp2,hp3) and
  3048. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3049. (taicpu(hp3).condition in [C_E,C_NE]) then
  3050. begin
  3051. TransferUsedRegs(TmpUsedRegs);
  3052. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3053. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3054. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3055. begin
  3056. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3057. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3058. taicpu(hp1).opcode:=A_TEST;
  3059. { Shrink the TEST instruction down to the smallest possible size }
  3060. case taicpu(hp1).oper[0]^.val of
  3061. 0..255:
  3062. if (taicpu(hp1).opsize <> S_B)
  3063. {$ifndef x86_64}
  3064. and (
  3065. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3066. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3067. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3068. )
  3069. {$endif x86_64}
  3070. then
  3071. begin
  3072. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3073. { Only print debug message if the TEST instruction
  3074. is a different size before and after }
  3075. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3076. taicpu(hp1).opsize := S_B;
  3077. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3078. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3079. end;
  3080. 256..65535:
  3081. if (taicpu(hp1).opsize <> S_W) then
  3082. begin
  3083. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3084. { Only print debug message if the TEST instruction
  3085. is a different size before and after }
  3086. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3087. taicpu(hp1).opsize := S_W;
  3088. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3089. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3090. end;
  3091. {$ifdef x86_64}
  3092. 65536..$7FFFFFFF:
  3093. if (taicpu(hp1).opsize <> S_L) then
  3094. begin
  3095. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3096. { Only print debug message if the TEST instruction
  3097. is a different size before and after }
  3098. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3099. taicpu(hp1).opsize := S_L;
  3100. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3101. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3102. end;
  3103. {$endif x86_64}
  3104. else
  3105. ;
  3106. end;
  3107. RemoveInstruction(hp2);
  3108. RemoveCurrentP(p);
  3109. Result:=true;
  3110. exit;
  3111. end;
  3112. end;
  3113. end;
  3114. if IsMOVZXAcceptable and
  3115. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3116. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3117. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3118. then
  3119. begin
  3120. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3121. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3122. case taicpu(p).opsize of
  3123. S_B:
  3124. if (taicpu(hp1).oper[0]^.val = $ff) then
  3125. begin
  3126. { Convert:
  3127. movb x, %regl movb x, %regl
  3128. andw ffh, %regw andl ffh, %regd
  3129. To:
  3130. movzbw x, %regd movzbl x, %regd
  3131. (Identical registers, just different sizes)
  3132. }
  3133. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3134. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3135. case taicpu(hp1).opsize of
  3136. S_W: NewSize := S_BW;
  3137. S_L: NewSize := S_BL;
  3138. {$ifdef x86_64}
  3139. S_Q: NewSize := S_BQ;
  3140. {$endif x86_64}
  3141. else
  3142. InternalError(2018011510);
  3143. end;
  3144. end
  3145. else
  3146. NewSize := S_NO;
  3147. S_W:
  3148. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3149. begin
  3150. { Convert:
  3151. movw x, %regw
  3152. andl ffffh, %regd
  3153. To:
  3154. movzwl x, %regd
  3155. (Identical registers, just different sizes)
  3156. }
  3157. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3158. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3159. case taicpu(hp1).opsize of
  3160. S_L: NewSize := S_WL;
  3161. {$ifdef x86_64}
  3162. S_Q: NewSize := S_WQ;
  3163. {$endif x86_64}
  3164. else
  3165. InternalError(2018011511);
  3166. end;
  3167. end
  3168. else
  3169. NewSize := S_NO;
  3170. else
  3171. NewSize := S_NO;
  3172. end;
  3173. if NewSize <> S_NO then
  3174. begin
  3175. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3176. { The actual optimization }
  3177. taicpu(p).opcode := A_MOVZX;
  3178. taicpu(p).changeopsize(NewSize);
  3179. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3180. { Make sure we deal with any reference counts that were increased }
  3181. if taicpu(hp1).oper[1]^.typ = top_ref then
  3182. begin
  3183. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3184. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3185. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3186. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3187. end;
  3188. { Safeguard if "and" is followed by a conditional command }
  3189. TransferUsedRegs(TmpUsedRegs);
  3190. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3191. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3192. begin
  3193. { At this point, the "and" command is effectively equivalent to
  3194. "test %reg,%reg". This will be handled separately by the
  3195. Peephole Optimizer. [Kit] }
  3196. DebugMsg(SPeepholeOptimization + PreMessage +
  3197. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3198. end
  3199. else
  3200. begin
  3201. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3202. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3203. RemoveInstruction(hp1);
  3204. end;
  3205. Result := True;
  3206. Exit;
  3207. { Go through DeepMOVOpt again (jump to "while True do") }
  3208. Continue;
  3209. end;
  3210. end;
  3211. end;
  3212. if taicpu(p).oper[0]^.typ = top_reg then
  3213. begin
  3214. p_SourceReg := taicpu(p).oper[0]^.reg;
  3215. { Look for:
  3216. mov %reg1,%reg2
  3217. ??? %reg2,r/m
  3218. Change to:
  3219. mov %reg1,%reg2
  3220. ??? %reg1,r/m
  3221. }
  3222. if RegReadByInstruction(p_TargetReg, hp1) and
  3223. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3224. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3225. begin
  3226. { A change has occurred, just not in p }
  3227. Include(OptsToCheck, aoc_ForceNewIteration);
  3228. TransferUsedRegs(TmpUsedRegs);
  3229. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3230. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3231. { Just in case something didn't get modified (e.g. an
  3232. implicit register) }
  3233. not RegReadByInstruction(p_TargetReg, hp1) then
  3234. begin
  3235. { We can remove the original MOV }
  3236. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3237. RemoveCurrentP(p);
  3238. { UsedRegs got updated by RemoveCurrentp }
  3239. Result := True;
  3240. Exit;
  3241. end;
  3242. { If we know a MOV instruction has become a null operation, we might as well
  3243. get rid of it now to save time. }
  3244. if (taicpu(hp1).opcode = A_MOV) and
  3245. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3246. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3247. { Just being a register is enough to confirm it's a null operation }
  3248. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3249. begin
  3250. Result := True;
  3251. { Speed-up to reduce a pipeline stall... if we had something like...
  3252. movl %eax,%edx
  3253. movw %dx,%ax
  3254. ... the second instruction would change to movw %ax,%ax, but
  3255. given that it is now %ax that's active rather than %eax,
  3256. penalties might occur due to a partial register write, so instead,
  3257. change it to a MOVZX instruction when optimising for speed.
  3258. }
  3259. if not (cs_opt_size in current_settings.optimizerswitches) and
  3260. IsMOVZXAcceptable and
  3261. (taicpu(hp1).opsize < taicpu(p).opsize)
  3262. {$ifdef x86_64}
  3263. { operations already implicitly set the upper 64 bits to zero }
  3264. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3265. {$endif x86_64}
  3266. then
  3267. begin
  3268. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3269. case taicpu(p).opsize of
  3270. S_W:
  3271. if taicpu(hp1).opsize = S_B then
  3272. taicpu(hp1).opsize := S_BL
  3273. else
  3274. InternalError(2020012911);
  3275. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3276. case taicpu(hp1).opsize of
  3277. S_B:
  3278. taicpu(hp1).opsize := S_BL;
  3279. S_W:
  3280. taicpu(hp1).opsize := S_WL;
  3281. else
  3282. InternalError(2020012912);
  3283. end;
  3284. else
  3285. InternalError(2020012910);
  3286. end;
  3287. taicpu(hp1).opcode := A_MOVZX;
  3288. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3289. end
  3290. else
  3291. begin
  3292. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3293. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3294. RemoveInstruction(hp1);
  3295. { The instruction after what was hp1 is now the immediate next instruction,
  3296. so we can continue to make optimisations if it's present }
  3297. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3298. Exit;
  3299. hp1 := hp2;
  3300. end;
  3301. end;
  3302. end;
  3303. {$ifdef x86_64}
  3304. { Change:
  3305. movl %reg1l,%reg2l
  3306. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3307. To:
  3308. movl %reg1l,%reg2l
  3309. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3310. If %reg1 = %reg3, convert to:
  3311. movl %reg1l,%reg2l
  3312. andl %reg1l,%reg1l
  3313. }
  3314. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3315. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3316. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3317. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3318. begin
  3319. TransferUsedRegs(TmpUsedRegs);
  3320. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3321. taicpu(hp1).opsize := S_L;
  3322. taicpu(hp1).loadreg(0, p_SourceReg);
  3323. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3324. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3325. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3326. begin
  3327. { %reg1 = %reg3 }
  3328. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3329. taicpu(hp1).opcode := A_AND;
  3330. end
  3331. else
  3332. begin
  3333. { %reg1 <> %reg3 }
  3334. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3335. end;
  3336. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3337. begin
  3338. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3339. RemoveCurrentP(p);
  3340. Result := True;
  3341. Exit;
  3342. end
  3343. else
  3344. begin
  3345. { Initial instruction wasn't actually changed }
  3346. Include(OptsToCheck, aoc_ForceNewIteration);
  3347. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3348. appears below since %reg1 has technically changed }
  3349. if taicpu(hp1).opcode = A_AND then
  3350. Exit;
  3351. end;
  3352. end;
  3353. {$endif x86_64}
  3354. end
  3355. else if taicpu(p).oper[0]^.typ = top_const then
  3356. begin
  3357. if (taicpu(hp1).opcode = A_OR) and
  3358. (taicpu(p).oper[1]^.typ = top_reg) and
  3359. MatchOperand(taicpu(p).oper[0]^, 0) and
  3360. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3361. begin
  3362. { mov 0, %reg
  3363. or ###,%reg
  3364. Change to (only if the flags are not used):
  3365. mov ###,%reg
  3366. }
  3367. TransferUsedRegs(TmpUsedRegs);
  3368. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3369. DoOptimisation := True;
  3370. { Even if the flags are used, we might be able to do the optimisation
  3371. if the conditions are predictable }
  3372. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3373. begin
  3374. { Only perform if ### = %reg (the same register) or equal to 0,
  3375. so %reg is guaranteed to still have a value of zero }
  3376. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3377. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3378. begin
  3379. hp2 := hp1;
  3380. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3381. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3382. GetNextInstruction(hp2, hp3) do
  3383. begin
  3384. { Don't continue modifying if the flags state is getting changed }
  3385. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3386. Break;
  3387. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3388. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3389. begin
  3390. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3391. begin
  3392. { Condition is always true }
  3393. case taicpu(hp3).opcode of
  3394. A_Jcc:
  3395. begin
  3396. { Check for jump shortcuts before we destroy the condition }
  3397. hp4 := hp3;
  3398. DoJumpOptimizations(hp3, TempBool);
  3399. { Make sure hp3 hasn't changed }
  3400. if (hp4 = hp3) then
  3401. begin
  3402. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3403. MakeUnconditional(taicpu(hp3));
  3404. end;
  3405. Result := True;
  3406. end;
  3407. A_CMOVcc:
  3408. begin
  3409. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3410. taicpu(hp3).opcode := A_MOV;
  3411. taicpu(hp3).condition := C_None;
  3412. Result := True;
  3413. end;
  3414. A_SETcc:
  3415. begin
  3416. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3417. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3418. taicpu(hp3).opcode := A_MOV;
  3419. taicpu(hp3).ops := 2;
  3420. taicpu(hp3).condition := C_None;
  3421. taicpu(hp3).opsize := S_B;
  3422. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3423. taicpu(hp3).loadconst(0, 1);
  3424. Result := True;
  3425. end;
  3426. else
  3427. InternalError(2021090701);
  3428. end;
  3429. end
  3430. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3431. begin
  3432. { Condition is always false }
  3433. case taicpu(hp3).opcode of
  3434. A_Jcc:
  3435. begin
  3436. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3437. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3438. RemoveInstruction(hp3);
  3439. Result := True;
  3440. { Since hp3 was deleted, hp2 must not be updated }
  3441. Continue;
  3442. end;
  3443. A_CMOVcc:
  3444. begin
  3445. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3446. RemoveInstruction(hp3);
  3447. Result := True;
  3448. { Since hp3 was deleted, hp2 must not be updated }
  3449. Continue;
  3450. end;
  3451. A_SETcc:
  3452. begin
  3453. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3454. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3455. taicpu(hp3).opcode := A_MOV;
  3456. taicpu(hp3).ops := 2;
  3457. taicpu(hp3).condition := C_None;
  3458. taicpu(hp3).opsize := S_B;
  3459. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3460. taicpu(hp3).loadconst(0, 0);
  3461. Result := True;
  3462. end;
  3463. else
  3464. InternalError(2021090702);
  3465. end;
  3466. end
  3467. else
  3468. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3469. DoOptimisation := False;
  3470. end;
  3471. hp2 := hp3;
  3472. end;
  3473. if DoOptimisation then
  3474. begin
  3475. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3476. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3477. { Flags are still in use - don't optimise }
  3478. DoOptimisation := False;
  3479. end;
  3480. end
  3481. else
  3482. DoOptimisation := False;
  3483. end;
  3484. if DoOptimisation then
  3485. begin
  3486. {$ifdef x86_64}
  3487. { OR only supports 32-bit sign-extended constants for 64-bit
  3488. instructions, so compensate for this if the constant is
  3489. encoded as a value greater than or equal to 2^31 }
  3490. if (taicpu(hp1).opsize = S_Q) and
  3491. (taicpu(hp1).oper[0]^.typ = top_const) and
  3492. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3493. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3494. {$endif x86_64}
  3495. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3496. taicpu(hp1).opcode := A_MOV;
  3497. RemoveCurrentP(p);
  3498. Result := True;
  3499. Exit;
  3500. end;
  3501. end;
  3502. end
  3503. else if
  3504. { oper[0] is a reference }
  3505. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3506. begin
  3507. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3508. begin
  3509. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3510. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3511. ) or
  3512. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3513. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3514. )
  3515. ) and
  3516. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3517. { mov ref,reg1
  3518. lea (reg1,reg2),reg2
  3519. to
  3520. add ref,reg2 }
  3521. begin
  3522. TransferUsedRegs(TmpUsedRegs);
  3523. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3524. { If the flags register is in use, don't change the instruction to an
  3525. ADD otherwise this will scramble the flags. [Kit] }
  3526. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3527. { reg1 may not be used afterwards }
  3528. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3529. begin
  3530. Taicpu(hp1).opcode:=A_ADD;
  3531. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3532. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3533. RemoveCurrentp(p);
  3534. result:=true;
  3535. exit;
  3536. end;
  3537. end;
  3538. { If the LEA instruction can be converted into an arithmetic instruction,
  3539. it may be possible to then fold it in the next optimisation. }
  3540. if ConvertLEA(taicpu(hp1)) then
  3541. Include(OptsToCheck, aoc_ForceNewIteration);
  3542. end;
  3543. {
  3544. mov ref,reg0
  3545. <op> reg0,reg1
  3546. dealloc reg0
  3547. to
  3548. <op> ref,reg1
  3549. }
  3550. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3551. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3552. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3553. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3554. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3555. begin
  3556. TransferUsedRegs(TmpUsedRegs);
  3557. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3559. begin
  3560. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3561. { loadref increases the reference count, so decrement it again }
  3562. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3563. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3564. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3565. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3566. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3567. { See if we can remove the allocation of reg0 }
  3568. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3569. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3570. RemoveCurrentp(p);
  3571. Result:=true;
  3572. exit;
  3573. end;
  3574. end;
  3575. end;
  3576. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3577. overwrites the original destination register. e.g.
  3578. movl ###,%reg2d
  3579. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3580. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3581. }
  3582. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3583. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3584. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3585. begin
  3586. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3587. begin
  3588. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3589. case taicpu(p).oper[0]^.typ of
  3590. top_const:
  3591. { We have something like:
  3592. movb $x, %regb
  3593. movzbl %regb,%regd
  3594. Change to:
  3595. movl $x, %regd
  3596. }
  3597. begin
  3598. case taicpu(hp1).opsize of
  3599. S_BW:
  3600. begin
  3601. convert_mov_value(A_MOVSX, $FF);
  3602. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3603. taicpu(p).opsize := S_W;
  3604. end;
  3605. S_BL:
  3606. begin
  3607. convert_mov_value(A_MOVSX, $FF);
  3608. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3609. taicpu(p).opsize := S_L;
  3610. end;
  3611. S_WL:
  3612. begin
  3613. convert_mov_value(A_MOVSX, $FFFF);
  3614. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3615. taicpu(p).opsize := S_L;
  3616. end;
  3617. {$ifdef x86_64}
  3618. S_BQ:
  3619. begin
  3620. convert_mov_value(A_MOVSX, $FF);
  3621. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3622. taicpu(p).opsize := S_Q;
  3623. end;
  3624. S_WQ:
  3625. begin
  3626. convert_mov_value(A_MOVSX, $FFFF);
  3627. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3628. taicpu(p).opsize := S_Q;
  3629. end;
  3630. S_LQ:
  3631. begin
  3632. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3633. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3634. taicpu(p).opsize := S_Q;
  3635. end;
  3636. {$endif x86_64}
  3637. else
  3638. { If hp1 was a MOV instruction, it should have been
  3639. optimised already }
  3640. InternalError(2020021001);
  3641. end;
  3642. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3643. RemoveInstruction(hp1);
  3644. Result := True;
  3645. Exit;
  3646. end;
  3647. top_ref:
  3648. begin
  3649. { We have something like:
  3650. movb mem, %regb
  3651. movzbl %regb,%regd
  3652. Change to:
  3653. movzbl mem, %regd
  3654. }
  3655. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3656. begin
  3657. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3658. taicpu(p).opcode := taicpu(hp1).opcode;
  3659. taicpu(p).opsize := taicpu(hp1).opsize;
  3660. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3661. RemoveInstruction(hp1);
  3662. Result := True;
  3663. Exit;
  3664. end;
  3665. end;
  3666. else
  3667. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3668. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3669. Exit;
  3670. end;
  3671. end
  3672. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3673. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3674. optimised }
  3675. else
  3676. begin
  3677. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3678. RemoveCurrentP(p);
  3679. Result := True;
  3680. Exit;
  3681. end;
  3682. end;
  3683. if (taicpu(hp1).opcode = A_MOV) and
  3684. (
  3685. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3686. {$ifdef x86_64}
  3687. or (
  3688. { Permit zero extension from 32- to 64-bit when writing
  3689. a constant (it will be checked to see if it fits into
  3690. a signed 32-bit integer) }
  3691. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3692. (
  3693. { Valid situations... writing an unsigned 32-bit
  3694. immediate, or the destination is a 64-bit register }
  3695. (taicpu(p).oper[0]^.typ = top_const) or
  3696. (taicpu(hp1).oper[1]^.typ = top_reg)
  3697. ) and
  3698. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3699. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3700. )
  3701. {$endif x86_64}
  3702. ) then
  3703. begin
  3704. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3705. TransferUsedRegs(TmpUsedRegs);
  3706. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3707. { we have
  3708. mov x, %treg
  3709. mov %treg, y
  3710. }
  3711. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3712. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3713. begin
  3714. { we've got
  3715. mov x, %treg
  3716. mov %treg, y
  3717. with %treg is not used after }
  3718. case taicpu(p).oper[0]^.typ Of
  3719. { top_reg is covered by DeepMOVOpt }
  3720. top_const:
  3721. begin
  3722. { change
  3723. mov const, %treg
  3724. mov %treg, y
  3725. to
  3726. mov const, y
  3727. }
  3728. {$ifdef x86_64}
  3729. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3730. (
  3731. { For 32-to-64-bit zero-extension, the immediate
  3732. must be between 0 and 2^31 - 1}
  3733. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3734. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3735. ) or
  3736. (
  3737. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3738. (
  3739. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3740. )
  3741. ) then
  3742. {$endif x86_64}
  3743. begin
  3744. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3745. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3746. RemoveCurrentP(p);
  3747. Result := True;
  3748. Exit;
  3749. end;
  3750. end;
  3751. top_ref:
  3752. case taicpu(hp1).oper[1]^.typ of
  3753. top_reg:
  3754. { change
  3755. mov mem, %treg
  3756. mov %treg, %reg
  3757. to
  3758. mov mem, %reg"
  3759. }
  3760. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3761. begin
  3762. {$ifdef x86_64}
  3763. { If zero extending from 32-bit to 64-bit,
  3764. we have to make sure the replaced
  3765. register is the right size }
  3766. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3767. {$else}
  3768. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3769. {$endif x86_64}
  3770. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3771. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3772. RemoveInstruction(hp1);
  3773. Result := True;
  3774. Exit;
  3775. end
  3776. else if
  3777. { Make sure that if a reference is used, its
  3778. registers are not modified in between }
  3779. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3780. begin
  3781. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3782. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3783. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3784. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3785. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3786. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3787. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3788. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3789. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3790. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3791. RemoveCurrentP(p);
  3792. Result := True;
  3793. Exit;
  3794. end;
  3795. top_ref:
  3796. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3797. begin
  3798. {$ifdef x86_64}
  3799. { Look for the following to simplify:
  3800. mov x(mem1), %reg
  3801. mov %reg, y(mem2)
  3802. mov x+8(mem1), %reg
  3803. mov %reg, y+8(mem2)
  3804. Change to:
  3805. movdqu x(mem1), %xmmreg
  3806. movdqu %xmmreg, y(mem2)
  3807. ...but only as long as the memory blocks don't overlap
  3808. }
  3809. SourceRef := taicpu(p).oper[0]^.ref^;
  3810. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3811. if (taicpu(p).opsize = S_Q) and
  3812. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3813. GetNextInstruction(hp1, hp2) and
  3814. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3815. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3816. begin
  3817. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3819. Inc(SourceRef.offset, 8);
  3820. if UseAVX then
  3821. begin
  3822. MovAligned := A_VMOVDQA;
  3823. MovUnaligned := A_VMOVDQU;
  3824. end
  3825. else
  3826. begin
  3827. MovAligned := A_MOVDQA;
  3828. MovUnaligned := A_MOVDQU;
  3829. end;
  3830. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3831. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3832. begin
  3833. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3834. Inc(TargetRef.offset, 8);
  3835. if GetNextInstruction(hp2, hp3) and
  3836. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3837. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3838. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3839. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3840. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3841. begin
  3842. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3843. if NewMMReg <> NR_NO then
  3844. begin
  3845. { Remember that the offsets are 8 ahead }
  3846. if ((SourceRef.offset mod 16) = 8) and
  3847. (
  3848. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3849. (SourceRef.base = current_procinfo.framepointer) or
  3850. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3851. ) then
  3852. taicpu(p).opcode := MovAligned
  3853. else
  3854. taicpu(p).opcode := MovUnaligned;
  3855. taicpu(p).opsize := S_XMM;
  3856. taicpu(p).oper[1]^.reg := NewMMReg;
  3857. if ((TargetRef.offset mod 16) = 8) and
  3858. (
  3859. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3860. (TargetRef.base = current_procinfo.framepointer) or
  3861. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3862. ) then
  3863. taicpu(hp1).opcode := MovAligned
  3864. else
  3865. taicpu(hp1).opcode := MovUnaligned;
  3866. taicpu(hp1).opsize := S_XMM;
  3867. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3868. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3869. RemoveInstruction(hp2);
  3870. RemoveInstruction(hp3);
  3871. Result := True;
  3872. Exit;
  3873. end;
  3874. end;
  3875. end
  3876. else
  3877. begin
  3878. { See if the next references are 8 less rather than 8 greater }
  3879. Dec(SourceRef.offset, 16); { -8 the other way }
  3880. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3881. begin
  3882. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3883. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3884. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3885. GetNextInstruction(hp2, hp3) and
  3886. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3887. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3888. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3889. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3890. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3891. begin
  3892. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3893. if NewMMReg <> NR_NO then
  3894. begin
  3895. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3896. if ((SourceRef.offset mod 16) = 0) and
  3897. (
  3898. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3899. (SourceRef.base = current_procinfo.framepointer) or
  3900. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3901. ) then
  3902. taicpu(hp2).opcode := MovAligned
  3903. else
  3904. taicpu(hp2).opcode := MovUnaligned;
  3905. taicpu(hp2).opsize := S_XMM;
  3906. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3907. if ((TargetRef.offset mod 16) = 0) and
  3908. (
  3909. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3910. (TargetRef.base = current_procinfo.framepointer) or
  3911. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3912. ) then
  3913. taicpu(hp3).opcode := MovAligned
  3914. else
  3915. taicpu(hp3).opcode := MovUnaligned;
  3916. taicpu(hp3).opsize := S_XMM;
  3917. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3918. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3919. RemoveInstruction(hp1);
  3920. RemoveCurrentP(p);
  3921. Result := True;
  3922. Exit;
  3923. end;
  3924. end;
  3925. end;
  3926. end;
  3927. end;
  3928. {$endif x86_64}
  3929. end;
  3930. else
  3931. { The write target should be a reg or a ref }
  3932. InternalError(2021091601);
  3933. end;
  3934. else
  3935. ;
  3936. end;
  3937. end
  3938. else if (taicpu(p).oper[0]^.typ = top_const) and
  3939. { %treg is used afterwards, but all eventualities other
  3940. than the first MOV instruction being a constant are
  3941. covered by DeepMOVOpt, so only check for that }
  3942. (
  3943. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3944. not (cs_opt_size in current_settings.optimizerswitches) or
  3945. (taicpu(hp1).opsize = S_B)
  3946. ) and
  3947. (
  3948. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3949. (
  3950. { For 32-to-64-bit zero-extension, the immediate
  3951. must be between 0 and 2^31 - 1}
  3952. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3953. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3954. ) or
  3955. (
  3956. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3957. (
  3958. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3959. )
  3960. )
  3961. ) then
  3962. begin
  3963. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3964. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3965. Include(OptsToCheck, aoc_ForceNewIteration);
  3966. end;
  3967. end;
  3968. Break;
  3969. end;
  3970. end;
  3971. if taicpu(p).oper[0]^.typ = top_reg then
  3972. begin
  3973. { oper[1] is a reference }
  3974. { Saves on a large number of dereferences }
  3975. p_SourceReg := taicpu(p).oper[0]^.reg;
  3976. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3977. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3978. else
  3979. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3980. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3981. begin
  3982. if taicpu(p).oper[1]^.typ = top_reg then
  3983. begin
  3984. p_TargetReg := taicpu(p).oper[1]^.reg;
  3985. { Change:
  3986. movl %reg1,%reg2
  3987. ...
  3988. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3989. ...
  3990. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3991. To:
  3992. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3993. ...
  3994. movl x(%reg1),%reg1
  3995. ...
  3996. movl %reg1,%regX
  3997. }
  3998. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3999. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4000. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4001. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4002. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4003. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4004. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4005. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4006. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4007. begin
  4008. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4009. if RegInRef(p_TargetReg, SourceRef) and
  4010. { If %reg1 also appears in the second reference, then it will
  4011. not refer to the same memory block as the first reference }
  4012. not RegInRef(p_SourceReg, SourceRef) then
  4013. begin
  4014. { Check to see if the references match if %reg2 is changed to %reg1 }
  4015. if SourceRef.base = p_TargetReg then
  4016. SourceRef.base := p_SourceReg;
  4017. if SourceRef.index = p_TargetReg then
  4018. SourceRef.index := p_SourceReg;
  4019. { RefsEqual also checks to ensure both references are non-volatile }
  4020. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4021. begin
  4022. taicpu(hp2).loadreg(0, p_SourceReg);
  4023. TransferUsedRegs(TmpUsedRegs);
  4024. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4025. { Make sure the register is allocated between these instructions
  4026. even though it doesn't change value, since it may cause
  4027. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4028. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4029. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4030. Result := True;
  4031. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4032. begin
  4033. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4034. RemoveCurrentP(p);
  4035. Exit;
  4036. end
  4037. else
  4038. begin
  4039. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4040. begin
  4041. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4042. RemoveCurrentP(p);
  4043. Exit;
  4044. end;
  4045. end;
  4046. { If we reach this point, p and hp1 weren't actually modified,
  4047. so we can do a bit more work on this pass }
  4048. end;
  4049. end;
  4050. end;
  4051. end;
  4052. end;
  4053. end;
  4054. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4055. { All the next optimisations require a next instruction }
  4056. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4057. Exit;
  4058. { Next instruction is also a MOV ? }
  4059. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4060. begin
  4061. if MatchOpType(taicpu(p), top_const, top_ref) and
  4062. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4063. TryConstMerge(p, hp1) then
  4064. begin
  4065. Result := True;
  4066. { In case we have four byte writes in a row, check for 2 more
  4067. right now so we don't have to wait for another iteration of
  4068. pass 1
  4069. }
  4070. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4071. case taicpu(p).opsize of
  4072. S_W:
  4073. begin
  4074. if GetNextInstruction(p, hp1) and
  4075. MatchInstruction(hp1, A_MOV, [S_B]) and
  4076. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4077. GetNextInstruction(hp1, hp2) and
  4078. MatchInstruction(hp2, A_MOV, [S_B]) and
  4079. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4080. { Try to merge the two bytes }
  4081. TryConstMerge(hp1, hp2) then
  4082. { Now try to merge the two words (hp2 will get deleted) }
  4083. TryConstMerge(p, hp1);
  4084. end;
  4085. S_L:
  4086. begin
  4087. { Though this only really benefits x86_64 and not i386, it
  4088. gets a potential optimisation done faster and hence
  4089. reduces the number of times OptPass1MOV is entered }
  4090. if GetNextInstruction(p, hp1) and
  4091. MatchInstruction(hp1, A_MOV, [S_W]) and
  4092. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4093. GetNextInstruction(hp1, hp2) and
  4094. MatchInstruction(hp2, A_MOV, [S_W]) and
  4095. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4096. { Try to merge the two words }
  4097. TryConstMerge(hp1, hp2) then
  4098. { This will always fail on i386, so don't bother
  4099. calling it unless we're doing x86_64 }
  4100. {$ifdef x86_64}
  4101. { Now try to merge the two longwords (hp2 will get deleted) }
  4102. TryConstMerge(p, hp1)
  4103. {$endif x86_64}
  4104. ;
  4105. end;
  4106. else
  4107. ;
  4108. end;
  4109. Exit;
  4110. end;
  4111. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4112. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4113. { mov reg1, mem1 or mov mem1, reg1
  4114. mov mem2, reg2 mov reg2, mem2}
  4115. begin
  4116. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4117. { mov reg1, mem1 or mov mem1, reg1
  4118. mov mem2, reg1 mov reg2, mem1}
  4119. begin
  4120. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4121. { Removes the second statement from
  4122. mov reg1, mem1/reg2
  4123. mov mem1/reg2, reg1 }
  4124. begin
  4125. if taicpu(p).oper[0]^.typ=top_reg then
  4126. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4127. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4128. RemoveInstruction(hp1);
  4129. Result:=true;
  4130. exit;
  4131. end
  4132. else
  4133. begin
  4134. TransferUsedRegs(TmpUsedRegs);
  4135. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4136. if (taicpu(p).oper[1]^.typ = top_ref) and
  4137. { mov reg1, mem1
  4138. mov mem2, reg1 }
  4139. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4140. GetNextInstruction(hp1, hp2) and
  4141. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4142. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4143. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4144. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4145. { change to
  4146. mov reg1, mem1 mov reg1, mem1
  4147. mov mem2, reg1 cmp reg1, mem2
  4148. cmp mem1, reg1
  4149. }
  4150. begin
  4151. RemoveInstruction(hp2);
  4152. taicpu(hp1).opcode := A_CMP;
  4153. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4154. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4155. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4156. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4157. end;
  4158. end;
  4159. end
  4160. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4161. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4162. begin
  4163. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4164. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4165. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4166. end
  4167. else
  4168. begin
  4169. TransferUsedRegs(TmpUsedRegs);
  4170. if GetNextInstruction(hp1, hp2) and
  4171. MatchOpType(taicpu(p),top_ref,top_reg) and
  4172. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4173. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4174. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4175. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4176. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4177. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4178. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4179. { mov mem1, %reg1
  4180. mov %reg1, mem2
  4181. mov mem2, reg2
  4182. to:
  4183. mov mem1, reg2
  4184. mov reg2, mem2}
  4185. begin
  4186. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4187. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4188. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4189. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4190. RemoveInstruction(hp2);
  4191. Result := True;
  4192. end
  4193. {$ifdef i386}
  4194. { this is enabled for i386 only, as the rules to create the reg sets below
  4195. are too complicated for x86-64, so this makes this code too error prone
  4196. on x86-64
  4197. }
  4198. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4199. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4200. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4201. { mov mem1, reg1 mov mem1, reg1
  4202. mov reg1, mem2 mov reg1, mem2
  4203. mov mem2, reg2 mov mem2, reg1
  4204. to: to:
  4205. mov mem1, reg1 mov mem1, reg1
  4206. mov mem1, reg2 mov reg1, mem2
  4207. mov reg1, mem2
  4208. or (if mem1 depends on reg1
  4209. and/or if mem2 depends on reg2)
  4210. to:
  4211. mov mem1, reg1
  4212. mov reg1, mem2
  4213. mov reg1, reg2
  4214. }
  4215. begin
  4216. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4217. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4218. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4219. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4220. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4221. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4222. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4223. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4224. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4225. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4226. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4227. end
  4228. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4229. begin
  4230. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4231. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4232. end
  4233. else
  4234. begin
  4235. RemoveInstruction(hp2);
  4236. end
  4237. {$endif i386}
  4238. ;
  4239. end;
  4240. end
  4241. { movl [mem1],reg1
  4242. movl [mem1],reg2
  4243. to
  4244. movl [mem1],reg1
  4245. movl reg1,reg2
  4246. }
  4247. else if not CheckMovMov2MovMov2(p, hp1) and
  4248. { movl const1,[mem1]
  4249. movl [mem1],reg1
  4250. to
  4251. movl const1,reg1
  4252. movl reg1,[mem1]
  4253. }
  4254. MatchOpType(Taicpu(p),top_const,top_ref) and
  4255. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4256. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4257. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4258. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4259. begin
  4260. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4261. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4262. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4263. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4264. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4265. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4266. Result:=true;
  4267. exit;
  4268. end;
  4269. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4270. end;
  4271. { search further than the next instruction for a mov (as long as it's not a jump) }
  4272. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4273. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4274. (taicpu(p).oper[1]^.typ = top_reg) and
  4275. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4276. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4277. begin
  4278. { we work with hp2 here, so hp1 can be still used later on when
  4279. checking for GetNextInstruction_p }
  4280. hp3 := hp1;
  4281. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4282. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4283. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4284. TransferUsedRegs(TmpUsedRegs);
  4285. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4286. if NotFirstIteration then
  4287. JumpTracking := TLinkedList.Create
  4288. else
  4289. JumpTracking := nil;
  4290. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4291. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4292. (hp2.typ=ait_instruction) do
  4293. begin
  4294. case taicpu(hp2).opcode of
  4295. A_POP:
  4296. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4297. begin
  4298. if not CrossJump and
  4299. not RegUsedBetween(p_TargetReg, p, hp2) then
  4300. begin
  4301. { We can remove the original MOV since the register
  4302. wasn't used between it and its popping from the stack }
  4303. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4304. RemoveCurrentp(p, hp1);
  4305. Result := True;
  4306. JumpTracking.Free;
  4307. Exit;
  4308. end;
  4309. { Can't go any further }
  4310. Break;
  4311. end;
  4312. A_MOV:
  4313. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4314. ((taicpu(p).oper[0]^.typ=top_const) or
  4315. ((taicpu(p).oper[0]^.typ=top_reg) and
  4316. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4317. )
  4318. ) then
  4319. begin
  4320. { we have
  4321. mov x, %treg
  4322. mov %treg, y
  4323. }
  4324. { We don't need to call UpdateUsedRegs for every instruction between
  4325. p and hp2 because the register we're concerned about will not
  4326. become deallocated (otherwise GetNextInstructionUsingReg would
  4327. have stopped at an earlier instruction). [Kit] }
  4328. TempRegUsed :=
  4329. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4330. RegReadByInstruction(p_TargetReg, hp3) or
  4331. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4332. case taicpu(p).oper[0]^.typ Of
  4333. top_reg:
  4334. begin
  4335. { change
  4336. mov %reg, %treg
  4337. mov %treg, y
  4338. to
  4339. mov %reg, y
  4340. }
  4341. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4342. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4343. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4344. begin
  4345. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4346. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4347. if TempRegUsed then
  4348. begin
  4349. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4350. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4351. { Set the start of the next GetNextInstructionUsingRegCond search
  4352. to start at the entry right before hp2 (which is about to be removed) }
  4353. hp3 := tai(hp2.Previous);
  4354. RemoveInstruction(hp2);
  4355. Include(OptsToCheck, aoc_ForceNewIteration);
  4356. { See if there's more we can optimise }
  4357. Continue;
  4358. end
  4359. else
  4360. begin
  4361. RemoveInstruction(hp2);
  4362. { We can remove the original MOV too }
  4363. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4364. RemoveCurrentP(p, hp1);
  4365. Result:=true;
  4366. JumpTracking.Free;
  4367. Exit;
  4368. end;
  4369. end
  4370. else
  4371. begin
  4372. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4373. taicpu(hp2).loadReg(0, p_SourceReg);
  4374. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4375. { Check to see if the register also appears in the reference }
  4376. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4377. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4378. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4379. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4380. begin
  4381. { Don't remove the first instruction if the temporary register is in use }
  4382. if not TempRegUsed then
  4383. begin
  4384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4385. RemoveCurrentP(p, hp1);
  4386. Result:=true;
  4387. JumpTracking.Free;
  4388. Exit;
  4389. end;
  4390. { No need to set Result to True here. If there's another instruction later
  4391. on that can be optimised, it will be detected when the main Pass 1 loop
  4392. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4393. hp3 := hp2;
  4394. Continue;
  4395. end;
  4396. end;
  4397. end;
  4398. top_const:
  4399. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4400. begin
  4401. { change
  4402. mov const, %treg
  4403. mov %treg, y
  4404. to
  4405. mov const, y
  4406. }
  4407. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4408. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4409. begin
  4410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4411. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4412. if TempRegUsed then
  4413. begin
  4414. { Don't remove the first instruction if the temporary register is in use }
  4415. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4416. { No need to set Result to True. If there's another instruction later on
  4417. that can be optimised, it will be detected when the main Pass 1 loop
  4418. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4419. end
  4420. else
  4421. begin
  4422. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4423. RemoveCurrentP(p, hp1);
  4424. Result:=true;
  4425. Exit;
  4426. end;
  4427. end;
  4428. end;
  4429. else
  4430. Internalerror(2019103001);
  4431. end;
  4432. end
  4433. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4434. begin
  4435. if not CrossJump and
  4436. not RegUsedBetween(p_TargetReg, p, hp2) and
  4437. not RegReadByInstruction(p_TargetReg, hp2) then
  4438. begin
  4439. { Register is not used before it is overwritten }
  4440. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4441. RemoveCurrentp(p, hp1);
  4442. Result := True;
  4443. Exit;
  4444. end;
  4445. if (taicpu(p).oper[0]^.typ = top_const) and
  4446. (taicpu(hp2).oper[0]^.typ = top_const) then
  4447. begin
  4448. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4449. begin
  4450. { Same value - register hasn't changed }
  4451. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4452. RemoveInstruction(hp2);
  4453. Include(OptsToCheck, aoc_ForceNewIteration);
  4454. { See if there's more we can optimise }
  4455. Continue;
  4456. end;
  4457. end;
  4458. {$ifdef x86_64}
  4459. end
  4460. { Change:
  4461. movl %reg1l,%reg2l
  4462. ...
  4463. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4464. To:
  4465. movl %reg1l,%reg2l
  4466. ...
  4467. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4468. If %reg1 = %reg3, convert to:
  4469. movl %reg1l,%reg2l
  4470. ...
  4471. andl %reg1l,%reg1l
  4472. }
  4473. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4474. (taicpu(p).oper[0]^.typ = top_reg) and
  4475. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4476. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4477. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4478. begin
  4479. TempRegUsed :=
  4480. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4481. RegReadByInstruction(p_TargetReg, hp3) or
  4482. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4483. taicpu(hp2).opsize := S_L;
  4484. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4485. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4486. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4487. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4488. begin
  4489. { %reg1 = %reg3 }
  4490. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4491. taicpu(hp2).opcode := A_AND;
  4492. end
  4493. else
  4494. begin
  4495. { %reg1 <> %reg3 }
  4496. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4497. end;
  4498. if not TempRegUsed then
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4501. RemoveCurrentP(p, hp1);
  4502. Result := True;
  4503. Exit;
  4504. end
  4505. else
  4506. begin
  4507. { Initial instruction wasn't actually changed }
  4508. Include(OptsToCheck, aoc_ForceNewIteration);
  4509. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4510. appears below since %reg1 has technically changed }
  4511. if taicpu(hp2).opcode = A_AND then
  4512. Break;
  4513. end;
  4514. {$endif x86_64}
  4515. end
  4516. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4517. GetNextInstruction(hp2, hp4) and
  4518. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4519. { Optimise the following first:
  4520. movl [mem1],reg1
  4521. movl [mem1],reg2
  4522. to
  4523. movl [mem1],reg1
  4524. movl reg1,reg2
  4525. If [mem1] contains the target register and reg1 is the
  4526. the source register, this optimisation will get missed
  4527. and produce less efficient code later on.
  4528. }
  4529. if CheckMovMov2MovMov2(hp2, hp4) then
  4530. { Initial instruction wasn't actually changed }
  4531. Include(OptsToCheck, aoc_ForceNewIteration);
  4532. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4533. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4534. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4535. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4536. begin
  4537. {
  4538. Change from:
  4539. mov ###, %reg
  4540. ...
  4541. movs/z %reg,%reg (Same register, just different sizes)
  4542. To:
  4543. movs/z ###, %reg (Longer version)
  4544. ...
  4545. (remove)
  4546. }
  4547. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4548. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4549. { Keep the first instruction as mov if ### is a constant }
  4550. if taicpu(p).oper[0]^.typ = top_const then
  4551. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4552. else
  4553. begin
  4554. taicpu(p).opcode := taicpu(hp2).opcode;
  4555. taicpu(p).opsize := taicpu(hp2).opsize;
  4556. end;
  4557. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4558. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4559. RemoveInstruction(hp2);
  4560. Result := True;
  4561. JumpTracking.Free;
  4562. Exit;
  4563. end;
  4564. else
  4565. { Move down to the if-block below };
  4566. end;
  4567. { Also catches MOV/S/Z instructions that aren't modified }
  4568. if taicpu(p).oper[0]^.typ = top_reg then
  4569. begin
  4570. p_SourceReg := taicpu(p).oper[0]^.reg;
  4571. if
  4572. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4573. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4574. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4575. begin
  4576. Result := True;
  4577. { Just in case something didn't get modified (e.g. an
  4578. implicit register). Also, if it does read from this
  4579. register, then there's no longer an advantage to
  4580. changing the register on subsequent instructions.}
  4581. if not RegReadByInstruction(p_TargetReg, hp2) then
  4582. begin
  4583. { If a conditional jump was crossed, do not delete
  4584. the original MOV no matter what }
  4585. if not CrossJump and
  4586. { RegEndOfLife returns True if the register is
  4587. deallocated before the next instruction or has
  4588. been loaded with a new value }
  4589. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4590. begin
  4591. { We can remove the original MOV }
  4592. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4593. RemoveCurrentp(p, hp1);
  4594. JumpTracking.Free;
  4595. Result := True;
  4596. Exit;
  4597. end;
  4598. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4599. begin
  4600. { See if there's more we can optimise }
  4601. hp3 := hp2;
  4602. Continue;
  4603. end;
  4604. end;
  4605. end;
  4606. end;
  4607. { Break out of the while loop under normal circumstances }
  4608. Break;
  4609. end;
  4610. JumpTracking.Free;
  4611. end;
  4612. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4613. (taicpu(p).oper[1]^.typ = top_reg) and
  4614. (taicpu(p).opsize = S_L) and
  4615. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4616. (hp2.typ = ait_instruction) and
  4617. (taicpu(hp2).opcode = A_AND) and
  4618. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4619. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4620. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4621. ) then
  4622. begin
  4623. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4624. begin
  4625. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4626. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4627. begin
  4628. { Optimize out:
  4629. mov x, %reg
  4630. and ffffffffh, %reg
  4631. }
  4632. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4633. RemoveInstruction(hp2);
  4634. Result:=true;
  4635. exit;
  4636. end;
  4637. end;
  4638. end;
  4639. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4640. x >= RetOffset) as it doesn't do anything (it writes either to a
  4641. parameter or to the temporary storage room for the function
  4642. result)
  4643. }
  4644. if IsExitCode(hp1) and
  4645. (taicpu(p).oper[1]^.typ = top_ref) and
  4646. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4647. (
  4648. (
  4649. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4650. not (
  4651. assigned(current_procinfo.procdef.funcretsym) and
  4652. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4653. )
  4654. ) or
  4655. { Also discard writes to the stack that are below the base pointer,
  4656. as this is temporary storage rather than a function result on the
  4657. stack, say. }
  4658. (
  4659. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4660. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4661. )
  4662. ) then
  4663. begin
  4664. RemoveCurrentp(p, hp1);
  4665. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4666. RemoveLastDeallocForFuncRes(p);
  4667. Result:=true;
  4668. exit;
  4669. end;
  4670. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4671. begin
  4672. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4673. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4674. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4675. begin
  4676. { change
  4677. mov reg1, mem1
  4678. test/cmp x, mem1
  4679. to
  4680. mov reg1, mem1
  4681. test/cmp x, reg1
  4682. }
  4683. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4684. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4685. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4686. Result := True;
  4687. Exit;
  4688. end;
  4689. if DoMovCmpMemOpt(p, hp1) then
  4690. begin
  4691. Result := True;
  4692. Exit;
  4693. end;
  4694. end;
  4695. if (taicpu(p).oper[1]^.typ = top_reg) and
  4696. (hp1.typ = ait_instruction) and
  4697. GetNextInstruction(hp1, hp2) and
  4698. MatchInstruction(hp2,A_MOV,[]) and
  4699. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4700. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4701. (
  4702. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4703. {$ifdef x86_64}
  4704. or
  4705. (
  4706. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4707. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4708. )
  4709. {$endif x86_64}
  4710. ) then
  4711. begin
  4712. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4713. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4714. { change movsX/movzX reg/ref, reg2
  4715. add/sub/or/... reg3/$const, reg2
  4716. mov reg2 reg/ref
  4717. dealloc reg2
  4718. to
  4719. add/sub/or/... reg3/$const, reg/ref }
  4720. begin
  4721. TransferUsedRegs(TmpUsedRegs);
  4722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4723. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4724. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4725. begin
  4726. { by example:
  4727. movswl %si,%eax movswl %si,%eax p
  4728. decl %eax addl %edx,%eax hp1
  4729. movw %ax,%si movw %ax,%si hp2
  4730. ->
  4731. movswl %si,%eax movswl %si,%eax p
  4732. decw %eax addw %edx,%eax hp1
  4733. movw %ax,%si movw %ax,%si hp2
  4734. }
  4735. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4736. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4737. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4738. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4739. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4740. {
  4741. ->
  4742. movswl %si,%eax movswl %si,%eax p
  4743. decw %si addw %dx,%si hp1
  4744. movw %ax,%si movw %ax,%si hp2
  4745. }
  4746. case taicpu(hp1).ops of
  4747. 1:
  4748. begin
  4749. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4750. if taicpu(hp1).oper[0]^.typ=top_reg then
  4751. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4752. end;
  4753. 2:
  4754. begin
  4755. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4756. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4757. (taicpu(hp1).opcode<>A_SHL) and
  4758. (taicpu(hp1).opcode<>A_SHR) and
  4759. (taicpu(hp1).opcode<>A_SAR) then
  4760. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4761. end;
  4762. else
  4763. internalerror(2008042701);
  4764. end;
  4765. {
  4766. ->
  4767. decw %si addw %dx,%si p
  4768. }
  4769. RemoveInstruction(hp2);
  4770. RemoveCurrentP(p, hp1);
  4771. Result:=True;
  4772. Exit;
  4773. end;
  4774. end;
  4775. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4776. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4777. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4778. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4779. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4780. ) and
  4781. { if ref contains a symbol, we cannot change its size to a smaller size }
  4782. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4783. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4784. )
  4785. {$ifdef i386}
  4786. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4787. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4788. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4789. {$endif i386}
  4790. then
  4791. { change movsX/movzX reg/ref, reg2
  4792. add/sub/or/... regX/$const, reg2
  4793. mov reg2, reg3
  4794. dealloc reg2
  4795. to
  4796. movsX/movzX reg/ref, reg3
  4797. add/sub/or/... reg3/$const, reg3
  4798. }
  4799. begin
  4800. TransferUsedRegs(TmpUsedRegs);
  4801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4802. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4803. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4804. begin
  4805. { by example:
  4806. movswl %si,%eax movswl %si,%eax p
  4807. decl %eax addl %edx,%eax hp1
  4808. movw %ax,%si movw %ax,%si hp2
  4809. ->
  4810. movswl %si,%eax movswl %si,%eax p
  4811. decw %eax addw %edx,%eax hp1
  4812. movw %ax,%si movw %ax,%si hp2
  4813. }
  4814. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4815. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4816. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4817. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4818. { limit size of constants as well to avoid assembler errors, but
  4819. check opsize to avoid overflow when left shifting the 1 }
  4820. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4821. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4822. {$ifdef x86_64}
  4823. { Be careful of, for example:
  4824. movl %reg1,%reg2
  4825. addl %reg3,%reg2
  4826. movq %reg2,%reg4
  4827. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4828. }
  4829. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4830. begin
  4831. taicpu(hp2).changeopsize(S_L);
  4832. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4833. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4834. end;
  4835. {$endif x86_64}
  4836. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4837. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4838. if taicpu(p).oper[0]^.typ=top_reg then
  4839. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4840. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4841. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4842. {
  4843. ->
  4844. movswl %si,%eax movswl %si,%eax p
  4845. decw %si addw %dx,%si hp1
  4846. movw %ax,%si movw %ax,%si hp2
  4847. }
  4848. case taicpu(hp1).ops of
  4849. 1:
  4850. begin
  4851. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4852. if taicpu(hp1).oper[0]^.typ=top_reg then
  4853. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4854. end;
  4855. 2:
  4856. begin
  4857. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4858. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4859. (taicpu(hp1).opcode<>A_SHL) and
  4860. (taicpu(hp1).opcode<>A_SHR) and
  4861. (taicpu(hp1).opcode<>A_SAR) then
  4862. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4863. end;
  4864. else
  4865. internalerror(2018111801);
  4866. end;
  4867. {
  4868. ->
  4869. decw %si addw %dx,%si p
  4870. }
  4871. RemoveInstruction(hp2);
  4872. end;
  4873. end;
  4874. end;
  4875. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4876. GetNextInstruction(hp1, hp2) and
  4877. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4878. MatchOperand(Taicpu(p).oper[0]^,0) and
  4879. (Taicpu(p).oper[1]^.typ = top_reg) and
  4880. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4881. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4882. { mov reg1,0
  4883. bts reg1,operand1 --> mov reg1,operand2
  4884. or reg1,operand2 bts reg1,operand1}
  4885. begin
  4886. Taicpu(hp2).opcode:=A_MOV;
  4887. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4888. asml.remove(hp1);
  4889. insertllitem(hp2,hp2.next,hp1);
  4890. RemoveCurrentp(p, hp1);
  4891. Result:=true;
  4892. exit;
  4893. end;
  4894. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4895. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4896. GetNextInstruction(hp1, hp2) and
  4897. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4898. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4899. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4900. { change
  4901. mov reg1,reg2
  4902. sub reg3,reg2
  4903. cmp reg3,reg1
  4904. into
  4905. mov reg1,reg2
  4906. sub reg3,reg2
  4907. }
  4908. begin
  4909. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4910. RemoveInstruction(hp2);
  4911. Result:=true;
  4912. exit;
  4913. end;
  4914. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4915. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4916. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4917. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4918. begin
  4919. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4920. {$ifdef x86_64}
  4921. { Convert:
  4922. movq x(ref),%reg64
  4923. shrq y,%reg64
  4924. To:
  4925. movl x+4(ref),%reg32
  4926. shrl y-32,%reg32 (Remove if y = 32)
  4927. }
  4928. if (taicpu(p).opsize = S_Q) and
  4929. (taicpu(hp1).opcode = A_SHR) and
  4930. (taicpu(hp1).oper[0]^.val >= 32) then
  4931. begin
  4932. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4933. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4934. { Convert to 32-bit }
  4935. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4936. taicpu(p).opsize := S_L;
  4937. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4938. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4939. if (taicpu(hp1).oper[0]^.val = 32) then
  4940. begin
  4941. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4942. RemoveInstruction(hp1);
  4943. end
  4944. else
  4945. begin
  4946. { This will potentially open up more arithmetic operations since
  4947. the peephole optimizer now has a big hint that only the lower
  4948. 32 bits are currently in use (and opcodes are smaller in size) }
  4949. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4950. taicpu(hp1).opsize := S_L;
  4951. Dec(taicpu(hp1).oper[0]^.val, 32);
  4952. DebugMsg(SPeepholeOptimization + PreMessage +
  4953. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4954. end;
  4955. Result := True;
  4956. Exit;
  4957. end;
  4958. {$endif x86_64}
  4959. { Convert:
  4960. movl x(ref),%reg
  4961. shrl $24,%reg
  4962. To:
  4963. movzbl x+3(ref),%reg
  4964. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4965. Also accept sar instead of shr, but convert to movsx instead of movzx
  4966. }
  4967. if taicpu(hp1).opcode = A_SHR then
  4968. MovUnaligned := A_MOVZX
  4969. else
  4970. MovUnaligned := A_MOVSX;
  4971. NewSize := S_NO;
  4972. NewOffset := 0;
  4973. case taicpu(p).opsize of
  4974. S_B:
  4975. { No valid combinations };
  4976. S_W:
  4977. if (taicpu(hp1).oper[0]^.val = 8) then
  4978. begin
  4979. NewSize := S_BW;
  4980. NewOffset := 1;
  4981. end;
  4982. S_L:
  4983. case taicpu(hp1).oper[0]^.val of
  4984. 16:
  4985. begin
  4986. NewSize := S_WL;
  4987. NewOffset := 2;
  4988. end;
  4989. 24:
  4990. begin
  4991. NewSize := S_BL;
  4992. NewOffset := 3;
  4993. end;
  4994. else
  4995. ;
  4996. end;
  4997. {$ifdef x86_64}
  4998. S_Q:
  4999. case taicpu(hp1).oper[0]^.val of
  5000. 32:
  5001. begin
  5002. if taicpu(hp1).opcode = A_SAR then
  5003. begin
  5004. { 32-bit to 64-bit is a distinct instruction }
  5005. MovUnaligned := A_MOVSXD;
  5006. NewSize := S_LQ;
  5007. NewOffset := 4;
  5008. end
  5009. else
  5010. { Should have been handled by MovShr2Mov above }
  5011. InternalError(2022081811);
  5012. end;
  5013. 48:
  5014. begin
  5015. NewSize := S_WQ;
  5016. NewOffset := 6;
  5017. end;
  5018. 56:
  5019. begin
  5020. NewSize := S_BQ;
  5021. NewOffset := 7;
  5022. end;
  5023. else
  5024. ;
  5025. end;
  5026. {$endif x86_64}
  5027. else
  5028. InternalError(2022081810);
  5029. end;
  5030. if (NewSize <> S_NO) and
  5031. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5032. begin
  5033. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5034. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5035. debug_op2str(MovUnaligned);
  5036. {$ifdef x86_64}
  5037. if MovUnaligned <> A_MOVSXD then
  5038. { Don't add size suffix for MOVSXD }
  5039. {$endif x86_64}
  5040. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5041. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5042. taicpu(p).opcode := MovUnaligned;
  5043. taicpu(p).opsize := NewSize;
  5044. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5045. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5046. RemoveInstruction(hp1);
  5047. Result := True;
  5048. Exit;
  5049. end;
  5050. end;
  5051. { Backward optimisation shared with OptPass2MOV }
  5052. if FuncMov2Func(p, hp1) then
  5053. begin
  5054. Result := True;
  5055. Exit;
  5056. end;
  5057. end;
  5058. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5059. var
  5060. hp1 : tai;
  5061. begin
  5062. Result:=false;
  5063. if taicpu(p).ops <> 2 then
  5064. exit;
  5065. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5066. GetNextInstruction(p,hp1) then
  5067. begin
  5068. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5069. (taicpu(hp1).ops = 2) then
  5070. begin
  5071. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5072. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5073. { movXX reg1, mem1 or movXX mem1, reg1
  5074. movXX mem2, reg2 movXX reg2, mem2}
  5075. begin
  5076. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5077. { movXX reg1, mem1 or movXX mem1, reg1
  5078. movXX mem2, reg1 movXX reg2, mem1}
  5079. begin
  5080. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5081. begin
  5082. { Removes the second statement from
  5083. movXX reg1, mem1/reg2
  5084. movXX mem1/reg2, reg1
  5085. }
  5086. if taicpu(p).oper[0]^.typ=top_reg then
  5087. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5088. { Removes the second statement from
  5089. movXX mem1/reg1, reg2
  5090. movXX reg2, mem1/reg1
  5091. }
  5092. if (taicpu(p).oper[1]^.typ=top_reg) and
  5093. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5094. begin
  5095. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5096. RemoveInstruction(hp1);
  5097. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5098. Result:=true;
  5099. exit;
  5100. end
  5101. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5102. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5103. begin
  5104. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5105. RemoveInstruction(hp1);
  5106. Result:=true;
  5107. exit;
  5108. end;
  5109. end
  5110. end;
  5111. end;
  5112. end;
  5113. end;
  5114. end;
  5115. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5116. var
  5117. hp1 : tai;
  5118. begin
  5119. result:=false;
  5120. { replace
  5121. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5122. MovX %mreg2,%mreg1
  5123. dealloc %mreg2
  5124. by
  5125. <Op>X %mreg2,%mreg1
  5126. ?
  5127. }
  5128. if GetNextInstruction(p,hp1) and
  5129. { we mix single and double opperations here because we assume that the compiler
  5130. generates vmovapd only after double operations and vmovaps only after single operations }
  5131. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5132. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5133. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5134. (taicpu(p).oper[0]^.typ=top_reg) then
  5135. begin
  5136. TransferUsedRegs(TmpUsedRegs);
  5137. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5138. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5139. begin
  5140. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5141. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5142. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5143. RemoveInstruction(hp1);
  5144. result:=true;
  5145. end;
  5146. end;
  5147. end;
  5148. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5149. var
  5150. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5151. JumpLabel, JumpLabel_dist: TAsmLabel;
  5152. FirstValue, SecondValue: TCGInt;
  5153. function OptimizeJump(var InputP: tai): Boolean;
  5154. var
  5155. TempBool: Boolean;
  5156. begin
  5157. Result := False;
  5158. TempBool := True;
  5159. if DoJumpOptimizations(InputP, TempBool) or
  5160. not TempBool then
  5161. begin
  5162. Result := True;
  5163. if Assigned(InputP) then
  5164. begin
  5165. { CollapseZeroDistJump will be set to the label or an align
  5166. before it after the jump if it optimises, whether or not
  5167. the label is live or dead }
  5168. if (InputP.typ = ait_align) or
  5169. (
  5170. (InputP.typ = ait_label) and
  5171. not (tai_label(InputP).labsym.is_used)
  5172. ) then
  5173. GetNextInstruction(InputP, InputP);
  5174. end;
  5175. Exit;
  5176. end;
  5177. end;
  5178. begin
  5179. Result := False;
  5180. if (taicpu(p).oper[0]^.typ = top_const) and
  5181. (taicpu(p).oper[0]^.val <> -1) then
  5182. begin
  5183. { Convert unsigned maximum constants to -1 to aid optimisation }
  5184. case taicpu(p).opsize of
  5185. S_B:
  5186. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5187. begin
  5188. taicpu(p).oper[0]^.val := -1;
  5189. Result := True;
  5190. Exit;
  5191. end;
  5192. S_W:
  5193. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5194. begin
  5195. taicpu(p).oper[0]^.val := -1;
  5196. Result := True;
  5197. Exit;
  5198. end;
  5199. S_L:
  5200. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5201. begin
  5202. taicpu(p).oper[0]^.val := -1;
  5203. Result := True;
  5204. Exit;
  5205. end;
  5206. {$ifdef x86_64}
  5207. S_Q:
  5208. { Storing anything greater than $7FFFFFFF is not possible so do
  5209. nothing };
  5210. {$endif x86_64}
  5211. else
  5212. InternalError(2021121001);
  5213. end;
  5214. end;
  5215. if GetNextInstruction(p, hp1) and
  5216. TrySwapMovCmp(p, hp1) then
  5217. begin
  5218. Result := True;
  5219. Exit;
  5220. end;
  5221. p_label := nil;
  5222. JumpLabel := nil;
  5223. if MatchInstruction(hp1, A_Jcc, []) then
  5224. begin
  5225. if OptimizeJump(hp1) then
  5226. begin
  5227. Result := True;
  5228. if Assigned(hp1) then
  5229. begin
  5230. { CollapseZeroDistJump will be set to the label or an align
  5231. before it after the jump if it optimises, whether or not
  5232. the label is live or dead }
  5233. if (hp1.typ = ait_align) or
  5234. (
  5235. (hp1.typ = ait_label) and
  5236. not (tai_label(hp1).labsym.is_used)
  5237. ) then
  5238. GetNextInstruction(hp1, hp1);
  5239. end;
  5240. TransferUsedRegs(TmpUsedRegs);
  5241. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5242. if not Assigned(hp1) or
  5243. (
  5244. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5245. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5246. ) then
  5247. begin
  5248. { No more conditional jumps; conditional statement is no longer required }
  5249. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5250. RemoveCurrentP(p);
  5251. end;
  5252. Exit;
  5253. end;
  5254. if IsJumpToLabel(taicpu(hp1)) then
  5255. begin
  5256. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5257. if Assigned(JumpLabel) then
  5258. p_label := getlabelwithsym(JumpLabel);
  5259. end;
  5260. end;
  5261. { Search for:
  5262. test $x,(reg/ref)
  5263. jne @lbl1
  5264. test $y,(reg/ref) (same register or reference)
  5265. jne @lbl1
  5266. Change to:
  5267. test $(x or y),(reg/ref)
  5268. jne @lbl1
  5269. (Note, this doesn't work with je instead of jne)
  5270. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5271. Also search for:
  5272. test $x,(reg/ref)
  5273. je @lbl1
  5274. ...
  5275. test $y,(reg/ref)
  5276. je/jne @lbl2
  5277. If (x or y) = x, then the second jump is deterministic
  5278. }
  5279. if (
  5280. (
  5281. (taicpu(p).oper[0]^.typ = top_const) or
  5282. (
  5283. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5284. (taicpu(p).oper[0]^.typ = top_reg) and
  5285. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5286. )
  5287. ) and
  5288. MatchInstruction(hp1, A_JCC, [])
  5289. ) then
  5290. begin
  5291. if (taicpu(p).oper[0]^.typ = top_reg) and
  5292. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5293. FirstValue := -1
  5294. else
  5295. FirstValue := taicpu(p).oper[0]^.val;
  5296. { If we have several test/jne's in a row, it might be the case that
  5297. the second label doesn't go to the same location, but the one
  5298. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5299. so accommodate for this with a while loop.
  5300. }
  5301. hp1_last := hp1;
  5302. while (
  5303. (
  5304. (taicpu(p).oper[1]^.typ = top_reg) and
  5305. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5306. ) or GetNextInstruction(hp1_last, p_dist)
  5307. ) and (p_dist.typ = ait_instruction) do
  5308. begin
  5309. if (
  5310. (
  5311. (taicpu(p_dist).opcode = A_TEST) and
  5312. (
  5313. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5314. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5315. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5316. )
  5317. ) or
  5318. (
  5319. { cmp 0,%reg = test %reg,%reg }
  5320. (taicpu(p_dist).opcode = A_CMP) and
  5321. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5322. )
  5323. ) and
  5324. { Make sure the destination operands are actually the same }
  5325. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5326. GetNextInstruction(p_dist, hp1_dist) and
  5327. MatchInstruction(hp1_dist, A_JCC, []) then
  5328. begin
  5329. if OptimizeJump(hp1_dist) then
  5330. begin
  5331. Result := True;
  5332. Exit;
  5333. end;
  5334. if
  5335. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5336. (
  5337. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5338. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5339. ) then
  5340. SecondValue := -1
  5341. else
  5342. SecondValue := taicpu(p_dist).oper[0]^.val;
  5343. { If both of the TEST constants are identical, delete the
  5344. second TEST that is unnecessary (be careful though, just
  5345. in case the flags are modified in between) }
  5346. if (FirstValue = SecondValue) then
  5347. begin
  5348. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5349. begin
  5350. { Since the second jump's condition is a subset of the first, we
  5351. know it will never branch because the first jump dominates it.
  5352. Get it out of the way now rather than wait for the jump
  5353. optimisations for a speed boost. }
  5354. if IsJumpToLabel(taicpu(hp1_dist)) then
  5355. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5356. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5357. RemoveInstruction(hp1_dist);
  5358. Result := True;
  5359. end
  5360. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5361. begin
  5362. { If the inverse of the first condition is a subset of the second,
  5363. the second one will definitely branch if the first one doesn't }
  5364. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5365. { We can remove the TEST instruction too }
  5366. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5367. RemoveInstruction(p_dist);
  5368. MakeUnconditional(taicpu(hp1_dist));
  5369. RemoveDeadCodeAfterJump(hp1_dist);
  5370. { Since the jump is now unconditional, we can't
  5371. continue any further with this particular
  5372. optimisation. The original TEST is still intact
  5373. though, so there might be something else we can
  5374. do }
  5375. Include(OptsToCheck, aoc_ForceNewIteration);
  5376. Break;
  5377. end;
  5378. if Result or
  5379. { If a jump wasn't removed or made unconditional, only
  5380. remove the identical TEST instruction if the flags
  5381. weren't modified }
  5382. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5383. begin
  5384. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5385. RemoveInstruction(p_dist);
  5386. { If the jump was removed or made unconditional, we
  5387. don't need to allocate NR_DEFAULTFLAGS over the
  5388. entire range }
  5389. if not Result then
  5390. begin
  5391. { Mark the flags as 'in use' over the entire range }
  5392. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5393. { Speed gain - continue search from the Jcc instruction }
  5394. hp1_last := hp1_dist;
  5395. { Only the TEST instruction was removed, and the
  5396. original was unchanged, so we can safely do
  5397. another iteration of the while loop }
  5398. Include(OptsToCheck, aoc_ForceNewIteration);
  5399. Continue;
  5400. end;
  5401. Exit;
  5402. end;
  5403. end;
  5404. hp1_last := nil;
  5405. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5406. (
  5407. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5408. { Always adjacent under -O2 and under }
  5409. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5410. (
  5411. GetNextInstruction(hp1, hp1_last) and
  5412. (hp1_last = p_dist)
  5413. )
  5414. ) and
  5415. (
  5416. (
  5417. { Test the following variant:
  5418. test $x,(reg/ref)
  5419. jne @lbl1
  5420. test $y,(reg/ref)
  5421. je @lbl2
  5422. @lbl1:
  5423. Becomes:
  5424. test $(x or y),(reg/ref)
  5425. je @lbl2
  5426. @lbl1: (may become a dead label)
  5427. }
  5428. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5429. GetNextInstruction(hp1_dist, hp1_last) and
  5430. (hp1_last = p_label)
  5431. ) or
  5432. (
  5433. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5434. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5435. then the second jump will never branch, so it can also be
  5436. removed regardless of where it goes }
  5437. (
  5438. (FirstValue = -1) or
  5439. (SecondValue = -1) or
  5440. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5441. )
  5442. )
  5443. ) then
  5444. begin
  5445. { Same jump location... can be a register since nothing's changed }
  5446. { If any of the entries are equivalent to test %reg,%reg, then the
  5447. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5448. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5449. if (hp1_last = p_label) then
  5450. begin
  5451. { Variant }
  5452. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5453. RemoveInstruction(p_dist);
  5454. if Assigned(JumpLabel) then
  5455. JumpLabel.decrefs;
  5456. RemoveInstruction(hp1);
  5457. end
  5458. else
  5459. begin
  5460. { Only remove the second test if no jumps or other conditional instructions follow }
  5461. TransferUsedRegs(TmpUsedRegs);
  5462. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5463. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5464. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5465. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5466. begin
  5467. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5468. RemoveInstruction(p_dist);
  5469. { Remove the first jump, not the second, to keep
  5470. any register deallocations between the second
  5471. TEST/JNE pair in the same place. Aids future
  5472. optimisation. }
  5473. if Assigned(JumpLabel) then
  5474. JumpLabel.decrefs;
  5475. RemoveInstruction(hp1);
  5476. end
  5477. else
  5478. begin
  5479. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5480. if IsJumpToLabel(taicpu(hp1_dist)) then
  5481. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5482. { Remove second jump in this instance }
  5483. RemoveInstruction(hp1_dist);
  5484. end;
  5485. end;
  5486. Result := True;
  5487. Exit;
  5488. end;
  5489. end;
  5490. if { If -O2 and under, it may stop on any old instruction }
  5491. (cs_opt_level3 in current_settings.optimizerswitches) and
  5492. (taicpu(p).oper[1]^.typ = top_reg) and
  5493. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5494. begin
  5495. hp1_last := p_dist;
  5496. Continue;
  5497. end;
  5498. Break;
  5499. end;
  5500. end;
  5501. { Search for:
  5502. test %reg,%reg
  5503. j(c1) @lbl1
  5504. ...
  5505. @lbl:
  5506. test %reg,%reg (same register)
  5507. j(c2) @lbl2
  5508. If c2 is a subset of c1, change to:
  5509. test %reg,%reg
  5510. j(c1) @lbl2
  5511. (@lbl1 may become a dead label as a result)
  5512. }
  5513. if (taicpu(p).oper[1]^.typ = top_reg) and
  5514. (taicpu(p).oper[0]^.typ = top_reg) and
  5515. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5516. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5517. Assigned(p_label) and
  5518. GetNextInstruction(p_label, p_dist) and
  5519. MatchInstruction(p_dist, A_TEST, []) and
  5520. { It's fine if the second test uses smaller sub-registers }
  5521. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5522. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5523. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5524. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5525. GetNextInstruction(p_dist, hp1_dist) and
  5526. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5527. begin
  5528. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5529. if JumpLabel = JumpLabel_dist then
  5530. { This is an infinite loop }
  5531. Exit;
  5532. { Best optimisation when the first condition is a subset (or equal) of the second }
  5533. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5534. begin
  5535. { Any registers used here will already be allocated }
  5536. if Assigned(JumpLabel) then
  5537. JumpLabel.DecRefs;
  5538. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5539. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5540. Result := True;
  5541. Exit;
  5542. end;
  5543. end;
  5544. end;
  5545. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5546. var
  5547. hp1, hp2: tai;
  5548. ActiveReg: TRegister;
  5549. OldOffset: asizeint;
  5550. ThisConst: TCGInt;
  5551. function RegDeallocated: Boolean;
  5552. begin
  5553. TransferUsedRegs(TmpUsedRegs);
  5554. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5555. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5556. end;
  5557. begin
  5558. result:=false;
  5559. hp1 := nil;
  5560. { replace
  5561. addX const,%reg1
  5562. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5563. dealloc %reg1
  5564. by
  5565. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5566. }
  5567. if MatchOpType(taicpu(p),top_const,top_reg) then
  5568. begin
  5569. ActiveReg := taicpu(p).oper[1]^.reg;
  5570. { Ensures the entire register was updated }
  5571. if (taicpu(p).opsize >= S_L) and
  5572. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5573. MatchInstruction(hp1,A_LEA,[]) and
  5574. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5575. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5576. (
  5577. { Cover the case where the register in the reference is also the destination register }
  5578. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5579. (
  5580. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5581. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5582. RegDeallocated
  5583. )
  5584. ) then
  5585. begin
  5586. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5587. {$push}
  5588. {$R-}{$Q-}
  5589. { Explicitly disable overflow checking for these offset calculation
  5590. as those do not matter for the final result }
  5591. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5592. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5593. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5594. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5595. {$pop}
  5596. {$ifdef x86_64}
  5597. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5598. begin
  5599. { Overflow; abort }
  5600. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5601. end
  5602. else
  5603. {$endif x86_64}
  5604. begin
  5605. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5606. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5607. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5608. RemoveCurrentP(p, hp1)
  5609. else
  5610. RemoveCurrentP(p);
  5611. result:=true;
  5612. Exit;
  5613. end;
  5614. end;
  5615. if (
  5616. { Save calling GetNextInstructionUsingReg again }
  5617. Assigned(hp1) or
  5618. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5619. ) and
  5620. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5621. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5622. begin
  5623. if taicpu(hp1).oper[0]^.typ = top_const then
  5624. begin
  5625. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5626. if taicpu(hp1).opcode = A_ADD then
  5627. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5628. else
  5629. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5630. Result := True;
  5631. { Handle any overflows }
  5632. case taicpu(p).opsize of
  5633. S_B:
  5634. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5635. S_W:
  5636. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5637. S_L:
  5638. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5639. {$ifdef x86_64}
  5640. S_Q:
  5641. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5642. { Overflow; abort }
  5643. Result := False
  5644. else
  5645. taicpu(p).oper[0]^.val := ThisConst;
  5646. {$endif x86_64}
  5647. else
  5648. InternalError(2021102610);
  5649. end;
  5650. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5651. if Result then
  5652. begin
  5653. if (taicpu(p).oper[0]^.val < 0) and
  5654. (
  5655. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5656. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5657. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5658. ) then
  5659. begin
  5660. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5661. taicpu(p).opcode := A_SUB;
  5662. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5663. end
  5664. else
  5665. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5666. RemoveInstruction(hp1);
  5667. end;
  5668. end
  5669. else
  5670. begin
  5671. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5672. TransferUsedRegs(TmpUsedRegs);
  5673. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5674. hp2 := p;
  5675. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5676. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5677. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5678. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5679. begin
  5680. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5681. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5682. Asml.Remove(p);
  5683. Asml.InsertAfter(p, hp1);
  5684. p := hp1;
  5685. Result := True;
  5686. Exit;
  5687. end;
  5688. end;
  5689. end;
  5690. if DoArithCombineOpt(p) then
  5691. Result:=true;
  5692. end;
  5693. end;
  5694. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5695. var
  5696. hp1, hp2: tai;
  5697. ref: Integer;
  5698. saveref: treference;
  5699. offsetcalc: Int64;
  5700. TempReg: TRegister;
  5701. Multiple: TCGInt;
  5702. Adjacent, IntermediateRegDiscarded: Boolean;
  5703. begin
  5704. Result:=false;
  5705. { play save and throw an error if LEA uses a seg register prefix,
  5706. this is most likely an error somewhere else }
  5707. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5708. internalerror(2022022001);
  5709. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5710. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5711. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5712. (
  5713. { do not mess with leas accessing the stack pointer
  5714. unless it's a null operation }
  5715. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5716. (
  5717. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5718. (taicpu(p).oper[0]^.ref^.offset = 0)
  5719. )
  5720. ) and
  5721. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5722. begin
  5723. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5724. begin
  5725. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5726. begin
  5727. taicpu(p).opcode := A_MOV;
  5728. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5729. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5730. end
  5731. else
  5732. begin
  5733. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5734. RemoveCurrentP(p);
  5735. end;
  5736. Result:=true;
  5737. exit;
  5738. end
  5739. else if (
  5740. { continue to use lea to adjust the stack pointer,
  5741. it is the recommended way, but only if not optimizing for size }
  5742. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5743. (cs_opt_size in current_settings.optimizerswitches)
  5744. ) and
  5745. { If the flags register is in use, don't change the instruction
  5746. to an ADD otherwise this will scramble the flags. [Kit] }
  5747. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5748. ConvertLEA(taicpu(p)) then
  5749. begin
  5750. Result:=true;
  5751. exit;
  5752. end;
  5753. end;
  5754. { Don't optimise if the stack or frame pointer is the destination register }
  5755. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5756. Exit;
  5757. if GetNextInstruction(p,hp1) and
  5758. (hp1.typ=ait_instruction) then
  5759. begin
  5760. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5761. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5762. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5763. begin
  5764. TransferUsedRegs(TmpUsedRegs);
  5765. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5766. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5767. begin
  5768. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5769. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5770. RemoveInstruction(hp1);
  5771. result:=true;
  5772. exit;
  5773. end;
  5774. end;
  5775. { changes
  5776. lea <ref1>, reg1
  5777. <op> ...,<ref. with reg1>,...
  5778. to
  5779. <op> ...,<ref1>,... }
  5780. { find a reference which uses reg1 }
  5781. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  5782. ref:=0
  5783. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  5784. ref:=1
  5785. else
  5786. ref:=-1;
  5787. if (ref<>-1) and
  5788. { reg1 must be either the base or the index }
  5789. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5790. begin
  5791. { reg1 can be removed from the reference }
  5792. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5793. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5794. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5795. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5796. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5797. else
  5798. Internalerror(2019111201);
  5799. { check if the can insert all data of the lea into the second instruction }
  5800. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5801. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5802. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5803. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5804. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5805. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5806. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5807. {$ifdef x86_64}
  5808. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5809. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5810. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5811. )
  5812. {$endif x86_64}
  5813. then
  5814. begin
  5815. { reg1 might not used by the second instruction after it is remove from the reference }
  5816. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5817. begin
  5818. TransferUsedRegs(TmpUsedRegs);
  5819. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5820. { reg1 is not updated so it might not be used afterwards }
  5821. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5822. begin
  5823. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5824. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5825. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5826. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5827. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5828. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5829. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5830. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5831. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5832. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5833. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5834. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5835. RemoveCurrentP(p, hp1);
  5836. result:=true;
  5837. exit;
  5838. end
  5839. end;
  5840. end;
  5841. { recover }
  5842. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5843. end;
  5844. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5845. if Adjacent or
  5846. { Check further ahead (up to 2 instructions ahead for -O2) }
  5847. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5848. begin
  5849. { Check common LEA/LEA conditions }
  5850. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5851. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5852. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5853. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5854. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5855. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5856. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5857. (
  5858. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5859. calling it (since it calls GetNextInstruction) }
  5860. Adjacent or
  5861. (
  5862. (
  5863. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5864. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5865. ) and (
  5866. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5867. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5868. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5869. )
  5870. )
  5871. ) then
  5872. begin
  5873. TransferUsedRegs(TmpUsedRegs);
  5874. hp2 := p;
  5875. repeat
  5876. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5877. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5878. IntermediateRegDiscarded :=
  5879. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5880. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5881. { changes
  5882. lea offset1(regX,scale), reg1
  5883. lea offset2(reg1,reg1), reg2
  5884. to
  5885. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5886. and
  5887. lea offset1(regX,scale1), reg1
  5888. lea offset2(reg1,scale2), reg2
  5889. to
  5890. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5891. and
  5892. lea offset1(regX,scale1), reg1
  5893. lea offset2(reg3,reg1,scale2), reg2
  5894. to
  5895. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5896. ... so long as the final scale does not exceed 8
  5897. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5898. }
  5899. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5900. (
  5901. { Don't optimise if size is a concern and the intermediate register remains in use }
  5902. IntermediateRegDiscarded or
  5903. (
  5904. not (cs_opt_size in current_settings.optimizerswitches) and
  5905. { If the intermediate register is not discarded, it must not
  5906. appear in the first LEA's reference. (Fixes #41166) }
  5907. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5908. )
  5909. ) and
  5910. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5911. (
  5912. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5913. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5914. ) and (
  5915. (
  5916. { lea (reg1,scale2), reg2 variant }
  5917. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5918. (
  5919. Adjacent or
  5920. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5921. ) and
  5922. (
  5923. (
  5924. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5925. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5926. ) or (
  5927. { lea (regX,regX), reg1 variant }
  5928. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5929. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5930. )
  5931. )
  5932. ) or (
  5933. { lea (reg1,reg1), reg1 variant }
  5934. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5935. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5936. )
  5937. ) then
  5938. begin
  5939. { Make everything homogeneous to make calculations easier }
  5940. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5941. begin
  5942. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5943. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5944. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5945. else
  5946. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5947. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5948. end;
  5949. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5950. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5951. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5952. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5953. begin
  5954. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5955. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5956. begin
  5957. { Put the register to change in the index register }
  5958. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5959. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5960. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5961. end;
  5962. { Change lea (reg,reg) to lea(,reg,2) }
  5963. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5964. begin
  5965. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5966. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5967. end;
  5968. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5969. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5970. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5971. { Just to prevent miscalculations }
  5972. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5973. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5974. else
  5975. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5976. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5977. if IntermediateRegDiscarded then
  5978. begin
  5979. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5980. RemoveCurrentP(p);
  5981. end
  5982. else
  5983. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5984. result:=true;
  5985. exit;
  5986. end;
  5987. end;
  5988. { changes
  5989. lea offset1(regX), reg1
  5990. lea offset2(reg1), reg2
  5991. to
  5992. lea offset1+offset2(regX), reg2 }
  5993. if (
  5994. { Don't optimise if size is a concern and the intermediate register remains in use }
  5995. IntermediateRegDiscarded or
  5996. (
  5997. not (cs_opt_size in current_settings.optimizerswitches) and
  5998. { If the intermediate register is not discarded, it must not
  5999. appear in the first LEA's reference. (Fixes #41166) }
  6000. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6001. )
  6002. ) and
  6003. (
  6004. (
  6005. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6006. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6007. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6008. ) or (
  6009. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6010. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6011. (
  6012. (
  6013. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6014. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6015. ) or (
  6016. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6017. (
  6018. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6019. (
  6020. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6021. (
  6022. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6023. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6024. )
  6025. )
  6026. )
  6027. )
  6028. )
  6029. )
  6030. ) then
  6031. begin
  6032. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6033. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6034. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6035. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6036. begin
  6037. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6038. begin
  6039. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6040. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6041. { if the register is used as index and base, we have to increase for base as well
  6042. and adapt base }
  6043. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6044. begin
  6045. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6046. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6047. end;
  6048. end
  6049. else
  6050. begin
  6051. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6052. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6053. end;
  6054. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6055. begin
  6056. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6057. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6058. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6059. { Catch the situation where the base = index
  6060. and treat this as *2. The scalefactor of
  6061. p will be 0 or 1 due to the conditional
  6062. checks above. Fixes i40647 }
  6063. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6064. else
  6065. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6066. end;
  6067. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6068. if IntermediateRegDiscarded then
  6069. begin
  6070. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6071. RemoveCurrentP(p);
  6072. end
  6073. else
  6074. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6075. result:=true;
  6076. exit;
  6077. end;
  6078. end;
  6079. end;
  6080. { Change:
  6081. leal/q $x(%reg1),%reg2
  6082. ...
  6083. shll/q $y,%reg2
  6084. To:
  6085. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6086. }
  6087. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6088. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6089. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6090. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6091. (taicpu(hp1).oper[0]^.val <= 3) then
  6092. begin
  6093. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6094. TransferUsedRegs(TmpUsedRegs);
  6095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6096. if
  6097. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6098. (this works even if scalefactor is zero) }
  6099. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6100. { Ensure offset doesn't go out of bounds }
  6101. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6102. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6103. (
  6104. (
  6105. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6106. (
  6107. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6108. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6109. (
  6110. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6111. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6112. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6113. )
  6114. )
  6115. ) or (
  6116. (
  6117. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6118. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6119. ) and
  6120. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6121. )
  6122. ) then
  6123. begin
  6124. repeat
  6125. with taicpu(p).oper[0]^.ref^ do
  6126. begin
  6127. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6128. if index = base then
  6129. begin
  6130. if Multiple > 4 then
  6131. { Optimisation will no longer work because resultant
  6132. scale factor will exceed 8 }
  6133. Break;
  6134. base := NR_NO;
  6135. scalefactor := 2;
  6136. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6137. end
  6138. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6139. begin
  6140. { Scale factor only works on the index register }
  6141. index := base;
  6142. base := NR_NO;
  6143. end;
  6144. { For safety }
  6145. if scalefactor <= 1 then
  6146. begin
  6147. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6148. scalefactor := Multiple;
  6149. end
  6150. else
  6151. begin
  6152. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6153. scalefactor := scalefactor * Multiple;
  6154. end;
  6155. offset := offset * Multiple;
  6156. end;
  6157. RemoveInstruction(hp1);
  6158. Result := True;
  6159. Exit;
  6160. { This repeat..until loop exists for the benefit of Break }
  6161. until True;
  6162. end;
  6163. end;
  6164. end;
  6165. end;
  6166. end;
  6167. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6168. var
  6169. hp1 : tai;
  6170. SubInstr: Boolean;
  6171. ThisConst: TCGInt;
  6172. const
  6173. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6174. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6175. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6176. begin
  6177. Result := False;
  6178. if taicpu(p).oper[0]^.typ <> top_const then
  6179. { Should have been confirmed before calling }
  6180. InternalError(2021102601);
  6181. SubInstr := (taicpu(p).opcode = A_SUB);
  6182. if GetLastInstruction(p, hp1) and
  6183. (hp1.typ = ait_instruction) and
  6184. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6185. begin
  6186. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6187. { Bad size }
  6188. InternalError(2022042001);
  6189. case taicpu(hp1).opcode Of
  6190. A_INC:
  6191. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6192. begin
  6193. if SubInstr then
  6194. ThisConst := taicpu(p).oper[0]^.val - 1
  6195. else
  6196. ThisConst := taicpu(p).oper[0]^.val + 1;
  6197. end
  6198. else
  6199. Exit;
  6200. A_DEC:
  6201. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6202. begin
  6203. if SubInstr then
  6204. ThisConst := taicpu(p).oper[0]^.val + 1
  6205. else
  6206. ThisConst := taicpu(p).oper[0]^.val - 1;
  6207. end
  6208. else
  6209. Exit;
  6210. A_SUB:
  6211. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6212. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6213. begin
  6214. if SubInstr then
  6215. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6216. else
  6217. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6218. end
  6219. else
  6220. Exit;
  6221. A_ADD:
  6222. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6223. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6224. begin
  6225. if SubInstr then
  6226. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6227. else
  6228. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6229. end
  6230. else
  6231. Exit;
  6232. else
  6233. Exit;
  6234. end;
  6235. { Check that the values are in range }
  6236. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6237. { Overflow; abort }
  6238. Exit;
  6239. if (ThisConst = 0) then
  6240. begin
  6241. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6242. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6243. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6244. RemoveInstruction(hp1);
  6245. hp1 := tai(p.next);
  6246. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6247. if not GetLastInstruction(hp1, p) then
  6248. p := hp1;
  6249. end
  6250. else
  6251. begin
  6252. if taicpu(hp1).opercnt=1 then
  6253. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6254. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6255. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6256. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6257. else
  6258. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6259. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6260. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6261. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6262. RemoveInstruction(hp1);
  6263. taicpu(p).loadconst(0, ThisConst);
  6264. end;
  6265. Result := True;
  6266. end;
  6267. end;
  6268. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6269. begin
  6270. Result := False;
  6271. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6272. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6273. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6274. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6275. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6276. (
  6277. (
  6278. (taicpu(hp1).opcode = A_TEST)
  6279. ) or (
  6280. (taicpu(hp1).opcode = A_CMP) and
  6281. { A sanity check more than anything }
  6282. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6283. )
  6284. ) then
  6285. begin
  6286. { change
  6287. mov mem, %reg
  6288. ...
  6289. cmp/test x, %reg / test %reg,%reg
  6290. (reg deallocated)
  6291. to
  6292. cmp/test x, mem / cmp 0, mem
  6293. }
  6294. TransferUsedRegs(TmpUsedRegs);
  6295. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6296. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6297. begin
  6298. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6299. if (taicpu(hp1).opcode = A_TEST) and
  6300. (
  6301. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6302. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6303. ) then
  6304. begin
  6305. taicpu(hp1).opcode := A_CMP;
  6306. taicpu(hp1).loadconst(0, 0);
  6307. end;
  6308. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6309. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6310. RemoveCurrentP(p);
  6311. if (p <> hp1) then
  6312. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6313. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6314. { Make sure the flags are allocated across the CMP instruction }
  6315. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6316. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6317. Result := True;
  6318. Exit;
  6319. end;
  6320. end;
  6321. end;
  6322. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6323. var
  6324. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6325. ThisReg, SecondReg: TRegister;
  6326. JumpLoc: TAsmLabel;
  6327. NewSize: TOpSize;
  6328. begin
  6329. Result := False;
  6330. {
  6331. Convert:
  6332. j<c> .L1
  6333. .L2:
  6334. mov 1,reg
  6335. jmp .L3 (or ret, although it might not be a RET yet)
  6336. .L1:
  6337. mov 0,reg
  6338. jmp .L3 (or ret)
  6339. ( As long as .L3 <> .L1 or .L2)
  6340. To:
  6341. mov 0,reg
  6342. set<not(c)> reg
  6343. jmp .L3 (or ret)
  6344. .L2:
  6345. mov 1,reg
  6346. jmp .L3 (or ret)
  6347. .L1:
  6348. mov 0,reg
  6349. jmp .L3 (or ret)
  6350. }
  6351. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6352. Exit;
  6353. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6354. if GetNextInstruction(hp_label, hp2) and
  6355. MatchInstruction(hp2,A_MOV,[]) and
  6356. (taicpu(hp2).oper[0]^.typ = top_const) and
  6357. (
  6358. (
  6359. (taicpu(hp2).oper[1]^.typ = top_reg)
  6360. {$ifdef i386}
  6361. { Under i386, ESI, EDI, EBP and ESP
  6362. don't have an 8-bit representation }
  6363. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6364. {$endif i386}
  6365. ) or (
  6366. {$ifdef i386}
  6367. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6368. {$endif i386}
  6369. (taicpu(hp2).opsize = S_B)
  6370. )
  6371. ) and
  6372. GetNextInstruction(hp2, hp3) and
  6373. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6374. (
  6375. (taicpu(hp3).opcode=A_RET) or
  6376. (
  6377. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6378. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6379. )
  6380. ) and
  6381. GetNextInstruction(hp3, hp4) and
  6382. FindLabel(JumpLoc, hp4) and
  6383. (
  6384. not (cs_opt_size in current_settings.optimizerswitches) or
  6385. { If the initial jump is the label's only reference, then it will
  6386. become a dead label if the other conditions are met and hence
  6387. remove at least 2 instructions, including a jump }
  6388. (JumpLoc.getrefs = 1)
  6389. ) and
  6390. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6391. that will be optimised out }
  6392. GetNextInstruction(hp4, hp5) and
  6393. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6394. (taicpu(hp5).oper[0]^.typ = top_const) and
  6395. (
  6396. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6397. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6398. ) and
  6399. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6400. GetNextInstruction(hp5,hp6) and
  6401. (
  6402. not (hp6.typ in [ait_align, ait_label]) or
  6403. SkipLabels(hp6, hp6)
  6404. ) and
  6405. (hp6.typ=ait_instruction) then
  6406. begin
  6407. { First, let's look at the two jumps that are hp3 and hp6 }
  6408. if not
  6409. (
  6410. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6411. (
  6412. (taicpu(hp6).opcode=A_RET) or
  6413. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6414. )
  6415. ) then
  6416. { If condition is False, then the JMP/RET instructions matched conventionally }
  6417. begin
  6418. { See if one of the jumps can be instantly converted into a RET }
  6419. if (taicpu(hp3).opcode=A_JMP) then
  6420. begin
  6421. { Reuse hp5 }
  6422. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6423. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6424. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6425. Exit;
  6426. if MatchInstruction(hp5, A_RET, []) then
  6427. begin
  6428. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6429. ConvertJumpToRET(hp3, hp5);
  6430. Result := True;
  6431. end
  6432. else
  6433. Exit;
  6434. end;
  6435. if (taicpu(hp6).opcode=A_JMP) then
  6436. begin
  6437. { Reuse hp5 }
  6438. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6439. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6440. Exit;
  6441. if MatchInstruction(hp5, A_RET, []) then
  6442. begin
  6443. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6444. ConvertJumpToRET(hp6, hp5);
  6445. Result := True;
  6446. end
  6447. else
  6448. Exit;
  6449. end;
  6450. if not
  6451. (
  6452. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6453. (
  6454. (taicpu(hp6).opcode=A_RET) or
  6455. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6456. )
  6457. ) then
  6458. { Still doesn't match }
  6459. Exit;
  6460. end;
  6461. if (taicpu(hp2).oper[0]^.val = 1) then
  6462. begin
  6463. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6464. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6465. end
  6466. else
  6467. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6468. if taicpu(hp2).opsize=S_B then
  6469. begin
  6470. if taicpu(hp2).oper[1]^.typ = top_reg then
  6471. begin
  6472. SecondReg := taicpu(hp2).oper[1]^.reg;
  6473. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6474. end
  6475. else
  6476. begin
  6477. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6478. SecondReg := NR_NO;
  6479. end;
  6480. hp_pos := p;
  6481. hp_allocstart := hp4;
  6482. end
  6483. else
  6484. begin
  6485. { Will be a register because the size can't be S_B otherwise }
  6486. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6487. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6488. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6489. if (cs_opt_size in current_settings.optimizerswitches) then
  6490. begin
  6491. { Favour using MOVZX when optimising for size }
  6492. case taicpu(hp2).opsize of
  6493. S_W:
  6494. NewSize := S_BW;
  6495. S_L:
  6496. NewSize := S_BL;
  6497. {$ifdef x86_64}
  6498. S_Q:
  6499. begin
  6500. NewSize := S_BL;
  6501. { Will implicitly zero-extend to 64-bit }
  6502. setsubreg(SecondReg, R_SUBD);
  6503. end;
  6504. {$endif x86_64}
  6505. else
  6506. InternalError(2022101301);
  6507. end;
  6508. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6509. { Inserting it right before p will guarantee that the flags are also tracked }
  6510. Asml.InsertBefore(hp5, p);
  6511. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6512. hp_pos := hp5;
  6513. hp_allocstart := hp4;
  6514. end
  6515. else
  6516. begin
  6517. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6518. { Inserting it right before p will guarantee that the flags are also tracked }
  6519. Asml.InsertBefore(hp5, p);
  6520. hp_pos := p;
  6521. hp_allocstart := hp5;
  6522. end;
  6523. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6524. end;
  6525. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6526. taicpu(hp4).condition := taicpu(p).condition;
  6527. asml.InsertBefore(hp4, hp_pos);
  6528. if taicpu(hp3).is_jmp then
  6529. begin
  6530. JumpLoc.decrefs;
  6531. MakeUnconditional(taicpu(p));
  6532. { This also increases the reference count }
  6533. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6534. end
  6535. else
  6536. ConvertJumpToRET(p, hp3);
  6537. if SecondReg <> NR_NO then
  6538. { Ensure the destination register is allocated over this region }
  6539. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6540. if (JumpLoc.getrefs = 0) then
  6541. RemoveDeadCodeAfterJump(hp3);
  6542. Result:=true;
  6543. exit;
  6544. end;
  6545. end;
  6546. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6547. var
  6548. hp1, hp2: tai;
  6549. ActiveReg: TRegister;
  6550. OldOffset: asizeint;
  6551. ThisConst: TCGInt;
  6552. function RegDeallocated: Boolean;
  6553. begin
  6554. TransferUsedRegs(TmpUsedRegs);
  6555. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6556. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6557. end;
  6558. begin
  6559. Result:=false;
  6560. hp1 := nil;
  6561. { replace
  6562. subX const,%reg1
  6563. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6564. dealloc %reg1
  6565. by
  6566. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6567. }
  6568. if MatchOpType(taicpu(p),top_const,top_reg) then
  6569. begin
  6570. ActiveReg := taicpu(p).oper[1]^.reg;
  6571. { Ensures the entire register was updated }
  6572. if (taicpu(p).opsize >= S_L) and
  6573. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6574. MatchInstruction(hp1,A_LEA,[]) and
  6575. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6576. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6577. (
  6578. { Cover the case where the register in the reference is also the destination register }
  6579. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6580. (
  6581. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6582. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6583. RegDeallocated
  6584. )
  6585. ) then
  6586. begin
  6587. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6588. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6589. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6590. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6591. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6592. {$ifdef x86_64}
  6593. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6594. begin
  6595. { Overflow; abort }
  6596. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6597. end
  6598. else
  6599. {$endif x86_64}
  6600. begin
  6601. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6602. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6603. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6604. RemoveCurrentP(p, hp1)
  6605. else
  6606. RemoveCurrentP(p);
  6607. result:=true;
  6608. Exit;
  6609. end;
  6610. end;
  6611. if (
  6612. { Save calling GetNextInstructionUsingReg again }
  6613. Assigned(hp1) or
  6614. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6615. ) and
  6616. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6617. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6618. begin
  6619. if taicpu(hp1).oper[0]^.typ = top_const then
  6620. begin
  6621. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6622. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6623. Result := True;
  6624. { Handle any overflows }
  6625. case taicpu(p).opsize of
  6626. S_B:
  6627. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6628. S_W:
  6629. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6630. S_L:
  6631. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6632. {$ifdef x86_64}
  6633. S_Q:
  6634. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6635. { Overflow; abort }
  6636. Result := False
  6637. else
  6638. taicpu(p).oper[0]^.val := ThisConst;
  6639. {$endif x86_64}
  6640. else
  6641. InternalError(2021102611);
  6642. end;
  6643. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6644. if Result then
  6645. begin
  6646. if (taicpu(p).oper[0]^.val < 0) and
  6647. (
  6648. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6649. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6650. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6651. ) then
  6652. begin
  6653. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6654. taicpu(p).opcode := A_SUB;
  6655. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6656. end
  6657. else
  6658. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6659. RemoveInstruction(hp1);
  6660. end;
  6661. end
  6662. else
  6663. begin
  6664. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6665. TransferUsedRegs(TmpUsedRegs);
  6666. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6667. hp2 := p;
  6668. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6669. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6670. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6671. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6672. begin
  6673. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6674. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6675. Asml.Remove(p);
  6676. Asml.InsertAfter(p, hp1);
  6677. p := hp1;
  6678. Result := True;
  6679. Exit;
  6680. end;
  6681. end;
  6682. end;
  6683. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6684. { * change "sub/add const1, reg" or "dec reg" followed by
  6685. "sub const2, reg" to one "sub ..., reg" }
  6686. {$ifdef i386}
  6687. if (taicpu(p).oper[0]^.val = 2) and
  6688. (ActiveReg = NR_ESP) and
  6689. { Don't do the sub/push optimization if the sub }
  6690. { comes from setting up the stack frame (JM) }
  6691. (not(GetLastInstruction(p,hp1)) or
  6692. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6693. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6694. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6695. begin
  6696. hp1 := tai(p.next);
  6697. while Assigned(hp1) and
  6698. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6699. not RegReadByInstruction(NR_ESP,hp1) and
  6700. not RegModifiedByInstruction(NR_ESP,hp1) do
  6701. hp1 := tai(hp1.next);
  6702. if Assigned(hp1) and
  6703. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6704. begin
  6705. taicpu(hp1).changeopsize(S_L);
  6706. if taicpu(hp1).oper[0]^.typ=top_reg then
  6707. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6708. hp1 := tai(p.next);
  6709. RemoveCurrentp(p, hp1);
  6710. Result:=true;
  6711. exit;
  6712. end;
  6713. end;
  6714. {$endif i386}
  6715. if DoArithCombineOpt(p) then
  6716. Result:=true;
  6717. end;
  6718. end;
  6719. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6720. var
  6721. TmpBool1,TmpBool2 : Boolean;
  6722. tmpref : treference;
  6723. hp1,hp2: tai;
  6724. mask, shiftval: tcgint;
  6725. begin
  6726. Result:=false;
  6727. { All these optimisations work on "shl/sal const,%reg" }
  6728. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6729. Exit;
  6730. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6731. (taicpu(p).oper[0]^.val <= 3) then
  6732. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6733. begin
  6734. { should we check the next instruction? }
  6735. TmpBool1 := True;
  6736. { have we found an add/sub which could be
  6737. integrated in the lea? }
  6738. TmpBool2 := False;
  6739. reference_reset(tmpref,2,[]);
  6740. TmpRef.index := taicpu(p).oper[1]^.reg;
  6741. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6742. while TmpBool1 and
  6743. GetNextInstruction(p, hp1) and
  6744. (tai(hp1).typ = ait_instruction) and
  6745. ((((taicpu(hp1).opcode = A_ADD) or
  6746. (taicpu(hp1).opcode = A_SUB)) and
  6747. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6748. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6749. (((taicpu(hp1).opcode = A_INC) or
  6750. (taicpu(hp1).opcode = A_DEC)) and
  6751. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6752. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6753. ((taicpu(hp1).opcode = A_LEA) and
  6754. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6755. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6756. (not GetNextInstruction(hp1,hp2) or
  6757. not instrReadsFlags(hp2)) Do
  6758. begin
  6759. TmpBool1 := False;
  6760. if taicpu(hp1).opcode=A_LEA then
  6761. begin
  6762. if (TmpRef.base = NR_NO) and
  6763. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6764. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6765. { Segment register isn't a concern here }
  6766. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6767. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6768. begin
  6769. TmpBool1 := True;
  6770. TmpBool2 := True;
  6771. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6772. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6773. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6774. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6775. RemoveInstruction(hp1);
  6776. end
  6777. end
  6778. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6779. begin
  6780. TmpBool1 := True;
  6781. TmpBool2 := True;
  6782. case taicpu(hp1).opcode of
  6783. A_ADD:
  6784. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6785. A_SUB:
  6786. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6787. else
  6788. internalerror(2019050536);
  6789. end;
  6790. RemoveInstruction(hp1);
  6791. end
  6792. else
  6793. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6794. (((taicpu(hp1).opcode = A_ADD) and
  6795. (TmpRef.base = NR_NO)) or
  6796. (taicpu(hp1).opcode = A_INC) or
  6797. (taicpu(hp1).opcode = A_DEC)) then
  6798. begin
  6799. TmpBool1 := True;
  6800. TmpBool2 := True;
  6801. case taicpu(hp1).opcode of
  6802. A_ADD:
  6803. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6804. A_INC:
  6805. inc(TmpRef.offset);
  6806. A_DEC:
  6807. dec(TmpRef.offset);
  6808. else
  6809. internalerror(2019050535);
  6810. end;
  6811. RemoveInstruction(hp1);
  6812. end;
  6813. end;
  6814. if TmpBool2
  6815. {$ifndef x86_64}
  6816. or
  6817. ((current_settings.optimizecputype < cpu_Pentium2) and
  6818. (taicpu(p).oper[0]^.val <= 3) and
  6819. not(cs_opt_size in current_settings.optimizerswitches))
  6820. {$endif x86_64}
  6821. then
  6822. begin
  6823. if not(TmpBool2) and
  6824. (taicpu(p).oper[0]^.val=1) then
  6825. begin
  6826. taicpu(p).opcode := A_ADD;
  6827. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6828. end
  6829. else
  6830. begin
  6831. taicpu(p).opcode := A_LEA;
  6832. taicpu(p).loadref(0, TmpRef);
  6833. end;
  6834. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6835. Result := True;
  6836. end;
  6837. end
  6838. {$ifndef x86_64}
  6839. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6840. begin
  6841. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6842. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6843. (unlike shl, which is only Tairable in the U pipe) }
  6844. if taicpu(p).oper[0]^.val=1 then
  6845. begin
  6846. taicpu(p).opcode := A_ADD;
  6847. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6848. Result := True;
  6849. end
  6850. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6851. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6852. else if (taicpu(p).opsize = S_L) and
  6853. (taicpu(p).oper[0]^.val<= 3) then
  6854. begin
  6855. reference_reset(tmpref,2,[]);
  6856. TmpRef.index := taicpu(p).oper[1]^.reg;
  6857. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6858. taicpu(p).opcode := A_LEA;
  6859. taicpu(p).loadref(0, TmpRef);
  6860. Result := True;
  6861. end;
  6862. end
  6863. {$endif x86_64}
  6864. else if
  6865. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6866. (
  6867. (
  6868. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6869. SetAndTest(hp1, hp2)
  6870. {$ifdef x86_64}
  6871. ) or
  6872. (
  6873. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6874. GetNextInstruction(hp1, hp2) and
  6875. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6876. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6877. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6878. {$endif x86_64}
  6879. )
  6880. ) and
  6881. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6882. begin
  6883. { Change:
  6884. shl x, %reg1
  6885. mov -(1<<x), %reg2
  6886. and %reg2, %reg1
  6887. Or:
  6888. shl x, %reg1
  6889. and -(1<<x), %reg1
  6890. To just:
  6891. shl x, %reg1
  6892. Since the and operation only zeroes bits that are already zero from the shl operation
  6893. }
  6894. case taicpu(p).oper[0]^.val of
  6895. 8:
  6896. mask:=$FFFFFFFFFFFFFF00;
  6897. 16:
  6898. mask:=$FFFFFFFFFFFF0000;
  6899. 32:
  6900. mask:=$FFFFFFFF00000000;
  6901. 63:
  6902. { Constant pre-calculated to prevent overflow errors with Int64 }
  6903. mask:=$8000000000000000;
  6904. else
  6905. begin
  6906. if taicpu(p).oper[0]^.val >= 64 then
  6907. { Shouldn't happen realistically, since the register
  6908. is guaranteed to be set to zero at this point }
  6909. mask := 0
  6910. else
  6911. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6912. end;
  6913. end;
  6914. if taicpu(hp1).oper[0]^.val = mask then
  6915. begin
  6916. { Everything checks out, perform the optimisation, as long as
  6917. the FLAGS register isn't being used}
  6918. TransferUsedRegs(TmpUsedRegs);
  6919. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6920. {$ifdef x86_64}
  6921. if (hp1 <> hp2) then
  6922. begin
  6923. { "shl/mov/and" version }
  6924. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6925. { Don't do the optimisation if the FLAGS register is in use }
  6926. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6927. begin
  6928. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6929. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6930. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6931. begin
  6932. RemoveInstruction(hp1);
  6933. Result := True;
  6934. end;
  6935. { Only set Result to True if the 'mov' instruction was removed }
  6936. RemoveInstruction(hp2);
  6937. end;
  6938. end
  6939. else
  6940. {$endif x86_64}
  6941. begin
  6942. { "shl/and" version }
  6943. { Don't do the optimisation if the FLAGS register is in use }
  6944. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6945. begin
  6946. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6947. RemoveInstruction(hp1);
  6948. Result := True;
  6949. end;
  6950. end;
  6951. Exit;
  6952. end
  6953. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6954. begin
  6955. { Even if the mask doesn't allow for its removal, we might be
  6956. able to optimise the mask for the "shl/and" version, which
  6957. may permit other peephole optimisations }
  6958. {$ifdef DEBUG_AOPTCPU}
  6959. mask := taicpu(hp1).oper[0]^.val and mask;
  6960. if taicpu(hp1).oper[0]^.val <> mask then
  6961. begin
  6962. DebugMsg(
  6963. SPeepholeOptimization +
  6964. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6965. ' to $' + debug_tostr(mask) +
  6966. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6967. taicpu(hp1).oper[0]^.val := mask;
  6968. end;
  6969. {$else DEBUG_AOPTCPU}
  6970. { If debugging is off, just set the operand even if it's the same }
  6971. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6972. {$endif DEBUG_AOPTCPU}
  6973. end;
  6974. end;
  6975. {
  6976. change
  6977. shl/sal const,reg
  6978. <op> ...(...,reg,1),...
  6979. into
  6980. <op> ...(...,reg,1 shl const),...
  6981. if const in 1..3
  6982. }
  6983. if MatchOpType(taicpu(p), top_const, top_reg) and
  6984. (taicpu(p).oper[0]^.val in [1..3]) and
  6985. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6986. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6987. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6988. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6989. MatchOpType(taicpu(hp1),top_ref))
  6990. ) and
  6991. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6992. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6993. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6994. begin
  6995. TransferUsedRegs(TmpUsedRegs);
  6996. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6997. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6998. begin
  6999. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7000. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7001. RemoveCurrentP(p);
  7002. Result:=true;
  7003. exit;
  7004. end;
  7005. end;
  7006. if MatchOpType(taicpu(p), top_const, top_reg) and
  7007. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7008. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7009. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7010. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7011. begin
  7012. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7013. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7014. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7015. {$ifdef x86_64}
  7016. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7017. {$endif x86_64}
  7018. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7019. begin
  7020. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7021. taicpu(hp1).opcode:=A_MOV;
  7022. taicpu(hp1).oper[0]^.val:=0;
  7023. end
  7024. else
  7025. begin
  7026. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7027. taicpu(hp1).oper[0]^.val:=shiftval;
  7028. end;
  7029. RemoveCurrentP(p);
  7030. Result:=true;
  7031. exit;
  7032. end;
  7033. end;
  7034. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7035. begin
  7036. case shr_size of
  7037. S_B:
  7038. { No valid combinations }
  7039. Result := False;
  7040. S_W:
  7041. Result := (Shift >= 8) and (movz_size = S_BW);
  7042. S_L:
  7043. Result :=
  7044. (Shift >= 24) { Any opsize is valid for this shift } or
  7045. ((Shift >= 16) and (movz_size = S_WL));
  7046. {$ifdef x86_64}
  7047. S_Q:
  7048. Result :=
  7049. (Shift >= 56) { Any opsize is valid for this shift } or
  7050. ((Shift >= 48) and (movz_size = S_WL));
  7051. {$endif x86_64}
  7052. else
  7053. InternalError(2022081510);
  7054. end;
  7055. end;
  7056. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7057. var
  7058. hp1, hp2: tai;
  7059. IdentityMask, Shift: TCGInt;
  7060. LimitSize: Topsize;
  7061. DoNotMerge: Boolean;
  7062. begin
  7063. if not MatchInstruction(p, A_SHR, []) then
  7064. InternalError(2025040301);
  7065. Result := False;
  7066. DoNotMerge := False;
  7067. Shift := taicpu(p).oper[0]^.val;
  7068. LimitSize := taicpu(p).opsize;
  7069. hp1 := p;
  7070. repeat
  7071. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7072. Exit;
  7073. case taicpu(hp1).opcode of
  7074. A_AND:
  7075. { Detect:
  7076. shr x, %reg
  7077. and y, %reg
  7078. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7079. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7080. (Post-peephole only)
  7081. }
  7082. if PostPeephole and
  7083. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7084. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7085. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7086. begin
  7087. { Make sure the FLAGS register isn't in use }
  7088. TransferUsedRegs(TmpUsedRegs);
  7089. hp2 := p;
  7090. repeat
  7091. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7092. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7093. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7094. begin
  7095. { Generate the identity mask }
  7096. case taicpu(p).opsize of
  7097. S_B:
  7098. IdentityMask := $FF shr Shift;
  7099. S_W:
  7100. IdentityMask := $FFFF shr Shift;
  7101. S_L:
  7102. IdentityMask := $FFFFFFFF shr Shift;
  7103. {$ifdef x86_64}
  7104. S_Q:
  7105. { We need to force the operands to be unsigned 64-bit
  7106. integers otherwise the wrong value is generated }
  7107. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7108. {$endif x86_64}
  7109. else
  7110. InternalError(2022081501);
  7111. end;
  7112. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7113. begin
  7114. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7115. { All the possible 1 bits are covered, so we can remove the AND }
  7116. hp2 := tai(hp1.Previous);
  7117. RemoveInstruction(hp1);
  7118. { p wasn't actually changed, so don't set Result to True,
  7119. but a change was nonetheless made elsewhere }
  7120. Include(OptsToCheck, aoc_ForceNewIteration);
  7121. { Do another pass in case other AND or MOVZX instructions
  7122. follow }
  7123. hp1 := hp2;
  7124. Continue;
  7125. end;
  7126. end;
  7127. end;
  7128. A_TEST, A_CMP:
  7129. { Skip over relevant comparisons, but shift instructions must
  7130. now not be merged since the original value is being read }
  7131. begin
  7132. DoNotMerge := True;
  7133. Continue;
  7134. end;
  7135. A_Jcc:
  7136. { Skip over conditional jumps and relevant comparisons }
  7137. Continue;
  7138. A_MOVZX:
  7139. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7140. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7141. begin
  7142. { Since the original register is being read as is, subsequent
  7143. SHRs must not be merged at this point }
  7144. DoNotMerge := True;
  7145. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7146. begin
  7147. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7148. begin
  7149. { If the MOVZX instruction reads and writes the same register,
  7150. defer this to the post-peephole optimisation stage }
  7151. if PostPeephole then
  7152. begin
  7153. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7154. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7155. hp2 := tai(hp1.Previous);
  7156. RemoveInstruction(hp1);
  7157. hp1 := hp2;
  7158. end;
  7159. end
  7160. else { Different register target }
  7161. begin
  7162. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7163. taicpu(hp1).opcode := A_MOV;
  7164. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7165. case taicpu(hp1).opsize of
  7166. S_BW:
  7167. taicpu(hp1).opsize := S_W;
  7168. S_BL, S_WL:
  7169. taicpu(hp1).opsize := S_L;
  7170. else
  7171. InternalError(2022081503);
  7172. end;
  7173. { p itself hasn't changed, so no need to set Result to True }
  7174. Include(OptsToCheck, aoc_ForceNewIteration);
  7175. { See if there's anything afterwards that can be
  7176. optimised, since the input register hasn't changed }
  7177. Continue;
  7178. end;
  7179. Exit;
  7180. end
  7181. else if PostPeephole and
  7182. (Shift > 0) and
  7183. (taicpu(p).opsize = S_W) and
  7184. (taicpu(hp1).opsize = S_WL) and
  7185. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7186. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7187. begin
  7188. { Detect:
  7189. shr x, %ax (x > 0)
  7190. ...
  7191. movzwl %ax,%eax
  7192. -
  7193. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7194. But first, check to see if movzwl %ax,%eax can be removed...
  7195. }
  7196. hp2 := tai(hp1.Previous);
  7197. TransferUsedRegs(TmpUsedRegs);
  7198. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7199. if PostPeepholeOptMovZX(hp1) then
  7200. hp1 := hp2
  7201. else
  7202. begin
  7203. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7204. taicpu(hp1).opcode := A_CWDE;
  7205. taicpu(hp1).clearop(0);
  7206. taicpu(hp1).clearop(1);
  7207. taicpu(hp1).ops := 0;
  7208. end;
  7209. RestoreUsedRegs(TmpUsedRegs);
  7210. { Don't need to set aoc_ForceNewIteration if
  7211. PostPeepholeOptMovZX returned True because it's the
  7212. post-peephole stage }
  7213. end;
  7214. { Move onto the next instruction }
  7215. Continue;
  7216. end;
  7217. A_SHL, A_SAL, A_SHR:
  7218. if (taicpu(hp1).opsize <= LimitSize) and
  7219. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7220. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7221. begin
  7222. { Make sure the sizes don't exceed the register size limit
  7223. (measured by the shift value falling below the limit) }
  7224. if taicpu(hp1).opsize < LimitSize then
  7225. LimitSize := taicpu(hp1).opsize;
  7226. if taicpu(hp1).opcode = A_SHR then
  7227. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7228. else
  7229. begin
  7230. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7231. DoNotMerge := True;
  7232. end;
  7233. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7234. Exit;
  7235. { Since we've established that the combined shift is within
  7236. limits, we can actually combine the adjacent SHR
  7237. instructions even if they're different sizes }
  7238. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7239. begin
  7240. hp2 := tai(hp1.Previous);
  7241. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7242. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7243. RemoveInstruction(hp1);
  7244. hp1 := hp2;
  7245. { Though p has changed, only the constant has, and its
  7246. effects can still be detected on the next iteration of
  7247. the repeat..until loop }
  7248. Include(OptsToCheck, aoc_ForceNewIteration);
  7249. end;
  7250. { Move onto the next instruction }
  7251. Continue;
  7252. end;
  7253. else
  7254. ;
  7255. end;
  7256. { If the register isn't actually modified, move onto the next instruction,
  7257. but set DoNotMerge to True since the register is being read }
  7258. if (
  7259. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7260. the next instruction, whether or not it contains the register }
  7261. (cs_opt_level3 in current_settings.optimizerswitches) or
  7262. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7263. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7264. begin
  7265. DoNotMerge := True;
  7266. Continue;
  7267. end;
  7268. Break;
  7269. until False;
  7270. end;
  7271. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7272. begin
  7273. Result := False;
  7274. { All these optimisations work on "shr const,%reg" }
  7275. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7276. Exit;
  7277. Result := HandleSHRMerge(p, False);
  7278. end;
  7279. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7280. var
  7281. CurrentRef: TReference;
  7282. FullReg: TRegister;
  7283. hp1, hp2: tai;
  7284. begin
  7285. Result := False;
  7286. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7287. Exit;
  7288. { We assume you've checked if the operand is actually a reference by
  7289. this point. If it isn't, you'll most likely get an access violation }
  7290. CurrentRef := first_mov.oper[1]^.ref^;
  7291. { Memory must be aligned }
  7292. if (CurrentRef.offset mod 4) <> 0 then
  7293. Exit;
  7294. Inc(CurrentRef.offset);
  7295. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7296. if MatchOperand(second_mov.oper[0]^, 0) and
  7297. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7298. GetNextInstruction(second_mov, hp1) and
  7299. (hp1.typ = ait_instruction) and
  7300. (taicpu(hp1).opcode = A_MOV) and
  7301. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7302. (taicpu(hp1).oper[0]^.val = 0) then
  7303. begin
  7304. Inc(CurrentRef.offset);
  7305. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7306. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7307. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7308. begin
  7309. case taicpu(hp1).opsize of
  7310. S_B:
  7311. if GetNextInstruction(hp1, hp2) and
  7312. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7313. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7314. (taicpu(hp2).oper[0]^.val = 0) then
  7315. begin
  7316. Inc(CurrentRef.offset);
  7317. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7318. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7319. (taicpu(hp2).opsize = S_B) then
  7320. begin
  7321. RemoveInstruction(hp1);
  7322. RemoveInstruction(hp2);
  7323. first_mov.opsize := S_L;
  7324. if first_mov.oper[0]^.typ = top_reg then
  7325. begin
  7326. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7327. { Reuse second_mov as a MOVZX instruction }
  7328. second_mov.opcode := A_MOVZX;
  7329. second_mov.opsize := S_BL;
  7330. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7331. second_mov.loadreg(1, FullReg);
  7332. first_mov.oper[0]^.reg := FullReg;
  7333. asml.Remove(second_mov);
  7334. asml.InsertBefore(second_mov, first_mov);
  7335. end
  7336. else
  7337. { It's a value }
  7338. begin
  7339. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7340. RemoveInstruction(second_mov);
  7341. end;
  7342. Result := True;
  7343. Exit;
  7344. end;
  7345. end;
  7346. S_W:
  7347. begin
  7348. RemoveInstruction(hp1);
  7349. first_mov.opsize := S_L;
  7350. if first_mov.oper[0]^.typ = top_reg then
  7351. begin
  7352. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7353. { Reuse second_mov as a MOVZX instruction }
  7354. second_mov.opcode := A_MOVZX;
  7355. second_mov.opsize := S_BL;
  7356. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7357. second_mov.loadreg(1, FullReg);
  7358. first_mov.oper[0]^.reg := FullReg;
  7359. asml.Remove(second_mov);
  7360. asml.InsertBefore(second_mov, first_mov);
  7361. end
  7362. else
  7363. { It's a value }
  7364. begin
  7365. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7366. RemoveInstruction(second_mov);
  7367. end;
  7368. Result := True;
  7369. Exit;
  7370. end;
  7371. else
  7372. ;
  7373. end;
  7374. end;
  7375. end;
  7376. end;
  7377. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7378. { returns true if a "continue" should be done after this optimization }
  7379. var
  7380. hp1, hp2, hp3: tai;
  7381. begin
  7382. Result := false;
  7383. hp3 := nil;
  7384. if MatchOpType(taicpu(p),top_ref) and
  7385. GetNextInstruction(p, hp1) and
  7386. (hp1.typ = ait_instruction) and
  7387. (((taicpu(hp1).opcode = A_FLD) and
  7388. (taicpu(p).opcode = A_FSTP)) or
  7389. ((taicpu(p).opcode = A_FISTP) and
  7390. (taicpu(hp1).opcode = A_FILD))) and
  7391. MatchOpType(taicpu(hp1),top_ref) and
  7392. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7393. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7394. begin
  7395. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7396. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7397. GetNextInstruction(hp1, hp2) and
  7398. (((hp2.typ = ait_instruction) and
  7399. IsExitCode(hp2) and
  7400. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7401. not(assigned(current_procinfo.procdef.funcretsym) and
  7402. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7403. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7404. { fstp <temp>
  7405. fld <temp>
  7406. <dealloc> <temp>
  7407. }
  7408. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7409. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7410. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7411. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7412. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7413. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7414. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7415. )
  7416. )
  7417. ) then
  7418. begin
  7419. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7420. RemoveInstruction(hp1);
  7421. RemoveCurrentP(p, hp2);
  7422. { first case: exit code }
  7423. if hp2.typ = ait_instruction then
  7424. RemoveLastDeallocForFuncRes(p);
  7425. Result := true;
  7426. end
  7427. else
  7428. { we can do this only in fast math mode as fstp is rounding ...
  7429. ... still disabled as it breaks the compiler and/or rtl }
  7430. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7431. { ... or if another fstp equal to the first one follows }
  7432. GetNextInstruction(hp1,hp2) and
  7433. (hp2.typ = ait_instruction) and
  7434. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7435. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7436. begin
  7437. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7438. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7439. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7440. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7441. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7442. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7443. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7444. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7445. ) then
  7446. begin
  7447. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7448. RemoveCurrentP(p,hp2);
  7449. RemoveInstruction(hp1);
  7450. Result := true;
  7451. end
  7452. else if { fst can't store an extended/comp value }
  7453. (taicpu(p).opsize <> S_FX) and
  7454. (taicpu(p).opsize <> S_IQ) then
  7455. begin
  7456. if (taicpu(p).opcode = A_FSTP) then
  7457. taicpu(p).opcode := A_FST
  7458. else
  7459. taicpu(p).opcode := A_FIST;
  7460. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7461. RemoveInstruction(hp1);
  7462. Result := true;
  7463. end;
  7464. end;
  7465. end;
  7466. end;
  7467. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7468. var
  7469. hp1, hp2, hp3: tai;
  7470. begin
  7471. result:=false;
  7472. if MatchOpType(taicpu(p),top_reg) and
  7473. GetNextInstruction(p, hp1) and
  7474. (hp1.typ = Ait_Instruction) and
  7475. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7476. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7477. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7478. { change to
  7479. fld reg fxxx reg,st
  7480. fxxxp st, st1 (hp1)
  7481. Remark: non commutative operations must be reversed!
  7482. }
  7483. begin
  7484. case taicpu(hp1).opcode Of
  7485. A_FMULP,A_FADDP,
  7486. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7487. begin
  7488. case taicpu(hp1).opcode Of
  7489. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7490. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7491. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7492. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7493. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7494. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7495. else
  7496. internalerror(2019050534);
  7497. end;
  7498. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7499. taicpu(hp1).oper[1]^.reg := NR_ST;
  7500. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7501. RemoveCurrentP(p, hp1);
  7502. Result:=true;
  7503. exit;
  7504. end;
  7505. else
  7506. ;
  7507. end;
  7508. end
  7509. else
  7510. if MatchOpType(taicpu(p),top_ref) and
  7511. GetNextInstruction(p, hp2) and
  7512. (hp2.typ = Ait_Instruction) and
  7513. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7514. (taicpu(p).opsize in [S_FS, S_FL]) and
  7515. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7516. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7517. if GetLastInstruction(p, hp1) and
  7518. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7519. MatchOpType(taicpu(hp1),top_ref) and
  7520. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7521. if ((taicpu(hp2).opcode = A_FMULP) or
  7522. (taicpu(hp2).opcode = A_FADDP)) then
  7523. { change to
  7524. fld/fst mem1 (hp1) fld/fst mem1
  7525. fld mem1 (p) fadd/
  7526. faddp/ fmul st, st
  7527. fmulp st, st1 (hp2) }
  7528. begin
  7529. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7530. RemoveCurrentP(p, hp1);
  7531. if (taicpu(hp2).opcode = A_FADDP) then
  7532. taicpu(hp2).opcode := A_FADD
  7533. else
  7534. taicpu(hp2).opcode := A_FMUL;
  7535. taicpu(hp2).oper[1]^.reg := NR_ST;
  7536. end
  7537. else
  7538. { change to
  7539. fld/fst mem1 (hp1) fld/fst mem1
  7540. fld mem1 (p) fld st
  7541. }
  7542. begin
  7543. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7544. taicpu(p).changeopsize(S_FL);
  7545. taicpu(p).loadreg(0,NR_ST);
  7546. end
  7547. else
  7548. begin
  7549. case taicpu(hp2).opcode Of
  7550. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7551. { change to
  7552. fld/fst mem1 (hp1) fld/fst mem1
  7553. fld mem2 (p) fxxx mem2
  7554. fxxxp st, st1 (hp2) }
  7555. begin
  7556. case taicpu(hp2).opcode Of
  7557. A_FADDP: taicpu(p).opcode := A_FADD;
  7558. A_FMULP: taicpu(p).opcode := A_FMUL;
  7559. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7560. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7561. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7562. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7563. else
  7564. internalerror(2019050533);
  7565. end;
  7566. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7567. RemoveInstruction(hp2);
  7568. end
  7569. else
  7570. ;
  7571. end
  7572. end
  7573. end;
  7574. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7575. begin
  7576. Result := condition_in(cond1, cond2) or
  7577. { Not strictly subsets due to the actual flags checked, but because we're
  7578. comparing integers, E is a subset of AE and GE and their aliases }
  7579. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7580. end;
  7581. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7582. var
  7583. v: TCGInt;
  7584. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7585. FirstMatch, TempBool: Boolean;
  7586. NewReg: TRegister;
  7587. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7588. begin
  7589. Result:=false;
  7590. { All these optimisations need a next instruction }
  7591. if not GetNextInstruction(p, hp1) then
  7592. Exit;
  7593. true_hp1 := hp1;
  7594. { Search for:
  7595. cmp ###,###
  7596. j(c1) @lbl1
  7597. ...
  7598. @lbl:
  7599. cmp ###,### (same comparison as above)
  7600. j(c2) @lbl2
  7601. If c1 is a subset of c2, change to:
  7602. cmp ###,###
  7603. j(c1) @lbl2
  7604. (@lbl1 may become a dead label as a result)
  7605. }
  7606. { Also handle cases where there are multiple jumps in a row }
  7607. p_jump := hp1;
  7608. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7609. begin
  7610. Prefetch(p_jump.Next);
  7611. if IsJumpToLabel(taicpu(p_jump)) then
  7612. begin
  7613. { Do jump optimisations first in case the condition becomes
  7614. unnecessary }
  7615. TempBool := True;
  7616. if DoJumpOptimizations(p_jump, TempBool) or
  7617. not TempBool then
  7618. begin
  7619. if Assigned(p_jump) then
  7620. begin
  7621. { CollapseZeroDistJump will be set to the label or an align
  7622. before it after the jump if it optimises, whether or not
  7623. the label is live or dead }
  7624. if (p_jump.typ = ait_align) or
  7625. (
  7626. (p_jump.typ = ait_label) and
  7627. not (tai_label(p_jump).labsym.is_used)
  7628. ) then
  7629. GetNextInstruction(p_jump, p_jump);
  7630. end;
  7631. TransferUsedRegs(TmpUsedRegs);
  7632. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7633. if not Assigned(p_jump) or
  7634. (
  7635. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7636. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7637. ) then
  7638. begin
  7639. { No more conditional jumps; conditional statement is no longer required }
  7640. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7641. RemoveCurrentP(p);
  7642. Result := True;
  7643. Exit;
  7644. end;
  7645. hp1 := p_jump;
  7646. Include(OptsToCheck, aoc_ForceNewIteration);
  7647. Continue;
  7648. end;
  7649. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7650. if GetNextInstruction(p_jump, hp2) and
  7651. (
  7652. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7653. not TempBool
  7654. ) then
  7655. begin
  7656. hp1 := p_jump;
  7657. Include(OptsToCheck, aoc_ForceNewIteration);
  7658. Continue;
  7659. end;
  7660. p_label := nil;
  7661. if Assigned(JumpLabel) then
  7662. p_label := getlabelwithsym(JumpLabel);
  7663. if Assigned(p_label) and
  7664. GetNextInstruction(p_label, p_dist) and
  7665. MatchInstruction(p_dist, A_CMP, []) and
  7666. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7667. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7668. GetNextInstruction(p_dist, hp1_dist) and
  7669. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7670. begin
  7671. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7672. if JumpLabel = JumpLabel_dist then
  7673. { This is an infinite loop }
  7674. Exit;
  7675. { Best optimisation when the first condition is a subset (or equal) of the second }
  7676. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7677. begin
  7678. { Any registers used here will already be allocated }
  7679. if Assigned(JumpLabel) then
  7680. JumpLabel.DecRefs;
  7681. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7682. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7683. Include(OptsToCheck, aoc_ForceNewIteration);
  7684. { Don't exit yet. Since p and p_jump haven't actually been
  7685. removed, we can check for more on this iteration }
  7686. end
  7687. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7688. GetNextInstruction(hp1_dist, hp1_label) and
  7689. (hp1_label.typ = ait_label) then
  7690. begin
  7691. JumpLabel_far := tai_label(hp1_label).labsym;
  7692. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7693. { This is an infinite loop }
  7694. Exit;
  7695. if Assigned(JumpLabel_far) then
  7696. begin
  7697. { In this situation, if the first jump branches, the second one will never,
  7698. branch so change the destination label to after the second jump }
  7699. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7700. if Assigned(JumpLabel) then
  7701. JumpLabel.DecRefs;
  7702. JumpLabel_far.IncRefs;
  7703. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7704. Result := True;
  7705. { Don't exit yet. Since p and p_jump haven't actually been
  7706. removed, we can check for more on this iteration }
  7707. Continue;
  7708. end;
  7709. end;
  7710. end;
  7711. end;
  7712. { Search for:
  7713. cmp ###,###
  7714. j(c1) @lbl1
  7715. cmp ###,### (same as first)
  7716. Remove second cmp
  7717. }
  7718. if GetNextInstruction(p_jump, hp2) and
  7719. (
  7720. (
  7721. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7722. (
  7723. (
  7724. MatchOpType(taicpu(p), top_const, top_reg) and
  7725. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7726. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7727. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7728. ) or (
  7729. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7730. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7731. )
  7732. )
  7733. ) or (
  7734. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7735. MatchOperand(taicpu(p).oper[0]^, 0) and
  7736. (taicpu(p).oper[1]^.typ = top_reg) and
  7737. MatchInstruction(hp2, A_TEST, []) and
  7738. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7739. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7740. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7741. )
  7742. ) then
  7743. begin
  7744. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7745. TransferUsedRegs(TmpUsedRegs);
  7746. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7747. RemoveInstruction(hp2);
  7748. Result := True;
  7749. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7750. end
  7751. else
  7752. begin
  7753. { hp2 is the next instruction, so save time and just set p_jump
  7754. to it instead of calling GetNextInstruction below }
  7755. p_jump := hp2;
  7756. Continue;
  7757. end;
  7758. GetNextInstruction(p_jump, p_jump);
  7759. end;
  7760. if (
  7761. { Don't call GetNextInstruction again if we already have it }
  7762. (true_hp1 = p_jump) or
  7763. GetNextInstruction(p, hp1)
  7764. ) and
  7765. MatchInstruction(hp1, A_Jcc, []) and
  7766. IsJumpToLabel(taicpu(hp1)) and
  7767. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7768. GetNextInstruction(hp1, hp2) then
  7769. begin
  7770. {
  7771. cmp x, y (or "cmp y, x")
  7772. je @lbl
  7773. mov x, y
  7774. @lbl:
  7775. (x and y can be constants, registers or references)
  7776. Change to:
  7777. mov x, y (x and y will always be equal in the end)
  7778. @lbl: (may beceome a dead label)
  7779. Also:
  7780. cmp x, y (or "cmp y, x")
  7781. jne @lbl
  7782. mov x, y
  7783. @lbl:
  7784. (x and y can be constants, registers or references)
  7785. Change to:
  7786. Absolutely nothing! (Except @lbl if it's still live)
  7787. }
  7788. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7789. (
  7790. (
  7791. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7792. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7793. ) or (
  7794. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7795. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7796. )
  7797. ) and
  7798. GetNextInstruction(hp2, hp1_label) and
  7799. (hp1_label.typ = ait_label) and
  7800. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7801. begin
  7802. tai_label(hp1_label).labsym.DecRefs;
  7803. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7804. begin
  7805. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7806. RemoveInstruction(hp2);
  7807. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7808. end
  7809. else
  7810. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7811. RemoveInstruction(hp1);
  7812. RemoveCurrentp(p, hp2);
  7813. Result := True;
  7814. Exit;
  7815. end;
  7816. {
  7817. Try to optimise the following:
  7818. cmp $x,### ($x and $y can be registers or constants)
  7819. je @lbl1 (only reference)
  7820. cmp $y,### (### are identical)
  7821. @Lbl:
  7822. sete %reg1
  7823. Change to:
  7824. cmp $x,###
  7825. sete %reg2 (allocate new %reg2)
  7826. cmp $y,###
  7827. sete %reg1
  7828. orb %reg2,%reg1
  7829. (dealloc %reg2)
  7830. This adds an instruction (so don't perform under -Os), but it removes
  7831. a conditional branch.
  7832. }
  7833. if not (cs_opt_size in current_settings.optimizerswitches) and
  7834. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7835. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7836. { The first operand of CMP instructions can only be a register or
  7837. immediate anyway, so no need to check }
  7838. GetNextInstruction(hp2, p_label) and
  7839. (p_label.typ = ait_label) and
  7840. (tai_label(p_label).labsym.getrefs = 1) and
  7841. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7842. GetNextInstruction(p_label, p_dist) and
  7843. MatchInstruction(p_dist, A_SETcc, []) and
  7844. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7845. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7846. begin
  7847. TransferUsedRegs(TmpUsedRegs);
  7848. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7849. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7850. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7851. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7852. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7853. { Get the instruction after the SETcc instruction so we can
  7854. allocate a new register over the entire range }
  7855. GetNextInstruction(p_dist, hp1_dist) then
  7856. begin
  7857. { Register can appear in p if it's not used afterwards, so only
  7858. allocate between hp1 and hp1_dist }
  7859. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7860. if NewReg <> NR_NO then
  7861. begin
  7862. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7863. { Change the jump instruction into a SETcc instruction }
  7864. taicpu(hp1).opcode := A_SETcc;
  7865. taicpu(hp1).opsize := S_B;
  7866. taicpu(hp1).loadreg(0, NewReg);
  7867. { This is now a dead label }
  7868. tai_label(p_label).labsym.decrefs;
  7869. { Prefer adding before the next instruction so the FLAGS
  7870. register is deallicated first }
  7871. AsmL.InsertBefore(
  7872. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7873. hp1_dist
  7874. );
  7875. Result := True;
  7876. { Don't exit yet, as p wasn't changed and hp1, while
  7877. modified, is still intact and might be optimised by the
  7878. SETcc optimisation below }
  7879. end;
  7880. end;
  7881. end;
  7882. end;
  7883. if (taicpu(p).oper[0]^.typ = top_const) and
  7884. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7885. begin
  7886. if (taicpu(p).oper[0]^.val = 0) and
  7887. (taicpu(p).oper[1]^.typ = top_reg) then
  7888. begin
  7889. hp2 := p;
  7890. FirstMatch := True;
  7891. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7892. anything meaningful once it's converted to "test %reg,%reg";
  7893. additionally, some jumps will always (or never) branch, so
  7894. evaluate every jump immediately following the
  7895. comparison, optimising the conditions if possible.
  7896. Similarly with SETcc... those that are always set to 0 or 1
  7897. are changed to MOV instructions }
  7898. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7899. (
  7900. GetNextInstruction(hp2, hp1) and
  7901. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7902. ) do
  7903. begin
  7904. Prefetch(hp1.Next);
  7905. FirstMatch := False;
  7906. case taicpu(hp1).condition of
  7907. C_B, C_C, C_NAE, C_O:
  7908. { For B/NAE:
  7909. Will never branch since an unsigned integer can never be below zero
  7910. For C/O:
  7911. Result cannot overflow because 0 is being subtracted
  7912. }
  7913. begin
  7914. if taicpu(hp1).opcode = A_Jcc then
  7915. begin
  7916. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7917. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7918. RemoveInstruction(hp1);
  7919. { Since hp1 was deleted, hp2 must not be updated }
  7920. Continue;
  7921. end
  7922. else
  7923. begin
  7924. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7925. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7926. taicpu(hp1).opcode := A_MOV;
  7927. taicpu(hp1).ops := 2;
  7928. taicpu(hp1).condition := C_None;
  7929. taicpu(hp1).opsize := S_B;
  7930. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7931. taicpu(hp1).loadconst(0, 0);
  7932. end;
  7933. end;
  7934. C_BE, C_NA:
  7935. begin
  7936. { Will only branch if equal to zero }
  7937. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7938. taicpu(hp1).condition := C_E;
  7939. end;
  7940. C_A, C_NBE:
  7941. begin
  7942. { Will only branch if not equal to zero }
  7943. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7944. taicpu(hp1).condition := C_NE;
  7945. end;
  7946. C_AE, C_NB, C_NC, C_NO:
  7947. begin
  7948. { Will always branch }
  7949. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7950. if taicpu(hp1).opcode = A_Jcc then
  7951. begin
  7952. MakeUnconditional(taicpu(hp1));
  7953. { Any jumps/set that follow will now be dead code }
  7954. RemoveDeadCodeAfterJump(taicpu(hp1));
  7955. Break;
  7956. end
  7957. else
  7958. begin
  7959. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7960. taicpu(hp1).opcode := A_MOV;
  7961. taicpu(hp1).ops := 2;
  7962. taicpu(hp1).condition := C_None;
  7963. taicpu(hp1).opsize := S_B;
  7964. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7965. taicpu(hp1).loadconst(0, 1);
  7966. end;
  7967. end;
  7968. C_None:
  7969. InternalError(2020012201);
  7970. C_P, C_PE, C_NP, C_PO:
  7971. { We can't handle parity checks and they should never be generated
  7972. after a general-purpose CMP (it's used in some floating-point
  7973. comparisons that don't use CMP) }
  7974. InternalError(2020012202);
  7975. else
  7976. { Zero/Equality, Sign, their complements and all of the
  7977. signed comparisons do not need to be converted };
  7978. end;
  7979. hp2 := hp1;
  7980. end;
  7981. { Convert the instruction to a TEST }
  7982. taicpu(p).opcode := A_TEST;
  7983. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7984. Result := True;
  7985. Exit;
  7986. end
  7987. else
  7988. begin
  7989. TransferUsedRegs(TmpUsedRegs);
  7990. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7991. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7992. begin
  7993. if (taicpu(p).oper[0]^.val = 1) and
  7994. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7995. begin
  7996. { Convert; To:
  7997. cmp $1,r/m cmp $0,r/m
  7998. jl @lbl jle @lbl
  7999. (Also do inverted conditions)
  8000. }
  8001. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8002. taicpu(p).oper[0]^.val := 0;
  8003. if taicpu(hp1).condition in [C_L, C_NGE] then
  8004. taicpu(hp1).condition := C_LE
  8005. else
  8006. taicpu(hp1).condition := C_NLE;
  8007. { If the instruction is now "cmp $0,%reg", convert it to a
  8008. TEST (and effectively do the work of the "cmp $0,%reg" in
  8009. the block above)
  8010. }
  8011. if (taicpu(p).oper[1]^.typ = top_reg) then
  8012. begin
  8013. taicpu(p).opcode := A_TEST;
  8014. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8015. end;
  8016. Result := True;
  8017. Exit;
  8018. end
  8019. else if (taicpu(p).oper[1]^.typ = top_reg)
  8020. {$ifdef x86_64}
  8021. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8022. {$endif x86_64}
  8023. then
  8024. begin
  8025. { cmp register,$8000 neg register
  8026. je target --> jo target
  8027. .... only if register is deallocated before jump.}
  8028. case Taicpu(p).opsize of
  8029. S_B: v:=$80;
  8030. S_W: v:=$8000;
  8031. S_L: v:=qword($80000000);
  8032. else
  8033. internalerror(2013112905);
  8034. end;
  8035. if (taicpu(p).oper[0]^.val=v) and
  8036. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8037. begin
  8038. TransferUsedRegs(TmpUsedRegs);
  8039. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8040. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8041. begin
  8042. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8043. Taicpu(p).opcode:=A_NEG;
  8044. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8045. Taicpu(p).clearop(1);
  8046. Taicpu(p).ops:=1;
  8047. if Taicpu(hp1).condition=C_E then
  8048. Taicpu(hp1).condition:=C_O
  8049. else
  8050. Taicpu(hp1).condition:=C_NO;
  8051. Result:=true;
  8052. exit;
  8053. end;
  8054. end;
  8055. end;
  8056. end;
  8057. end;
  8058. end;
  8059. if TrySwapMovCmp(p, hp1) then
  8060. begin
  8061. Result := True;
  8062. Exit;
  8063. end;
  8064. end;
  8065. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8066. var
  8067. hp1: tai;
  8068. begin
  8069. {
  8070. remove the second (v)pxor from
  8071. pxor reg,reg
  8072. ...
  8073. pxor reg,reg
  8074. }
  8075. Result:=false;
  8076. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8077. MatchOpType(taicpu(p),top_reg,top_reg) and
  8078. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8079. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8080. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8081. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8082. begin
  8083. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8084. RemoveInstruction(hp1);
  8085. Result:=true;
  8086. Exit;
  8087. end
  8088. {
  8089. replace
  8090. pxor reg1,reg1
  8091. movapd/s reg1,reg2
  8092. dealloc reg1
  8093. by
  8094. pxor reg2,reg2
  8095. }
  8096. else if GetNextInstruction(p,hp1) and
  8097. { we mix single and double opperations here because we assume that the compiler
  8098. generates vmovapd only after double operations and vmovaps only after single operations }
  8099. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8100. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8101. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8102. (taicpu(p).oper[0]^.typ=top_reg) then
  8103. begin
  8104. TransferUsedRegs(TmpUsedRegs);
  8105. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8106. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8107. begin
  8108. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8109. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8110. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8111. RemoveInstruction(hp1);
  8112. result:=true;
  8113. end;
  8114. end;
  8115. end;
  8116. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8117. var
  8118. hp1: tai;
  8119. begin
  8120. {
  8121. remove the second (v)pxor from
  8122. (v)pxor reg,reg
  8123. ...
  8124. (v)pxor reg,reg
  8125. }
  8126. Result:=false;
  8127. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8128. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8129. begin
  8130. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8131. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8132. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8133. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8134. begin
  8135. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8136. RemoveInstruction(hp1);
  8137. Result:=true;
  8138. Exit;
  8139. end;
  8140. {$ifdef x86_64}
  8141. {
  8142. replace
  8143. vpxor reg1,reg1,reg1
  8144. vmov reg,mem
  8145. by
  8146. movq $0,mem
  8147. }
  8148. if GetNextInstruction(p,hp1) and
  8149. MatchInstruction(hp1,A_VMOVSD,[]) and
  8150. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8151. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8152. begin
  8153. TransferUsedRegs(TmpUsedRegs);
  8154. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8155. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8156. begin
  8157. taicpu(hp1).loadconst(0,0);
  8158. taicpu(hp1).opcode:=A_MOV;
  8159. taicpu(hp1).opsize:=S_Q;
  8160. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8161. RemoveCurrentP(p);
  8162. result:=true;
  8163. Exit;
  8164. end;
  8165. end;
  8166. {$endif x86_64}
  8167. end
  8168. {
  8169. replace
  8170. vpxor reg1,reg1,reg2
  8171. by
  8172. vpxor reg2,reg2,reg2
  8173. to avoid unncessary data dependencies
  8174. }
  8175. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8176. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8177. begin
  8178. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8179. { avoid unncessary data dependency }
  8180. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8181. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8182. result:=true;
  8183. exit;
  8184. end;
  8185. Result:=OptPass1VOP(p);
  8186. end;
  8187. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8188. var
  8189. hp1 : tai;
  8190. begin
  8191. result:=false;
  8192. { replace
  8193. IMul const,%mreg1,%mreg2
  8194. Mov %reg2,%mreg3
  8195. dealloc %mreg3
  8196. by
  8197. Imul const,%mreg1,%mreg23
  8198. }
  8199. if (taicpu(p).ops=3) and
  8200. GetNextInstruction(p,hp1) and
  8201. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8202. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8203. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8204. begin
  8205. TransferUsedRegs(TmpUsedRegs);
  8206. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8207. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8208. begin
  8209. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8210. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8211. RemoveInstruction(hp1);
  8212. result:=true;
  8213. end;
  8214. end;
  8215. end;
  8216. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8217. var
  8218. hp1 : tai;
  8219. begin
  8220. result:=false;
  8221. { replace
  8222. IMul %reg0,%reg1,%reg2
  8223. Mov %reg2,%reg3
  8224. dealloc %reg2
  8225. by
  8226. Imul %reg0,%reg1,%reg3
  8227. }
  8228. if GetNextInstruction(p,hp1) and
  8229. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8230. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8231. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8232. begin
  8233. TransferUsedRegs(TmpUsedRegs);
  8234. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8235. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8236. begin
  8237. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8238. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8239. RemoveInstruction(hp1);
  8240. result:=true;
  8241. end;
  8242. end;
  8243. end;
  8244. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8245. var
  8246. hp1: tai;
  8247. begin
  8248. Result:=false;
  8249. { get rid of
  8250. (v)cvtss2sd reg0,<reg1,>reg2
  8251. (v)cvtss2sd reg2,<reg2,>reg0
  8252. }
  8253. if GetNextInstruction(p,hp1) and
  8254. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8255. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8256. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8257. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8258. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8259. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8260. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8261. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8262. )
  8263. ) then
  8264. begin
  8265. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8266. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8267. begin
  8268. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8269. RemoveCurrentP(p);
  8270. RemoveInstruction(hp1);
  8271. end
  8272. else
  8273. begin
  8274. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8275. if taicpu(hp1).opcode=A_CVTSD2SS then
  8276. begin
  8277. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8278. taicpu(p).opcode:=A_MOVAPS;
  8279. end
  8280. else
  8281. begin
  8282. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8283. taicpu(p).opcode:=A_VMOVAPS;
  8284. end;
  8285. taicpu(p).ops:=2;
  8286. RemoveInstruction(hp1);
  8287. end;
  8288. Result:=true;
  8289. Exit;
  8290. end;
  8291. end;
  8292. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8293. var
  8294. hp1, hp2, hp3, hp4, hp5: tai;
  8295. ThisReg: TRegister;
  8296. begin
  8297. Result := False;
  8298. if not GetNextInstruction(p,hp1) then
  8299. Exit;
  8300. {
  8301. convert
  8302. j<c> .L1
  8303. mov 1,reg
  8304. jmp .L2
  8305. .L1
  8306. mov 0,reg
  8307. .L2
  8308. into
  8309. mov 0,reg
  8310. set<not(c)> reg
  8311. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8312. would destroy the flag contents
  8313. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8314. executed at the same time as a previous comparison.
  8315. set<not(c)> reg
  8316. movzx reg, reg
  8317. }
  8318. if MatchInstruction(hp1,A_MOV,[]) and
  8319. (taicpu(hp1).oper[0]^.typ = top_const) and
  8320. (
  8321. (
  8322. (taicpu(hp1).oper[1]^.typ = top_reg)
  8323. {$ifdef i386}
  8324. { Under i386, ESI, EDI, EBP and ESP
  8325. don't have an 8-bit representation }
  8326. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8327. {$endif i386}
  8328. ) or (
  8329. {$ifdef i386}
  8330. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8331. {$endif i386}
  8332. (taicpu(hp1).opsize = S_B)
  8333. )
  8334. ) and
  8335. GetNextInstruction(hp1,hp2) and
  8336. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8337. GetNextInstruction(hp2,hp3) and
  8338. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8339. GetNextInstruction(hp3,hp4) and
  8340. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8341. (taicpu(hp4).oper[0]^.typ = top_const) and
  8342. (
  8343. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8344. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8345. ) and
  8346. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8347. GetNextInstruction(hp4,hp5) and
  8348. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8349. begin
  8350. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8351. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8352. tai_label(hp3).labsym.DecRefs;
  8353. { If this isn't the only reference to the middle label, we can
  8354. still make a saving - only that the first jump and everything
  8355. that follows will remain. }
  8356. if (tai_label(hp3).labsym.getrefs = 0) then
  8357. begin
  8358. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8359. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8360. else
  8361. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8362. { remove jump, first label and second MOV (also catching any aligns) }
  8363. repeat
  8364. if not GetNextInstruction(hp2, hp3) then
  8365. InternalError(2021040810);
  8366. RemoveInstruction(hp2);
  8367. hp2 := hp3;
  8368. until hp2 = hp5;
  8369. { Don't decrement reference count before the removal loop
  8370. above, otherwise GetNextInstruction won't stop on the
  8371. the label }
  8372. tai_label(hp5).labsym.DecRefs;
  8373. end
  8374. else
  8375. begin
  8376. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8377. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8378. else
  8379. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8380. end;
  8381. taicpu(p).opcode:=A_SETcc;
  8382. taicpu(p).opsize:=S_B;
  8383. taicpu(p).is_jmp:=False;
  8384. if taicpu(hp1).opsize=S_B then
  8385. begin
  8386. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8387. if taicpu(hp1).oper[1]^.typ = top_reg then
  8388. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8389. RemoveInstruction(hp1);
  8390. end
  8391. else
  8392. begin
  8393. { Will be a register because the size can't be S_B otherwise }
  8394. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8395. taicpu(p).loadreg(0, ThisReg);
  8396. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8397. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8398. begin
  8399. case taicpu(hp1).opsize of
  8400. S_W:
  8401. taicpu(hp1).opsize := S_BW;
  8402. S_L:
  8403. taicpu(hp1).opsize := S_BL;
  8404. {$ifdef x86_64}
  8405. S_Q:
  8406. begin
  8407. taicpu(hp1).opsize := S_BL;
  8408. { Change the destination register to 32-bit }
  8409. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8410. end;
  8411. {$endif x86_64}
  8412. else
  8413. InternalError(2021040820);
  8414. end;
  8415. taicpu(hp1).opcode := A_MOVZX;
  8416. taicpu(hp1).loadreg(0, ThisReg);
  8417. end
  8418. else
  8419. begin
  8420. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8421. { hp1 is already a MOV instruction with the correct register }
  8422. taicpu(hp1).loadconst(0, 0);
  8423. { Inserting it right before p will guarantee that the flags are also tracked }
  8424. asml.Remove(hp1);
  8425. asml.InsertBefore(hp1, p);
  8426. end;
  8427. end;
  8428. Result:=true;
  8429. exit;
  8430. end
  8431. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8432. Result := TryJccStcClcOpt(p, hp1)
  8433. else if (hp1.typ = ait_label) then
  8434. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8435. end;
  8436. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8437. var
  8438. hp1, hp2, hp3: tai;
  8439. SourceRef, TargetRef: TReference;
  8440. CurrentReg: TRegister;
  8441. begin
  8442. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8443. if not UseAVX then
  8444. InternalError(2021100501);
  8445. Result := False;
  8446. { Look for the following to simplify:
  8447. vmovdqa/u x(mem1), %xmmreg
  8448. vmovdqa/u %xmmreg, y(mem2)
  8449. vmovdqa/u x+16(mem1), %xmmreg
  8450. vmovdqa/u %xmmreg, y+16(mem2)
  8451. Change to:
  8452. vmovdqa/u x(mem1), %ymmreg
  8453. vmovdqa/u %ymmreg, y(mem2)
  8454. vpxor %ymmreg, %ymmreg, %ymmreg
  8455. ( The VPXOR instruction is to zero the upper half, thus removing the
  8456. need to call the potentially expensive VZEROUPPER instruction. Other
  8457. peephole optimisations can remove VPXOR if it's unnecessary )
  8458. }
  8459. TransferUsedRegs(TmpUsedRegs);
  8460. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8461. { NOTE: In the optimisations below, if the references dictate that an
  8462. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8463. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8464. if (taicpu(p).opsize = S_XMM) and
  8465. MatchOpType(taicpu(p), top_ref, top_reg) and
  8466. GetNextInstruction(p, hp1) and
  8467. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8468. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8469. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8470. begin
  8471. SourceRef := taicpu(p).oper[0]^.ref^;
  8472. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8473. if GetNextInstruction(hp1, hp2) and
  8474. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8475. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8476. begin
  8477. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8478. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8479. Inc(SourceRef.offset, 16);
  8480. { Reuse the register in the first block move }
  8481. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8482. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8483. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8484. begin
  8485. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8486. Inc(TargetRef.offset, 16);
  8487. if GetNextInstruction(hp2, hp3) and
  8488. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8489. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8490. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8491. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8492. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8493. begin
  8494. { Update the register tracking to the new size }
  8495. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8496. { Remember that the offsets are 16 ahead }
  8497. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8498. if not (
  8499. ((SourceRef.offset mod 32) = 16) and
  8500. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8501. ) then
  8502. taicpu(p).opcode := A_VMOVDQU;
  8503. taicpu(p).opsize := S_YMM;
  8504. taicpu(p).oper[1]^.reg := CurrentReg;
  8505. if not (
  8506. ((TargetRef.offset mod 32) = 16) and
  8507. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8508. ) then
  8509. taicpu(hp1).opcode := A_VMOVDQU;
  8510. taicpu(hp1).opsize := S_YMM;
  8511. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8512. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8513. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8514. if (pi_uses_ymm in current_procinfo.flags) then
  8515. RemoveInstruction(hp2)
  8516. else
  8517. begin
  8518. taicpu(hp2).opcode := A_VPXOR;
  8519. taicpu(hp2).opsize := S_YMM;
  8520. taicpu(hp2).loadreg(0, CurrentReg);
  8521. taicpu(hp2).loadreg(1, CurrentReg);
  8522. taicpu(hp2).loadreg(2, CurrentReg);
  8523. taicpu(hp2).ops := 3;
  8524. end;
  8525. RemoveInstruction(hp3);
  8526. Result := True;
  8527. Exit;
  8528. end;
  8529. end
  8530. else
  8531. begin
  8532. { See if the next references are 16 less rather than 16 greater }
  8533. Dec(SourceRef.offset, 32); { -16 the other way }
  8534. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8535. begin
  8536. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8537. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8538. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8539. GetNextInstruction(hp2, hp3) and
  8540. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8541. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8542. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8543. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8544. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8545. begin
  8546. { Update the register tracking to the new size }
  8547. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8548. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8549. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8550. if not(
  8551. ((SourceRef.offset mod 32) = 0) and
  8552. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8553. ) then
  8554. taicpu(hp2).opcode := A_VMOVDQU;
  8555. taicpu(hp2).opsize := S_YMM;
  8556. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8557. if not (
  8558. ((TargetRef.offset mod 32) = 0) and
  8559. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8560. ) then
  8561. taicpu(hp3).opcode := A_VMOVDQU;
  8562. taicpu(hp3).opsize := S_YMM;
  8563. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8564. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8565. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8566. if (pi_uses_ymm in current_procinfo.flags) then
  8567. RemoveInstruction(hp1)
  8568. else
  8569. begin
  8570. taicpu(hp1).opcode := A_VPXOR;
  8571. taicpu(hp1).opsize := S_YMM;
  8572. taicpu(hp1).loadreg(0, CurrentReg);
  8573. taicpu(hp1).loadreg(1, CurrentReg);
  8574. taicpu(hp1).loadreg(2, CurrentReg);
  8575. taicpu(hp1).ops := 3;
  8576. Asml.Remove(hp1);
  8577. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8578. end;
  8579. RemoveCurrentP(p, hp2);
  8580. Result := True;
  8581. Exit;
  8582. end;
  8583. end;
  8584. end;
  8585. end;
  8586. end;
  8587. end;
  8588. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8589. var
  8590. hp2, hp3, first_assignment: tai;
  8591. IncCount, OperIdx: Integer;
  8592. OrigLabel: TAsmLabel;
  8593. begin
  8594. Count := 0;
  8595. Result := False;
  8596. first_assignment := nil;
  8597. if (LoopCount >= 20) then
  8598. begin
  8599. { Guard against infinite loops }
  8600. Exit;
  8601. end;
  8602. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8603. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8604. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8605. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8606. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8607. Exit;
  8608. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8609. {
  8610. change
  8611. jmp .L1
  8612. ...
  8613. .L1:
  8614. mov ##, ## ( multiple movs possible )
  8615. jmp/ret
  8616. into
  8617. mov ##, ##
  8618. jmp/ret
  8619. }
  8620. if not Assigned(hp1) then
  8621. begin
  8622. hp1 := GetLabelWithSym(OrigLabel);
  8623. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8624. Exit;
  8625. end;
  8626. hp2 := hp1;
  8627. while Assigned(hp2) do
  8628. begin
  8629. if Assigned(hp2) and (hp2.typ = ait_label) then
  8630. SkipLabels(hp2,hp2);
  8631. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8632. Break;
  8633. case taicpu(hp2).opcode of
  8634. A_MOVSD:
  8635. begin
  8636. if taicpu(hp2).ops = 0 then
  8637. { Wrong MOVSD }
  8638. Break;
  8639. Inc(Count);
  8640. if Count >= 5 then
  8641. { Too many to be worthwhile }
  8642. Break;
  8643. GetNextInstruction(hp2, hp2);
  8644. Continue;
  8645. end;
  8646. A_MOV,
  8647. A_MOVD,
  8648. A_MOVQ,
  8649. A_MOVSX,
  8650. {$ifdef x86_64}
  8651. A_MOVSXD,
  8652. {$endif x86_64}
  8653. A_MOVZX,
  8654. A_MOVAPS,
  8655. A_MOVUPS,
  8656. A_MOVSS,
  8657. A_MOVAPD,
  8658. A_MOVUPD,
  8659. A_MOVDQA,
  8660. A_MOVDQU,
  8661. A_VMOVSS,
  8662. A_VMOVAPS,
  8663. A_VMOVUPS,
  8664. A_VMOVSD,
  8665. A_VMOVAPD,
  8666. A_VMOVUPD,
  8667. A_VMOVDQA,
  8668. A_VMOVDQU:
  8669. begin
  8670. Inc(Count);
  8671. if Count >= 5 then
  8672. { Too many to be worthwhile }
  8673. Break;
  8674. GetNextInstruction(hp2, hp2);
  8675. Continue;
  8676. end;
  8677. A_JMP:
  8678. begin
  8679. { Guard against infinite loops }
  8680. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8681. Exit;
  8682. { Analyse this jump first in case it also duplicates assignments }
  8683. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8684. begin
  8685. { Something did change! }
  8686. Result := True;
  8687. Inc(Count, IncCount);
  8688. if Count >= 5 then
  8689. begin
  8690. { Too many to be worthwhile }
  8691. Exit;
  8692. end;
  8693. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8694. Break;
  8695. end;
  8696. Result := True;
  8697. Break;
  8698. end;
  8699. A_RET:
  8700. begin
  8701. Result := True;
  8702. Break;
  8703. end;
  8704. else
  8705. Break;
  8706. end;
  8707. end;
  8708. if Result then
  8709. begin
  8710. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8711. if Count = 0 then
  8712. begin
  8713. Result := False;
  8714. Exit;
  8715. end;
  8716. TransferUsedRegs(TmpUsedRegs);
  8717. hp3 := p;
  8718. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8719. while True do
  8720. begin
  8721. if Assigned(hp1) and (hp1.typ = ait_label) then
  8722. SkipLabels(hp1,hp1);
  8723. case hp1.typ of
  8724. ait_regalloc:
  8725. if tai_regalloc(hp1).ratype = ra_dealloc then
  8726. begin
  8727. { Duplicate the register deallocation... }
  8728. hp3:=tai(hp1.getcopy);
  8729. if first_assignment = nil then
  8730. first_assignment := hp3;
  8731. asml.InsertBefore(hp3, p);
  8732. { ... but also reallocate it after the jump }
  8733. hp3:=tai(hp1.getcopy);
  8734. tai_regalloc(hp3).ratype := ra_alloc;
  8735. asml.InsertAfter(hp3, p);
  8736. end;
  8737. ait_instruction:
  8738. case taicpu(hp1).opcode of
  8739. A_JMP:
  8740. begin
  8741. { Change the original jump to the new destination }
  8742. OrigLabel.decrefs;
  8743. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8744. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8745. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8746. if not Assigned(first_assignment) then
  8747. InternalError(2021040810)
  8748. else
  8749. p := first_assignment;
  8750. Exit;
  8751. end;
  8752. A_RET:
  8753. begin
  8754. { Now change the jump into a RET instruction }
  8755. ConvertJumpToRET(p, hp1);
  8756. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8757. if not Assigned(first_assignment) then
  8758. InternalError(2021040811)
  8759. else
  8760. p := first_assignment;
  8761. Exit;
  8762. end;
  8763. else
  8764. begin
  8765. { Duplicate the MOV instruction }
  8766. hp3:=tai(hp1.getcopy);
  8767. if first_assignment = nil then
  8768. first_assignment := hp3;
  8769. asml.InsertBefore(hp3, p);
  8770. { Make sure the compiler knows about any final registers written here }
  8771. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8772. with taicpu(hp3).oper[OperIdx]^ do
  8773. begin
  8774. case typ of
  8775. top_ref:
  8776. begin
  8777. if (ref^.base <> NR_NO) and
  8778. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8779. (
  8780. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8781. (
  8782. { Allow the frame pointer if it's not being used by the procedure as such }
  8783. Assigned(current_procinfo) and
  8784. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8785. )
  8786. )
  8787. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8788. then
  8789. begin
  8790. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8791. if not Assigned(first_assignment) then
  8792. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8793. end;
  8794. if (ref^.index <> NR_NO) and
  8795. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8796. (
  8797. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8798. (
  8799. { Allow the frame pointer if it's not being used by the procedure as such }
  8800. Assigned(current_procinfo) and
  8801. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8802. )
  8803. )
  8804. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8805. (ref^.index <> ref^.base) then
  8806. begin
  8807. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8808. if not Assigned(first_assignment) then
  8809. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8810. end;
  8811. end;
  8812. top_reg:
  8813. begin
  8814. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8815. if not Assigned(first_assignment) then
  8816. IncludeRegInUsedRegs(reg, UsedRegs);
  8817. end;
  8818. else
  8819. ;
  8820. end;
  8821. end;
  8822. end;
  8823. end;
  8824. else
  8825. InternalError(2021040720);
  8826. end;
  8827. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8828. { Should have dropped out earlier }
  8829. InternalError(2021040710);
  8830. end;
  8831. end;
  8832. end;
  8833. const
  8834. WriteOp: array[0..3] of set of TInsChange = (
  8835. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8836. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8837. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8838. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8839. RegWriteFlags: array[0..7] of set of TInsChange = (
  8840. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8841. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8842. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8843. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8844. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8845. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8846. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8847. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8848. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8849. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8850. var
  8851. hp2: tai;
  8852. X: Integer;
  8853. begin
  8854. { If we have something like:
  8855. op ###,###
  8856. mov ###,###
  8857. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8858. interfere in regards to what they write to.
  8859. NOTE: p must be a 2-operand instruction
  8860. }
  8861. Result := False;
  8862. if (hp1.typ <> ait_instruction) or
  8863. taicpu(hp1).is_jmp or
  8864. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8865. Exit;
  8866. { NOP is a pipeline fence, likely marking the beginning of the function
  8867. epilogue, so drop out. Similarly, drop out if POP or RET are
  8868. encountered }
  8869. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8870. Exit;
  8871. if (taicpu(hp1).opcode = A_MOVSD) and
  8872. (taicpu(hp1).ops = 0) then
  8873. { Wrong MOVSD }
  8874. Exit;
  8875. { Check for writes to specific registers first }
  8876. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8877. for X := 0 to 7 do
  8878. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8879. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8880. Exit;
  8881. for X := 0 to taicpu(hp1).ops - 1 do
  8882. begin
  8883. { Check to see if this operand writes to something }
  8884. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8885. { And matches something in the CMP/TEST instruction }
  8886. (
  8887. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8888. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8889. (
  8890. { If it's a register, make sure the register written to doesn't
  8891. appear in the cmp instruction as part of a reference }
  8892. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8893. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8894. )
  8895. ) then
  8896. Exit;
  8897. end;
  8898. { Check p to make sure it doesn't write to something that affects hp1 }
  8899. { Check for writes to specific registers first }
  8900. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8901. for X := 0 to 7 do
  8902. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8903. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8904. Exit;
  8905. for X := 0 to taicpu(p).ops - 1 do
  8906. begin
  8907. { Check to see if this operand writes to something }
  8908. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8909. { And matches something in hp1 }
  8910. (taicpu(p).oper[X]^.typ = top_reg) and
  8911. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8912. Exit;
  8913. end;
  8914. { The instruction can be safely moved }
  8915. asml.Remove(hp1);
  8916. { Try to insert after the last instructions where the FLAGS register is not
  8917. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8918. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8919. asml.InsertBefore(hp1, hp2)
  8920. { Failing that, try to insert after the last instructions where the
  8921. FLAGS register is not yet in use }
  8922. else if GetLastInstruction(p, hp2) and
  8923. (
  8924. (hp2.typ <> ait_instruction) or
  8925. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8926. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8927. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8928. ) then
  8929. asml.InsertAfter(hp1, hp2)
  8930. else
  8931. { Note, if p.Previous is nil (even if it should logically never be the
  8932. case), FindRegAllocBackward immediately exits with False and so we
  8933. safely land here (we can't just pass p because FindRegAllocBackward
  8934. immediately exits on an instruction). [Kit] }
  8935. asml.InsertBefore(hp1, p);
  8936. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8937. { We can't trust UsedRegs because we're looking backwards, although we
  8938. know the registers are allocated after p at the very least, so manually
  8939. create tai_regalloc objects if needed }
  8940. for X := 0 to taicpu(hp1).ops - 1 do
  8941. case taicpu(hp1).oper[X]^.typ of
  8942. top_reg:
  8943. begin
  8944. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8945. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8946. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8947. end;
  8948. top_ref:
  8949. begin
  8950. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8951. begin
  8952. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8953. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8954. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8955. end;
  8956. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8957. begin
  8958. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8959. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8960. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8961. end;
  8962. end;
  8963. else
  8964. ;
  8965. end;
  8966. Result := True;
  8967. end;
  8968. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8969. var
  8970. hp2: tai;
  8971. X: Integer;
  8972. begin
  8973. { If we have something like:
  8974. cmp ###,%reg1
  8975. mov 0,%reg2
  8976. And no modified registers are shared, move the instruction to before
  8977. the comparison as this means it can be optimised without worrying
  8978. about the FLAGS register. (CMP/MOV is generated by
  8979. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8980. As long as the second instruction doesn't use the flags or one of the
  8981. registers used by CMP or TEST (also check any references that use the
  8982. registers), then it can be moved prior to the comparison.
  8983. }
  8984. Result := False;
  8985. if not TrySwapMovOp(p, hp1) then
  8986. Exit;
  8987. if taicpu(hp1).opcode = A_LEA then
  8988. { The flags will be overwritten by the CMP/TEST instruction }
  8989. ConvertLEA(taicpu(hp1));
  8990. Result := True;
  8991. { Can we move it one further back? }
  8992. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8993. { Check to see if CMP/TEST is a comparison against zero }
  8994. (
  8995. (
  8996. (taicpu(p).opcode = A_CMP) and
  8997. MatchOperand(taicpu(p).oper[0]^, 0)
  8998. ) or
  8999. (
  9000. (taicpu(p).opcode = A_TEST) and
  9001. (
  9002. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9003. MatchOperand(taicpu(p).oper[0]^, -1)
  9004. )
  9005. )
  9006. ) and
  9007. { These instructions set the zero flag if the result is zero }
  9008. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9009. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9010. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9011. TrySwapMovOp(hp2, hp1);
  9012. end;
  9013. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9014. var
  9015. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9016. JumpLabel: TAsmLabel;
  9017. TmpBool: Boolean;
  9018. begin
  9019. Result := False;
  9020. { Look for:
  9021. stc/clc
  9022. j(c) .L1
  9023. ...
  9024. .L1:
  9025. set(n)cb %reg
  9026. (flags deallocated)
  9027. j(c) .L2
  9028. Change to:
  9029. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9030. j(c) .L2
  9031. }
  9032. p_last := p;
  9033. while GetNextInstruction(p_last, hp1) and
  9034. (hp1.typ = ait_instruction) and
  9035. IsJumpToLabel(taicpu(hp1)) do
  9036. begin
  9037. if DoJumpOptimizations(hp1, TmpBool) then
  9038. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9039. Continue;
  9040. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9041. if not Assigned(JumpLabel) then
  9042. InternalError(2024012801);
  9043. { Optimise the J(c); stc/clc optimisation first since this will
  9044. get missed if the main optimisation takes place }
  9045. if (taicpu(hp1).opcode = A_JCC) then
  9046. begin
  9047. if GetNextInstruction(hp1, hp2) and
  9048. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9049. TryJccStcClcOpt(hp1, hp2) then
  9050. begin
  9051. Result := True;
  9052. Exit;
  9053. end;
  9054. hp2 := nil; { Suppress compiler warning }
  9055. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9056. { Make sure the flags aren't used again }
  9057. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9058. begin
  9059. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9060. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9061. begin
  9062. if (taicpu(p).opcode = A_STC) then
  9063. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9064. else
  9065. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9066. MakeUnconditional(taicpu(hp1));
  9067. { Move the jump to after the flag deallocations }
  9068. Asml.Remove(hp1);
  9069. Asml.InsertAfter(hp1, hp2);
  9070. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9071. Result := True;
  9072. Exit;
  9073. end
  9074. else
  9075. begin
  9076. if (taicpu(p).opcode = A_STC) then
  9077. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9078. else
  9079. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9080. { In this case, the jump is deterministic in that it will never be taken }
  9081. JumpLabel.DecRefs;
  9082. RemoveInstruction(hp1);
  9083. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9084. Result := True;
  9085. Exit;
  9086. end;
  9087. end;
  9088. end;
  9089. hp2 := nil; { Suppress compiler warning }
  9090. if
  9091. { Make sure the carry flag doesn't appear in the jump conditions }
  9092. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9093. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9094. GetNextInstruction(hp2, p_dist) and
  9095. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9096. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9097. begin
  9098. case taicpu(p_dist).opcode of
  9099. A_Jcc:
  9100. begin
  9101. if DoJumpOptimizations(p_dist, TmpBool) then
  9102. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9103. Continue;
  9104. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9105. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9106. begin
  9107. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9108. JumpLabel.decrefs;
  9109. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9110. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9111. Result := True;
  9112. Exit;
  9113. end
  9114. else if GetNextInstruction(p_dist, hp1_dist) and
  9115. (hp1_dist.typ = ait_label) then
  9116. begin
  9117. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9118. JumpLabel.decrefs;
  9119. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9120. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9121. Result := True;
  9122. Exit;
  9123. end;
  9124. end;
  9125. A_SETcc:
  9126. if { Make sure the flags aren't used again }
  9127. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9128. GetNextInstruction(hp2, hp1_dist) and
  9129. (hp1_dist.typ = ait_instruction) and
  9130. IsJumpToLabel(taicpu(hp1_dist)) and
  9131. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9132. { This works if hp1_dist or both are regular JMP instructions }
  9133. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9134. (
  9135. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9136. { Make sure the register isn't still in use, otherwise it
  9137. may get corrupted (fixes #40659) }
  9138. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9139. ) then
  9140. begin
  9141. taicpu(p).allocate_oper(2);
  9142. taicpu(p).ops := 2;
  9143. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9144. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9145. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9146. taicpu(p).opcode := A_MOV;
  9147. taicpu(p).opsize := S_B;
  9148. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9149. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9150. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9151. JumpLabel.decrefs;
  9152. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9153. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9154. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9155. (tai_regalloc(hp2).ratype = ra_alloc) then
  9156. begin
  9157. Asml.Remove(hp2);
  9158. Asml.InsertAfter(hp2, p);
  9159. end;
  9160. Result := True;
  9161. Exit;
  9162. end;
  9163. else
  9164. ;
  9165. end;
  9166. end;
  9167. p_last := hp1;
  9168. end;
  9169. end;
  9170. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9171. var
  9172. hp2, hp3: tai;
  9173. TempBool: Boolean;
  9174. begin
  9175. Result := False;
  9176. {
  9177. j(c) .L1
  9178. stc/clc
  9179. .L1:
  9180. jc/jnc .L2
  9181. (Flags deallocated)
  9182. Change to:
  9183. j)c) .L1
  9184. jmp .L2
  9185. .L1:
  9186. jc/jnc .L2
  9187. Then call DoJumpOptimizations to convert to:
  9188. j(nc) .L2
  9189. .L1: (may become a dead label)
  9190. jc/jnc .L2
  9191. }
  9192. if GetNextInstruction(hp1, hp2) and
  9193. (hp2.typ = ait_label) and
  9194. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9195. GetNextInstruction(hp2, hp3) and
  9196. MatchInstruction(hp3, A_Jcc, []) and
  9197. (
  9198. (
  9199. (taicpu(hp3).condition = C_C) and
  9200. (taicpu(hp1).opcode = A_STC)
  9201. ) or (
  9202. (taicpu(hp3).condition = C_NC) and
  9203. (taicpu(hp1).opcode = A_CLC)
  9204. )
  9205. ) and
  9206. { Make sure the flags aren't used again }
  9207. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9208. begin
  9209. taicpu(hp1).allocate_oper(1);
  9210. taicpu(hp1).ops := 1;
  9211. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9212. taicpu(hp1).opcode := A_JMP;
  9213. taicpu(hp1).is_jmp := True;
  9214. TempBool := True; { Prevent compiler warnings }
  9215. if DoJumpOptimizations(p, TempBool) then
  9216. Result := True
  9217. else
  9218. Include(OptsToCheck, aoc_ForceNewIteration);
  9219. end;
  9220. end;
  9221. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9222. begin
  9223. { This generally only executes under -O3 and above }
  9224. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9225. end;
  9226. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9227. var
  9228. hp1, hp2: tai;
  9229. FoundComparison: Boolean;
  9230. begin
  9231. { Run the pass 1 optimisations as well, since they may have some effect
  9232. after the CMOV blocks are created in OptPass2Jcc }
  9233. Result := False;
  9234. { Result := OptPass1CMOVcc(p);
  9235. if Result then
  9236. Exit;}
  9237. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9238. and make a slightly inefficent result on branching-type blocks, notably
  9239. when setting a function result then jumping to the function epilogue.
  9240. In this case, change:
  9241. cmov(c) %reg1,%reg2
  9242. j(c) @lbl
  9243. (%reg2 deallocated)
  9244. To:
  9245. mov %reg11,%reg2
  9246. j(c) @lbl
  9247. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9248. jump because if it's not present, we may end up with a jump that's
  9249. completely unrelated.
  9250. }
  9251. hp1 := p;
  9252. while GetNextInstruction(hp1, hp1) and
  9253. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9254. if (hp1.typ = ait_instruction) and
  9255. (taicpu(hp1).opcode = A_Jcc) and
  9256. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9257. begin
  9258. TransferUsedRegs(TmpUsedRegs);
  9259. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9260. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9261. (
  9262. { See if we can find a more distant instruction that overwrites
  9263. the destination register }
  9264. (cs_opt_level3 in current_settings.optimizerswitches) and
  9265. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9266. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9267. ) then
  9268. begin
  9269. if (taicpu(p).oper[0]^.typ = top_reg) then
  9270. begin
  9271. { Search backwards to see if the source register is set to a
  9272. constant }
  9273. FoundComparison := False;
  9274. hp1 := p;
  9275. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9276. begin
  9277. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9278. begin
  9279. FoundComparison := True;
  9280. Continue;
  9281. end;
  9282. { Once we find the CMP, TEST or similar instruction, we
  9283. have to stop if we find anything other than a MOV }
  9284. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9285. Break;
  9286. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9287. { Destination register was modified }
  9288. Break;
  9289. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9290. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9291. begin
  9292. { Found a constant! }
  9293. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9294. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9295. { The source register is no longer in use }
  9296. RemoveInstruction(hp1);
  9297. Break;
  9298. end;
  9299. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9300. { Some other instruction has modified the source register }
  9301. Break;
  9302. end;
  9303. end;
  9304. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9305. taicpu(p).opcode := A_MOV;
  9306. taicpu(p).condition := C_None;
  9307. { Rely on the post peephole stage to put the MOV before the
  9308. CMP/TEST instruction that appears prior }
  9309. Result := True;
  9310. Exit;
  9311. end;
  9312. end;
  9313. end;
  9314. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9315. function IsXCHGAcceptable: Boolean; inline;
  9316. begin
  9317. { Always accept if optimising for size }
  9318. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9319. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9320. than 3, so it becomes a saving compared to three MOVs with two of
  9321. them able to execute simultaneously. [Kit] }
  9322. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9323. end;
  9324. var
  9325. NewRef: TReference;
  9326. hp1, hp2, hp3, hp4: Tai;
  9327. {$ifndef x86_64}
  9328. OperIdx: Integer;
  9329. {$endif x86_64}
  9330. NewInstr : Taicpu;
  9331. NewAligh : Tai_align;
  9332. DestLabel: TAsmLabel;
  9333. TempTracking: TAllUsedRegs;
  9334. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9335. var
  9336. NextInstr: tai;
  9337. begin
  9338. Result := False;
  9339. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9340. if not GetNextInstruction(InputInstr, NextInstr) or
  9341. (
  9342. { The FLAGS register isn't always tracked properly, so do not
  9343. perform this optimisation if a conditional statement follows }
  9344. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9345. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9346. ) then
  9347. begin
  9348. reference_reset(NewRef, 1, []);
  9349. NewRef.base := taicpu(p).oper[0]^.reg;
  9350. NewRef.scalefactor := 1;
  9351. if taicpu(InputInstr).opcode = A_ADD then
  9352. begin
  9353. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9354. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9355. end
  9356. else
  9357. begin
  9358. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9359. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9360. end;
  9361. taicpu(p).opcode := A_LEA;
  9362. taicpu(p).loadref(0, NewRef);
  9363. { For the sake of debugging, have the line info match the
  9364. arithmetic instruction rather than the MOV instruction }
  9365. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9366. RemoveInstruction(InputInstr);
  9367. Result := True;
  9368. end;
  9369. end;
  9370. begin
  9371. Result:=false;
  9372. { This optimisation adds an instruction, so only do it for speed }
  9373. if not (cs_opt_size in current_settings.optimizerswitches) and
  9374. MatchOpType(taicpu(p), top_const, top_reg) and
  9375. (taicpu(p).oper[0]^.val = 0) then
  9376. begin
  9377. { To avoid compiler warning }
  9378. DestLabel := nil;
  9379. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9380. InternalError(2021040750);
  9381. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9382. Exit;
  9383. case hp1.typ of
  9384. ait_label:
  9385. begin
  9386. { Change:
  9387. mov $0,%reg mov $0,%reg
  9388. @Lbl1: @Lbl1:
  9389. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9390. je @Lbl2 jne @Lbl2
  9391. To: To:
  9392. mov $0,%reg mov $0,%reg
  9393. jmp @Lbl2 jmp @Lbl3
  9394. (align) (align)
  9395. @Lbl1: @Lbl1:
  9396. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9397. je @Lbl2 je @Lbl2
  9398. @Lbl3: <-- Only if label exists
  9399. (Not if it's optimised for size)
  9400. }
  9401. if not GetNextInstruction(hp1, hp2) then
  9402. Exit;
  9403. if (hp2.typ = ait_instruction) and
  9404. (
  9405. { Register sizes must exactly match }
  9406. (
  9407. (taicpu(hp2).opcode = A_CMP) and
  9408. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9409. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9410. ) or (
  9411. (taicpu(hp2).opcode = A_TEST) and
  9412. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9413. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9414. )
  9415. ) and GetNextInstruction(hp2, hp3) and
  9416. (hp3.typ = ait_instruction) and
  9417. (taicpu(hp3).opcode = A_JCC) and
  9418. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  9419. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9420. begin
  9421. { Check condition of jump }
  9422. { Always true? }
  9423. if condition_in(C_E, taicpu(hp3).condition) then
  9424. begin
  9425. { Copy label symbol and obtain matching label entry for the
  9426. conditional jump, as this will be our destination}
  9427. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9428. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9429. Result := True;
  9430. end
  9431. { Always false? }
  9432. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9433. begin
  9434. { This is only worth it if there's a jump to take }
  9435. case hp2.typ of
  9436. ait_instruction:
  9437. begin
  9438. if taicpu(hp2).opcode = A_JMP then
  9439. begin
  9440. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9441. { An unconditional jump follows the conditional jump which will always be false,
  9442. so use this jump's destination for the new jump }
  9443. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9444. Result := True;
  9445. end
  9446. else if taicpu(hp2).opcode = A_JCC then
  9447. begin
  9448. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9449. if condition_in(C_E, taicpu(hp2).condition) then
  9450. begin
  9451. { A second conditional jump follows the conditional jump which will always be false,
  9452. while the second jump is always True, so use this jump's destination for the new jump }
  9453. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9454. Result := True;
  9455. end;
  9456. { Don't risk it if the jump isn't always true (Result remains False) }
  9457. end;
  9458. end;
  9459. else
  9460. { If anything else don't optimise };
  9461. end;
  9462. end;
  9463. if Result then
  9464. begin
  9465. { Just so we have something to insert as a paremeter}
  9466. reference_reset(NewRef, 1, []);
  9467. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9468. { Now actually load the correct parameter (this also
  9469. increases the reference count) }
  9470. NewInstr.loadsymbol(0, DestLabel, 0);
  9471. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9472. begin
  9473. { Get instruction before original label (may not be p under -O3) }
  9474. if not GetLastInstruction(hp1, hp2) then
  9475. { Shouldn't fail here }
  9476. InternalError(2021040701);
  9477. end
  9478. else
  9479. hp2 := p;
  9480. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9481. AsmL.InsertAfter(NewInstr, hp2);
  9482. { Add new alignment field }
  9483. (* AsmL.InsertAfter(
  9484. cai_align.create_max(
  9485. current_settings.alignment.jumpalign,
  9486. current_settings.alignment.jumpalignskipmax
  9487. ),
  9488. NewInstr
  9489. ); *)
  9490. end;
  9491. Exit;
  9492. end;
  9493. end;
  9494. else
  9495. ;
  9496. end;
  9497. end;
  9498. if not GetNextInstruction(p, hp1) then
  9499. Exit;
  9500. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9501. begin
  9502. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9503. begin
  9504. Result := True;
  9505. Exit;
  9506. end;
  9507. { This optimisation is only effective on a second run of Pass 2,
  9508. hence -O3 or above.
  9509. Change:
  9510. mov %reg1,%reg2
  9511. cmp/test (contains %reg1)
  9512. mov x, %reg1
  9513. (another mov or a j(c))
  9514. To:
  9515. mov %reg1,%reg2
  9516. mov x, %reg1
  9517. cmp (%reg1 replaced with %reg2)
  9518. (another mov or a j(c))
  9519. The requirement of an additional MOV or a jump ensures there
  9520. isn't performance loss, since a j(c) will permit macro-fusion
  9521. with the cmp instruction, while another MOV likely means it's
  9522. not all being executed in a single cycle due to parallelisation.
  9523. }
  9524. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9525. MatchOpType(taicpu(p), top_reg, top_reg) and
  9526. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9527. GetNextInstruction(hp1, hp2) and
  9528. MatchInstruction(hp2, A_MOV, []) and
  9529. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9530. { Registers don't have to be the same size in this case }
  9531. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9532. GetNextInstruction(hp2, hp3) and
  9533. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9534. { Make sure the operands in the camparison can be safely replaced }
  9535. (
  9536. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9537. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9538. ) and
  9539. (
  9540. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9541. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9542. ) then
  9543. begin
  9544. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9545. AsmL.Remove(hp2);
  9546. AsmL.InsertAfter(hp2, p);
  9547. Result := True;
  9548. Exit;
  9549. end;
  9550. end;
  9551. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9552. begin
  9553. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9554. further, but we can't just put this jump optimisation in pass 1
  9555. because it tends to perform worse when conditional jumps are
  9556. nearby (e.g. when converting CMOV instructions). [Kit] }
  9557. CopyUsedRegs(TempTracking);
  9558. UpdateUsedRegs(tai(p.Next));
  9559. if OptPass2JMP(hp1) then
  9560. begin
  9561. { Restore register state }
  9562. RestoreUsedRegs(TempTracking);
  9563. ReleaseUsedRegs(TempTracking);
  9564. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9565. OptPass1MOV(p);
  9566. Result := True;
  9567. Exit;
  9568. end;
  9569. { If OptPass2JMP returned False, no optimisations were done to
  9570. the jump and there are no further optimisations that can be done
  9571. to the MOV instruction on this pass other than FuncMov2Func }
  9572. { Restore register state }
  9573. RestoreUsedRegs(TempTracking);
  9574. ReleaseUsedRegs(TempTracking);
  9575. Result := FuncMov2Func(p, hp1);
  9576. Exit;
  9577. end;
  9578. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9579. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9580. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9581. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9582. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9583. begin
  9584. { Change:
  9585. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9586. addl/q $x,%reg2 subl/q $x,%reg2
  9587. To:
  9588. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9589. }
  9590. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9591. { be lazy, checking separately for sub would be slightly better }
  9592. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9593. begin
  9594. TransferUsedRegs(TmpUsedRegs);
  9595. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9596. if TryMovArith2Lea(hp1) then
  9597. begin
  9598. Result := True;
  9599. Exit;
  9600. end
  9601. end
  9602. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9603. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9604. { Same as above, but also adds or subtracts to %reg2 in between.
  9605. It's still valid as long as the flags aren't in use }
  9606. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9607. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9608. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9609. { be lazy, checking separately for sub would be slightly better }
  9610. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9611. begin
  9612. TransferUsedRegs(TmpUsedRegs);
  9613. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9614. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9615. if TryMovArith2Lea(hp2) then
  9616. begin
  9617. Result := True;
  9618. Exit;
  9619. end;
  9620. end;
  9621. end;
  9622. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9623. {$ifdef x86_64}
  9624. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9625. {$else x86_64}
  9626. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9627. {$endif x86_64}
  9628. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9629. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9630. { mov reg1, reg2 mov reg1, reg2
  9631. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9632. begin
  9633. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9634. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9635. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9636. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9637. TransferUsedRegs(TmpUsedRegs);
  9638. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9639. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9640. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9641. then
  9642. begin
  9643. RemoveCurrentP(p, hp1);
  9644. Result:=true;
  9645. end;
  9646. Exit;
  9647. end;
  9648. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9649. IsXCHGAcceptable and
  9650. { XCHG doesn't support 8-bit registers }
  9651. (taicpu(p).opsize <> S_B) and
  9652. MatchInstruction(hp1, A_MOV, []) and
  9653. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9654. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9655. GetNextInstruction(hp1, hp2) and
  9656. MatchInstruction(hp2, A_MOV, []) and
  9657. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9658. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9659. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9660. begin
  9661. { mov %reg1,%reg2
  9662. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9663. mov %reg2,%reg3
  9664. (%reg2 not used afterwards)
  9665. Note that xchg takes 3 cycles to execute, and generally mov's take
  9666. only one cycle apiece, but the first two mov's can be executed in
  9667. parallel, only taking 2 cycles overall. Older processors should
  9668. therefore only optimise for size. [Kit]
  9669. }
  9670. TransferUsedRegs(TmpUsedRegs);
  9671. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9672. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9673. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9674. begin
  9675. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9676. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9677. taicpu(hp1).opcode := A_XCHG;
  9678. RemoveCurrentP(p, hp1);
  9679. RemoveInstruction(hp2);
  9680. Result := True;
  9681. Exit;
  9682. end;
  9683. end;
  9684. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9685. MatchInstruction(hp1, A_SAR, []) then
  9686. begin
  9687. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9688. begin
  9689. { the use of %edx also covers the opsize being S_L }
  9690. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9691. begin
  9692. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9693. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9694. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9695. begin
  9696. { Change:
  9697. movl %eax,%edx
  9698. sarl $31,%edx
  9699. To:
  9700. cltd
  9701. }
  9702. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9703. RemoveInstruction(hp1);
  9704. taicpu(p).opcode := A_CDQ;
  9705. taicpu(p).opsize := S_NO;
  9706. taicpu(p).clearop(1);
  9707. taicpu(p).clearop(0);
  9708. taicpu(p).ops:=0;
  9709. Result := True;
  9710. Exit;
  9711. end
  9712. else if (cs_opt_size in current_settings.optimizerswitches) and
  9713. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9714. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9715. begin
  9716. { Change:
  9717. movl %edx,%eax
  9718. sarl $31,%edx
  9719. To:
  9720. movl %edx,%eax
  9721. cltd
  9722. Note that this creates a dependency between the two instructions,
  9723. so only perform if optimising for size.
  9724. }
  9725. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9726. taicpu(hp1).opcode := A_CDQ;
  9727. taicpu(hp1).opsize := S_NO;
  9728. taicpu(hp1).clearop(1);
  9729. taicpu(hp1).clearop(0);
  9730. taicpu(hp1).ops:=0;
  9731. Include(OptsToCheck, aoc_ForceNewIteration);
  9732. Exit;
  9733. end;
  9734. {$ifndef x86_64}
  9735. end
  9736. { Don't bother if CMOV is supported, because a more optimal
  9737. sequence would have been generated for the Abs() intrinsic }
  9738. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9739. { the use of %eax also covers the opsize being S_L }
  9740. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9741. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9742. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9743. GetNextInstruction(hp1, hp2) and
  9744. MatchInstruction(hp2, A_XOR, [S_L]) and
  9745. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9746. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9747. GetNextInstruction(hp2, hp3) and
  9748. MatchInstruction(hp3, A_SUB, [S_L]) and
  9749. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9750. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9751. begin
  9752. { Change:
  9753. movl %eax,%edx
  9754. sarl $31,%eax
  9755. xorl %eax,%edx
  9756. subl %eax,%edx
  9757. (Instruction that uses %edx)
  9758. (%eax deallocated)
  9759. (%edx deallocated)
  9760. To:
  9761. cltd
  9762. xorl %edx,%eax <-- Note the registers have swapped
  9763. subl %edx,%eax
  9764. (Instruction that uses %eax) <-- %eax rather than %edx
  9765. }
  9766. TransferUsedRegs(TmpUsedRegs);
  9767. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9768. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9769. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9770. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9771. begin
  9772. if GetNextInstruction(hp3, hp4) and
  9773. not RegModifiedByInstruction(NR_EDX, hp4) and
  9774. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9775. begin
  9776. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9777. taicpu(p).opcode := A_CDQ;
  9778. taicpu(p).clearop(1);
  9779. taicpu(p).clearop(0);
  9780. taicpu(p).ops:=0;
  9781. RemoveInstruction(hp1);
  9782. taicpu(hp2).loadreg(0, NR_EDX);
  9783. taicpu(hp2).loadreg(1, NR_EAX);
  9784. taicpu(hp3).loadreg(0, NR_EDX);
  9785. taicpu(hp3).loadreg(1, NR_EAX);
  9786. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9787. { Convert references in the following instruction (hp4) from %edx to %eax }
  9788. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9789. with taicpu(hp4).oper[OperIdx]^ do
  9790. case typ of
  9791. top_reg:
  9792. if getsupreg(reg) = RS_EDX then
  9793. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9794. top_ref:
  9795. begin
  9796. if getsupreg(reg) = RS_EDX then
  9797. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9798. if getsupreg(reg) = RS_EDX then
  9799. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9800. end;
  9801. else
  9802. ;
  9803. end;
  9804. Result := True;
  9805. Exit;
  9806. end;
  9807. end;
  9808. {$else x86_64}
  9809. end;
  9810. end
  9811. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9812. { the use of %rdx also covers the opsize being S_Q }
  9813. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9814. begin
  9815. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9816. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9817. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9818. begin
  9819. { Change:
  9820. movq %rax,%rdx
  9821. sarq $63,%rdx
  9822. To:
  9823. cqto
  9824. }
  9825. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9826. RemoveInstruction(hp1);
  9827. taicpu(p).opcode := A_CQO;
  9828. taicpu(p).opsize := S_NO;
  9829. taicpu(p).clearop(1);
  9830. taicpu(p).clearop(0);
  9831. taicpu(p).ops:=0;
  9832. Result := True;
  9833. Exit;
  9834. end
  9835. else if (cs_opt_size in current_settings.optimizerswitches) and
  9836. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9837. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9838. begin
  9839. { Change:
  9840. movq %rdx,%rax
  9841. sarq $63,%rdx
  9842. To:
  9843. movq %rdx,%rax
  9844. cqto
  9845. Note that this creates a dependency between the two instructions,
  9846. so only perform if optimising for size.
  9847. }
  9848. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9849. taicpu(hp1).opcode := A_CQO;
  9850. taicpu(hp1).opsize := S_NO;
  9851. taicpu(hp1).clearop(1);
  9852. taicpu(hp1).clearop(0);
  9853. taicpu(hp1).ops:=0;
  9854. Include(OptsToCheck, aoc_ForceNewIteration);
  9855. Exit;
  9856. {$endif x86_64}
  9857. end;
  9858. end;
  9859. end;
  9860. if MatchInstruction(hp1, A_MOV, []) and
  9861. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9862. { Though "GetNextInstruction" could be factored out, along with
  9863. the instructions that depend on hp2, it is an expensive call that
  9864. should be delayed for as long as possible, hence we do cheaper
  9865. checks first that are likely to be False. [Kit] }
  9866. begin
  9867. if (
  9868. (
  9869. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9870. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9871. (
  9872. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9873. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9874. )
  9875. ) or
  9876. (
  9877. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9878. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9879. (
  9880. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9881. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9882. )
  9883. )
  9884. ) and
  9885. GetNextInstruction(hp1, hp2) and
  9886. MatchInstruction(hp2, A_SAR, []) and
  9887. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9888. begin
  9889. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9890. begin
  9891. { Change:
  9892. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9893. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9894. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9895. To:
  9896. movl r/m,%eax <- Note the change in register
  9897. cltd
  9898. }
  9899. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9900. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9901. taicpu(p).loadreg(1, NR_EAX);
  9902. taicpu(hp1).opcode := A_CDQ;
  9903. taicpu(hp1).clearop(1);
  9904. taicpu(hp1).clearop(0);
  9905. taicpu(hp1).ops:=0;
  9906. RemoveInstruction(hp2);
  9907. Include(OptsToCheck, aoc_ForceNewIteration);
  9908. (*
  9909. {$ifdef x86_64}
  9910. end
  9911. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9912. { This code sequence does not get generated - however it might become useful
  9913. if and when 128-bit signed integer types make an appearance, so the code
  9914. is kept here for when it is eventually needed. [Kit] }
  9915. (
  9916. (
  9917. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9918. (
  9919. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9920. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9921. )
  9922. ) or
  9923. (
  9924. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9925. (
  9926. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9927. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9928. )
  9929. )
  9930. ) and
  9931. GetNextInstruction(hp1, hp2) and
  9932. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9933. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9934. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9935. begin
  9936. { Change:
  9937. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9938. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9939. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9940. To:
  9941. movq r/m,%rax <- Note the change in register
  9942. cqto
  9943. }
  9944. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9945. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9946. taicpu(p).loadreg(1, NR_RAX);
  9947. taicpu(hp1).opcode := A_CQO;
  9948. taicpu(hp1).clearop(1);
  9949. taicpu(hp1).clearop(0);
  9950. taicpu(hp1).ops:=0;
  9951. RemoveInstruction(hp2);
  9952. Include(OptsToCheck, aoc_ForceNewIteration);
  9953. {$endif x86_64}
  9954. *)
  9955. end;
  9956. end;
  9957. {$ifdef x86_64}
  9958. end;
  9959. if (taicpu(p).opsize = S_L) and
  9960. (taicpu(p).oper[1]^.typ = top_reg) and
  9961. (
  9962. MatchInstruction(hp1, A_MOV,[]) and
  9963. (taicpu(hp1).opsize = S_L) and
  9964. (taicpu(hp1).oper[1]^.typ = top_reg)
  9965. ) and (
  9966. GetNextInstruction(hp1, hp2) and
  9967. (tai(hp2).typ=ait_instruction) and
  9968. (taicpu(hp2).opsize = S_Q) and
  9969. (
  9970. (
  9971. MatchInstruction(hp2, A_ADD,[]) and
  9972. (taicpu(hp2).opsize = S_Q) and
  9973. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9974. (
  9975. (
  9976. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9977. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9978. ) or (
  9979. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9980. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9981. )
  9982. )
  9983. ) or (
  9984. MatchInstruction(hp2, A_LEA,[]) and
  9985. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9986. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9987. (
  9988. (
  9989. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9990. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9991. ) or (
  9992. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9993. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9994. )
  9995. ) and (
  9996. (
  9997. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9998. ) or (
  9999. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10000. )
  10001. )
  10002. )
  10003. )
  10004. ) and (
  10005. GetNextInstruction(hp2, hp3) and
  10006. MatchInstruction(hp3, A_SHR,[]) and
  10007. (taicpu(hp3).opsize = S_Q) and
  10008. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10009. (taicpu(hp3).oper[0]^.val = 1) and
  10010. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10011. ) then
  10012. begin
  10013. { Change movl x, reg1d movl x, reg1d
  10014. movl y, reg2d movl y, reg2d
  10015. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10016. shrq $1, reg1q shrq $1, reg1q
  10017. ( reg1d and reg2d can be switched around in the first two instructions )
  10018. To movl x, reg1d
  10019. addl y, reg1d
  10020. rcrl $1, reg1d
  10021. This corresponds to the common expression (x + y) shr 1, where
  10022. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10023. smaller code, but won't account for x + y causing an overflow). [Kit]
  10024. }
  10025. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10026. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10027. begin
  10028. { Change first MOV command to have the same register as the final output }
  10029. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10030. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10031. Result := True;
  10032. end
  10033. else
  10034. begin
  10035. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10036. Include(OptsToCheck, aoc_ForceNewIteration);
  10037. end;
  10038. { Change second MOV command to an ADD command. This is easier than
  10039. converting the existing command because it means we don't have to
  10040. touch 'y', which might be a complicated reference, and also the
  10041. fact that the third command might either be ADD or LEA. [Kit] }
  10042. taicpu(hp1).opcode := A_ADD;
  10043. { Delete old ADD/LEA instruction }
  10044. RemoveInstruction(hp2);
  10045. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10046. taicpu(hp3).opcode := A_RCR;
  10047. taicpu(hp3).changeopsize(S_L);
  10048. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10049. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10050. called, so FuncMov2Func below is safe to call }
  10051. {$endif x86_64}
  10052. end;
  10053. if FuncMov2Func(p, hp1) then
  10054. begin
  10055. Result := True;
  10056. Exit;
  10057. end;
  10058. end;
  10059. {$push}
  10060. {$q-}{$r-}
  10061. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10062. var
  10063. ThisReg: TRegister;
  10064. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10065. TargetSubReg: TSubRegister;
  10066. hp1, hp2: tai;
  10067. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10068. { Store list of found instructions so we don't have to call
  10069. GetNextInstructionUsingReg multiple times }
  10070. InstrList: array of taicpu;
  10071. InstrMax, Index: Integer;
  10072. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10073. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10074. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10075. WorkingValue: TCgInt;
  10076. PreMessage: string;
  10077. { Data flow analysis }
  10078. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10079. BitwiseOnly, OrXorUsed,
  10080. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10081. function CheckOverflowConditions: Boolean;
  10082. begin
  10083. Result := True;
  10084. if (TestValSignedMax > SignedUpperLimit) then
  10085. UpperSignedOverflow := True;
  10086. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10087. LowerSignedOverflow := True;
  10088. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10089. LowerUnsignedOverflow := True;
  10090. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10091. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10092. begin
  10093. { Absolute overflow }
  10094. Result := False;
  10095. Exit;
  10096. end;
  10097. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10098. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10099. ShiftDownOverflow := True;
  10100. if (TestValMin < 0) or (TestValMax < 0) then
  10101. begin
  10102. LowerUnsignedOverflow := True;
  10103. UpperUnsignedOverflow := True;
  10104. end;
  10105. end;
  10106. function AdjustInitialLoadAndSize: Boolean;
  10107. begin
  10108. Result := False;
  10109. if not p_removed then
  10110. begin
  10111. if TargetSize = MinSize then
  10112. begin
  10113. { Convert the input MOVZX to a MOV }
  10114. if (taicpu(p).oper[0]^.typ = top_reg) and
  10115. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10116. begin
  10117. { Or remove it completely! }
  10118. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10119. RemoveCurrentP(p);
  10120. p_removed := True;
  10121. end
  10122. else
  10123. begin
  10124. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10125. taicpu(p).opcode := A_MOV;
  10126. taicpu(p).oper[1]^.reg := ThisReg;
  10127. taicpu(p).opsize := TargetSize;
  10128. end;
  10129. Result := True;
  10130. end
  10131. else if TargetSize <> MaxSize then
  10132. begin
  10133. case MaxSize of
  10134. S_L:
  10135. if TargetSize = S_W then
  10136. begin
  10137. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10138. taicpu(p).opsize := S_BW;
  10139. taicpu(p).oper[1]^.reg := ThisReg;
  10140. Result := True;
  10141. end
  10142. else
  10143. InternalError(2020112341);
  10144. S_W:
  10145. if TargetSize = S_L then
  10146. begin
  10147. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10148. taicpu(p).opsize := S_BL;
  10149. taicpu(p).oper[1]^.reg := ThisReg;
  10150. Result := True;
  10151. end
  10152. else
  10153. InternalError(2020112342);
  10154. else
  10155. ;
  10156. end;
  10157. end
  10158. else if not hp1_removed and not RegInUse then
  10159. begin
  10160. { If we have something like:
  10161. movzbl (oper),%regd
  10162. add x, %regd
  10163. movzbl %regb, %regd
  10164. We can reduce the register size to the input of the final
  10165. movzbl instruction. Overflows won't have any effect.
  10166. }
  10167. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10168. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10169. begin
  10170. TargetSize := S_B;
  10171. setsubreg(ThisReg, R_SUBL);
  10172. Result := True;
  10173. end
  10174. else if (taicpu(p).opsize = S_WL) and
  10175. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10176. begin
  10177. TargetSize := S_W;
  10178. setsubreg(ThisReg, R_SUBW);
  10179. Result := True;
  10180. end;
  10181. if Result then
  10182. begin
  10183. { Convert the input MOVZX to a MOV }
  10184. if (taicpu(p).oper[0]^.typ = top_reg) and
  10185. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10186. begin
  10187. { Or remove it completely! }
  10188. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10189. RemoveCurrentP(p);
  10190. p_removed := True;
  10191. end
  10192. else
  10193. begin
  10194. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10195. taicpu(p).opcode := A_MOV;
  10196. taicpu(p).oper[1]^.reg := ThisReg;
  10197. taicpu(p).opsize := TargetSize;
  10198. end;
  10199. end;
  10200. end;
  10201. end;
  10202. end;
  10203. procedure AdjustFinalLoad;
  10204. begin
  10205. if not LowerUnsignedOverflow then
  10206. begin
  10207. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10208. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10209. begin
  10210. { Convert the output MOVZX to a MOV }
  10211. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10212. begin
  10213. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10214. if (MinSize = S_B) or
  10215. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10216. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10217. begin
  10218. { Remove it completely! }
  10219. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10220. { Be careful; if p = hp1 and p was also removed, p
  10221. will become a dangling pointer }
  10222. if p = hp1 then
  10223. begin
  10224. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10225. p_removed := True;
  10226. end
  10227. else
  10228. RemoveInstruction(hp1);
  10229. hp1_removed := True;
  10230. end;
  10231. end
  10232. else
  10233. begin
  10234. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10235. taicpu(hp1).opcode := A_MOV;
  10236. taicpu(hp1).oper[0]^.reg := ThisReg;
  10237. taicpu(hp1).opsize := TargetSize;
  10238. end;
  10239. end
  10240. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10241. begin
  10242. { Need to change the size of the output }
  10243. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10244. taicpu(hp1).oper[0]^.reg := ThisReg;
  10245. taicpu(hp1).opsize := S_BL;
  10246. end;
  10247. end;
  10248. end;
  10249. function CompressInstructions: Boolean;
  10250. var
  10251. LocalIndex: Integer;
  10252. begin
  10253. Result := False;
  10254. { The objective here is to try to find a combination that
  10255. removes one of the MOV/Z instructions. }
  10256. if (
  10257. (taicpu(p).oper[0]^.typ <> top_reg) or
  10258. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10259. ) and
  10260. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10261. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10262. begin
  10263. { Make a preference to remove the second MOVZX instruction }
  10264. case taicpu(hp1).opsize of
  10265. S_BL, S_WL:
  10266. begin
  10267. TargetSize := S_L;
  10268. TargetSubReg := R_SUBD;
  10269. end;
  10270. S_BW:
  10271. begin
  10272. TargetSize := S_W;
  10273. TargetSubReg := R_SUBW;
  10274. end;
  10275. else
  10276. InternalError(2020112302);
  10277. end;
  10278. end
  10279. else
  10280. begin
  10281. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10282. begin
  10283. { Exceeded lower bound but not upper bound }
  10284. TargetSize := MaxSize;
  10285. end
  10286. else if not LowerUnsignedOverflow then
  10287. begin
  10288. { Size didn't exceed lower bound }
  10289. TargetSize := MinSize;
  10290. end
  10291. else
  10292. Exit;
  10293. end;
  10294. case TargetSize of
  10295. S_B:
  10296. TargetSubReg := R_SUBL;
  10297. S_W:
  10298. TargetSubReg := R_SUBW;
  10299. S_L:
  10300. TargetSubReg := R_SUBD;
  10301. else
  10302. InternalError(2020112350);
  10303. end;
  10304. { Update the register to its new size }
  10305. setsubreg(ThisReg, TargetSubReg);
  10306. RegInUse := False;
  10307. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10308. begin
  10309. { Check to see if the active register is used afterwards;
  10310. if not, we can change it and make a saving. }
  10311. TransferUsedRegs(TmpUsedRegs);
  10312. { The target register may be marked as in use to cross
  10313. a jump to a distant label, so exclude it }
  10314. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10315. hp2 := p;
  10316. repeat
  10317. { Explicitly check for the excluded register (don't include the first
  10318. instruction as it may be reading from here }
  10319. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10320. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10321. begin
  10322. RegInUse := True;
  10323. Break;
  10324. end;
  10325. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10326. if not GetNextInstruction(hp2, hp2) then
  10327. InternalError(2020112340);
  10328. until (hp2 = hp1);
  10329. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10330. { We might still be able to get away with this }
  10331. RegInUse := not
  10332. (
  10333. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10334. (hp2.typ = ait_instruction) and
  10335. (
  10336. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10337. instruction that doesn't actually contain ThisReg }
  10338. (cs_opt_level3 in current_settings.optimizerswitches) or
  10339. RegInInstruction(ThisReg, hp2)
  10340. ) and
  10341. RegLoadedWithNewValue(ThisReg, hp2)
  10342. );
  10343. if not RegInUse then
  10344. begin
  10345. { Force the register size to the same as this instruction so it can be removed}
  10346. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10347. begin
  10348. TargetSize := S_L;
  10349. TargetSubReg := R_SUBD;
  10350. end
  10351. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10352. begin
  10353. TargetSize := S_W;
  10354. TargetSubReg := R_SUBW;
  10355. end;
  10356. ThisReg := taicpu(hp1).oper[1]^.reg;
  10357. setsubreg(ThisReg, TargetSubReg);
  10358. RegChanged := True;
  10359. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10360. TransferUsedRegs(TmpUsedRegs);
  10361. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10362. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10363. if p = hp1 then
  10364. begin
  10365. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10366. p_removed := True;
  10367. end
  10368. else
  10369. RemoveInstruction(hp1);
  10370. hp1_removed := True;
  10371. { Instruction will become "mov %reg,%reg" }
  10372. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10373. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10374. begin
  10375. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10376. RemoveCurrentP(p);
  10377. p_removed := True;
  10378. end
  10379. else
  10380. taicpu(p).oper[1]^.reg := ThisReg;
  10381. Result := True;
  10382. end
  10383. else
  10384. begin
  10385. if TargetSize <> MaxSize then
  10386. begin
  10387. { Since the register is in use, we have to force it to
  10388. MaxSize otherwise part of it may become undefined later on }
  10389. TargetSize := MaxSize;
  10390. case TargetSize of
  10391. S_B:
  10392. TargetSubReg := R_SUBL;
  10393. S_W:
  10394. TargetSubReg := R_SUBW;
  10395. S_L:
  10396. TargetSubReg := R_SUBD;
  10397. else
  10398. InternalError(2020112351);
  10399. end;
  10400. setsubreg(ThisReg, TargetSubReg);
  10401. end;
  10402. AdjustFinalLoad;
  10403. end;
  10404. end
  10405. else
  10406. AdjustFinalLoad;
  10407. Result := AdjustInitialLoadAndSize or Result;
  10408. { Now go through every instruction we found and change the
  10409. size. If TargetSize = MaxSize, then almost no changes are
  10410. needed and Result can remain False if it hasn't been set
  10411. yet.
  10412. If RegChanged is True, then the register requires changing
  10413. and so the point about TargetSize = MaxSize doesn't apply. }
  10414. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10415. begin
  10416. for LocalIndex := 0 to InstrMax do
  10417. begin
  10418. { If p_removed is true, then the original MOV/Z was removed
  10419. and removing the AND instruction may not be safe if it
  10420. appears first }
  10421. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10422. InternalError(2020112310);
  10423. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10424. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10425. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10426. InstrList[LocalIndex].opsize := TargetSize;
  10427. end;
  10428. Result := True;
  10429. end;
  10430. end;
  10431. begin
  10432. Result := False;
  10433. p_removed := False;
  10434. hp1_removed := False;
  10435. ThisReg := taicpu(p).oper[1]^.reg;
  10436. { Check for:
  10437. movs/z ###,%ecx (or %cx or %rcx)
  10438. ...
  10439. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10440. (dealloc %ecx)
  10441. Change to:
  10442. mov ###,%cl (if ### = %cl, then remove completely)
  10443. ...
  10444. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10445. }
  10446. if (getsupreg(ThisReg) = RS_ECX) and
  10447. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10448. (hp1.typ = ait_instruction) and
  10449. (
  10450. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10451. instruction that doesn't actually contain ECX }
  10452. (cs_opt_level3 in current_settings.optimizerswitches) or
  10453. RegInInstruction(NR_ECX, hp1) or
  10454. (
  10455. { It's common for the shift/rotate's read/write register to be
  10456. initialised in between, so under -O2 and under, search ahead
  10457. one more instruction
  10458. }
  10459. GetNextInstruction(hp1, hp1) and
  10460. (hp1.typ = ait_instruction) and
  10461. RegInInstruction(NR_ECX, hp1)
  10462. )
  10463. ) and
  10464. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10465. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10466. begin
  10467. TransferUsedRegs(TmpUsedRegs);
  10468. hp2 := p;
  10469. repeat
  10470. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10471. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10472. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10473. begin
  10474. case taicpu(p).opsize of
  10475. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10476. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10477. begin
  10478. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10479. RemoveCurrentP(p);
  10480. end
  10481. else
  10482. begin
  10483. taicpu(p).opcode := A_MOV;
  10484. taicpu(p).opsize := S_B;
  10485. taicpu(p).oper[1]^.reg := NR_CL;
  10486. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10487. end;
  10488. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10489. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10490. begin
  10491. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10492. RemoveCurrentP(p);
  10493. end
  10494. else
  10495. begin
  10496. taicpu(p).opcode := A_MOV;
  10497. taicpu(p).opsize := S_W;
  10498. taicpu(p).oper[1]^.reg := NR_CX;
  10499. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10500. end;
  10501. {$ifdef x86_64}
  10502. S_LQ:
  10503. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10504. begin
  10505. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10506. RemoveCurrentP(p);
  10507. end
  10508. else
  10509. begin
  10510. taicpu(p).opcode := A_MOV;
  10511. taicpu(p).opsize := S_L;
  10512. taicpu(p).oper[1]^.reg := NR_ECX;
  10513. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10514. end;
  10515. {$endif x86_64}
  10516. else
  10517. InternalError(2021120401);
  10518. end;
  10519. Result := True;
  10520. Exit;
  10521. end;
  10522. end;
  10523. { This is anything but quick! }
  10524. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10525. Exit;
  10526. SetLength(InstrList, 0);
  10527. InstrMax := -1;
  10528. case taicpu(p).opsize of
  10529. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10530. begin
  10531. {$if defined(i386) or defined(i8086)}
  10532. { If the target size is 8-bit, make sure we can actually encode it }
  10533. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10534. Exit;
  10535. {$endif i386 or i8086}
  10536. LowerLimit := $FF;
  10537. SignedLowerLimit := $7F;
  10538. SignedLowerLimitBottom := -128;
  10539. MinSize := S_B;
  10540. if taicpu(p).opsize = S_BW then
  10541. begin
  10542. MaxSize := S_W;
  10543. UpperLimit := $FFFF;
  10544. SignedUpperLimit := $7FFF;
  10545. SignedUpperLimitBottom := -32768;
  10546. end
  10547. else
  10548. begin
  10549. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10550. MaxSize := S_L;
  10551. UpperLimit := $FFFFFFFF;
  10552. SignedUpperLimit := $7FFFFFFF;
  10553. SignedUpperLimitBottom := -2147483648;
  10554. end;
  10555. end;
  10556. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10557. begin
  10558. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10559. LowerLimit := $FFFF;
  10560. SignedLowerLimit := $7FFF;
  10561. SignedLowerLimitBottom := -32768;
  10562. UpperLimit := $FFFFFFFF;
  10563. SignedUpperLimit := $7FFFFFFF;
  10564. SignedUpperLimitBottom := -2147483648;
  10565. MinSize := S_W;
  10566. MaxSize := S_L;
  10567. end;
  10568. {$ifdef x86_64}
  10569. S_LQ:
  10570. begin
  10571. { Both the lower and upper limits are set to 32-bit. If a limit
  10572. is breached, then optimisation is impossible }
  10573. LowerLimit := $FFFFFFFF;
  10574. SignedLowerLimit := $7FFFFFFF;
  10575. SignedLowerLimitBottom := -2147483648;
  10576. UpperLimit := $FFFFFFFF;
  10577. SignedUpperLimit := $7FFFFFFF;
  10578. SignedUpperLimitBottom := -2147483648;
  10579. MinSize := S_L;
  10580. MaxSize := S_L;
  10581. end;
  10582. {$endif x86_64}
  10583. else
  10584. InternalError(2020112301);
  10585. end;
  10586. TestValMin := 0;
  10587. TestValMax := LowerLimit;
  10588. TestValSignedMax := SignedLowerLimit;
  10589. TryShiftDownLimit := LowerLimit;
  10590. TryShiftDown := S_NO;
  10591. ShiftDownOverflow := False;
  10592. RegChanged := False;
  10593. BitwiseOnly := True;
  10594. OrXorUsed := False;
  10595. UpperSignedOverflow := False;
  10596. LowerSignedOverflow := False;
  10597. UpperUnsignedOverflow := False;
  10598. LowerUnsignedOverflow := False;
  10599. hp1 := p;
  10600. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10601. (hp1.typ = ait_instruction) and
  10602. (
  10603. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10604. instruction that doesn't actually contain ThisReg }
  10605. (cs_opt_level3 in current_settings.optimizerswitches) or
  10606. { This allows this Movx optimisation to work through the SETcc instructions
  10607. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10608. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10609. skip over these SETcc instructions). }
  10610. (taicpu(hp1).opcode = A_SETcc) or
  10611. RegInInstruction(ThisReg, hp1)
  10612. ) do
  10613. begin
  10614. case taicpu(hp1).opcode of
  10615. A_INC,A_DEC:
  10616. begin
  10617. { Has to be an exact match on the register }
  10618. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10619. Break;
  10620. if taicpu(hp1).opcode = A_INC then
  10621. begin
  10622. Inc(TestValMin);
  10623. Inc(TestValMax);
  10624. Inc(TestValSignedMax);
  10625. end
  10626. else
  10627. begin
  10628. Dec(TestValMin);
  10629. Dec(TestValMax);
  10630. Dec(TestValSignedMax);
  10631. end;
  10632. end;
  10633. A_TEST, A_CMP:
  10634. begin
  10635. if (
  10636. { Too high a risk of non-linear behaviour that breaks DFA
  10637. here, unless it's cmp $0,%reg, which is equivalent to
  10638. test %reg,%reg }
  10639. OrXorUsed and
  10640. (taicpu(hp1).opcode = A_CMP) and
  10641. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10642. ) or
  10643. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10644. { Has to be an exact match on the register }
  10645. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10646. (
  10647. { Permit "test %reg,%reg" }
  10648. (taicpu(hp1).opcode = A_TEST) and
  10649. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10650. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10651. ) or
  10652. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10653. { Make sure the comparison value is not smaller than the
  10654. smallest allowed signed value for the minimum size (e.g.
  10655. -128 for 8-bit) }
  10656. not (
  10657. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10658. { Is it in the negative range? }
  10659. (
  10660. (taicpu(hp1).oper[0]^.val < 0) and
  10661. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10662. )
  10663. ) then
  10664. Break;
  10665. { Check to see if the active register is used afterwards }
  10666. TransferUsedRegs(TmpUsedRegs);
  10667. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10668. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10669. begin
  10670. { Make sure the comparison or any previous instructions
  10671. hasn't pushed the test values outside of the range of
  10672. MinSize }
  10673. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10674. begin
  10675. { Exceeded lower bound but not upper bound }
  10676. Exit;
  10677. end
  10678. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10679. begin
  10680. { Size didn't exceed lower bound }
  10681. TargetSize := MinSize;
  10682. end
  10683. else
  10684. Break;
  10685. case TargetSize of
  10686. S_B:
  10687. TargetSubReg := R_SUBL;
  10688. S_W:
  10689. TargetSubReg := R_SUBW;
  10690. S_L:
  10691. TargetSubReg := R_SUBD;
  10692. else
  10693. InternalError(2021051002);
  10694. end;
  10695. if TargetSize <> MaxSize then
  10696. begin
  10697. { Update the register to its new size }
  10698. setsubreg(ThisReg, TargetSubReg);
  10699. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10700. taicpu(hp1).oper[1]^.reg := ThisReg;
  10701. taicpu(hp1).opsize := TargetSize;
  10702. { Convert the input MOVZX to a MOV if necessary }
  10703. AdjustInitialLoadAndSize;
  10704. if (InstrMax >= 0) then
  10705. begin
  10706. for Index := 0 to InstrMax do
  10707. begin
  10708. { If p_removed is true, then the original MOV/Z was removed
  10709. and removing the AND instruction may not be safe if it
  10710. appears first }
  10711. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10712. InternalError(2020112311);
  10713. if InstrList[Index].oper[0]^.typ = top_reg then
  10714. InstrList[Index].oper[0]^.reg := ThisReg;
  10715. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10716. InstrList[Index].opsize := MinSize;
  10717. end;
  10718. end;
  10719. Result := True;
  10720. end;
  10721. Exit;
  10722. end;
  10723. end;
  10724. A_SETcc:
  10725. begin
  10726. { This allows this Movx optimisation to work through the SETcc instructions
  10727. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10728. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10729. skip over these SETcc instructions). }
  10730. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10731. { Of course, break out if the current register is used }
  10732. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10733. Break
  10734. else
  10735. { We must use Continue so the instruction doesn't get added
  10736. to InstrList }
  10737. Continue;
  10738. end;
  10739. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10740. begin
  10741. if
  10742. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10743. { Has to be an exact match on the register }
  10744. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10745. (
  10746. (
  10747. (taicpu(hp1).oper[0]^.typ = top_const) and
  10748. (
  10749. (
  10750. (taicpu(hp1).opcode = A_SHL) and
  10751. (
  10752. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10753. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10754. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10755. )
  10756. ) or (
  10757. (taicpu(hp1).opcode <> A_SHL) and
  10758. (
  10759. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10760. { Is it in the negative range? }
  10761. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10762. )
  10763. )
  10764. )
  10765. ) or (
  10766. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10767. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10768. )
  10769. ) then
  10770. Break;
  10771. { Only process OR and XOR if there are only bitwise operations,
  10772. since otherwise they can too easily fool the data flow
  10773. analysis (they can cause non-linear behaviour) }
  10774. case taicpu(hp1).opcode of
  10775. A_ADD:
  10776. begin
  10777. if OrXorUsed then
  10778. { Too high a risk of non-linear behaviour that breaks DFA here }
  10779. Break
  10780. else
  10781. BitwiseOnly := False;
  10782. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10783. begin
  10784. TestValMin := TestValMin * 2;
  10785. TestValMax := TestValMax * 2;
  10786. TestValSignedMax := TestValSignedMax * 2;
  10787. end
  10788. else
  10789. begin
  10790. WorkingValue := taicpu(hp1).oper[0]^.val;
  10791. TestValMin := TestValMin + WorkingValue;
  10792. TestValMax := TestValMax + WorkingValue;
  10793. TestValSignedMax := TestValSignedMax + WorkingValue;
  10794. end;
  10795. end;
  10796. A_SUB:
  10797. begin
  10798. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10799. begin
  10800. TestValMin := 0;
  10801. TestValMax := 0;
  10802. TestValSignedMax := 0;
  10803. end
  10804. else
  10805. begin
  10806. if OrXorUsed then
  10807. { Too high a risk of non-linear behaviour that breaks DFA here }
  10808. Break
  10809. else
  10810. BitwiseOnly := False;
  10811. WorkingValue := taicpu(hp1).oper[0]^.val;
  10812. TestValMin := TestValMin - WorkingValue;
  10813. TestValMax := TestValMax - WorkingValue;
  10814. TestValSignedMax := TestValSignedMax - WorkingValue;
  10815. end;
  10816. end;
  10817. A_AND:
  10818. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10819. begin
  10820. { we might be able to go smaller if AND appears first }
  10821. if InstrMax = -1 then
  10822. case MinSize of
  10823. S_B:
  10824. ;
  10825. S_W:
  10826. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10827. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10828. begin
  10829. TryShiftDown := S_B;
  10830. TryShiftDownLimit := $FF;
  10831. end;
  10832. S_L:
  10833. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10834. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10835. begin
  10836. TryShiftDown := S_B;
  10837. TryShiftDownLimit := $FF;
  10838. end
  10839. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10840. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10841. begin
  10842. TryShiftDown := S_W;
  10843. TryShiftDownLimit := $FFFF;
  10844. end;
  10845. else
  10846. InternalError(2020112320);
  10847. end;
  10848. WorkingValue := taicpu(hp1).oper[0]^.val;
  10849. TestValMin := TestValMin and WorkingValue;
  10850. TestValMax := TestValMax and WorkingValue;
  10851. TestValSignedMax := TestValSignedMax and WorkingValue;
  10852. end;
  10853. A_OR:
  10854. begin
  10855. if not BitwiseOnly then
  10856. Break;
  10857. OrXorUsed := True;
  10858. WorkingValue := taicpu(hp1).oper[0]^.val;
  10859. TestValMin := TestValMin or WorkingValue;
  10860. TestValMax := TestValMax or WorkingValue;
  10861. TestValSignedMax := TestValSignedMax or WorkingValue;
  10862. end;
  10863. A_XOR:
  10864. begin
  10865. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10866. begin
  10867. TestValMin := 0;
  10868. TestValMax := 0;
  10869. TestValSignedMax := 0;
  10870. end
  10871. else
  10872. begin
  10873. if not BitwiseOnly then
  10874. Break;
  10875. OrXorUsed := True;
  10876. WorkingValue := taicpu(hp1).oper[0]^.val;
  10877. TestValMin := TestValMin xor WorkingValue;
  10878. TestValMax := TestValMax xor WorkingValue;
  10879. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10880. end;
  10881. end;
  10882. A_SHL:
  10883. begin
  10884. BitwiseOnly := False;
  10885. WorkingValue := taicpu(hp1).oper[0]^.val;
  10886. TestValMin := TestValMin shl WorkingValue;
  10887. TestValMax := TestValMax shl WorkingValue;
  10888. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10889. end;
  10890. A_SHR,
  10891. { The first instruction was MOVZX, so the value won't be negative }
  10892. A_SAR:
  10893. begin
  10894. if InstrMax <> -1 then
  10895. BitwiseOnly := False
  10896. else
  10897. { we might be able to go smaller if SHR appears first }
  10898. case MinSize of
  10899. S_B:
  10900. ;
  10901. S_W:
  10902. if (taicpu(hp1).oper[0]^.val >= 8) then
  10903. begin
  10904. TryShiftDown := S_B;
  10905. TryShiftDownLimit := $FF;
  10906. TryShiftDownSignedLimit := $7F;
  10907. TryShiftDownSignedLimitLower := -128;
  10908. end;
  10909. S_L:
  10910. if (taicpu(hp1).oper[0]^.val >= 24) then
  10911. begin
  10912. TryShiftDown := S_B;
  10913. TryShiftDownLimit := $FF;
  10914. TryShiftDownSignedLimit := $7F;
  10915. TryShiftDownSignedLimitLower := -128;
  10916. end
  10917. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10918. begin
  10919. TryShiftDown := S_W;
  10920. TryShiftDownLimit := $FFFF;
  10921. TryShiftDownSignedLimit := $7FFF;
  10922. TryShiftDownSignedLimitLower := -32768;
  10923. end;
  10924. else
  10925. InternalError(2020112321);
  10926. end;
  10927. WorkingValue := taicpu(hp1).oper[0]^.val;
  10928. if taicpu(hp1).opcode = A_SAR then
  10929. begin
  10930. TestValMin := SarInt64(TestValMin, WorkingValue);
  10931. TestValMax := SarInt64(TestValMax, WorkingValue);
  10932. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10933. end
  10934. else
  10935. begin
  10936. TestValMin := TestValMin shr WorkingValue;
  10937. TestValMax := TestValMax shr WorkingValue;
  10938. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10939. end;
  10940. end;
  10941. else
  10942. InternalError(2020112303);
  10943. end;
  10944. end;
  10945. (*
  10946. A_IMUL:
  10947. case taicpu(hp1).ops of
  10948. 2:
  10949. begin
  10950. if not MatchOpType(hp1, top_reg, top_reg) or
  10951. { Has to be an exact match on the register }
  10952. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10953. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10954. Break;
  10955. TestValMin := TestValMin * TestValMin;
  10956. TestValMax := TestValMax * TestValMax;
  10957. TestValSignedMax := TestValSignedMax * TestValMax;
  10958. end;
  10959. 3:
  10960. begin
  10961. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10962. { Has to be an exact match on the register }
  10963. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10964. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10965. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10966. { Is it in the negative range? }
  10967. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10968. Break;
  10969. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10970. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10971. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10972. end;
  10973. else
  10974. Break;
  10975. end;
  10976. A_IDIV:
  10977. case taicpu(hp1).ops of
  10978. 3:
  10979. begin
  10980. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10981. { Has to be an exact match on the register }
  10982. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10983. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10984. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10985. { Is it in the negative range? }
  10986. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10987. Break;
  10988. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10989. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10990. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10991. end;
  10992. else
  10993. Break;
  10994. end;
  10995. *)
  10996. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10997. begin
  10998. { If there are no instructions in between, then we might be able to make a saving }
  10999. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11000. Break;
  11001. { We have something like:
  11002. movzbw %dl,%dx
  11003. ...
  11004. movswl %dx,%edx
  11005. Change the latter to a zero-extension then enter the
  11006. A_MOVZX case branch.
  11007. }
  11008. {$ifdef x86_64}
  11009. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11010. begin
  11011. { this becomes a zero extension from 32-bit to 64-bit, but
  11012. the upper 32 bits are already zero, so just delete the
  11013. instruction }
  11014. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11015. RemoveInstruction(hp1);
  11016. Result := True;
  11017. Exit;
  11018. end
  11019. else
  11020. {$endif x86_64}
  11021. begin
  11022. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11023. taicpu(hp1).opcode := A_MOVZX;
  11024. {$ifdef x86_64}
  11025. case taicpu(hp1).opsize of
  11026. S_BQ:
  11027. begin
  11028. taicpu(hp1).opsize := S_BL;
  11029. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11030. end;
  11031. S_WQ:
  11032. begin
  11033. taicpu(hp1).opsize := S_WL;
  11034. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11035. end;
  11036. S_LQ:
  11037. begin
  11038. taicpu(hp1).opcode := A_MOV;
  11039. taicpu(hp1).opsize := S_L;
  11040. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11041. { In this instance, we need to break out because the
  11042. instruction is no longer MOVZX or MOVSXD }
  11043. Result := True;
  11044. Exit;
  11045. end;
  11046. else
  11047. ;
  11048. end;
  11049. {$endif x86_64}
  11050. Result := CompressInstructions;
  11051. Exit;
  11052. end;
  11053. end;
  11054. A_MOVZX:
  11055. begin
  11056. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11057. Break;
  11058. if (InstrMax = -1) then
  11059. begin
  11060. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11061. begin
  11062. { Optimise around i40003 }
  11063. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  11064. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11065. {$ifndef x86_64}
  11066. and (
  11067. (taicpu(p).oper[0]^.typ <> top_reg) or
  11068. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11069. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11070. )
  11071. {$endif not x86_64}
  11072. then
  11073. begin
  11074. if (taicpu(p).oper[0]^.typ = top_reg) then
  11075. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11076. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11077. taicpu(p).opsize := S_BL;
  11078. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11079. RemoveInstruction(hp1);
  11080. Result := True;
  11081. Exit;
  11082. end;
  11083. end
  11084. else
  11085. begin
  11086. { Will return false if the second parameter isn't ThisReg
  11087. (can happen on -O2 and under) }
  11088. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11089. begin
  11090. { The two MOVZX instructions are adjacent, so remove the first one }
  11091. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11092. RemoveCurrentP(p);
  11093. Result := True;
  11094. Exit;
  11095. end;
  11096. Break;
  11097. end;
  11098. end;
  11099. Result := CompressInstructions;
  11100. Exit;
  11101. end;
  11102. else
  11103. { This includes ADC, SBB and IDIV }
  11104. Break;
  11105. end;
  11106. if not CheckOverflowConditions then
  11107. Break;
  11108. { Contains highest index (so instruction count - 1) }
  11109. Inc(InstrMax);
  11110. if InstrMax > High(InstrList) then
  11111. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11112. InstrList[InstrMax] := taicpu(hp1);
  11113. end;
  11114. end;
  11115. {$pop}
  11116. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11117. var
  11118. hp1 : tai;
  11119. begin
  11120. Result:=false;
  11121. if (taicpu(p).ops >= 2) and
  11122. ((taicpu(p).oper[0]^.typ = top_const) or
  11123. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11124. (taicpu(p).oper[1]^.typ = top_reg) and
  11125. ((taicpu(p).ops = 2) or
  11126. ((taicpu(p).oper[2]^.typ = top_reg) and
  11127. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11128. GetLastInstruction(p,hp1) and
  11129. MatchInstruction(hp1,A_MOV,[]) and
  11130. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11131. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11132. begin
  11133. TransferUsedRegs(TmpUsedRegs);
  11134. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11135. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11136. { change
  11137. mov reg1,reg2
  11138. imul y,reg2 to imul y,reg1,reg2 }
  11139. begin
  11140. taicpu(p).ops := 3;
  11141. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11142. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11143. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11144. RemoveInstruction(hp1);
  11145. result:=true;
  11146. end;
  11147. end;
  11148. end;
  11149. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11150. var
  11151. ThisLabel: TAsmLabel;
  11152. begin
  11153. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11154. ThisLabel.decrefs;
  11155. taicpu(p).condition := C_None;
  11156. taicpu(p).opcode := A_RET;
  11157. taicpu(p).is_jmp := false;
  11158. taicpu(p).ops := taicpu(ret_p).ops;
  11159. case taicpu(ret_p).ops of
  11160. 0:
  11161. taicpu(p).clearop(0);
  11162. 1:
  11163. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11164. else
  11165. internalerror(2016041301);
  11166. end;
  11167. { If the original label is now dead, it might turn out that the label
  11168. immediately follows p. As a result, everything beyond it, which will
  11169. be just some final register configuration and a RET instruction, is
  11170. now dead code. [Kit] }
  11171. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11172. running RemoveDeadCodeAfterJump for each RET instruction, because
  11173. this optimisation rarely happens and most RETs appear at the end of
  11174. routines where there is nothing that can be stripped. [Kit] }
  11175. if not ThisLabel.is_used then
  11176. RemoveDeadCodeAfterJump(p);
  11177. end;
  11178. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11179. var
  11180. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11181. Unconditional, PotentialModified: Boolean;
  11182. OperPtr: POper;
  11183. NewRef: TReference;
  11184. InstrList: array of taicpu;
  11185. InstrMax, Index: Integer;
  11186. const
  11187. {$ifdef DEBUG_AOPTCPU}
  11188. SNoFlags: shortstring = ' so the flags aren''t modified';
  11189. {$else DEBUG_AOPTCPU}
  11190. SNoFlags = '';
  11191. {$endif DEBUG_AOPTCPU}
  11192. begin
  11193. Result:=false;
  11194. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11195. begin
  11196. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11197. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11198. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11199. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11200. GetNextInstruction(hp1, hp2) and
  11201. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11202. { Change from: To:
  11203. set(C) %reg j(~C) label
  11204. test %reg,%reg/cmp $0,%reg
  11205. je label
  11206. set(C) %reg j(C) label
  11207. test %reg,%reg/cmp $0,%reg
  11208. jne label
  11209. (Also do something similar with sete/setne instead of je/jne)
  11210. }
  11211. begin
  11212. { Before we do anything else, we need to check the instructions
  11213. in between SETcc and TEST to make sure they don't modify the
  11214. FLAGS register - if -O2 or under, there won't be any
  11215. instructions between SET and TEST }
  11216. TransferUsedRegs(TmpUsedRegs);
  11217. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11218. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11219. begin
  11220. next := p;
  11221. SetLength(InstrList, 0);
  11222. InstrMax := -1;
  11223. PotentialModified := False;
  11224. { Make a note of every instruction that modifies the FLAGS
  11225. register }
  11226. while GetNextInstruction(next, next) and (next <> hp1) do
  11227. begin
  11228. if next.typ <> ait_instruction then
  11229. { GetNextInstructionUsingReg should have returned False }
  11230. InternalError(2021051701);
  11231. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11232. begin
  11233. case taicpu(next).opcode of
  11234. A_SETcc,
  11235. A_CMOVcc,
  11236. A_Jcc:
  11237. begin
  11238. if PotentialModified then
  11239. { Not safe because the flags were modified earlier }
  11240. Exit
  11241. else
  11242. { Condition is the same as the initial SETcc, so this is safe
  11243. (don't add to instruction list though) }
  11244. Continue;
  11245. end;
  11246. A_ADD:
  11247. begin
  11248. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11249. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11250. (taicpu(next).oper[1]^.typ <> top_reg) or
  11251. { Must write to a register }
  11252. (taicpu(next).oper[0]^.typ = top_ref) then
  11253. { Require a constant or a register }
  11254. Exit;
  11255. PotentialModified := True;
  11256. end;
  11257. A_SUB:
  11258. begin
  11259. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11260. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11261. (taicpu(next).oper[1]^.typ <> top_reg) or
  11262. { Must write to a register }
  11263. (taicpu(next).oper[0]^.typ <> top_const) or
  11264. (taicpu(next).oper[0]^.val = $80000000) then
  11265. { Can't subtract a register with LEA - also
  11266. check that the value isn't -2^31, as this
  11267. can't be negated }
  11268. Exit;
  11269. PotentialModified := True;
  11270. end;
  11271. A_SAL,
  11272. A_SHL:
  11273. begin
  11274. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11275. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11276. (taicpu(next).oper[1]^.typ <> top_reg) or
  11277. { Must write to a register }
  11278. (taicpu(next).oper[0]^.typ <> top_const) or
  11279. (taicpu(next).oper[0]^.val < 0) or
  11280. (taicpu(next).oper[0]^.val > 3) then
  11281. Exit;
  11282. PotentialModified := True;
  11283. end;
  11284. A_IMUL:
  11285. begin
  11286. if (taicpu(next).ops <> 3) or
  11287. (taicpu(next).oper[1]^.typ <> top_reg) or
  11288. { Must write to a register }
  11289. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11290. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11291. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11292. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11293. Exit
  11294. else
  11295. PotentialModified := True;
  11296. end;
  11297. else
  11298. { Don't know how to change this, so abort }
  11299. Exit;
  11300. end;
  11301. { Contains highest index (so instruction count - 1) }
  11302. Inc(InstrMax);
  11303. if InstrMax > High(InstrList) then
  11304. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11305. InstrList[InstrMax] := taicpu(next);
  11306. end;
  11307. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11308. end;
  11309. if not Assigned(next) or (next <> hp1) then
  11310. { It should be equal to hp1 }
  11311. InternalError(2021051702);
  11312. { Cycle through each instruction and check to see if we can
  11313. change them to versions that don't modify the flags }
  11314. if (InstrMax >= 0) then
  11315. begin
  11316. for Index := 0 to InstrMax do
  11317. case InstrList[Index].opcode of
  11318. A_ADD:
  11319. begin
  11320. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11321. InstrList[Index].opcode := A_LEA;
  11322. reference_reset(NewRef, 1, []);
  11323. NewRef.base := InstrList[Index].oper[1]^.reg;
  11324. if InstrList[Index].oper[0]^.typ = top_reg then
  11325. begin
  11326. NewRef.index := InstrList[Index].oper[0]^.reg;
  11327. NewRef.scalefactor := 1;
  11328. end
  11329. else
  11330. NewRef.offset := InstrList[Index].oper[0]^.val;
  11331. InstrList[Index].loadref(0, NewRef);
  11332. end;
  11333. A_SUB:
  11334. begin
  11335. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11336. InstrList[Index].opcode := A_LEA;
  11337. reference_reset(NewRef, 1, []);
  11338. NewRef.base := InstrList[Index].oper[1]^.reg;
  11339. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11340. InstrList[Index].loadref(0, NewRef);
  11341. end;
  11342. A_SHL,
  11343. A_SAL:
  11344. begin
  11345. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11346. InstrList[Index].opcode := A_LEA;
  11347. reference_reset(NewRef, 1, []);
  11348. NewRef.index := InstrList[Index].oper[1]^.reg;
  11349. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11350. InstrList[Index].loadref(0, NewRef);
  11351. end;
  11352. A_IMUL:
  11353. begin
  11354. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11355. InstrList[Index].opcode := A_LEA;
  11356. reference_reset(NewRef, 1, []);
  11357. NewRef.index := InstrList[Index].oper[1]^.reg;
  11358. case InstrList[Index].oper[0]^.val of
  11359. 2, 4, 8:
  11360. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11361. else {3, 5 and 9}
  11362. begin
  11363. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11364. NewRef.base := InstrList[Index].oper[1]^.reg;
  11365. end;
  11366. end;
  11367. InstrList[Index].loadref(0, NewRef);
  11368. end;
  11369. else
  11370. InternalError(2021051710);
  11371. end;
  11372. end;
  11373. { Mark the FLAGS register as used across this whole block }
  11374. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11375. end;
  11376. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11377. JumpC := taicpu(hp2).condition;
  11378. Unconditional := False;
  11379. if conditions_equal(JumpC, C_E) then
  11380. SetC := inverse_cond(taicpu(p).condition)
  11381. else if conditions_equal(JumpC, C_NE) then
  11382. SetC := taicpu(p).condition
  11383. else
  11384. { We've got something weird here (and inefficent) }
  11385. begin
  11386. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11387. SetC := C_NONE;
  11388. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11389. if condition_in(C_AE, JumpC) then
  11390. Unconditional := True
  11391. else
  11392. { Not sure what to do with this jump - drop out }
  11393. Exit;
  11394. end;
  11395. RemoveInstruction(hp1);
  11396. if Unconditional then
  11397. MakeUnconditional(taicpu(hp2))
  11398. else
  11399. begin
  11400. if SetC = C_NONE then
  11401. InternalError(2018061402);
  11402. taicpu(hp2).SetCondition(SetC);
  11403. end;
  11404. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11405. TmpUsedRegs }
  11406. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11407. begin
  11408. RemoveCurrentp(p, hp2);
  11409. if taicpu(hp2).opcode = A_SETcc then
  11410. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11411. else
  11412. begin
  11413. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11414. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11415. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11416. end;
  11417. end
  11418. else
  11419. if taicpu(hp2).opcode = A_SETcc then
  11420. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11421. else
  11422. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11423. Result := True;
  11424. end
  11425. else if
  11426. { Make sure the instructions are adjacent }
  11427. (
  11428. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11429. GetNextInstruction(p, hp1)
  11430. ) and
  11431. MatchInstruction(hp1, A_MOV, [S_B]) and
  11432. { Writing to memory is allowed }
  11433. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11434. begin
  11435. {
  11436. Watch out for sequences such as:
  11437. set(c)b %regb
  11438. movb %regb,(ref)
  11439. movb $0,1(ref)
  11440. movb $0,2(ref)
  11441. movb $0,3(ref)
  11442. Much more efficient to turn it into:
  11443. movl $0,%regl
  11444. set(c)b %regb
  11445. movl %regl,(ref)
  11446. Or:
  11447. set(c)b %regb
  11448. movzbl %regb,%regl
  11449. movl %regl,(ref)
  11450. }
  11451. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11452. GetNextInstruction(hp1, hp2) and
  11453. MatchInstruction(hp2, A_MOV, [S_B]) and
  11454. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11455. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11456. begin
  11457. { Don't do anything else except set Result to True }
  11458. end
  11459. else
  11460. begin
  11461. if taicpu(p).oper[0]^.typ = top_reg then
  11462. begin
  11463. TransferUsedRegs(TmpUsedRegs);
  11464. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11465. end;
  11466. { If it's not a register, it's a memory address }
  11467. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11468. begin
  11469. { Even if the register is still in use, we can minimise the
  11470. pipeline stall by changing the MOV into another SETcc. }
  11471. taicpu(hp1).opcode := A_SETcc;
  11472. taicpu(hp1).condition := taicpu(p).condition;
  11473. if taicpu(hp1).oper[1]^.typ = top_ref then
  11474. begin
  11475. { Swapping the operand pointers like this is probably a
  11476. bit naughty, but it is far faster than using loadoper
  11477. to transfer the reference from oper[1] to oper[0] if
  11478. you take into account the extra procedure calls and
  11479. the memory allocation and deallocation required }
  11480. OperPtr := taicpu(hp1).oper[1];
  11481. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11482. taicpu(hp1).oper[0] := OperPtr;
  11483. end
  11484. else
  11485. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11486. taicpu(hp1).clearop(1);
  11487. taicpu(hp1).ops := 1;
  11488. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11489. end
  11490. else
  11491. begin
  11492. if taicpu(hp1).oper[1]^.typ = top_reg then
  11493. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11494. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11495. RemoveInstruction(hp1);
  11496. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11497. end
  11498. end;
  11499. Result := True;
  11500. end;
  11501. end;
  11502. end;
  11503. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11504. var
  11505. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11506. TargetReg: TRegister;
  11507. condition, inverted_condition: TAsmCond;
  11508. FoundMOV: Boolean;
  11509. begin
  11510. Result := False;
  11511. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11512. create the most optimial instructions possible due to limited
  11513. register availability, and there are situations where two
  11514. complementary "simple" CMOV blocks are created which, after the fact
  11515. can be merged into a "double" block. For example:
  11516. movw $257,%ax
  11517. movw $2,%r8w
  11518. xorl r9d,%r9d
  11519. testw $16,18(%rcx)
  11520. cmovew %ax,%dx
  11521. cmovew %r8w,%bx
  11522. cmovel %r9d,%r14d
  11523. movw $1283,%ax
  11524. movw $4,%r8w
  11525. movl $9,%r9d
  11526. cmovnew %ax,%dx
  11527. cmovnew %r8w,%bx
  11528. cmovnel %r9d,%r14d
  11529. The CMOVNE instructions at the end can be removed, and the
  11530. destination registers copied into the MOV instructions directly
  11531. above them, before finally being moved to before the first CMOVE
  11532. instructions, to produce:
  11533. movw $257,%ax
  11534. movw $2,%r8w
  11535. xorl r9d,%r9d
  11536. testw $16,18(%rcx)
  11537. movw $1283,%dx
  11538. movw $4,%bx
  11539. movl $9,%r14d
  11540. cmovew %ax,%dx
  11541. cmovew %r8w,%bx
  11542. cmovel %r9d,%r14d
  11543. Which can then be later optimised to:
  11544. movw $257,%ax
  11545. movw $2,%r8w
  11546. xorl r9d,%r9d
  11547. movw $1283,%dx
  11548. movw $4,%bx
  11549. movl $9,%r14d
  11550. testw $16,18(%rcx)
  11551. cmovew %ax,%dx
  11552. cmovew %r8w,%bx
  11553. cmovel %r9d,%r14d
  11554. }
  11555. TargetReg := taicpu(hp1).oper[1]^.reg;
  11556. condition := taicpu(hp1).condition;
  11557. inverted_condition := inverse_cond(condition);
  11558. pFirstMov := nil;
  11559. pLastMov := nil;
  11560. pCMOV := nil;
  11561. if (p.typ = ait_instruction) then
  11562. pCond := p
  11563. else if not GetNextInstruction(p, pCond) then
  11564. InternalError(2024012501);
  11565. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11566. { We should get the CMP or TEST instructeion }
  11567. InternalError(2024012502);
  11568. if (
  11569. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11570. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11571. ) then
  11572. begin
  11573. { We have to tread carefully here, hence why we're not using
  11574. GetNextInstructionUsingReg... we can only accept MOV and other
  11575. CMOV instructions. Anything else and we must drop out}
  11576. hp2 := hp1;
  11577. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11578. begin
  11579. if (hp2.typ <> ait_instruction) then
  11580. Exit;
  11581. case taicpu(hp2).opcode of
  11582. A_MOV:
  11583. begin
  11584. if not Assigned(pFirstMov) then
  11585. pFirstMov := hp2;
  11586. pLastMOV := hp2;
  11587. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11588. { Something different - drop out }
  11589. Exit;
  11590. { Otherwise, leave it for now }
  11591. end;
  11592. A_CMOVcc:
  11593. begin
  11594. if taicpu(hp2).condition = inverted_condition then
  11595. begin
  11596. { We found what we're looking for }
  11597. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11598. begin
  11599. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11600. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11601. begin
  11602. pCMOV := hp2;
  11603. Break;
  11604. end
  11605. else
  11606. { Unsafe reference - drop out }
  11607. Exit;
  11608. end;
  11609. end
  11610. else if taicpu(hp2).condition <> condition then
  11611. { Something weird - drop out }
  11612. Exit;
  11613. end;
  11614. else
  11615. { Invalid }
  11616. Exit;
  11617. end;
  11618. end;
  11619. if not Assigned(pCMOV) then
  11620. { No complementary CMOV found }
  11621. Exit;
  11622. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11623. begin
  11624. { Don't need to do anything special or search for a matching MOV }
  11625. Asml.Remove(pCMOV);
  11626. if RegInInstruction(TargetReg, pCond) then
  11627. { Make sure we don't overwrite the register if it's being used in the condition }
  11628. Asml.InsertAfter(pCMOV, pCond)
  11629. else
  11630. Asml.InsertBefore(pCMOV, pCond);
  11631. taicpu(pCMOV).opcode := A_MOV;
  11632. taicpu(pCMOV).condition := C_None;
  11633. { Don't need to worry about allocating new registers in these cases }
  11634. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11635. Result := True;
  11636. Exit;
  11637. end
  11638. else
  11639. begin
  11640. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11641. FoundMOV := False;
  11642. { Search for the MOV that sets the target register }
  11643. hp2 := pFirstMov;
  11644. repeat
  11645. if (taicpu(hp2).opcode = A_MOV) and
  11646. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11647. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11648. begin
  11649. { Change the destination }
  11650. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11651. if not FoundMOV then
  11652. begin
  11653. FoundMOV := True;
  11654. { Make sure the register is allocated }
  11655. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11656. end;
  11657. hp1 := tai(hp2.Previous);
  11658. Asml.Remove(hp2);
  11659. if RegInInstruction(TargetReg, pCond) then
  11660. { Make sure we don't overwrite the register if it's being used in the condition }
  11661. Asml.InsertAfter(hp2, pCond)
  11662. else
  11663. Asml.InsertBefore(hp2, pCond);
  11664. if (hp2 = pLastMov) then
  11665. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11666. Break;
  11667. hp2 := hp1;
  11668. end;
  11669. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11670. if FoundMOV then
  11671. { Delete the CMOV }
  11672. RemoveInstruction(pCMOV)
  11673. else
  11674. begin
  11675. { If no MOV was found, we have to actually move and transmute the CMOV }
  11676. Asml.Remove(pCMOV);
  11677. if RegInInstruction(TargetReg, pCond) then
  11678. { Make sure we don't overwrite the register if it's being used in the condition }
  11679. Asml.InsertAfter(pCMOV, pCond)
  11680. else
  11681. Asml.InsertBefore(pCMOV, pCond);
  11682. taicpu(pCMOV).opcode := A_MOV;
  11683. taicpu(pCMOV).condition := C_None;
  11684. end;
  11685. Result := True;
  11686. Exit;
  11687. end;
  11688. end;
  11689. end;
  11690. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11691. var
  11692. hp1, hp2, pCond: tai;
  11693. begin
  11694. Result := False;
  11695. { Search ahead for CMOV instructions }
  11696. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11697. begin
  11698. hp1 := p;
  11699. hp2 := p;
  11700. pCond := nil; { To prevent compiler warnings }
  11701. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11702. DEFAULTFLAGS }
  11703. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11704. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11705. pCond := p;
  11706. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11707. begin
  11708. if (hp1.typ <> ait_instruction) then
  11709. { Break out on markers and labels etc. }
  11710. Break;
  11711. case taicpu(hp1).opcode of
  11712. A_MOV:
  11713. { Ignore regular MOVs unless they are obviously not related
  11714. to a CMOV block }
  11715. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11716. Break;
  11717. A_CMOVcc:
  11718. if TryCmpCMovOpts(pCond, hp1) then
  11719. begin
  11720. hp1 := hp2;
  11721. { p itself isn't changed, and we're still inside a
  11722. while loop to catch subsequent CMOVs, so just flag
  11723. a new iteration }
  11724. Include(OptsToCheck, aoc_ForceNewIteration);
  11725. Continue;
  11726. end;
  11727. else
  11728. { Drop out if we find anything else }
  11729. Break;
  11730. end;
  11731. hp2 := hp1;
  11732. end;
  11733. end;
  11734. end;
  11735. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11736. var
  11737. hp1, hp2, pCond: tai;
  11738. SourceReg, TargetReg: TRegister;
  11739. begin
  11740. Result := False;
  11741. { In some situations, we end up with an inefficient arrangement of
  11742. instructions in the form of:
  11743. or %reg1,%reg2
  11744. (%reg1 deallocated)
  11745. test %reg2,%reg2
  11746. mov x,%reg2
  11747. we may be able to swap and rearrange the registers to produce:
  11748. or %reg2,%reg1
  11749. mov x,%reg2
  11750. test %reg1,%reg1
  11751. (%reg1 deallocated)
  11752. }
  11753. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11754. (taicpu(p).oper[1]^.typ = top_reg) and
  11755. (
  11756. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11757. MatchOperand(taicpu(p).oper[0]^, -1)
  11758. ) and
  11759. GetNextInstruction(p, hp1) and
  11760. MatchInstruction(hp1, A_MOV, []) and
  11761. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11762. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11763. begin
  11764. TargetReg := taicpu(p).oper[1]^.reg;
  11765. { Now look backwards to find a simple commutative operation: ADD,
  11766. IMUL (2-register version), OR, AND or XOR - whose destination
  11767. register is the same as TEST }
  11768. hp2 := p;
  11769. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11770. if RegInInstruction(TargetReg, hp2) then
  11771. begin
  11772. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11773. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11774. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11775. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11776. begin
  11777. SourceReg := taicpu(hp2).oper[0]^.reg;
  11778. if
  11779. { Make sure the MOV doesn't use the other register }
  11780. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11781. { And make sure the source register is not used afterwards }
  11782. not RegInUsedRegs(SourceReg, UsedRegs) then
  11783. begin
  11784. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11785. taicpu(hp2).oper[0]^.reg := TargetReg;
  11786. taicpu(hp2).oper[1]^.reg := SourceReg;
  11787. if taicpu(p).oper[0]^.typ = top_reg then
  11788. taicpu(p).oper[0]^.reg := SourceReg;
  11789. taicpu(p).oper[1]^.reg := SourceReg;
  11790. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11791. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11792. Include(OptsToCheck, aoc_ForceNewIteration);
  11793. { We can still check the following optimisations since
  11794. the instruction is still a TEST }
  11795. end;
  11796. end;
  11797. Break;
  11798. end;
  11799. end;
  11800. { Search ahead3 for CMOV instructions }
  11801. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11802. begin
  11803. hp1 := p;
  11804. hp2 := p;
  11805. pCond := nil; { To prevent compiler warnings }
  11806. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11807. DEFAULTFLAGS }
  11808. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11809. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11810. pCond := p;
  11811. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11812. begin
  11813. if (hp1.typ <> ait_instruction) then
  11814. { Break out on markers and labels etc. }
  11815. Break;
  11816. case taicpu(hp1).opcode of
  11817. A_MOV:
  11818. { Ignore regular MOVs unless they are obviously not related
  11819. to a CMOV block }
  11820. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11821. Break;
  11822. A_CMOVcc:
  11823. if TryCmpCMovOpts(pCond, hp1) then
  11824. begin
  11825. hp1 := hp2;
  11826. { p itself isn't changed, and we're still inside a
  11827. while loop to catch subsequent CMOVs, so just flag
  11828. a new iteration }
  11829. Include(OptsToCheck, aoc_ForceNewIteration);
  11830. Continue;
  11831. end;
  11832. else
  11833. { Drop out if we find anything else }
  11834. Break;
  11835. end;
  11836. hp2 := hp1;
  11837. end;
  11838. end;
  11839. end;
  11840. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11841. var
  11842. hp1: tai;
  11843. Count: Integer;
  11844. OrigLabel: TAsmLabel;
  11845. begin
  11846. result := False;
  11847. { Sometimes, the optimisations below can permit this }
  11848. RemoveDeadCodeAfterJump(p);
  11849. if (taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full) and (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  11850. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11851. begin
  11852. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11853. { Also a side-effect of optimisations }
  11854. if CollapseZeroDistJump(p, OrigLabel) then
  11855. begin
  11856. Result := True;
  11857. Exit;
  11858. end;
  11859. hp1 := GetLabelWithSym(OrigLabel);
  11860. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11861. begin
  11862. if taicpu(hp1).opcode = A_RET then
  11863. begin
  11864. {
  11865. change
  11866. jmp .L1
  11867. ...
  11868. .L1:
  11869. ret
  11870. into
  11871. ret
  11872. }
  11873. begin
  11874. ConvertJumpToRET(p, hp1);
  11875. result:=true;
  11876. end;
  11877. end
  11878. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11879. not (cs_opt_size in current_settings.optimizerswitches) and
  11880. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11881. begin
  11882. Result := True;
  11883. Exit;
  11884. end;
  11885. end;
  11886. end;
  11887. end;
  11888. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11889. begin
  11890. Result := assigned(p) and
  11891. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11892. (taicpu(p).oper[1]^.typ = top_reg) and
  11893. (
  11894. (taicpu(p).oper[0]^.typ = top_reg) or
  11895. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11896. it is not expected that this can cause a seg. violation }
  11897. (
  11898. (taicpu(p).oper[0]^.typ = top_ref) and
  11899. { TODO: Can we detect which references become constants at this
  11900. stage so we don't have to do a blanket ban? }
  11901. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11902. (
  11903. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11904. (
  11905. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11906. not RefModified and
  11907. { If the reference also appears in the condition, then we know it's safe, otherwise
  11908. any kind of access violation would have occurred already }
  11909. Assigned(cond_p) and
  11910. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11911. (cond_p.typ = ait_instruction) and
  11912. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11913. { Just consider 2-operand comparison instructions for now to be safe }
  11914. (taicpu(cond_p).ops = 2) and
  11915. (
  11916. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11917. (
  11918. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11919. { Don't risk identical registers but different offsets, as we may have constructs
  11920. such as buffer streams with things like length fields that indicate whether
  11921. any more data follows. And there are probably some contrived examples where
  11922. writing to offsets behind the one being read also lead to access violations }
  11923. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11924. (
  11925. { Check that we're not modifying a register that appears in the reference }
  11926. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11927. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11928. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11929. )
  11930. )
  11931. )
  11932. )
  11933. )
  11934. )
  11935. );
  11936. end;
  11937. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11938. begin
  11939. { Update integer registers, ignoring deallocations }
  11940. repeat
  11941. while assigned(p) and
  11942. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11943. (p.typ = ait_label) or
  11944. ((p.typ = ait_marker) and
  11945. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11946. p := tai(p.next);
  11947. while assigned(p) and
  11948. (p.typ=ait_RegAlloc) Do
  11949. begin
  11950. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11951. begin
  11952. case tai_regalloc(p).ratype of
  11953. ra_alloc :
  11954. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11955. else
  11956. ;
  11957. end;
  11958. end;
  11959. p := tai(p.next);
  11960. end;
  11961. until not(assigned(p)) or
  11962. (not(p.typ in SkipInstr) and
  11963. not((p.typ = ait_label) and
  11964. labelCanBeSkipped(tai_label(p))));
  11965. end;
  11966. {$ifndef 8086}
  11967. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11968. begin
  11969. Result := False;
  11970. EndJump := nil;
  11971. BlockStop := nil;
  11972. while (BlockStart <> fOptimizer.BlockEnd) and
  11973. { stop on labels }
  11974. (BlockStart.typ <> ait_label) do
  11975. begin
  11976. { Keep track of all integer registers that are used }
  11977. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11978. if BlockStart.typ = ait_instruction then
  11979. begin
  11980. if (taicpu(BlockStart).opcode = A_JMP) then
  11981. begin
  11982. if not IsJumpToLabel(taicpu(BlockStart)) or
  11983. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11984. Exit;
  11985. EndJump := BlockStart;
  11986. Break;
  11987. end
  11988. { Check to see if we have a valid MOV instruction instead }
  11989. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11990. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11991. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11992. begin
  11993. Exit;
  11994. end
  11995. else
  11996. { This will be a valid MOV }
  11997. fAllocationRange := BlockStart;
  11998. end;
  11999. OneBeforeBlock := BlockStart;
  12000. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12001. end;
  12002. if (BlockStart = fOptimizer.BlockEnd) then
  12003. Exit;
  12004. BlockStop := BlockStart;
  12005. Result := True;
  12006. end;
  12007. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12008. var
  12009. hp1: tai;
  12010. RefModified: Boolean;
  12011. begin
  12012. Result := 0;
  12013. hp1 := BlockStart;
  12014. RefModified := False; { As long as the condition is inverted, this can be reset }
  12015. while assigned(hp1) and
  12016. (hp1 <> BlockStop) do
  12017. begin
  12018. case hp1.typ of
  12019. ait_instruction:
  12020. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12021. begin
  12022. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12023. begin
  12024. Inc(Result);
  12025. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12026. Assigned(fCondition) and
  12027. { Will have 2 operands }
  12028. (
  12029. (
  12030. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12031. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12032. ) or
  12033. (
  12034. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12035. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12036. )
  12037. ) then
  12038. { It is no longer safe to use the reference in the condition.
  12039. this prevents problems such as:
  12040. mov (%reg),%reg
  12041. mov (%reg),...
  12042. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12043. (fixes #40165)
  12044. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12045. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12046. }
  12047. RefModified := True;
  12048. end
  12049. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12050. { CMOV with constants grows the code size }
  12051. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12052. begin
  12053. { Register was reserved by TryCMOVConst and
  12054. stored on ConstRegs }
  12055. end
  12056. else
  12057. begin
  12058. Result := -1;
  12059. Exit;
  12060. end;
  12061. end
  12062. else
  12063. begin
  12064. Result := -1;
  12065. Exit;
  12066. end;
  12067. else
  12068. { Most likely an align };
  12069. end;
  12070. fOptimizer.GetNextInstruction(hp1, hp1);
  12071. end;
  12072. end;
  12073. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12074. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12075. (this is done as a separate stage because the double types are extensions of the branching type,
  12076. but we can't discount the conditional jump until the last step) }
  12077. procedure EvaluateBranchingType;
  12078. begin
  12079. Inc(CMOVScore);
  12080. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12081. { Too many instructions to be worthwhile }
  12082. fState := tsInvalid;
  12083. end;
  12084. var
  12085. hp1: tai;
  12086. Count: Integer;
  12087. begin
  12088. { Table of valid CMOV block types
  12089. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12090. ---------- --------- --------- --------- --------- ---------
  12091. tsSimple X Yes X X X
  12092. tsDetour = 1st X X X X
  12093. tsBranching <> Mid Yes X X X
  12094. tsDouble End-label Yes * Yes X Yes
  12095. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12096. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12097. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12098. * Only one reference allowed
  12099. }
  12100. hp1 := nil; { To prevent compiler warnings }
  12101. Optimizer.CopyUsedRegs(RegisterTracking);
  12102. fOptimizer := Optimizer;
  12103. fLabel := AFirstLabel;
  12104. CMOVScore := 0;
  12105. ConstCount := 0;
  12106. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12107. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12108. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12109. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12110. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12111. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12112. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12113. fInsertionPoint := p_initialjump;
  12114. fCondition := nil;
  12115. fInitialJump := p_initialjump;
  12116. fFirstMovBlock := p_initialmov;
  12117. fFirstMovBlockStop := nil;
  12118. fSecondJump := nil;
  12119. fSecondMovBlock := nil;
  12120. fSecondMovBlockStop := nil;
  12121. fMidLabel := nil;
  12122. fSecondJump := nil;
  12123. fSecondMovBlock := nil;
  12124. fEndLabel := nil;
  12125. fAllocationRange := nil;
  12126. { Assume it all goes horribly wrong! }
  12127. fState := tsInvalid;
  12128. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12129. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12130. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  12131. begin
  12132. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12133. for Count := 0 to 1 do
  12134. with taicpu(fCondition).oper[Count]^ do
  12135. case typ of
  12136. top_reg:
  12137. if getregtype(reg) = R_INTREGISTER then
  12138. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12139. top_ref:
  12140. begin
  12141. if
  12142. {$ifdef x86_64}
  12143. (ref^.base <> NR_RIP) and
  12144. {$endif x86_64}
  12145. (ref^.base <> NR_NO) then
  12146. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12147. if (ref^.index <> NR_NO) then
  12148. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12149. end
  12150. else
  12151. ;
  12152. end;
  12153. { When inserting instructions before hp_prev, try to insert them
  12154. before the allocation of the FLAGS register }
  12155. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12156. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12157. { If not found, set it equal to the condition so it's something sensible }
  12158. fInsertionPoint := fCondition;
  12159. { When dealing with a comparison against zero, take note of the
  12160. instruction before it to see if we can move instructions further
  12161. back in order to benefit PostPeepholeOptTestOr.
  12162. }
  12163. if (
  12164. (
  12165. (taicpu(fCondition).opcode = A_CMP) and
  12166. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12167. ) or
  12168. (
  12169. (taicpu(fCondition).opcode = A_TEST) and
  12170. (
  12171. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12172. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12173. )
  12174. )
  12175. ) and
  12176. Optimizer.GetLastInstruction(fCondition, hp1) then
  12177. begin
  12178. { These instructions set the zero flag if the result is zero }
  12179. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12180. begin
  12181. fInsertionPoint := hp1;
  12182. { Also mark all the registers in this previous instruction
  12183. as 'in use', even if they've just been deallocated }
  12184. for Count := 0 to 1 do
  12185. with taicpu(hp1).oper[Count]^ do
  12186. case typ of
  12187. top_reg:
  12188. if getregtype(reg) = R_INTREGISTER then
  12189. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12190. top_ref:
  12191. begin
  12192. if
  12193. {$ifdef x86_64}
  12194. (ref^.base <> NR_RIP) and
  12195. {$endif x86_64}
  12196. (ref^.base <> NR_NO) then
  12197. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12198. if (ref^.index <> NR_NO) then
  12199. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12200. end
  12201. else
  12202. ;
  12203. end;
  12204. end;
  12205. end;
  12206. end
  12207. else
  12208. fCondition := nil;
  12209. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12210. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12211. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12212. { If not found, set it equal to p so it's something sensible }
  12213. fInsertionPoint := hp1;
  12214. hp1 := p_initialmov;
  12215. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12216. Exit;
  12217. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12218. if (hp1.typ <> ait_label) then { should be on a jump }
  12219. begin
  12220. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12221. { Need a label afterwards }
  12222. Exit;
  12223. end
  12224. else
  12225. fMidLabel := hp1;
  12226. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12227. { Not the correct label }
  12228. fMidLabel := nil;
  12229. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12230. { If there's neither a 2nd jump nor correct label, then it's invalid
  12231. (see above table) }
  12232. Exit;
  12233. { Analyse the first block of MOVs more closely }
  12234. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12235. if Assigned(fSecondJump) then
  12236. begin
  12237. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12238. begin
  12239. fState := tsDetour
  12240. end
  12241. else
  12242. begin
  12243. { Need the correct mid-label for this one }
  12244. if not Assigned(fMidLabel) then
  12245. Exit;
  12246. fState := tsBranching;
  12247. end;
  12248. end
  12249. else
  12250. { No jump. but mid-label is present }
  12251. fState := tsSimple;
  12252. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12253. begin
  12254. { Invalid or too many instructions to be worthwhile }
  12255. fState := tsInvalid;
  12256. Exit;
  12257. end;
  12258. { check further for
  12259. jCC xxx
  12260. <several movs 1>
  12261. jmp yyy
  12262. xxx:
  12263. <several movs 2>
  12264. yyy:
  12265. etc.
  12266. }
  12267. if (fState = tsBranching) and
  12268. { Estimate for required savings for extra jump }
  12269. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12270. { Only one reference is allowed for double blocks }
  12271. (AFirstLabel.getrefs = 1) then
  12272. begin
  12273. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12274. fSecondMovBlock := hp1;
  12275. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12276. begin
  12277. EvaluateBranchingType;
  12278. Exit;
  12279. end;
  12280. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12281. if (hp1.typ <> ait_label) then { should be on a jump }
  12282. begin
  12283. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12284. begin
  12285. { Need a label afterwards }
  12286. EvaluateBranchingType;
  12287. Exit;
  12288. end;
  12289. end
  12290. else
  12291. fEndLabel := hp1;
  12292. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12293. { Second jump doesn't go to the end }
  12294. fEndLabel := nil;
  12295. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12296. begin
  12297. { If there's neither a 3rd jump nor correct end label, then it's
  12298. not a invalid double block, but is a valid single branching
  12299. block (see above table) }
  12300. EvaluateBranchingType;
  12301. Exit;
  12302. end;
  12303. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12304. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12305. { Invalid or too many instructions to be worthwhile }
  12306. Exit;
  12307. Inc(CMOVScore, Count);
  12308. if Assigned(fThirdJump) then
  12309. begin
  12310. if not Assigned(fSecondJump) then
  12311. fState := tsDoubleSecondBranching
  12312. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12313. fState := tsDoubleBranchSame
  12314. else
  12315. fState := tsDoubleBranchDifferent;
  12316. end
  12317. else
  12318. fState := tsDouble;
  12319. end;
  12320. if fState = tsBranching then
  12321. EvaluateBranchingType;
  12322. end;
  12323. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12324. new register to store the constant }
  12325. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12326. var
  12327. RegSize: TSubRegister;
  12328. CurrentVal: TCGInt;
  12329. ANewReg: TRegister;
  12330. X: ShortInt;
  12331. begin
  12332. Result := False;
  12333. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12334. Exit;
  12335. if ConstCount >= MAX_CMOV_REGISTERS then
  12336. { Arrays are full }
  12337. Exit;
  12338. { Remember that CMOV can't encode 8-bit registers }
  12339. case taicpu(p).opsize of
  12340. S_W:
  12341. RegSize := R_SUBW;
  12342. S_L:
  12343. RegSize := R_SUBD;
  12344. {$ifdef x86_64}
  12345. S_Q:
  12346. RegSize := R_SUBQ;
  12347. {$endif x86_64}
  12348. else
  12349. InternalError(2021100401);
  12350. end;
  12351. { See if the value has already been reserved for another CMOV instruction }
  12352. CurrentVal := taicpu(p).oper[0]^.val;
  12353. for X := 0 to ConstCount - 1 do
  12354. if ConstVals[X] = CurrentVal then
  12355. begin
  12356. ConstRegs[ConstCount] := ConstRegs[X];
  12357. ConstSizes[ConstCount] := RegSize;
  12358. ConstVals[ConstCount] := CurrentVal;
  12359. Inc(ConstCount);
  12360. Inc(Count);
  12361. Result := True;
  12362. Exit;
  12363. end;
  12364. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12365. if ANewReg = NR_NO then
  12366. { No free registers }
  12367. Exit;
  12368. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12369. up vying for the same register }
  12370. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12371. ConstRegs[ConstCount] := ANewReg;
  12372. ConstSizes[ConstCount] := RegSize;
  12373. ConstVals[ConstCount] := CurrentVal;
  12374. Inc(ConstCount);
  12375. Inc(Count);
  12376. Result := True;
  12377. end;
  12378. destructor TCMOVTracking.Done;
  12379. begin
  12380. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12381. end;
  12382. procedure TCMOVTracking.Process(out new_p: tai);
  12383. var
  12384. Count, Writes: LongInt;
  12385. RegMatch: Boolean;
  12386. hp1, hp_new: tai;
  12387. inverted_condition, condition: TAsmCond;
  12388. begin
  12389. if (fState in [tsInvalid, tsProcessed]) then
  12390. InternalError(2023110701);
  12391. { Repurpose RegisterTracking to mark registers that we've defined }
  12392. RegisterTracking[R_INTREGISTER].Clear;
  12393. Count := 0;
  12394. Writes := 0;
  12395. condition := taicpu(fInitialJump).condition;
  12396. inverted_condition := inverse_cond(condition);
  12397. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12398. doesn't get CMOVs in this case }
  12399. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12400. begin
  12401. { Include the jump in the flag tracking }
  12402. if Assigned(fThirdJump) then
  12403. begin
  12404. if (fState = tsDoubleBranchSame) then
  12405. begin
  12406. { Will be an unconditional jump, so track to the instruction before it }
  12407. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12408. InternalError(2023110710);
  12409. end
  12410. else
  12411. hp1 := fThirdJump;
  12412. end
  12413. else
  12414. hp1 := fSecondMovBlockStop;
  12415. end
  12416. else
  12417. begin
  12418. { Include a conditional jump in the flag tracking }
  12419. if Assigned(fSecondJump) then
  12420. begin
  12421. if (fState = tsDetour) then
  12422. begin
  12423. { Will be an unconditional jump, so track to the instruction before it }
  12424. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12425. InternalError(2023110711);
  12426. end
  12427. else
  12428. hp1 := fSecondJump;
  12429. end
  12430. else
  12431. hp1 := fFirstMovBlockStop;
  12432. end;
  12433. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12434. { Process the second set of MOVs first, because if a destination
  12435. register is shared between the first and second MOV sets, it is more
  12436. efficient to turn the first one into a MOV instruction and place it
  12437. before the CMP if possible, but we won't know which registers are
  12438. shared until we've processed at least one list, so we might as well
  12439. make it the second one since that won't be modified again. }
  12440. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12441. begin
  12442. hp1 := fSecondMovBlock;
  12443. repeat
  12444. if not Assigned(hp1) then
  12445. InternalError(2018062902);
  12446. if (hp1.typ = ait_instruction) then
  12447. begin
  12448. { Extra safeguard }
  12449. if (taicpu(hp1).opcode <> A_MOV) then
  12450. InternalError(2018062903);
  12451. { Note: tsDoubleBranchDifferent is essentially identical to
  12452. tsBranching and the 2nd block is best left largely
  12453. untouched, but we need to evaluate which registers the MOVs
  12454. write to in order to track what would be complementary CMOV
  12455. pairs that can be further optimised. [Kit] }
  12456. if fState <> tsDoubleBranchDifferent then
  12457. begin
  12458. if taicpu(hp1).oper[0]^.typ = top_const then
  12459. begin
  12460. RegMatch := False;
  12461. for Count := 0 to ConstCount - 1 do
  12462. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12463. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12464. begin
  12465. RegMatch := True;
  12466. { If it's in RegisterTracking, then this register
  12467. is being used more than once and hence has
  12468. already had its value defined (it gets added to
  12469. UsedRegs through AllocRegBetween below) }
  12470. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12471. begin
  12472. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12473. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12474. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12475. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12476. ConstMovs[Count] := hp_new;
  12477. end
  12478. else
  12479. { We just need an instruction between hp_prev and hp1
  12480. where we know the register is marked as in use }
  12481. hp_new := fSecondMovBlock;
  12482. { Keep track of largest write for this register so it can be optimised later }
  12483. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12484. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12485. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12486. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12487. Break;
  12488. end;
  12489. if not RegMatch then
  12490. InternalError(2021100411);
  12491. end;
  12492. taicpu(hp1).opcode := A_CMOVcc;
  12493. taicpu(hp1).condition := condition;
  12494. end;
  12495. { Store these writes to search for duplicates later on }
  12496. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12497. Inc(Writes);
  12498. end;
  12499. fOptimizer.GetNextInstruction(hp1, hp1);
  12500. until (hp1 = fSecondMovBlockStop);
  12501. end;
  12502. { Now do the first set of MOVs }
  12503. hp1 := fFirstMovBlock;
  12504. repeat
  12505. if not Assigned(hp1) then
  12506. InternalError(2018062904);
  12507. if (hp1.typ = ait_instruction) then
  12508. begin
  12509. RegMatch := False;
  12510. { Extra safeguard }
  12511. if (taicpu(hp1).opcode <> A_MOV) then
  12512. InternalError(2018062905);
  12513. { Search through the RegWrites list to see if there are any
  12514. opposing CMOV pairs that write to the same register }
  12515. for Count := 0 to Writes - 1 do
  12516. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12517. begin
  12518. { We have a match. Keep this as a MOV }
  12519. { Move ahead in preparation }
  12520. fOptimizer.GetNextInstruction(hp1, hp1);
  12521. RegMatch := True;
  12522. Break;
  12523. end;
  12524. if RegMatch then
  12525. Continue;
  12526. if taicpu(hp1).oper[0]^.typ = top_const then
  12527. begin
  12528. for Count := 0 to ConstCount - 1 do
  12529. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12530. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12531. begin
  12532. RegMatch := True;
  12533. { If it's in RegisterTracking, then this register is
  12534. being used more than once and hence has already had
  12535. its value defined (it gets added to UsedRegs through
  12536. AllocRegBetween below) }
  12537. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12538. begin
  12539. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12540. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12541. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12542. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12543. ConstMovs[Count] := hp_new;
  12544. end
  12545. else
  12546. { We just need an instruction between hp_prev and hp1
  12547. where we know the register is marked as in use }
  12548. hp_new := fFirstMovBlock;
  12549. { Keep track of largest write for this register so it can be optimised later }
  12550. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12551. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12552. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12553. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12554. Break;
  12555. end;
  12556. if not RegMatch then
  12557. InternalError(2021100412);
  12558. end;
  12559. taicpu(hp1).opcode := A_CMOVcc;
  12560. taicpu(hp1).condition := inverted_condition;
  12561. if (fState = tsDoubleBranchDifferent) then
  12562. begin
  12563. { Store these writes to search for duplicates later on }
  12564. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12565. Inc(Writes);
  12566. end;
  12567. end;
  12568. fOptimizer.GetNextInstruction(hp1, hp1);
  12569. until (hp1 = fFirstMovBlockStop);
  12570. { Update initialisation MOVs to the smallest possible size }
  12571. for Count := 0 to ConstCount - 1 do
  12572. if Assigned(ConstMovs[Count]) then
  12573. begin
  12574. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12575. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12576. end;
  12577. case fState of
  12578. tsSimple:
  12579. begin
  12580. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12581. { No branch to delete }
  12582. end;
  12583. tsDetour:
  12584. begin
  12585. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12586. { Preserve jump }
  12587. end;
  12588. tsBranching, tsDoubleBranchDifferent:
  12589. begin
  12590. if (fState = tsBranching) then
  12591. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12592. else
  12593. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12594. taicpu(fSecondJump).opcode := A_JCC;
  12595. taicpu(fSecondJump).condition := inverted_condition;
  12596. end;
  12597. tsDouble, tsDoubleBranchSame:
  12598. begin
  12599. if (fState = tsDouble) then
  12600. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12601. else
  12602. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12603. { Delete second jump }
  12604. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12605. fOptimizer.RemoveInstruction(fSecondJump);
  12606. end;
  12607. tsDoubleSecondBranching:
  12608. begin
  12609. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12610. { Delete second jump, preserve third jump as conditional }
  12611. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12612. fOptimizer.RemoveInstruction(fSecondJump);
  12613. taicpu(fThirdJump).opcode := A_JCC;
  12614. taicpu(fThirdJump).condition := condition;
  12615. end;
  12616. else
  12617. InternalError(2023110720);
  12618. end;
  12619. { Now we can safely decrement the reference count }
  12620. tasmlabel(fLabel).decrefs;
  12621. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12622. { Remove the original jump }
  12623. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12624. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12625. fState := tsProcessed;
  12626. end;
  12627. {$endif 8086}
  12628. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12629. var
  12630. hp1,hp2: tai;
  12631. carryadd_opcode : TAsmOp;
  12632. symbol: TAsmSymbol;
  12633. increg, tmpreg: TRegister;
  12634. {$ifndef i8086}
  12635. CMOVTracking: PCMOVTracking;
  12636. hp3,hp4,hp5: tai;
  12637. {$endif i8086}
  12638. TempBool: Boolean;
  12639. begin
  12640. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12641. DoJumpOptimizations(p, TempBool) then
  12642. Exit(True);
  12643. result:=false;
  12644. if GetNextInstruction(p,hp1) then
  12645. begin
  12646. if (hp1.typ=ait_label) then
  12647. begin
  12648. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12649. Exit;
  12650. end
  12651. else if (hp1.typ<>ait_instruction) then
  12652. Exit;
  12653. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12654. if (
  12655. (
  12656. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12657. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12658. (Taicpu(hp1).oper[0]^.val=1)
  12659. ) or
  12660. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12661. ) and
  12662. GetNextInstruction(hp1,hp2) and
  12663. FindLabel(TAsmLabel(symbol), hp2) then
  12664. { jb @@1 cmc
  12665. inc/dec operand --> adc/sbb operand,0
  12666. @@1:
  12667. ... and ...
  12668. jnb @@1
  12669. inc/dec operand --> adc/sbb operand,0
  12670. @@1: }
  12671. begin
  12672. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12673. begin
  12674. case taicpu(hp1).opcode of
  12675. A_INC,
  12676. A_ADD:
  12677. carryadd_opcode:=A_ADC;
  12678. A_DEC,
  12679. A_SUB:
  12680. carryadd_opcode:=A_SBB;
  12681. else
  12682. InternalError(2021011001);
  12683. end;
  12684. Taicpu(p).clearop(0);
  12685. Taicpu(p).ops:=0;
  12686. Taicpu(p).is_jmp:=false;
  12687. Taicpu(p).opcode:=A_CMC;
  12688. Taicpu(p).condition:=C_NONE;
  12689. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12690. Taicpu(hp1).ops:=2;
  12691. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12692. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12693. else
  12694. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12695. Taicpu(hp1).loadconst(0,0);
  12696. Taicpu(hp1).opcode:=carryadd_opcode;
  12697. result:=true;
  12698. exit;
  12699. end
  12700. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12701. begin
  12702. case taicpu(hp1).opcode of
  12703. A_INC,
  12704. A_ADD:
  12705. carryadd_opcode:=A_ADC;
  12706. A_DEC,
  12707. A_SUB:
  12708. carryadd_opcode:=A_SBB;
  12709. else
  12710. InternalError(2021011002);
  12711. end;
  12712. Taicpu(hp1).ops:=2;
  12713. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12714. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12715. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12716. else
  12717. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12718. Taicpu(hp1).loadconst(0,0);
  12719. Taicpu(hp1).opcode:=carryadd_opcode;
  12720. RemoveCurrentP(p, hp1);
  12721. result:=true;
  12722. exit;
  12723. end
  12724. {
  12725. jcc @@1 setcc tmpreg
  12726. inc/dec/add/sub operand -> (movzx tmpreg)
  12727. @@1: add/sub tmpreg,operand
  12728. While this increases code size slightly, it makes the code much faster if the
  12729. jump is unpredictable
  12730. }
  12731. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12732. begin
  12733. { search for an available register which is volatile }
  12734. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12735. if increg <> NR_NO then
  12736. begin
  12737. { We don't need to check if tmpreg is in hp1 or not, because
  12738. it will be marked as in use at p (if not, this is
  12739. indictive of a compiler bug). }
  12740. TAsmLabel(symbol).decrefs;
  12741. Taicpu(p).clearop(0);
  12742. Taicpu(p).ops:=1;
  12743. Taicpu(p).is_jmp:=false;
  12744. Taicpu(p).opcode:=A_SETcc;
  12745. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12746. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12747. Taicpu(p).loadreg(0,increg);
  12748. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12749. begin
  12750. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12751. R_SUBW:
  12752. begin
  12753. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12754. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12755. end;
  12756. R_SUBD:
  12757. begin
  12758. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12759. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12760. end;
  12761. {$ifdef x86_64}
  12762. R_SUBQ:
  12763. begin
  12764. { MOVZX doesn't have a 64-bit variant, because
  12765. the 32-bit version implicitly zeroes the
  12766. upper 32-bits of the destination register }
  12767. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12768. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12769. setsubreg(tmpreg, R_SUBQ);
  12770. end;
  12771. {$endif x86_64}
  12772. else
  12773. Internalerror(2020030601);
  12774. end;
  12775. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12776. asml.InsertAfter(hp2,p);
  12777. end
  12778. else
  12779. tmpreg := increg;
  12780. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12781. begin
  12782. Taicpu(hp1).ops:=2;
  12783. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12784. end;
  12785. Taicpu(hp1).loadreg(0,tmpreg);
  12786. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12787. Result := True;
  12788. { p is no longer a Jcc instruction, so exit }
  12789. Exit;
  12790. end;
  12791. end;
  12792. end;
  12793. { Detect the following:
  12794. jmp<cond> @Lbl1
  12795. jmp @Lbl2
  12796. ...
  12797. @Lbl1:
  12798. ret
  12799. Change to:
  12800. jmp<inv_cond> @Lbl2
  12801. ret
  12802. }
  12803. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12804. begin
  12805. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12806. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12807. MatchInstruction(hp2,A_RET,[S_NO]) then
  12808. begin
  12809. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12810. { Change label address to that of the unconditional jump }
  12811. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12812. TAsmLabel(symbol).DecRefs;
  12813. taicpu(hp1).opcode := A_RET;
  12814. taicpu(hp1).is_jmp := false;
  12815. taicpu(hp1).ops := taicpu(hp2).ops;
  12816. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12817. case taicpu(hp2).ops of
  12818. 0:
  12819. taicpu(hp1).clearop(0);
  12820. 1:
  12821. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12822. else
  12823. internalerror(2016041302);
  12824. end;
  12825. end;
  12826. {$ifndef i8086}
  12827. end
  12828. {
  12829. convert
  12830. j<c> .L1
  12831. mov 1,reg
  12832. jmp .L2
  12833. .L1
  12834. mov 0,reg
  12835. .L2
  12836. into
  12837. mov 0,reg
  12838. set<not(c)> reg
  12839. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12840. would destroy the flag contents
  12841. }
  12842. else if MatchInstruction(hp1,A_MOV,[]) and
  12843. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12844. {$ifdef i386}
  12845. (
  12846. { Under i386, ESI, EDI, EBP and ESP
  12847. don't have an 8-bit representation }
  12848. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12849. ) and
  12850. {$endif i386}
  12851. (taicpu(hp1).oper[0]^.val=1) and
  12852. GetNextInstruction(hp1,hp2) and
  12853. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12854. GetNextInstruction(hp2,hp3) and
  12855. (hp3.typ=ait_label) and
  12856. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12857. (tai_label(hp3).labsym.getrefs=1) and
  12858. GetNextInstruction(hp3,hp4) and
  12859. MatchInstruction(hp4,A_MOV,[]) and
  12860. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12861. (taicpu(hp4).oper[0]^.val=0) and
  12862. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12863. GetNextInstruction(hp4,hp5) and
  12864. (hp5.typ=ait_label) and
  12865. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12866. (tai_label(hp5).labsym.getrefs=1) then
  12867. begin
  12868. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12869. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12870. { remove last label }
  12871. RemoveInstruction(hp5);
  12872. { remove second label }
  12873. RemoveInstruction(hp3);
  12874. { remove jmp }
  12875. RemoveInstruction(hp2);
  12876. if taicpu(hp1).opsize=S_B then
  12877. RemoveInstruction(hp1)
  12878. else
  12879. taicpu(hp1).loadconst(0,0);
  12880. taicpu(hp4).opcode:=A_SETcc;
  12881. taicpu(hp4).opsize:=S_B;
  12882. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12883. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12884. taicpu(hp4).opercnt:=1;
  12885. taicpu(hp4).ops:=1;
  12886. taicpu(hp4).freeop(1);
  12887. RemoveCurrentP(p);
  12888. Result:=true;
  12889. exit;
  12890. end
  12891. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12892. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12893. begin
  12894. { check for
  12895. jCC xxx
  12896. <several movs>
  12897. xxx:
  12898. Also spot:
  12899. Jcc xxx
  12900. <several movs>
  12901. jmp xxx
  12902. Change to:
  12903. <several cmovs with inverted condition>
  12904. jmp xxx (only for the 2nd case)
  12905. }
  12906. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12907. if CMOVTracking^.State <> tsInvalid then
  12908. begin
  12909. CMovTracking^.Process(p);
  12910. Result := True;
  12911. end;
  12912. CMOVTracking^.Done;
  12913. {$endif i8086}
  12914. end;
  12915. end;
  12916. end;
  12917. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12918. var
  12919. hp1,hp2,hp3: tai;
  12920. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12921. NewSize: TOpSize;
  12922. NewRegSize: TSubRegister;
  12923. Limit: TCgInt;
  12924. SwapOper: POper;
  12925. begin
  12926. result:=false;
  12927. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12928. GetNextInstruction(p,hp1) and
  12929. (hp1.typ = ait_instruction);
  12930. if reg_and_hp1_is_instr and
  12931. (
  12932. (taicpu(hp1).opcode <> A_LEA) or
  12933. { If the LEA instruction can be converted into an arithmetic instruction,
  12934. it may be possible to then fold it. }
  12935. (
  12936. { If the flags register is in use, don't change the instruction
  12937. to an ADD otherwise this will scramble the flags. [Kit] }
  12938. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12939. ConvertLEA(taicpu(hp1))
  12940. )
  12941. ) and
  12942. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12943. GetNextInstruction(hp1,hp2) and
  12944. MatchInstruction(hp2,A_MOV,[]) and
  12945. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12946. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12947. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12948. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12949. {$ifdef i386}
  12950. { not all registers have byte size sub registers on i386 }
  12951. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12952. {$endif i386}
  12953. (((taicpu(hp1).ops=2) and
  12954. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12955. ((taicpu(hp1).ops=1) and
  12956. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12957. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12958. begin
  12959. { change movsX/movzX reg/ref, reg2
  12960. add/sub/or/... reg3/$const, reg2
  12961. mov reg2 reg/ref
  12962. to add/sub/or/... reg3/$const, reg/ref }
  12963. { by example:
  12964. movswl %si,%eax movswl %si,%eax p
  12965. decl %eax addl %edx,%eax hp1
  12966. movw %ax,%si movw %ax,%si hp2
  12967. ->
  12968. movswl %si,%eax movswl %si,%eax p
  12969. decw %eax addw %edx,%eax hp1
  12970. movw %ax,%si movw %ax,%si hp2
  12971. }
  12972. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12973. {
  12974. ->
  12975. movswl %si,%eax movswl %si,%eax p
  12976. decw %si addw %dx,%si hp1
  12977. movw %ax,%si movw %ax,%si hp2
  12978. }
  12979. case taicpu(hp1).ops of
  12980. 1:
  12981. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12982. 2:
  12983. begin
  12984. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12985. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12986. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12987. end;
  12988. else
  12989. internalerror(2008042702);
  12990. end;
  12991. {
  12992. ->
  12993. decw %si addw %dx,%si p
  12994. }
  12995. DebugMsg(SPeepholeOptimization + 'var3',p);
  12996. RemoveCurrentP(p, hp1);
  12997. RemoveInstruction(hp2);
  12998. Result := True;
  12999. Exit;
  13000. end;
  13001. if reg_and_hp1_is_instr and
  13002. (taicpu(hp1).opcode = A_MOV) and
  13003. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13004. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13005. {$ifdef x86_64}
  13006. { check for implicit extension to 64 bit }
  13007. or
  13008. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13009. (taicpu(hp1).opsize=S_Q) and
  13010. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13011. )
  13012. {$endif x86_64}
  13013. )
  13014. then
  13015. begin
  13016. { change
  13017. movx %reg1,%reg2
  13018. mov %reg2,%reg3
  13019. dealloc %reg2
  13020. into
  13021. movx %reg,%reg3
  13022. }
  13023. TransferUsedRegs(TmpUsedRegs);
  13024. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13025. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13026. begin
  13027. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13028. {$ifdef x86_64}
  13029. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13030. (taicpu(hp1).opsize=S_Q) then
  13031. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13032. else
  13033. {$endif x86_64}
  13034. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13035. RemoveInstruction(hp1);
  13036. Result := True;
  13037. Exit;
  13038. end;
  13039. end;
  13040. if reg_and_hp1_is_instr and
  13041. ((taicpu(hp1).opcode=A_MOV) or
  13042. (taicpu(hp1).opcode=A_ADD) or
  13043. (taicpu(hp1).opcode=A_SUB) or
  13044. (taicpu(hp1).opcode=A_CMP) or
  13045. (taicpu(hp1).opcode=A_OR) or
  13046. (taicpu(hp1).opcode=A_XOR) or
  13047. (taicpu(hp1).opcode=A_AND)
  13048. ) and
  13049. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13050. begin
  13051. AndTest := (taicpu(hp1).opcode=A_AND) and
  13052. GetNextInstruction(hp1, hp2) and
  13053. (hp2.typ = ait_instruction) and
  13054. (
  13055. (
  13056. (taicpu(hp2).opcode=A_TEST) and
  13057. (
  13058. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13059. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13060. (
  13061. { If the AND and TEST instructions share a constant, this is also valid }
  13062. (taicpu(hp1).oper[0]^.typ = top_const) and
  13063. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13064. )
  13065. ) and
  13066. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13067. ) or
  13068. (
  13069. (taicpu(hp2).opcode=A_CMP) and
  13070. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13071. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13072. )
  13073. );
  13074. { change
  13075. movx (oper),%reg2
  13076. and $x,%reg2
  13077. test %reg2,%reg2
  13078. dealloc %reg2
  13079. into
  13080. op %reg1,%reg3
  13081. if the second op accesses only the bits stored in reg1
  13082. }
  13083. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13084. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13085. (taicpu(hp1).oper[0]^.typ = top_const) and
  13086. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13087. AndTest then
  13088. begin
  13089. { Check if the AND constant is in range }
  13090. case taicpu(p).opsize of
  13091. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13092. begin
  13093. NewSize := S_B;
  13094. Limit := $FF;
  13095. end;
  13096. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13097. begin
  13098. NewSize := S_W;
  13099. Limit := $FFFF;
  13100. end;
  13101. {$ifdef x86_64}
  13102. S_LQ:
  13103. begin
  13104. NewSize := S_L;
  13105. Limit := $FFFFFFFF;
  13106. end;
  13107. {$endif x86_64}
  13108. else
  13109. InternalError(2021120303);
  13110. end;
  13111. if (
  13112. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13113. { Check for negative operands }
  13114. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13115. ) and
  13116. GetNextInstruction(hp2,hp3) and
  13117. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13118. (taicpu(hp3).condition in [C_E,C_NE]) then
  13119. begin
  13120. TransferUsedRegs(TmpUsedRegs);
  13121. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13122. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13123. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13124. begin
  13125. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13126. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13127. taicpu(hp1).opcode := A_TEST;
  13128. taicpu(hp1).opsize := NewSize;
  13129. RemoveInstruction(hp2);
  13130. RemoveCurrentP(p, hp1);
  13131. Result:=true;
  13132. exit;
  13133. end;
  13134. end;
  13135. end;
  13136. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13137. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13138. (taicpu(hp1).opsize=S_B)) or
  13139. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13140. (taicpu(hp1).opsize=S_W))
  13141. {$ifdef x86_64}
  13142. or ((taicpu(p).opsize=S_LQ) and
  13143. (taicpu(hp1).opsize=S_L))
  13144. {$endif x86_64}
  13145. ) and
  13146. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13147. begin
  13148. { change
  13149. movx %reg1,%reg2
  13150. op %reg2,%reg3
  13151. dealloc %reg2
  13152. into
  13153. op %reg1,%reg3
  13154. if the second op accesses only the bits stored in reg1
  13155. }
  13156. TransferUsedRegs(TmpUsedRegs);
  13157. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13158. if AndTest then
  13159. begin
  13160. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13161. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13162. end
  13163. else
  13164. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13165. if not RegUsed then
  13166. begin
  13167. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13168. if taicpu(p).oper[0]^.typ=top_reg then
  13169. begin
  13170. case taicpu(hp1).opsize of
  13171. S_B:
  13172. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13173. S_W:
  13174. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13175. S_L:
  13176. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13177. else
  13178. Internalerror(2020102301);
  13179. end;
  13180. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13181. end
  13182. else
  13183. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13184. RemoveCurrentP(p);
  13185. if AndTest then
  13186. RemoveInstruction(hp2);
  13187. result:=true;
  13188. exit;
  13189. end;
  13190. end
  13191. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13192. (
  13193. { Bitwise operations only }
  13194. (taicpu(hp1).opcode=A_AND) or
  13195. (taicpu(hp1).opcode=A_TEST) or
  13196. (
  13197. (taicpu(hp1).oper[0]^.typ = top_const) and
  13198. (
  13199. (taicpu(hp1).opcode=A_OR) or
  13200. (taicpu(hp1).opcode=A_XOR)
  13201. )
  13202. )
  13203. ) and
  13204. (
  13205. (taicpu(hp1).oper[0]^.typ = top_const) or
  13206. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13207. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13208. ) then
  13209. begin
  13210. { change
  13211. movx %reg2,%reg2
  13212. op const,%reg2
  13213. into
  13214. op const,%reg2 (smaller version)
  13215. movx %reg2,%reg2
  13216. also change
  13217. movx %reg1,%reg2
  13218. and/test (oper),%reg2
  13219. dealloc %reg2
  13220. into
  13221. and/test (oper),%reg1
  13222. }
  13223. case taicpu(p).opsize of
  13224. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13225. begin
  13226. NewSize := S_B;
  13227. NewRegSize := R_SUBL;
  13228. Limit := $FF;
  13229. end;
  13230. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13231. begin
  13232. NewSize := S_W;
  13233. NewRegSize := R_SUBW;
  13234. Limit := $FFFF;
  13235. end;
  13236. {$ifdef x86_64}
  13237. S_LQ:
  13238. begin
  13239. NewSize := S_L;
  13240. NewRegSize := R_SUBD;
  13241. Limit := $FFFFFFFF;
  13242. end;
  13243. {$endif x86_64}
  13244. else
  13245. Internalerror(2021120302);
  13246. end;
  13247. TransferUsedRegs(TmpUsedRegs);
  13248. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13249. if AndTest then
  13250. begin
  13251. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13252. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13253. end
  13254. else
  13255. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13256. if
  13257. (
  13258. (taicpu(p).opcode = A_MOVZX) and
  13259. (
  13260. (taicpu(hp1).opcode=A_AND) or
  13261. (taicpu(hp1).opcode=A_TEST)
  13262. ) and
  13263. not (
  13264. { If both are references, then the final instruction will have
  13265. both operands as references, which is not allowed }
  13266. (taicpu(p).oper[0]^.typ = top_ref) and
  13267. (taicpu(hp1).oper[0]^.typ = top_ref)
  13268. ) and
  13269. not RegUsed
  13270. ) or
  13271. (
  13272. (
  13273. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13274. not RegUsed
  13275. ) and
  13276. (taicpu(p).oper[0]^.typ = top_reg) and
  13277. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13278. (taicpu(hp1).oper[0]^.typ = top_const) and
  13279. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13280. ) then
  13281. begin
  13282. {$if defined(i386) or defined(i8086)}
  13283. { If the target size is 8-bit, make sure we can actually encode it }
  13284. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  13285. Exit;
  13286. {$endif i386 or i8086}
  13287. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13288. taicpu(hp1).opsize := NewSize;
  13289. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13290. if AndTest then
  13291. begin
  13292. RemoveInstruction(hp2);
  13293. if not RegUsed then
  13294. begin
  13295. taicpu(hp1).opcode := A_TEST;
  13296. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13297. begin
  13298. { Make sure the reference is the second operand }
  13299. SwapOper := taicpu(hp1).oper[0];
  13300. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13301. taicpu(hp1).oper[1] := SwapOper;
  13302. end;
  13303. end;
  13304. end;
  13305. case taicpu(hp1).oper[0]^.typ of
  13306. top_reg:
  13307. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13308. top_const:
  13309. { For the AND/TEST case }
  13310. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13311. else
  13312. ;
  13313. end;
  13314. if RegUsed then
  13315. begin
  13316. AsmL.Remove(p);
  13317. AsmL.InsertAfter(p, hp1);
  13318. p := hp1;
  13319. end
  13320. else
  13321. RemoveCurrentP(p, hp1);
  13322. result:=true;
  13323. exit;
  13324. end;
  13325. end;
  13326. end;
  13327. if reg_and_hp1_is_instr and
  13328. (taicpu(p).oper[0]^.typ = top_reg) and
  13329. (
  13330. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13331. ) and
  13332. (taicpu(hp1).oper[0]^.typ = top_const) and
  13333. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13334. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13335. { Minimum shift value allowed is the bit difference between the sizes }
  13336. (taicpu(hp1).oper[0]^.val >=
  13337. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13338. 8 * (
  13339. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13340. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13341. )
  13342. ) then
  13343. begin
  13344. { For:
  13345. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13346. shl/sal ##, %reg1
  13347. Remove the movsx/movzx instruction if the shift overwrites the
  13348. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13349. }
  13350. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13351. RemoveCurrentP(p, hp1);
  13352. Result := True;
  13353. Exit;
  13354. end
  13355. else if reg_and_hp1_is_instr and
  13356. (taicpu(p).oper[0]^.typ = top_reg) and
  13357. (
  13358. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13359. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13360. ) and
  13361. (taicpu(hp1).oper[0]^.typ = top_const) and
  13362. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13363. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13364. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13365. (taicpu(hp1).oper[0]^.val <
  13366. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13367. 8 * (
  13368. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13369. )
  13370. ) then
  13371. begin
  13372. { For:
  13373. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13374. sar ##, %reg1 shr ##, %reg1
  13375. Move the shift to before the movx instruction if the shift value
  13376. is not too large.
  13377. }
  13378. asml.Remove(hp1);
  13379. asml.InsertBefore(hp1, p);
  13380. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13381. case taicpu(p).opsize of
  13382. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13383. taicpu(hp1).opsize := S_B;
  13384. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13385. taicpu(hp1).opsize := S_W;
  13386. {$ifdef x86_64}
  13387. S_LQ:
  13388. taicpu(hp1).opsize := S_L;
  13389. {$endif}
  13390. else
  13391. InternalError(2020112401);
  13392. end;
  13393. if (taicpu(hp1).opcode = A_SHR) then
  13394. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13395. else
  13396. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13397. Result := True;
  13398. end;
  13399. if reg_and_hp1_is_instr and
  13400. (taicpu(p).oper[0]^.typ = top_reg) and
  13401. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13402. (
  13403. (taicpu(hp1).opcode = taicpu(p).opcode)
  13404. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13405. {$ifdef x86_64}
  13406. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13407. {$endif x86_64}
  13408. ) then
  13409. begin
  13410. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13411. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13412. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13413. begin
  13414. {
  13415. For example:
  13416. movzbw %al,%ax
  13417. movzwl %ax,%eax
  13418. Compress into:
  13419. movzbl %al,%eax
  13420. }
  13421. RegUsed := False;
  13422. case taicpu(p).opsize of
  13423. S_BW:
  13424. case taicpu(hp1).opsize of
  13425. S_WL:
  13426. begin
  13427. taicpu(p).opsize := S_BL;
  13428. RegUsed := True;
  13429. end;
  13430. {$ifdef x86_64}
  13431. S_WQ:
  13432. begin
  13433. if taicpu(p).opcode = A_MOVZX then
  13434. begin
  13435. taicpu(p).opsize := S_BL;
  13436. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13437. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13438. end
  13439. else
  13440. taicpu(p).opsize := S_BQ;
  13441. RegUsed := True;
  13442. end;
  13443. {$endif x86_64}
  13444. else
  13445. ;
  13446. end;
  13447. {$ifdef x86_64}
  13448. S_BL:
  13449. case taicpu(hp1).opsize of
  13450. S_LQ:
  13451. begin
  13452. if taicpu(p).opcode = A_MOVZX then
  13453. begin
  13454. taicpu(p).opsize := S_BL;
  13455. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13456. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13457. end
  13458. else
  13459. taicpu(p).opsize := S_BQ;
  13460. RegUsed := True;
  13461. end;
  13462. else
  13463. ;
  13464. end;
  13465. S_WL:
  13466. case taicpu(hp1).opsize of
  13467. S_LQ:
  13468. begin
  13469. if taicpu(p).opcode = A_MOVZX then
  13470. begin
  13471. taicpu(p).opsize := S_WL;
  13472. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13473. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13474. end
  13475. else
  13476. taicpu(p).opsize := S_WQ;
  13477. RegUsed := True;
  13478. end;
  13479. else
  13480. ;
  13481. end;
  13482. {$endif x86_64}
  13483. else
  13484. ;
  13485. end;
  13486. if RegUsed then
  13487. begin
  13488. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13489. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13490. RemoveInstruction(hp1);
  13491. Result := True;
  13492. Exit;
  13493. end;
  13494. end;
  13495. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13496. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13497. GetNextInstruction(hp1, hp2) and
  13498. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13499. (
  13500. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13501. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13502. {$ifdef x86_64}
  13503. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13504. {$endif x86_64}
  13505. ) and
  13506. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13507. (
  13508. (
  13509. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13510. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13511. ) or
  13512. (
  13513. { Only allow the operands in reverse order for TEST instructions }
  13514. (taicpu(hp2).opcode = A_TEST) and
  13515. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13516. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13517. )
  13518. ) then
  13519. begin
  13520. {
  13521. For example:
  13522. movzbl %al,%eax
  13523. movzbl (ref),%edx
  13524. andl %edx,%eax
  13525. (%edx deallocated)
  13526. Change to:
  13527. andb (ref),%al
  13528. movzbl %al,%eax
  13529. Rules are:
  13530. - First two instructions have the same opcode and opsize
  13531. - First instruction's operands are the same super-register
  13532. - Second instruction operates on a different register
  13533. - Third instruction is AND, OR, XOR or TEST
  13534. - Third instruction's operands are the destination registers of the first two instructions
  13535. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13536. - Second instruction's destination register is deallocated afterwards
  13537. }
  13538. TransferUsedRegs(TmpUsedRegs);
  13539. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13540. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13541. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13542. begin
  13543. case taicpu(p).opsize of
  13544. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13545. NewSize := S_B;
  13546. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13547. NewSize := S_W;
  13548. {$ifdef x86_64}
  13549. S_LQ:
  13550. NewSize := S_L;
  13551. {$endif x86_64}
  13552. else
  13553. InternalError(2021120301);
  13554. end;
  13555. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13556. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13557. taicpu(hp2).opsize := NewSize;
  13558. RemoveInstruction(hp1);
  13559. { With TEST, it's best to keep the MOVX instruction at the top }
  13560. if (taicpu(hp2).opcode <> A_TEST) then
  13561. begin
  13562. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13563. asml.Remove(p);
  13564. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13565. asml.InsertAfter(p, hp2);
  13566. p := hp2;
  13567. end
  13568. else
  13569. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13570. Result := True;
  13571. Exit;
  13572. end;
  13573. end;
  13574. end;
  13575. if taicpu(p).opcode=A_MOVZX then
  13576. begin
  13577. { removes superfluous And's after movzx's }
  13578. if reg_and_hp1_is_instr and
  13579. (taicpu(hp1).opcode = A_AND) and
  13580. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13581. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13582. {$ifdef x86_64}
  13583. { check for implicit extension to 64 bit }
  13584. or
  13585. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13586. (taicpu(hp1).opsize=S_Q) and
  13587. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13588. )
  13589. {$endif x86_64}
  13590. )
  13591. then
  13592. begin
  13593. case taicpu(p).opsize Of
  13594. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13595. if (taicpu(hp1).oper[0]^.val = $ff) then
  13596. begin
  13597. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13598. RemoveInstruction(hp1);
  13599. Result:=true;
  13600. exit;
  13601. end;
  13602. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13603. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13604. begin
  13605. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13606. RemoveInstruction(hp1);
  13607. Result:=true;
  13608. exit;
  13609. end;
  13610. {$ifdef x86_64}
  13611. S_LQ:
  13612. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13613. begin
  13614. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13615. RemoveInstruction(hp1);
  13616. Result:=true;
  13617. exit;
  13618. end;
  13619. {$endif x86_64}
  13620. else
  13621. ;
  13622. end;
  13623. { we cannot get rid of the and, but can we get rid of the movz ?}
  13624. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13625. begin
  13626. case taicpu(p).opsize Of
  13627. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13628. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13629. begin
  13630. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13631. RemoveCurrentP(p,hp1);
  13632. Result:=true;
  13633. exit;
  13634. end;
  13635. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13636. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13637. begin
  13638. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13639. RemoveCurrentP(p,hp1);
  13640. Result:=true;
  13641. exit;
  13642. end;
  13643. {$ifdef x86_64}
  13644. S_LQ:
  13645. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13646. begin
  13647. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13648. RemoveCurrentP(p,hp1);
  13649. Result:=true;
  13650. exit;
  13651. end;
  13652. {$endif x86_64}
  13653. else
  13654. ;
  13655. end;
  13656. end;
  13657. end;
  13658. { changes some movzx constructs to faster synonyms (all examples
  13659. are given with eax/ax, but are also valid for other registers)}
  13660. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13661. begin
  13662. case taicpu(p).opsize of
  13663. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13664. (the machine code is equivalent to movzbl %al,%eax), but the
  13665. code generator still generates that assembler instruction and
  13666. it is silently converted. This should probably be checked.
  13667. [Kit] }
  13668. S_BW:
  13669. begin
  13670. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13671. (
  13672. not IsMOVZXAcceptable
  13673. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13674. or (
  13675. (cs_opt_size in current_settings.optimizerswitches) and
  13676. (taicpu(p).oper[1]^.reg = NR_AX)
  13677. )
  13678. ) then
  13679. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13680. begin
  13681. DebugMsg(SPeepholeOptimization + 'var7',p);
  13682. taicpu(p).opcode := A_AND;
  13683. taicpu(p).changeopsize(S_W);
  13684. taicpu(p).loadConst(0,$ff);
  13685. Result := True;
  13686. end
  13687. else if not IsMOVZXAcceptable and
  13688. GetNextInstruction(p, hp1) and
  13689. (tai(hp1).typ = ait_instruction) and
  13690. (taicpu(hp1).opcode = A_AND) and
  13691. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13692. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13693. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13694. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13695. begin
  13696. DebugMsg(SPeepholeOptimization + 'var8',p);
  13697. taicpu(p).opcode := A_MOV;
  13698. taicpu(p).changeopsize(S_W);
  13699. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13700. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13701. Result := True;
  13702. end;
  13703. end;
  13704. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13705. S_BL:
  13706. if not IsMOVZXAcceptable then
  13707. begin
  13708. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13709. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13710. begin
  13711. DebugMsg(SPeepholeOptimization + 'var9',p);
  13712. taicpu(p).opcode := A_AND;
  13713. taicpu(p).changeopsize(S_L);
  13714. taicpu(p).loadConst(0,$ff);
  13715. Result := True;
  13716. end
  13717. else if GetNextInstruction(p, hp1) and
  13718. (tai(hp1).typ = ait_instruction) and
  13719. (taicpu(hp1).opcode = A_AND) and
  13720. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13721. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13722. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13723. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13724. begin
  13725. DebugMsg(SPeepholeOptimization + 'var10',p);
  13726. taicpu(p).opcode := A_MOV;
  13727. taicpu(p).changeopsize(S_L);
  13728. { do not use R_SUBWHOLE
  13729. as movl %rdx,%eax
  13730. is invalid in assembler PM }
  13731. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13732. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13733. Result := True;
  13734. end;
  13735. end;
  13736. {$endif i8086}
  13737. S_WL:
  13738. if not IsMOVZXAcceptable then
  13739. begin
  13740. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13741. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13742. begin
  13743. DebugMsg(SPeepholeOptimization + 'var11',p);
  13744. taicpu(p).opcode := A_AND;
  13745. taicpu(p).changeopsize(S_L);
  13746. taicpu(p).loadConst(0,$ffff);
  13747. Result := True;
  13748. end
  13749. else if GetNextInstruction(p, hp1) and
  13750. (tai(hp1).typ = ait_instruction) and
  13751. (taicpu(hp1).opcode = A_AND) and
  13752. (taicpu(hp1).oper[0]^.typ = top_const) and
  13753. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13754. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13755. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13756. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13757. begin
  13758. DebugMsg(SPeepholeOptimization + 'var12',p);
  13759. taicpu(p).opcode := A_MOV;
  13760. taicpu(p).changeopsize(S_L);
  13761. { do not use R_SUBWHOLE
  13762. as movl %rdx,%eax
  13763. is invalid in assembler PM }
  13764. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13765. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13766. Result := True;
  13767. end;
  13768. end;
  13769. else
  13770. InternalError(2017050705);
  13771. end;
  13772. end
  13773. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13774. begin
  13775. if GetNextInstruction(p, hp1) and
  13776. (tai(hp1).typ = ait_instruction) and
  13777. (taicpu(hp1).opcode = A_AND) and
  13778. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13779. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13780. begin
  13781. case taicpu(p).opsize Of
  13782. S_BL:
  13783. if (taicpu(hp1).opsize <> S_L) or
  13784. (taicpu(hp1).oper[0]^.val > $FF) then
  13785. begin
  13786. DebugMsg(SPeepholeOptimization + 'var13',p);
  13787. taicpu(hp1).changeopsize(S_L);
  13788. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13789. Include(OptsToCheck, aoc_ForceNewIteration);
  13790. end;
  13791. S_WL:
  13792. if (taicpu(hp1).opsize <> S_L) or
  13793. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13794. begin
  13795. DebugMsg(SPeepholeOptimization + 'var14',p);
  13796. taicpu(hp1).changeopsize(S_L);
  13797. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13798. Include(OptsToCheck, aoc_ForceNewIteration);
  13799. end;
  13800. S_BW:
  13801. if (taicpu(hp1).opsize <> S_W) or
  13802. (taicpu(hp1).oper[0]^.val > $FF) then
  13803. begin
  13804. DebugMsg(SPeepholeOptimization + 'var15',p);
  13805. taicpu(hp1).changeopsize(S_W);
  13806. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13807. Include(OptsToCheck, aoc_ForceNewIteration);
  13808. end;
  13809. else
  13810. Internalerror(2017050704)
  13811. end;
  13812. end;
  13813. end;
  13814. end;
  13815. end;
  13816. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13817. var
  13818. hp1, hp2 : tai;
  13819. MaskLength : Cardinal;
  13820. MaskedBits : TCgInt;
  13821. ActiveReg : TRegister;
  13822. begin
  13823. Result:=false;
  13824. { There are no optimisations for reference targets }
  13825. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13826. Exit;
  13827. while GetNextInstruction(p, hp1) and
  13828. (hp1.typ = ait_instruction) do
  13829. begin
  13830. if (taicpu(p).oper[0]^.typ = top_const) then
  13831. begin
  13832. case taicpu(hp1).opcode of
  13833. A_AND:
  13834. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13835. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13836. { the second register must contain the first one, so compare their subreg types }
  13837. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13838. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13839. { change
  13840. and const1, reg
  13841. and const2, reg
  13842. to
  13843. and (const1 and const2), reg
  13844. }
  13845. begin
  13846. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13847. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13848. RemoveCurrentP(p, hp1);
  13849. Result:=true;
  13850. exit;
  13851. end;
  13852. A_CMP:
  13853. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13854. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13855. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13856. { Just check that the condition on the next instruction is compatible }
  13857. GetNextInstruction(hp1, hp2) and
  13858. (hp2.typ = ait_instruction) and
  13859. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13860. then
  13861. { change
  13862. and 2^n, reg
  13863. cmp 2^n, reg
  13864. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13865. to
  13866. and 2^n, reg
  13867. test reg, reg
  13868. j(~c) / set(~c) / cmov(~c)
  13869. }
  13870. begin
  13871. { Keep TEST instruction in, rather than remove it, because
  13872. it may trigger other optimisations such as MovAndTest2Test }
  13873. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13874. taicpu(hp1).opcode := A_TEST;
  13875. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13876. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13877. Result := True;
  13878. Exit;
  13879. end
  13880. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13881. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13882. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13883. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13884. { change
  13885. and $ff/$ff/$ffff, reg
  13886. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13887. dealloc reg
  13888. to
  13889. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13890. }
  13891. begin
  13892. TransferUsedRegs(TmpUsedRegs);
  13893. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13894. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13895. begin
  13896. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13897. case taicpu(p).oper[0]^.val of
  13898. $ff:
  13899. begin
  13900. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13901. taicpu(hp1).opsize:=S_B;
  13902. end;
  13903. $ffff:
  13904. begin
  13905. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13906. taicpu(hp1).opsize:=S_W;
  13907. end;
  13908. $ffffffff:
  13909. begin
  13910. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13911. taicpu(hp1).opsize:=S_L;
  13912. end;
  13913. else
  13914. Internalerror(2023030401);
  13915. end;
  13916. RemoveCurrentP(p);
  13917. Result := True;
  13918. Exit;
  13919. end;
  13920. end;
  13921. A_MOVZX:
  13922. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13923. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13924. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13925. (
  13926. (
  13927. (taicpu(p).opsize=S_W) and
  13928. (taicpu(hp1).opsize=S_BW)
  13929. ) or
  13930. (
  13931. (taicpu(p).opsize=S_L) and
  13932. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13933. )
  13934. {$ifdef x86_64}
  13935. or
  13936. (
  13937. (taicpu(p).opsize=S_Q) and
  13938. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13939. )
  13940. {$endif x86_64}
  13941. ) then
  13942. begin
  13943. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13944. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13945. ) or
  13946. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13947. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13948. then
  13949. begin
  13950. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13951. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13952. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13953. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13954. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13955. }
  13956. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13957. RemoveInstruction(hp1);
  13958. { See if there are other optimisations possible }
  13959. Continue;
  13960. end;
  13961. end;
  13962. A_SHL:
  13963. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13964. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13965. begin
  13966. {$ifopt R+}
  13967. {$define RANGE_WAS_ON}
  13968. {$R-}
  13969. {$endif}
  13970. { get length of potential and mask }
  13971. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13972. { really a mask? }
  13973. {$ifdef RANGE_WAS_ON}
  13974. {$R+}
  13975. {$endif}
  13976. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13977. { unmasked part shifted out? }
  13978. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13979. begin
  13980. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13981. RemoveCurrentP(p, hp1);
  13982. Result:=true;
  13983. exit;
  13984. end;
  13985. end;
  13986. A_SHR:
  13987. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13988. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13989. (taicpu(hp1).oper[0]^.val <= 63) then
  13990. begin
  13991. { Does SHR combined with the AND cover all the bits?
  13992. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13993. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13994. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13995. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13996. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13997. begin
  13998. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13999. RemoveCurrentP(p, hp1);
  14000. Result := True;
  14001. Exit;
  14002. end;
  14003. end;
  14004. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14005. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14006. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14007. begin
  14008. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14009. (
  14010. (
  14011. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14012. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14013. ) or (
  14014. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14015. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14016. {$ifdef x86_64}
  14017. ) or (
  14018. (taicpu(hp1).opsize = S_LQ) and
  14019. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14020. {$endif x86_64}
  14021. )
  14022. ) then
  14023. begin
  14024. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14025. begin
  14026. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14027. RemoveInstruction(hp1);
  14028. { See if there are other optimisations possible }
  14029. Continue;
  14030. end;
  14031. { The super-registers are the same though.
  14032. Note that this change by itself doesn't improve
  14033. code speed, but it opens up other optimisations. }
  14034. {$ifdef x86_64}
  14035. { Convert 64-bit register to 32-bit }
  14036. case taicpu(hp1).opsize of
  14037. S_BQ:
  14038. begin
  14039. taicpu(hp1).opsize := S_BL;
  14040. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14041. end;
  14042. S_WQ:
  14043. begin
  14044. taicpu(hp1).opsize := S_WL;
  14045. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14046. end
  14047. else
  14048. ;
  14049. end;
  14050. {$endif x86_64}
  14051. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14052. taicpu(hp1).opcode := A_MOVZX;
  14053. { See if there are other optimisations possible }
  14054. Continue;
  14055. end;
  14056. end;
  14057. else
  14058. ;
  14059. end;
  14060. end
  14061. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14062. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14063. begin
  14064. {$ifdef x86_64}
  14065. if (taicpu(p).opsize = S_Q) then
  14066. begin
  14067. { Never necessary }
  14068. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14069. RemoveCurrentP(p, hp1);
  14070. Result := True;
  14071. Exit;
  14072. end;
  14073. {$endif x86_64}
  14074. { Forward check to determine necessity of and %reg,%reg }
  14075. TransferUsedRegs(TmpUsedRegs);
  14076. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14077. { Saves on a bunch of dereferences }
  14078. ActiveReg := taicpu(p).oper[1]^.reg;
  14079. case taicpu(hp1).opcode of
  14080. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14081. if (
  14082. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14083. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14084. ) and
  14085. (
  14086. (taicpu(hp1).opcode <> A_MOV) or
  14087. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14088. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14089. ) and
  14090. not (
  14091. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14092. (taicpu(hp1).opcode = A_MOV) and
  14093. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14094. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14095. ) and
  14096. (
  14097. (
  14098. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14099. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14100. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14101. ) or
  14102. (
  14103. {$ifdef x86_64}
  14104. (
  14105. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14106. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14107. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14108. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14109. ) and
  14110. {$endif x86_64}
  14111. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14112. )
  14113. ) then
  14114. begin
  14115. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14116. RemoveCurrentP(p, hp1);
  14117. Result := True;
  14118. Exit;
  14119. end;
  14120. A_ADD,
  14121. A_AND,
  14122. A_BSF,
  14123. A_BSR,
  14124. A_BTC,
  14125. A_BTR,
  14126. A_BTS,
  14127. A_OR,
  14128. A_SUB,
  14129. A_XOR:
  14130. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14131. if (
  14132. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14133. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14134. ) and
  14135. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14136. begin
  14137. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14138. RemoveCurrentP(p, hp1);
  14139. Result := True;
  14140. Exit;
  14141. end;
  14142. A_CMP,
  14143. A_TEST:
  14144. if (
  14145. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14146. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14147. ) and
  14148. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14149. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14150. begin
  14151. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14152. RemoveCurrentP(p, hp1);
  14153. Result := True;
  14154. Exit;
  14155. end;
  14156. A_BSWAP,
  14157. A_NEG,
  14158. A_NOT:
  14159. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14160. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14161. begin
  14162. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14163. RemoveCurrentP(p, hp1);
  14164. Result := True;
  14165. Exit;
  14166. end;
  14167. else
  14168. ;
  14169. end;
  14170. end;
  14171. if (taicpu(hp1).is_jmp) and
  14172. (taicpu(hp1).opcode<>A_JMP) and
  14173. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14174. begin
  14175. { change
  14176. and x, reg
  14177. jxx
  14178. to
  14179. test x, reg
  14180. jxx
  14181. if reg is deallocated before the
  14182. jump, but only if it's a conditional jump (PFV)
  14183. }
  14184. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14185. taicpu(p).opcode := A_TEST;
  14186. Exit;
  14187. end;
  14188. Break;
  14189. end;
  14190. { Lone AND tests }
  14191. if (taicpu(p).oper[0]^.typ = top_const) then
  14192. begin
  14193. {
  14194. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14195. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14196. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14197. }
  14198. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14199. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14200. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14201. begin
  14202. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14203. if taicpu(p).opsize = S_L then
  14204. begin
  14205. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14206. Result := True;
  14207. end;
  14208. end;
  14209. end;
  14210. { Backward check to determine necessity of and %reg,%reg }
  14211. if (taicpu(p).oper[0]^.typ = top_reg) and
  14212. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14213. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14214. GetLastInstruction(p, hp2) and
  14215. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14216. { Check size of adjacent instruction to determine if the AND is
  14217. effectively a null operation }
  14218. (
  14219. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14220. { Note: Don't include S_Q }
  14221. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14222. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14223. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14224. ) then
  14225. begin
  14226. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14227. { If GetNextInstruction returned False, hp1 will be nil }
  14228. RemoveCurrentP(p, hp1);
  14229. Result := True;
  14230. Exit;
  14231. end;
  14232. end;
  14233. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14234. var
  14235. hp1, hp2: tai;
  14236. NewRef: TReference;
  14237. Distance: Cardinal;
  14238. TempTracking: TAllUsedRegs;
  14239. DoAddMov2Lea: Boolean;
  14240. { This entire nested function is used in an if-statement below, but we
  14241. want to avoid all the used reg transfers and GetNextInstruction calls
  14242. until we really have to check }
  14243. function MemRegisterNotUsedLater: Boolean; inline;
  14244. var
  14245. hp2: tai;
  14246. begin
  14247. TransferUsedRegs(TmpUsedRegs);
  14248. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14249. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14250. else
  14251. { p and hp1 will be adjacent }
  14252. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14253. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14254. end;
  14255. begin
  14256. Result := False;
  14257. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14258. (taicpu(p).oper[1]^.typ = top_reg) then
  14259. begin
  14260. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14261. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14262. (hp1.typ <> ait_instruction) or
  14263. not
  14264. (
  14265. (cs_opt_level3 in current_settings.optimizerswitches) or
  14266. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14267. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14268. ) then
  14269. Exit;
  14270. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14271. addq $x, %rax
  14272. movq %rax, %rdx
  14273. sarq $63, %rdx
  14274. (%rax still in use)
  14275. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14276. leaq $x(%rax),%rdx
  14277. addq $x, %rax
  14278. sarq $63, %rdx
  14279. ...which is okay since it breaks the dependency chain between
  14280. addq and movq, but if OptPass2MOV is called first:
  14281. addq $x, %rax
  14282. cqto
  14283. ...which is better in all ways, taking only 2 cycles to execute
  14284. and much smaller in code size.
  14285. }
  14286. { The extra register tracking is quite strenuous }
  14287. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14288. MatchInstruction(hp1, A_MOV, []) then
  14289. begin
  14290. { Update the register tracking to the MOV instruction }
  14291. CopyUsedRegs(TempTracking);
  14292. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14293. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14294. else
  14295. { p and hp1 will be adjacent }
  14296. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14297. hp2 := hp1;
  14298. if OptPass2MOV(hp1) then
  14299. Include(OptsToCheck, aoc_ForceNewIteration);
  14300. { Reset the tracking to the current instruction }
  14301. RestoreUsedRegs(TempTracking);
  14302. ReleaseUsedRegs(TempTracking);
  14303. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14304. OptPass2ADD get called again }
  14305. if (hp1 <> hp2) then
  14306. begin
  14307. Result := True;
  14308. Exit;
  14309. end;
  14310. end;
  14311. { Change:
  14312. add %reg2,%reg1
  14313. (%reg2 not modified in between)
  14314. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14315. To:
  14316. mov/s/z #(%reg1,%reg2),%reg1
  14317. }
  14318. if (taicpu(p).oper[0]^.typ = top_reg) and
  14319. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14320. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14321. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14322. (
  14323. (
  14324. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14325. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14326. { r/esp cannot be an index }
  14327. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14328. ) or (
  14329. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14330. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14331. )
  14332. ) and (
  14333. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14334. (
  14335. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14336. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14337. MemRegisterNotUsedLater
  14338. )
  14339. ) then
  14340. begin
  14341. if (
  14342. { Instructions are guaranteed to be adjacent on -O2 and under }
  14343. (cs_opt_level3 in current_settings.optimizerswitches) and
  14344. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14345. ) then
  14346. begin
  14347. { If the other register is used in between, move the MOV
  14348. instruction to right after the ADD instruction so a
  14349. saving can still be made }
  14350. Asml.Remove(hp1);
  14351. Asml.InsertAfter(hp1, p);
  14352. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14353. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14354. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14355. RemoveCurrentp(p, hp1);
  14356. end
  14357. else
  14358. begin
  14359. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14360. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14361. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14362. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14363. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14364. { hp1 may not be the immediate next instruction under -O3 }
  14365. RemoveCurrentp(p)
  14366. else
  14367. RemoveCurrentp(p, hp1);
  14368. end;
  14369. Result := True;
  14370. Exit;
  14371. end;
  14372. { Change:
  14373. addl/q $x,%reg1
  14374. movl/q %reg1,%reg2
  14375. To:
  14376. leal/q $x(%reg1),%reg2
  14377. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14378. Breaks the dependency chain.
  14379. }
  14380. if (taicpu(p).oper[0]^.typ = top_const) and
  14381. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14382. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14383. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14384. (
  14385. { Instructions are guaranteed to be adjacent on -O2 and under }
  14386. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14387. (
  14388. { If the flags are used, don't make the optimisation,
  14389. otherwise they will be scrambled. Fixes #41148 }
  14390. (
  14391. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14392. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14393. ) and
  14394. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14395. )
  14396. ) then
  14397. begin
  14398. TransferUsedRegs(TmpUsedRegs);
  14399. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14400. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14401. else
  14402. { p and hp1 will be adjacent }
  14403. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14404. if (
  14405. SetAndTest(
  14406. (
  14407. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14408. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14409. ),
  14410. DoAddMov2Lea
  14411. ) or
  14412. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14413. not (cs_opt_size in current_settings.optimizerswitches)
  14414. ) then
  14415. begin
  14416. { Change the MOV instruction to a LEA instruction, and update the
  14417. first operand }
  14418. reference_reset(NewRef, 1, []);
  14419. NewRef.base := taicpu(p).oper[1]^.reg;
  14420. NewRef.scalefactor := 1;
  14421. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14422. taicpu(hp1).opcode := A_LEA;
  14423. taicpu(hp1).loadref(0, NewRef);
  14424. if DoAddMov2Lea then
  14425. begin
  14426. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14427. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14428. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14429. { hp1 may not be the immediate next instruction under -O3 }
  14430. RemoveCurrentp(p)
  14431. else
  14432. RemoveCurrentp(p, hp1);
  14433. end
  14434. else
  14435. begin
  14436. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14437. { Move what is now the LEA instruction to before the ADD instruction }
  14438. Asml.Remove(hp1);
  14439. Asml.InsertBefore(hp1, p);
  14440. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14441. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14442. p := hp1;
  14443. end;
  14444. Result := True;
  14445. end;
  14446. end;
  14447. end;
  14448. end;
  14449. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14450. var
  14451. SubReg: TSubRegister;
  14452. hp1, hp2: tai;
  14453. CallJmp: Boolean;
  14454. begin
  14455. Result := False;
  14456. CallJmp := False;
  14457. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14458. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14459. with taicpu(p).oper[0]^.ref^ do
  14460. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14461. if (offset = 0) then
  14462. begin
  14463. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14464. begin
  14465. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14466. taicpu(p).opcode := A_ADD;
  14467. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14468. Result := True;
  14469. end
  14470. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14471. begin
  14472. if (base <> NR_NO) then
  14473. begin
  14474. if (scalefactor <= 1) then
  14475. begin
  14476. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14477. taicpu(p).opcode := A_ADD;
  14478. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14479. Result := True;
  14480. end;
  14481. end
  14482. else
  14483. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14484. if (scalefactor in [2, 4, 8]) then
  14485. begin
  14486. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14487. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14488. taicpu(p).opcode := A_SHL;
  14489. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14490. Result := True;
  14491. end;
  14492. end;
  14493. end
  14494. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14495. lot of latency, so break off the offset if %reg3 is used soon
  14496. afterwards }
  14497. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14498. { If 3-component addresses don't have additional latency, don't
  14499. perform this optimisation }
  14500. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14501. GetNextInstruction(p, hp1) and
  14502. (hp1.typ = ait_instruction) and
  14503. (
  14504. (
  14505. { Permit jumps and calls since they have a larger degree of overhead }
  14506. (
  14507. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14508. (
  14509. { ... unless the register specifies the location }
  14510. (taicpu(hp1).ops > 0) and
  14511. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14512. )
  14513. ) and
  14514. (
  14515. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14516. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14517. )
  14518. )
  14519. or
  14520. (
  14521. { Check up to two instructions ahead }
  14522. GetNextInstruction(hp1, hp2) and
  14523. (hp2.typ = ait_instruction) and
  14524. (
  14525. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14526. (
  14527. { Same as above }
  14528. (taicpu(hp2).ops > 0) and
  14529. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14530. )
  14531. ) and
  14532. (
  14533. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14534. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14535. )
  14536. )
  14537. ) then
  14538. begin
  14539. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14540. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14541. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14542. offset := 0;
  14543. if Assigned(symbol) or Assigned(relsymbol) then
  14544. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14545. else
  14546. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14547. { Inserting before the next instruction rather than after the
  14548. current instruction gives more accurate register tracking }
  14549. asml.InsertBefore(hp2, hp1);
  14550. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14551. Result := True;
  14552. end;
  14553. end;
  14554. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14555. var
  14556. hp1, hp2: tai;
  14557. NewRef: TReference;
  14558. Distance: Cardinal;
  14559. TempTracking: TAllUsedRegs;
  14560. DoSubMov2Lea: Boolean;
  14561. begin
  14562. Result := False;
  14563. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14564. MatchOpType(taicpu(p),top_const,top_reg) then
  14565. begin
  14566. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14567. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14568. (hp1.typ <> ait_instruction) or
  14569. not
  14570. (
  14571. (cs_opt_level3 in current_settings.optimizerswitches) or
  14572. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14573. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14574. ) then
  14575. Exit;
  14576. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14577. subq $x, %rax
  14578. movq %rax, %rdx
  14579. sarq $63, %rdx
  14580. (%rax still in use)
  14581. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14582. leaq $-x(%rax),%rdx
  14583. movq $x, %rax
  14584. sarq $63, %rdx
  14585. ...which is okay since it breaks the dependency chain between
  14586. subq and movq, but if OptPass2MOV is called first:
  14587. subq $x, %rax
  14588. cqto
  14589. ...which is better in all ways, taking only 2 cycles to execute
  14590. and much smaller in code size.
  14591. }
  14592. { The extra register tracking is quite strenuous }
  14593. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14594. MatchInstruction(hp1, A_MOV, []) then
  14595. begin
  14596. { Update the register tracking to the MOV instruction }
  14597. CopyUsedRegs(TempTracking);
  14598. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14599. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14600. else
  14601. { p and hp1 will be adjacent }
  14602. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14603. hp2 := hp1;
  14604. if OptPass2MOV(hp1) then
  14605. Include(OptsToCheck, aoc_ForceNewIteration);
  14606. { Reset the tracking to the current instruction }
  14607. RestoreUsedRegs(TempTracking);
  14608. ReleaseUsedRegs(TempTracking);
  14609. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14610. OptPass2SUB get called again }
  14611. if (hp1 <> hp2) then
  14612. begin
  14613. Result := True;
  14614. Exit;
  14615. end;
  14616. end;
  14617. { Change:
  14618. subl/q $x,%reg1
  14619. movl/q %reg1,%reg2
  14620. To:
  14621. leal/q $-x(%reg1),%reg2
  14622. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14623. Breaks the dependency chain and potentially permits the removal of
  14624. a CMP instruction if one follows.
  14625. }
  14626. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14627. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14628. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14629. (
  14630. { Instructions are guaranteed to be adjacent on -O2 and under }
  14631. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14632. (
  14633. { If the flags are used, don't make the optimisation,
  14634. otherwise they will be scrambled. Fixes #41148 }
  14635. (
  14636. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14637. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14638. ) and
  14639. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14640. )
  14641. ) then
  14642. begin
  14643. TransferUsedRegs(TmpUsedRegs);
  14644. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14645. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14646. else
  14647. { p and hp1 will be adjacent }
  14648. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14649. if (
  14650. SetAndTest(
  14651. (
  14652. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14653. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14654. ),
  14655. DoSubMov2Lea
  14656. ) or
  14657. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14658. not (cs_opt_size in current_settings.optimizerswitches)
  14659. ) then
  14660. begin
  14661. { Change the MOV instruction to a LEA instruction, and update the
  14662. first operand }
  14663. reference_reset(NewRef, 1, []);
  14664. NewRef.base := taicpu(p).oper[1]^.reg;
  14665. NewRef.scalefactor := 1;
  14666. NewRef.offset := -taicpu(p).oper[0]^.val;
  14667. taicpu(hp1).opcode := A_LEA;
  14668. taicpu(hp1).loadref(0, NewRef);
  14669. if DoSubMov2Lea then
  14670. begin
  14671. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14672. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14673. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14674. { hp1 may not be the immediate next instruction under -O3 }
  14675. RemoveCurrentp(p)
  14676. else
  14677. RemoveCurrentp(p, hp1);
  14678. end
  14679. else
  14680. begin
  14681. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14682. { Move what is now the LEA instruction to before the SUB instruction }
  14683. Asml.Remove(hp1);
  14684. Asml.InsertBefore(hp1, p);
  14685. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14686. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14687. p := hp1;
  14688. end;
  14689. Result := True;
  14690. end;
  14691. end;
  14692. end;
  14693. end;
  14694. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14695. begin
  14696. { we can skip all instructions not messing with the stack pointer }
  14697. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14698. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14699. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14700. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14701. ({(taicpu(hp1).ops=0) or }
  14702. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14703. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14704. ) and }
  14705. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14706. )
  14707. ) do
  14708. GetNextInstruction(hp1,hp1);
  14709. Result:=assigned(hp1);
  14710. end;
  14711. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14712. var
  14713. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14714. begin
  14715. Result:=false;
  14716. hp5:=nil;
  14717. hp6:=nil;
  14718. hp7:=nil;
  14719. hp8:=nil;
  14720. { replace
  14721. leal(q) x(<stackpointer>),<stackpointer>
  14722. <optional .seh_stackalloc ...>
  14723. <optional .seh_endprologue ...>
  14724. call procname
  14725. <optional NOP>
  14726. leal(q) -x(<stackpointer>),<stackpointer>
  14727. <optional VZEROUPPER>
  14728. ret
  14729. by
  14730. jmp procname
  14731. but do it only on level 4 because it destroys stack back traces
  14732. }
  14733. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14734. MatchOpType(taicpu(p),top_ref,top_reg) and
  14735. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14736. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14737. { the -8, -24, -40 are not required, but bail out early if possible,
  14738. higher values are unlikely }
  14739. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14740. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14741. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14742. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14743. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14744. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14745. GetNextInstruction(p, hp1) and
  14746. { Take a copy of hp1 }
  14747. SetAndTest(hp1, hp4) and
  14748. { trick to skip label }
  14749. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14750. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14751. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14752. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14753. SkipSimpleInstructions(hp1) and
  14754. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14755. GetNextInstruction(hp1, hp2) and
  14756. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14757. { skip nop instruction on win64 }
  14758. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14759. SetAndTest(hp2,hp6) and
  14760. GetNextInstruction(hp2,hp2) and
  14761. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14762. ) and
  14763. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14764. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14765. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14766. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14767. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14768. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14769. { Segment register will be NR_NO }
  14770. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14771. GetNextInstruction(hp2, hp3) and
  14772. { trick to skip label }
  14773. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14774. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14775. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14776. SetAndTest(hp3,hp5) and
  14777. GetNextInstruction(hp3,hp3) and
  14778. MatchInstruction(hp3,A_RET,[S_NO])
  14779. )
  14780. ) and
  14781. (taicpu(hp3).ops=0) then
  14782. begin
  14783. taicpu(hp1).opcode := A_JMP;
  14784. taicpu(hp1).is_jmp := true;
  14785. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14786. { search for the stackalloc directive and remove it }
  14787. hp7:=tai(p.next);
  14788. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14789. begin
  14790. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14791. begin
  14792. { sanity check }
  14793. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14794. Internalerror(2024012201);
  14795. hp8:=tai(hp7.next);
  14796. RemoveInstruction(tai(hp7));
  14797. hp7:=hp8;
  14798. break;
  14799. end
  14800. else
  14801. hp7:=tai(hp7.next);
  14802. end;
  14803. RemoveCurrentP(p, hp4);
  14804. RemoveInstruction(hp2);
  14805. RemoveInstruction(hp3);
  14806. { if there is a vzeroupper instruction then move it before the jmp }
  14807. if Assigned(hp5) then
  14808. begin
  14809. AsmL.Remove(hp5);
  14810. ASmL.InsertBefore(hp5,hp1)
  14811. end;
  14812. { remove nop on win64 }
  14813. if Assigned(hp6) then
  14814. RemoveInstruction(hp6);
  14815. Result:=true;
  14816. end;
  14817. end;
  14818. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14819. {$ifdef x86_64}
  14820. var
  14821. hp1, hp2, hp3, hp4, hp5: tai;
  14822. {$endif x86_64}
  14823. begin
  14824. Result:=false;
  14825. {$ifdef x86_64}
  14826. hp5:=nil;
  14827. { replace
  14828. push %rax
  14829. call procname
  14830. pop %rcx
  14831. ret
  14832. by
  14833. jmp procname
  14834. but do it only on level 4 because it destroys stack back traces
  14835. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14836. for all supported calling conventions
  14837. }
  14838. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14839. MatchOpType(taicpu(p),top_reg) and
  14840. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14841. GetNextInstruction(p, hp1) and
  14842. { Take a copy of hp1 }
  14843. SetAndTest(hp1, hp4) and
  14844. { trick to skip label }
  14845. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14846. SkipSimpleInstructions(hp1) and
  14847. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14848. GetNextInstruction(hp1, hp2) and
  14849. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14850. MatchOpType(taicpu(hp2),top_reg) and
  14851. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14852. GetNextInstruction(hp2, hp3) and
  14853. { trick to skip label }
  14854. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14855. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14856. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14857. SetAndTest(hp3,hp5) and
  14858. GetNextInstruction(hp3,hp3) and
  14859. MatchInstruction(hp3,A_RET,[S_NO])
  14860. )
  14861. ) and
  14862. (taicpu(hp3).ops=0) then
  14863. begin
  14864. taicpu(hp1).opcode := A_JMP;
  14865. taicpu(hp1).is_jmp := true;
  14866. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14867. RemoveCurrentP(p, hp4);
  14868. RemoveInstruction(hp2);
  14869. RemoveInstruction(hp3);
  14870. if Assigned(hp5) then
  14871. begin
  14872. AsmL.Remove(hp5);
  14873. ASmL.InsertBefore(hp5,hp1)
  14874. end;
  14875. Result:=true;
  14876. end;
  14877. {$endif x86_64}
  14878. end;
  14879. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14880. var
  14881. Value, RegName: string;
  14882. hp1: tai;
  14883. begin
  14884. Result:=false;
  14885. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14886. begin
  14887. case taicpu(p).oper[0]^.val of
  14888. 0:
  14889. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14890. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14891. (
  14892. { See if we can still convert the instruction }
  14893. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14894. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14895. ) then
  14896. begin
  14897. { change "mov $0,%reg" into "xor %reg,%reg" }
  14898. taicpu(p).opcode := A_XOR;
  14899. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14900. Result := True;
  14901. {$ifdef x86_64}
  14902. end
  14903. else if (taicpu(p).opsize = S_Q) then
  14904. begin
  14905. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14906. { The actual optimization }
  14907. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14908. taicpu(p).changeopsize(S_L);
  14909. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14910. Result := True;
  14911. end;
  14912. $1..$FFFFFFFF:
  14913. begin
  14914. { Code size reduction by J. Gareth "Kit" Moreton }
  14915. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14916. case taicpu(p).opsize of
  14917. S_Q:
  14918. begin
  14919. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14920. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14921. { The actual optimization }
  14922. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14923. taicpu(p).changeopsize(S_L);
  14924. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14925. Result := True;
  14926. end;
  14927. else
  14928. { Do nothing };
  14929. end;
  14930. {$endif x86_64}
  14931. end;
  14932. -1:
  14933. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14934. if (cs_opt_size in current_settings.optimizerswitches) and
  14935. (taicpu(p).opsize <> S_B) and
  14936. (
  14937. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14938. (
  14939. { See if we can still convert the instruction }
  14940. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14941. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14942. )
  14943. ) then
  14944. begin
  14945. { change "mov $-1,%reg" into "or $-1,%reg" }
  14946. { NOTES:
  14947. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14948. - This operation creates a false dependency on the register, so only do it when optimising for size
  14949. - It is possible to set memory operands using this method, but this creates an even greater false dependency, so don't do this at all
  14950. }
  14951. taicpu(p).opcode := A_OR;
  14952. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14953. Result := True;
  14954. end;
  14955. else
  14956. { Do nothing };
  14957. end;
  14958. end;
  14959. end;
  14960. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14961. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14962. begin
  14963. Result := False;
  14964. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14965. Exit;
  14966. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14967. so don't bother optimising }
  14968. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14969. Exit;
  14970. if (taicpu(p).oper[0]^.typ <> top_const) or
  14971. { If the value can fit into an 8-bit signed integer, a smaller
  14972. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14973. falls within this range }
  14974. (
  14975. (taicpu(p).oper[0]^.val > -128) and
  14976. (taicpu(p).oper[0]^.val <= 127)
  14977. ) then
  14978. Exit;
  14979. { If we're optimising for size, this is acceptable }
  14980. if (cs_opt_size in current_settings.optimizerswitches) then
  14981. Exit(True);
  14982. if (taicpu(p).oper[1]^.typ = top_reg) and
  14983. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14984. Exit(True);
  14985. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14986. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14987. Exit(True);
  14988. end;
  14989. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14990. var
  14991. hp1: tai;
  14992. Value: TCGInt;
  14993. begin
  14994. Result := False;
  14995. if MatchOpType(taicpu(p), top_const, top_reg) then
  14996. begin
  14997. { Detect:
  14998. andw x, %ax (0 <= x < $8000)
  14999. ...
  15000. movzwl %ax,%eax
  15001. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15002. }
  15003. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15004. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15005. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15006. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15007. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15008. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15009. begin
  15010. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15011. taicpu(hp1).opcode := A_CWDE;
  15012. taicpu(hp1).clearop(0);
  15013. taicpu(hp1).clearop(1);
  15014. taicpu(hp1).ops := 0;
  15015. { A change was made, but not with p, so don't set Result, but
  15016. notify the compiler that a change was made }
  15017. Include(OptsToCheck, aoc_ForceNewIteration);
  15018. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15019. end;
  15020. end;
  15021. { If "not x" is a power of 2 (popcnt = 1), change:
  15022. and $x, %reg/ref
  15023. To:
  15024. btr lb(x), %reg/ref
  15025. }
  15026. if IsBTXAcceptable(p) and
  15027. (
  15028. { Make sure a TEST doesn't follow that plays with the register }
  15029. not GetNextInstruction(p, hp1) or
  15030. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15031. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15032. ) then
  15033. begin
  15034. {$push}{$R-}{$Q-}
  15035. { Value is a sign-extended 32-bit integer - just correct it
  15036. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15037. checks to see if this operand is an immediate. }
  15038. Value := not taicpu(p).oper[0]^.val;
  15039. {$pop}
  15040. {$ifdef x86_64}
  15041. if taicpu(p).opsize = S_L then
  15042. {$endif x86_64}
  15043. Value := Value and $FFFFFFFF;
  15044. if (PopCnt(QWord(Value)) = 1) then
  15045. begin
  15046. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15047. taicpu(p).opcode := A_BTR;
  15048. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15049. Result := True;
  15050. Exit;
  15051. end;
  15052. end;
  15053. end;
  15054. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15055. begin
  15056. Result := False;
  15057. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15058. Exit;
  15059. { Convert:
  15060. movswl %ax,%eax -> cwtl
  15061. movslq %eax,%rax -> cdqe
  15062. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15063. refer to the same opcode and depends only on the assembler's
  15064. current operand-size attribute. [Kit]
  15065. }
  15066. with taicpu(p) do
  15067. case opsize of
  15068. S_WL:
  15069. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15070. begin
  15071. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15072. opcode := A_CWDE;
  15073. clearop(0);
  15074. clearop(1);
  15075. ops := 0;
  15076. Result := True;
  15077. end;
  15078. {$ifdef x86_64}
  15079. S_LQ:
  15080. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15081. begin
  15082. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15083. opcode := A_CDQE;
  15084. clearop(0);
  15085. clearop(1);
  15086. ops := 0;
  15087. Result := True;
  15088. end;
  15089. {$endif x86_64}
  15090. else
  15091. ;
  15092. end;
  15093. end;
  15094. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15095. var
  15096. hp1: tai;
  15097. begin
  15098. Result := False;
  15099. { All these optimisations work on "shr const,%reg" }
  15100. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15101. Exit;
  15102. if HandleSHRMerge(p, True) then
  15103. begin
  15104. Result := True;
  15105. Exit;
  15106. end;
  15107. { Detect the following (looking backwards):
  15108. shr %cl,%reg
  15109. shr x, %reg
  15110. Swap the two SHR instructions to minimise a pipeline stall.
  15111. }
  15112. if GetLastInstruction(p, hp1) and
  15113. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15114. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15115. { First operand will be %cl }
  15116. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15117. { Just to be sure }
  15118. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15119. begin
  15120. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15121. { Moving the entries this way ensures the register tracking remains correct }
  15122. Asml.Remove(p);
  15123. Asml.InsertBefore(p, hp1);
  15124. p := hp1;
  15125. { Don't set Result to True because the current instruction is now
  15126. "shr %cl,%reg" and there's nothing more we can do with it }
  15127. end;
  15128. end;
  15129. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15130. var
  15131. hp1, hp2: tai;
  15132. Opposite, SecondOpposite: TAsmOp;
  15133. NewCond: TAsmCond;
  15134. begin
  15135. Result := False;
  15136. { Change:
  15137. add/sub 128,(dest)
  15138. To:
  15139. sub/add -128,(dest)
  15140. This generaally takes fewer bytes to encode because -128 can be stored
  15141. in a signed byte, whereas +128 cannot.
  15142. }
  15143. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15144. begin
  15145. if taicpu(p).opcode = A_ADD then
  15146. Opposite := A_SUB
  15147. else
  15148. Opposite := A_ADD;
  15149. { Be careful if the flags are in use, because the CF flag inverts
  15150. when changing from ADD to SUB and vice versa }
  15151. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15152. GetNextInstruction(p, hp1) then
  15153. begin
  15154. TransferUsedRegs(TmpUsedRegs);
  15155. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15156. hp2 := hp1;
  15157. { Scan ahead to check if everything's safe }
  15158. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15159. begin
  15160. if (hp1.typ <> ait_instruction) then
  15161. { Probably unsafe since the flags are still in use }
  15162. Exit;
  15163. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15164. { Stop searching at an unconditional jump }
  15165. Break;
  15166. if not
  15167. (
  15168. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15169. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15170. ) and
  15171. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15172. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15173. Exit;
  15174. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15175. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15176. { Move to the next instruction }
  15177. GetNextInstruction(hp1, hp1);
  15178. end;
  15179. while Assigned(hp2) and (hp2 <> hp1) do
  15180. begin
  15181. NewCond := C_None;
  15182. case taicpu(hp2).condition of
  15183. C_A, C_NBE:
  15184. NewCond := C_BE;
  15185. C_B, C_C, C_NAE:
  15186. NewCond := C_AE;
  15187. C_AE, C_NB, C_NC:
  15188. NewCond := C_B;
  15189. C_BE, C_NA:
  15190. NewCond := C_A;
  15191. else
  15192. { No change needed };
  15193. end;
  15194. if NewCond <> C_None then
  15195. begin
  15196. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15197. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15198. taicpu(hp2).condition := NewCond;
  15199. end
  15200. else
  15201. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15202. begin
  15203. { Because of the flipping of the carry bit, to ensure
  15204. the operation remains equivalent, ADC becomes SBB
  15205. and vice versa, and the constant is not-inverted.
  15206. If multiple ADCs or SBBs appear in a row, each one
  15207. changed causes the carry bit to invert, so they all
  15208. need to be flipped }
  15209. if taicpu(hp2).opcode = A_ADC then
  15210. SecondOpposite := A_SBB
  15211. else
  15212. SecondOpposite := A_ADC;
  15213. if taicpu(hp2).oper[0]^.typ <> top_const then
  15214. { Should have broken out of this optimisation already }
  15215. InternalError(2021112901);
  15216. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  15217. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  15218. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15219. taicpu(hp2).opcode := SecondOpposite;
  15220. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15221. end;
  15222. { Move to the next instruction }
  15223. GetNextInstruction(hp2, hp2);
  15224. end;
  15225. if (hp2 <> hp1) then
  15226. InternalError(2021111501);
  15227. end;
  15228. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15229. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15230. taicpu(p).opcode := Opposite;
  15231. taicpu(p).oper[0]^.val := -128;
  15232. { No further optimisations can be made on this instruction, so move
  15233. onto the next one to save time }
  15234. p := tai(p.Next);
  15235. UpdateUsedRegs(p);
  15236. Result := True;
  15237. Exit;
  15238. end;
  15239. { Detect:
  15240. add/sub %reg2,(dest)
  15241. add/sub x, (dest)
  15242. (dest can be a register or a reference)
  15243. Swap the instructions to minimise a pipeline stall. This reverses the
  15244. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15245. optimisations could be made.
  15246. }
  15247. if (taicpu(p).oper[0]^.typ = top_reg) and
  15248. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15249. (
  15250. (
  15251. (taicpu(p).oper[1]^.typ = top_reg) and
  15252. { We can try searching further ahead if we're writing to a register }
  15253. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15254. ) or
  15255. (
  15256. (taicpu(p).oper[1]^.typ = top_ref) and
  15257. GetNextInstruction(p, hp1)
  15258. )
  15259. ) and
  15260. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15261. (taicpu(hp1).oper[0]^.typ = top_const) and
  15262. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15263. begin
  15264. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15265. TransferUsedRegs(TmpUsedRegs);
  15266. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15267. hp2 := p;
  15268. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15269. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15270. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15271. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15272. begin
  15273. asml.remove(hp1);
  15274. asml.InsertBefore(hp1, p);
  15275. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15276. Result := True;
  15277. end;
  15278. end;
  15279. end;
  15280. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15281. var
  15282. hp1: tai;
  15283. begin
  15284. Result:=false;
  15285. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15286. while GetNextInstruction(p, hp1) and
  15287. TrySwapMovCmp(p, hp1) do
  15288. begin
  15289. if MatchInstruction(hp1, A_MOV, []) then
  15290. begin
  15291. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15292. begin
  15293. { A little hacky, but since CMP doesn't read the flags, only
  15294. modify them, it's safe if they get scrambled by MOV -> XOR }
  15295. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15296. Result := PostPeepholeOptMov(hp1);
  15297. {$ifdef x86_64}
  15298. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15299. { Used to shrink instruction size }
  15300. PostPeepholeOptXor(hp1);
  15301. {$endif x86_64}
  15302. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15303. end
  15304. else
  15305. begin
  15306. Result := PostPeepholeOptMov(hp1);
  15307. {$ifdef x86_64}
  15308. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15309. { Used to shrink instruction size }
  15310. PostPeepholeOptXor(hp1);
  15311. {$endif x86_64}
  15312. end;
  15313. end;
  15314. { Enabling this flag is actually a null operation, but it marks
  15315. the code as 'modified' during this pass }
  15316. Include(OptsToCheck, aoc_ForceNewIteration);
  15317. end;
  15318. { change "cmp $0, %reg" to "test %reg, %reg" }
  15319. if MatchOpType(taicpu(p),top_const,top_reg) and
  15320. (taicpu(p).oper[0]^.val = 0) then
  15321. begin
  15322. taicpu(p).opcode := A_TEST;
  15323. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15324. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15325. Result:=true;
  15326. end;
  15327. end;
  15328. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15329. var
  15330. IsTestConstX, IsValid : Boolean;
  15331. hp1,hp2 : tai;
  15332. begin
  15333. Result:=false;
  15334. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15335. if (taicpu(p).opcode = A_TEST) then
  15336. while GetNextInstruction(p, hp1) and
  15337. TrySwapMovCmp(p, hp1) do
  15338. begin
  15339. if MatchInstruction(hp1, A_MOV, []) then
  15340. begin
  15341. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15342. begin
  15343. { A little hacky, but since TEST doesn't read the flags, only
  15344. modify them, it's safe if they get scrambled by MOV -> XOR }
  15345. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15346. Result := PostPeepholeOptMov(hp1);
  15347. {$ifdef x86_64}
  15348. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15349. { Used to shrink instruction size }
  15350. PostPeepholeOptXor(hp1);
  15351. {$endif x86_64}
  15352. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15353. end
  15354. else
  15355. begin
  15356. Result := PostPeepholeOptMov(hp1);
  15357. {$ifdef x86_64}
  15358. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15359. { Used to shrink instruction size }
  15360. PostPeepholeOptXor(hp1);
  15361. {$endif x86_64}
  15362. end;
  15363. end;
  15364. { Enabling this flag is actually a null operation, but it marks
  15365. the code as 'modified' during this pass }
  15366. Include(OptsToCheck, aoc_ForceNewIteration);
  15367. end;
  15368. { If x is a power of 2 (popcnt = 1), change:
  15369. or $x, %reg/ref
  15370. To:
  15371. bts lb(x), %reg/ref
  15372. }
  15373. if (taicpu(p).opcode = A_OR) and
  15374. IsBTXAcceptable(p) and
  15375. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15376. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15377. (
  15378. { Don't optimise if a test instruction follows }
  15379. not GetNextInstruction(p, hp1) or
  15380. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15381. ) then
  15382. begin
  15383. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  15384. taicpu(p).opcode := A_BTS;
  15385. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15386. Result := True;
  15387. Exit;
  15388. end;
  15389. { If x is a power of 2 (popcnt = 1), change:
  15390. test $x, %reg/ref
  15391. je / sete / cmove (or jne / setne)
  15392. To:
  15393. bt lb(x), %reg/ref
  15394. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15395. }
  15396. if (taicpu(p).opcode = A_TEST) and
  15397. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15398. (taicpu(p).oper[0]^.typ = top_const) and
  15399. (
  15400. (cs_opt_size in current_settings.optimizerswitches) or
  15401. (
  15402. (taicpu(p).oper[1]^.typ = top_reg) and
  15403. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15404. ) or
  15405. (
  15406. (taicpu(p).oper[1]^.typ <> top_reg) and
  15407. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15408. )
  15409. ) and
  15410. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15411. { For sizes less than S_L, the byte size is equal or larger with BT,
  15412. so don't bother optimising }
  15413. (taicpu(p).opsize >= S_L) then
  15414. begin
  15415. IsValid := True;
  15416. { Check the next set of instructions, watching the FLAGS register
  15417. and the conditions used }
  15418. TransferUsedRegs(TmpUsedRegs);
  15419. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15420. hp1 := p;
  15421. hp2 := nil;
  15422. while GetNextInstruction(hp1, hp1) do
  15423. begin
  15424. if not Assigned(hp2) then
  15425. { The first instruction after TEST }
  15426. hp2 := hp1;
  15427. if (hp1.typ <> ait_instruction) then
  15428. begin
  15429. { If the flags are no longer in use, everything is fine }
  15430. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15431. IsValid := False;
  15432. Break;
  15433. end;
  15434. case taicpu(hp1).condition of
  15435. C_None:
  15436. begin
  15437. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15438. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15439. { Something is not quite normal, so play safe and don't change }
  15440. IsValid := False;
  15441. Break;
  15442. end;
  15443. C_E, C_Z, C_NE, C_NZ:
  15444. { This is fine };
  15445. else
  15446. begin
  15447. { Unsupported condition }
  15448. IsValid := False;
  15449. Break;
  15450. end;
  15451. end;
  15452. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15453. end;
  15454. if IsValid then
  15455. begin
  15456. while hp2 <> hp1 do
  15457. begin
  15458. case taicpu(hp2).condition of
  15459. C_Z, C_E:
  15460. taicpu(hp2).condition := C_NC;
  15461. C_NZ, C_NE:
  15462. taicpu(hp2).condition := C_C;
  15463. else
  15464. { Should not get this by this point }
  15465. InternalError(2022110701);
  15466. end;
  15467. GetNextInstruction(hp2, hp2);
  15468. end;
  15469. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  15470. taicpu(p).opcode := A_BT;
  15471. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15472. Result := True;
  15473. Exit;
  15474. end;
  15475. end;
  15476. { removes the line marked with (x) from the sequence
  15477. and/or/xor/add/sub/... $x, %y
  15478. test/or %y, %y | test $-1, %y (x)
  15479. j(n)z _Label
  15480. as the first instruction already adjusts the ZF
  15481. %y operand may also be a reference }
  15482. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15483. MatchOperand(taicpu(p).oper[0]^,-1);
  15484. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15485. GetLastInstruction(p, hp1) and
  15486. (tai(hp1).typ = ait_instruction) and
  15487. GetNextInstruction(p,hp2) and
  15488. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15489. case taicpu(hp1).opcode Of
  15490. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15491. { These two instructions set the zero flag if the result is zero }
  15492. A_POPCNT, A_LZCNT:
  15493. begin
  15494. if (
  15495. { With POPCNT, an input of zero will set the zero flag
  15496. because the population count of zero is zero }
  15497. (taicpu(hp1).opcode = A_POPCNT) and
  15498. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15499. (
  15500. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15501. { Faster than going through the second half of the 'or'
  15502. condition below }
  15503. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15504. )
  15505. ) or (
  15506. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15507. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15508. { and in case of carry for A(E)/B(E)/C/NC }
  15509. (
  15510. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15511. (
  15512. (taicpu(hp1).opcode <> A_ADD) and
  15513. (taicpu(hp1).opcode <> A_SUB) and
  15514. (taicpu(hp1).opcode <> A_LZCNT)
  15515. )
  15516. )
  15517. ) then
  15518. begin
  15519. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15520. RemoveCurrentP(p, hp2);
  15521. Result:=true;
  15522. Exit;
  15523. end;
  15524. end;
  15525. A_SHL, A_SAL, A_SHR, A_SAR:
  15526. begin
  15527. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15528. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15529. { therefore, it's only safe to do this optimization for }
  15530. { shifts by a (nonzero) constant }
  15531. (taicpu(hp1).oper[0]^.typ = top_const) and
  15532. (taicpu(hp1).oper[0]^.val <> 0) and
  15533. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15534. { and in case of carry for A(E)/B(E)/C/NC }
  15535. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15536. begin
  15537. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15538. RemoveCurrentP(p, hp2);
  15539. Result:=true;
  15540. Exit;
  15541. end;
  15542. end;
  15543. A_DEC, A_INC, A_NEG:
  15544. begin
  15545. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15546. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15547. { and in case of carry for A(E)/B(E)/C/NC }
  15548. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15549. begin
  15550. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15551. RemoveCurrentP(p, hp2);
  15552. Result:=true;
  15553. Exit;
  15554. end;
  15555. end;
  15556. A_ANDN, A_BZHI:
  15557. begin
  15558. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15559. { Only the zero and sign flags are consistent with what the result is }
  15560. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15561. begin
  15562. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15563. RemoveCurrentP(p, hp2);
  15564. Result:=true;
  15565. Exit;
  15566. end;
  15567. end;
  15568. A_BEXTR:
  15569. begin
  15570. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15571. { Only the zero flag is set }
  15572. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15573. begin
  15574. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15575. RemoveCurrentP(p, hp2);
  15576. Result:=true;
  15577. Exit;
  15578. end;
  15579. end;
  15580. else
  15581. ;
  15582. end; { case }
  15583. { change "test $-1,%reg" into "test %reg,%reg" }
  15584. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15585. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15586. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15587. if MatchInstruction(p, A_OR, []) and
  15588. { Can only match if they're both registers }
  15589. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15590. begin
  15591. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15592. taicpu(p).opcode := A_TEST;
  15593. { No need to set Result to True, as we've done all the optimisations we can }
  15594. end;
  15595. end;
  15596. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15597. var
  15598. hp1,hp3 : tai;
  15599. {$ifndef x86_64}
  15600. hp2 : taicpu;
  15601. {$endif x86_64}
  15602. begin
  15603. Result:=false;
  15604. hp3:=nil;
  15605. {$ifndef x86_64}
  15606. { don't do this on modern CPUs, this really hurts them due to
  15607. broken call/ret pairing }
  15608. if (current_settings.optimizecputype < cpu_Pentium2) and
  15609. not(cs_create_pic in current_settings.moduleswitches) and
  15610. GetNextInstruction(p, hp1) and
  15611. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15612. MatchOpType(taicpu(hp1),top_ref) and
  15613. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15614. begin
  15615. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15616. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15617. InsertLLItem(p.previous, p, hp2);
  15618. taicpu(p).opcode := A_JMP;
  15619. taicpu(p).is_jmp := true;
  15620. RemoveInstruction(hp1);
  15621. Result:=true;
  15622. end
  15623. else
  15624. {$endif x86_64}
  15625. { replace
  15626. call procname
  15627. ret
  15628. by
  15629. jmp procname
  15630. but do it only on level 4 because it destroys stack back traces
  15631. else if the subroutine is marked as no return, remove the ret
  15632. }
  15633. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15634. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15635. GetNextInstruction(p, hp1) and
  15636. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15637. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15638. SetAndTest(hp1,hp3) and
  15639. GetNextInstruction(hp1,hp1) and
  15640. MatchInstruction(hp1,A_RET,[S_NO])
  15641. )
  15642. ) and
  15643. (taicpu(hp1).ops=0) then
  15644. begin
  15645. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15646. { we might destroy stack alignment here if we do not do a call }
  15647. (target_info.stackalign<=sizeof(SizeUInt)) then
  15648. begin
  15649. taicpu(p).opcode := A_JMP;
  15650. taicpu(p).is_jmp := true;
  15651. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15652. end
  15653. else
  15654. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15655. RemoveInstruction(hp1);
  15656. if Assigned(hp3) then
  15657. begin
  15658. AsmL.Remove(hp3);
  15659. AsmL.InsertBefore(hp3,p)
  15660. end;
  15661. Result:=true;
  15662. end;
  15663. end;
  15664. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15665. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15666. begin
  15667. case OpSize of
  15668. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15669. Result := (Val <= $FF) and (Val >= -128);
  15670. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15671. Result := (Val <= $FFFF) and (Val >= -32768);
  15672. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15673. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15674. else
  15675. Result := True;
  15676. end;
  15677. end;
  15678. var
  15679. hp1, hp2 : tai;
  15680. SizeChange: Boolean;
  15681. PreMessage: string;
  15682. begin
  15683. Result := False;
  15684. if (taicpu(p).oper[0]^.typ = top_reg) and
  15685. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15686. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15687. begin
  15688. { Change (using movzbl %al,%eax as an example):
  15689. movzbl %al, %eax movzbl %al, %eax
  15690. cmpl x, %eax testl %eax,%eax
  15691. To:
  15692. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15693. movzbl %al, %eax movzbl %al, %eax
  15694. Smaller instruction and minimises pipeline stall as the CPU
  15695. doesn't have to wait for the register to get zero-extended. [Kit]
  15696. Also allow if the smaller of the two registers is being checked,
  15697. as this still removes the false dependency.
  15698. }
  15699. if
  15700. (
  15701. (
  15702. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15703. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15704. ) or (
  15705. { If MatchOperand returns True, they must both be registers }
  15706. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15707. )
  15708. ) and
  15709. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15710. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15711. begin
  15712. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  15713. asml.Remove(hp1);
  15714. asml.InsertBefore(hp1, p);
  15715. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15716. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15717. begin
  15718. taicpu(hp1).opcode := A_TEST;
  15719. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15720. end;
  15721. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15722. case taicpu(p).opsize of
  15723. S_BW, S_BL:
  15724. begin
  15725. SizeChange := taicpu(hp1).opsize <> S_B;
  15726. taicpu(hp1).changeopsize(S_B);
  15727. end;
  15728. S_WL:
  15729. begin
  15730. SizeChange := taicpu(hp1).opsize <> S_W;
  15731. taicpu(hp1).changeopsize(S_W);
  15732. end
  15733. else
  15734. InternalError(2020112701);
  15735. end;
  15736. UpdateUsedRegs(tai(p.Next));
  15737. { Check if the register is used aferwards - if not, we can
  15738. remove the movzx instruction completely }
  15739. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15740. begin
  15741. { Hp1 is a better position than p for debugging purposes }
  15742. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15743. RemoveCurrentp(p, hp1);
  15744. Result := True;
  15745. end;
  15746. if SizeChange then
  15747. DebugMsg(SPeepholeOptimization + PreMessage +
  15748. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  15749. else
  15750. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15751. Exit;
  15752. end;
  15753. { Change (using movzwl %ax,%eax as an example):
  15754. movzwl %ax, %eax
  15755. movb %al, (dest) (Register is smaller than read register in movz)
  15756. To:
  15757. movb %al, (dest) (Move one back to avoid a false dependency)
  15758. movzwl %ax, %eax
  15759. }
  15760. if (taicpu(hp1).opcode = A_MOV) and
  15761. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15762. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15763. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15764. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15765. begin
  15766. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15767. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15768. asml.Remove(hp1);
  15769. asml.InsertBefore(hp1, p);
  15770. if taicpu(hp1).oper[1]^.typ = top_reg then
  15771. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15772. { Check if the register is used aferwards - if not, we can
  15773. remove the movzx instruction completely }
  15774. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15775. begin
  15776. { Hp1 is a better position than p for debugging purposes }
  15777. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15778. RemoveCurrentp(p, hp1);
  15779. Result := True;
  15780. end;
  15781. Exit;
  15782. end;
  15783. end;
  15784. end;
  15785. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15786. var
  15787. hp1: tai;
  15788. {$ifdef x86_64}
  15789. PreMessage, RegName: string;
  15790. {$endif x86_64}
  15791. begin
  15792. Result := False;
  15793. { If x is a power of 2 (popcnt = 1), change:
  15794. xor $x, %reg/ref
  15795. To:
  15796. btc lb(x), %reg/ref
  15797. }
  15798. if IsBTXAcceptable(p) and
  15799. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15800. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15801. (
  15802. { Don't optimise if a test instruction follows }
  15803. not GetNextInstruction(p, hp1) or
  15804. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15805. ) then
  15806. begin
  15807. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  15808. taicpu(p).opcode := A_BTC;
  15809. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15810. Result := True;
  15811. Exit;
  15812. end;
  15813. {$ifdef x86_64}
  15814. { Code size reduction by J. Gareth "Kit" Moreton }
  15815. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15816. as this removes the REX prefix }
  15817. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15818. Exit;
  15819. if taicpu(p).oper[0]^.typ <> top_reg then
  15820. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15821. InternalError(2018011500);
  15822. case taicpu(p).opsize of
  15823. S_Q:
  15824. begin
  15825. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15826. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15827. { The actual optimization }
  15828. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15829. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15830. taicpu(p).changeopsize(S_L);
  15831. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15832. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15833. end;
  15834. else
  15835. ;
  15836. end;
  15837. {$endif x86_64}
  15838. end;
  15839. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15840. var
  15841. XReg: TRegister;
  15842. begin
  15843. Result := False;
  15844. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15845. Smaller encoding and slightly faster on some platforms (also works for
  15846. ZMM-sized registers) }
  15847. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15848. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15849. begin
  15850. XReg := taicpu(p).oper[0]^.reg;
  15851. if (taicpu(p).oper[1]^.reg = XReg) then
  15852. begin
  15853. taicpu(p).changeopsize(S_XMM);
  15854. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15855. if (cs_opt_size in current_settings.optimizerswitches) then
  15856. begin
  15857. { Change input registers to %xmm0 to reduce size. Note that
  15858. there's a risk of a false dependency doing this, so only
  15859. optimise for size here }
  15860. XReg := NR_XMM0;
  15861. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15862. end
  15863. else
  15864. begin
  15865. setsubreg(XReg, R_SUBMMX);
  15866. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15867. end;
  15868. taicpu(p).oper[0]^.reg := XReg;
  15869. taicpu(p).oper[1]^.reg := XReg;
  15870. Result := True;
  15871. end;
  15872. end;
  15873. end;
  15874. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15875. var
  15876. hp1, p_new: tai;
  15877. begin
  15878. Result := False;
  15879. { Check for:
  15880. ret
  15881. .Lbl:
  15882. ret
  15883. Remove first 'ret'
  15884. }
  15885. if GetNextInstruction(p, hp1) and
  15886. { Remember where the label is }
  15887. SetAndTest(hp1, p_new) and
  15888. (hp1.typ in [ait_align, ait_label]) and
  15889. SkipLabels(hp1, hp1) and
  15890. MatchInstruction(hp1, A_RET, []) and
  15891. { To be safe, make sure the RET instructions are identical }
  15892. (taicpu(p).ops = taicpu(hp1).ops) and
  15893. (
  15894. (taicpu(p).ops = 0) or
  15895. (
  15896. (taicpu(p).ops = 1) and
  15897. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15898. )
  15899. ) then
  15900. begin
  15901. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15902. UpdateUsedRegs(tai(p.Next));
  15903. RemoveCurrentP(p, p_new);
  15904. Result := True;
  15905. Exit;
  15906. end;
  15907. end;
  15908. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15909. var
  15910. OperIdx: Integer;
  15911. begin
  15912. for OperIdx := 0 to p.ops - 1 do
  15913. if p.oper[OperIdx]^.typ = top_ref then
  15914. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15915. end;
  15916. end.