aoptx86.pas 710 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773
  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. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  76. { Attempts to allocate a volatile integer register for use between p and hp,
  77. using AUsedRegs for the current register usage information. Returns NR_NO
  78. if no free register could be found }
  79. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  80. { Attempts to allocate a volatile MM register for use between p and hp,
  81. using AUsedRegs for the current register usage information. Returns NR_NO
  82. if no free register could be found }
  83. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  84. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  85. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  86. { checks whether reading the value in reg1 depends on the value of reg2. This
  87. is very similar to SuperRegisterEquals, except it takes into account that
  88. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  89. depend on the value in AH). }
  90. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  91. { Replaces all references to AOldReg in a memory reference to ANewReg }
  92. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Replaces all references to AOldReg in an operand to ANewReg }
  94. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  95. { Replaces all references to AOldReg in an instruction to ANewReg,
  96. except where the register is being written }
  97. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  99. or writes to a global symbol }
  100. class function IsRefSafe(const ref: PReference): Boolean; static;
  101. { Returns true if the given MOV instruction can be safely converted to CMOV }
  102. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  103. { Like UpdateUsedRegs, but ignores deallocations }
  104. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  105. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  106. class function IsBTXAcceptable(p : tai) : boolean; static;
  107. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  108. conversion was successful }
  109. function ConvertLEA(const p : taicpu): Boolean;
  110. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  111. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  112. procedure DebugMsg(const s : string; p : tai);inline;
  113. class function IsExitCode(p : tai) : boolean; static;
  114. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  115. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  116. procedure RemoveLastDeallocForFuncRes(p : tai);
  117. function DoArithCombineOpt(var p : tai) : Boolean;
  118. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  119. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  120. function PrePeepholeOptSxx(var p : tai) : boolean;
  121. function PrePeepholeOptIMUL(var p : tai) : boolean;
  122. function PrePeepholeOptAND(var p : tai) : boolean;
  123. function OptPass1Test(var p: tai): boolean;
  124. function OptPass1Add(var p: tai): boolean;
  125. function OptPass1AND(var p : tai) : boolean;
  126. function OptPass1_V_MOVAP(var p : tai) : boolean;
  127. function OptPass1VOP(var p : tai) : boolean;
  128. function OptPass1MOV(var p : tai) : boolean;
  129. function OptPass1Movx(var p : tai) : boolean;
  130. function OptPass1MOVXX(var p : tai) : boolean;
  131. function OptPass1OP(var p : tai) : boolean;
  132. function OptPass1LEA(var p : tai) : boolean;
  133. function OptPass1Sub(var p : tai) : boolean;
  134. function OptPass1SHLSAL(var p : tai) : boolean;
  135. function OptPass1SHR(var p : tai) : boolean;
  136. function OptPass1FSTP(var p : tai) : boolean;
  137. function OptPass1FLD(var p : tai) : boolean;
  138. function OptPass1Cmp(var p : tai) : boolean;
  139. function OptPass1PXor(var p : tai) : boolean;
  140. function OptPass1VPXor(var p: tai): boolean;
  141. function OptPass1Imul(var p : tai) : boolean;
  142. function OptPass1Jcc(var p : tai) : boolean;
  143. function OptPass1SHXX(var p: tai): boolean;
  144. function OptPass1VMOVDQ(var p: tai): Boolean;
  145. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  146. function OptPass1STCCLC(var p: tai): Boolean;
  147. function OptPass2Movx(var p : tai): Boolean;
  148. function OptPass2MOV(var p : tai) : boolean;
  149. function OptPass2Imul(var p : tai) : boolean;
  150. function OptPass2Jmp(var p : tai) : boolean;
  151. function OptPass2Jcc(var p : tai) : boolean;
  152. function OptPass2Lea(var p: tai): Boolean;
  153. function OptPass2SUB(var p: tai): Boolean;
  154. function OptPass2ADD(var p : tai): Boolean;
  155. function OptPass2SETcc(var p : tai) : boolean;
  156. function OptPass2Cmp(var p: tai): Boolean;
  157. function OptPass2Test(var p: tai): Boolean;
  158. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  159. function PostPeepholeOptMov(var p : tai) : Boolean;
  160. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  161. function PostPeepholeOptXor(var p : tai) : Boolean;
  162. function PostPeepholeOptAnd(var p : tai) : boolean;
  163. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  164. function PostPeepholeOptCmp(var p : tai) : Boolean;
  165. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  166. function PostPeepholeOptCall(var p : tai) : Boolean;
  167. function PostPeepholeOptLea(var p : tai) : Boolean;
  168. function PostPeepholeOptPush(var p: tai): Boolean;
  169. function PostPeepholeOptShr(var p : tai) : boolean;
  170. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  171. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  172. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  173. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  174. function TrySwapMovOp(var p, hp1: tai): Boolean;
  175. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  176. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  177. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  178. { Processor-dependent reference optimisation }
  179. class procedure OptimizeRefs(var p: taicpu); static;
  180. end;
  181. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  182. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  183. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  184. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  185. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  186. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  187. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  188. {$if max_operands>2}
  189. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  190. {$endif max_operands>2}
  191. function RefsEqual(const r1, r2: treference): boolean;
  192. { Note that Result is set to True if the references COULD overlap but the
  193. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  194. might still overlap because %reg2 could be equal to %reg1-4 }
  195. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  196. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  197. { returns true, if ref is a reference using only the registers passed as base and index
  198. and having an offset }
  199. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  200. implementation
  201. uses
  202. cutils,verbose,
  203. systems,
  204. globals,
  205. cpuinfo,
  206. procinfo,
  207. paramgr,
  208. aasmbase,
  209. aoptbase,aoptutils,
  210. symconst,symsym,
  211. cgx86,
  212. itcpugas;
  213. {$ifndef 8086}
  214. const
  215. MAX_CMOV_INSTRUCTIONS = 4;
  216. MAX_CMOV_REGISTERS = 8;
  217. type
  218. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  219. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  220. tsProcessed);
  221. { For OptPass2Jcc }
  222. TCMOVTracking = object
  223. private
  224. CMOVScore, ConstCount: LongInt;
  225. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  226. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  227. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  228. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  229. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  230. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  231. fOptimizer: TX86AsmOptimizer;
  232. fLabel: TAsmSymbol;
  233. fInsertionPoint,
  234. fCondition,
  235. fInitialJump,
  236. fFirstMovBlock,
  237. fFirstMovBlockStop,
  238. fSecondJump,
  239. fThirdJump,
  240. fSecondMovBlock,
  241. fSecondMovBlockStop,
  242. fMidLabel,
  243. fEndLabel,
  244. fAllocationRange: tai;
  245. fState: TCMovTrackingState;
  246. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  247. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  248. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  249. public
  250. RegisterTracking: TAllUsedRegs;
  251. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  252. destructor Done;
  253. procedure Process(out new_p: tai);
  254. property State: TCMovTrackingState read fState;
  255. end;
  256. PCMOVTracking = ^TCMOVTracking;
  257. {$endif 8086}
  258. {$ifdef DEBUG_AOPTCPU}
  259. const
  260. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  261. {$else DEBUG_AOPTCPU}
  262. { Empty strings help the optimizer to remove string concatenations that won't
  263. ever appear to the user on release builds. [Kit] }
  264. const
  265. SPeepholeOptimization = '';
  266. {$endif DEBUG_AOPTCPU}
  267. LIST_STEP_SIZE = 4;
  268. type
  269. TJumpTrackingItem = class(TLinkedListItem)
  270. private
  271. FSymbol: TAsmSymbol;
  272. FRefs: LongInt;
  273. public
  274. constructor Create(ASymbol: TAsmSymbol);
  275. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  276. property Symbol: TAsmSymbol read FSymbol;
  277. property Refs: LongInt read FRefs;
  278. end;
  279. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  280. begin
  281. inherited Create;
  282. FSymbol := ASymbol;
  283. FRefs := 0;
  284. end;
  285. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. begin
  287. Inc(FRefs);
  288. end;
  289. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  290. begin
  291. result :=
  292. (instr.typ = ait_instruction) and
  293. (taicpu(instr).opcode = op) and
  294. ((opsize = []) or (taicpu(instr).opsize in opsize));
  295. end;
  296. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  297. begin
  298. result :=
  299. (instr.typ = ait_instruction) and
  300. ((taicpu(instr).opcode = op1) or
  301. (taicpu(instr).opcode = op2)
  302. ) and
  303. ((opsize = []) or (taicpu(instr).opsize in opsize));
  304. end;
  305. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  306. begin
  307. result :=
  308. (instr.typ = ait_instruction) and
  309. ((taicpu(instr).opcode = op1) or
  310. (taicpu(instr).opcode = op2) or
  311. (taicpu(instr).opcode = op3)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  316. const opsize : topsizes) : boolean;
  317. var
  318. op : TAsmOp;
  319. begin
  320. result:=false;
  321. if (instr.typ <> ait_instruction) or
  322. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  323. exit;
  324. for op in ops do
  325. begin
  326. if taicpu(instr).opcode = op then
  327. begin
  328. result:=true;
  329. exit;
  330. end;
  331. end;
  332. end;
  333. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  334. begin
  335. result := (oper.typ = top_reg) and (oper.reg = reg);
  336. end;
  337. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  338. begin
  339. result := (oper.typ = top_const) and (oper.val = a);
  340. end;
  341. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  342. begin
  343. result := oper1.typ = oper2.typ;
  344. if result then
  345. case oper1.typ of
  346. top_const:
  347. Result:=oper1.val = oper2.val;
  348. top_reg:
  349. Result:=oper1.reg = oper2.reg;
  350. top_ref:
  351. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  352. else
  353. internalerror(2013102801);
  354. end
  355. end;
  356. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  357. begin
  358. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  359. if result then
  360. case oper1.typ of
  361. top_const:
  362. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  363. top_reg:
  364. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  365. top_ref:
  366. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  367. else
  368. internalerror(2020052401);
  369. end
  370. end;
  371. function RefsEqual(const r1, r2: treference): boolean;
  372. begin
  373. RefsEqual :=
  374. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  375. (r1.relsymbol = r2.relsymbol) and
  376. (r1.segment = r2.segment) and (r1.base = r2.base) and
  377. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  378. (r1.offset = r2.offset) and
  379. (r1.volatility + r2.volatility = []);
  380. end;
  381. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  382. begin
  383. if (r1.symbol<>r2.symbol) then
  384. { If the index registers are different, there's a chance one could
  385. be set so it equals the other symbol }
  386. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  387. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  388. (r1.relsymbol = r2.relsymbol) and
  389. (r1.segment = r2.segment) and (r1.base = r2.base) and
  390. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  391. (r1.volatility + r2.volatility = []) then
  392. { In this case, it all depends on the offsets }
  393. Exit(abs(r1.offset - r2.offset) < Range);
  394. { There's a chance things MIGHT overlap, so take no chances }
  395. Result := True;
  396. end;
  397. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  398. begin
  399. Result:=(ref.offset=0) and
  400. (ref.scalefactor in [0,1]) and
  401. (ref.segment=NR_NO) and
  402. (ref.symbol=nil) and
  403. (ref.relsymbol=nil) and
  404. ((base=NR_INVALID) or
  405. (ref.base=base)) and
  406. ((index=NR_INVALID) or
  407. (ref.index=index)) and
  408. (ref.volatility=[]);
  409. end;
  410. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  411. begin
  412. Result:=(ref.scalefactor in [0,1]) and
  413. (ref.segment=NR_NO) and
  414. (ref.symbol=nil) and
  415. (ref.relsymbol=nil) and
  416. ((base=NR_INVALID) or
  417. (ref.base=base)) and
  418. ((index=NR_INVALID) or
  419. (ref.index=index)) and
  420. (ref.volatility=[]);
  421. end;
  422. function InstrReadsFlags(p: tai): boolean;
  423. begin
  424. InstrReadsFlags := true;
  425. case p.typ of
  426. ait_instruction:
  427. if InsProp[taicpu(p).opcode].Ch*
  428. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  429. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  430. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  431. exit;
  432. ait_label:
  433. exit;
  434. else
  435. ;
  436. end;
  437. InstrReadsFlags := false;
  438. end;
  439. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  440. begin
  441. Next:=Current;
  442. repeat
  443. Result:=GetNextInstruction(Next,Next);
  444. until not (Result) or
  445. not(cs_opt_level3 in current_settings.optimizerswitches) or
  446. (Next.typ<>ait_instruction) or
  447. RegInInstruction(reg,Next) or
  448. is_calljmp(taicpu(Next).opcode);
  449. end;
  450. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  451. var
  452. GetNextResult: Boolean;
  453. begin
  454. Result:=0;
  455. Next:=Current;
  456. repeat
  457. GetNextResult := GetNextInstruction(Next,Next);
  458. if GetNextResult then
  459. Inc(Result)
  460. else
  461. { Must return zero upon hitting the end of the linked list without a match }
  462. Result := 0;
  463. until not (GetNextResult) or
  464. not(cs_opt_level3 in current_settings.optimizerswitches) or
  465. (Next.typ<>ait_instruction) or
  466. RegInInstruction(reg,Next) or
  467. is_calljmp(taicpu(Next).opcode);
  468. end;
  469. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  470. procedure TrackJump(Symbol: TAsmSymbol);
  471. var
  472. Search: TJumpTrackingItem;
  473. begin
  474. { See if an entry already exists in our jump tracking list
  475. (faster to search backwards due to the higher chance of
  476. matching destinations) }
  477. Search := TJumpTrackingItem(JumpTracking.Last);
  478. while Assigned(Search) do
  479. begin
  480. if Search.Symbol = Symbol then
  481. begin
  482. { Found it - remove it so it can be pushed to the front }
  483. JumpTracking.Remove(Search);
  484. Break;
  485. end;
  486. Search := TJumpTrackingItem(Search.Previous);
  487. end;
  488. if not Assigned(Search) then
  489. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  490. JumpTracking.Concat(Search);
  491. Search.IncRefs;
  492. end;
  493. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  494. var
  495. Search: TJumpTrackingItem;
  496. begin
  497. Result := False;
  498. { See if this label appears in the tracking list }
  499. Search := TJumpTrackingItem(JumpTracking.Last);
  500. while Assigned(Search) do
  501. begin
  502. if Search.Symbol = Symbol then
  503. begin
  504. { Found it - let's see what we can discover }
  505. if Search.Symbol.getrefs = Search.Refs then
  506. begin
  507. { Success - all the references are accounted for }
  508. JumpTracking.Remove(Search);
  509. Search.Free;
  510. { It is logically impossible for CrossJump to be false here
  511. because we must have run into a conditional jump for
  512. this label at some point }
  513. if not CrossJump then
  514. InternalError(2022041710);
  515. if JumpTracking.First = nil then
  516. { Tracking list is now empty - no more cross jumps }
  517. CrossJump := False;
  518. Result := True;
  519. Exit;
  520. end;
  521. { If the references don't match, it's possible to enter
  522. this label through other means, so drop out }
  523. Exit;
  524. end;
  525. Search := TJumpTrackingItem(Search.Previous);
  526. end;
  527. end;
  528. var
  529. Next_Label: tai;
  530. begin
  531. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  532. Next := Current;
  533. repeat
  534. Result := GetNextInstruction(Next,Next);
  535. if not Result then
  536. Break;
  537. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  538. if is_calljmpuncondret(taicpu(Next).opcode) then
  539. begin
  540. if (taicpu(Next).opcode = A_JMP) and
  541. { Remove dead code now to save time }
  542. RemoveDeadCodeAfterJump(taicpu(Next)) then
  543. { A jump was removed, but not the current instruction, and
  544. Result doesn't necessarily translate into an optimisation
  545. routine's Result, so use the "Force New Iteration" flag so
  546. mark a new pass }
  547. Include(OptsToCheck, aoc_ForceNewIteration);
  548. if not Assigned(JumpTracking) then
  549. begin
  550. { Cross-label optimisations often causes other optimisations
  551. to perform worse because they're not given the chance to
  552. optimise locally. In this case, don't do the cross-label
  553. optimisations yet, but flag them as a potential possibility
  554. for the next iteration of Pass 1 }
  555. if not NotFirstIteration then
  556. Include(OptsToCheck, aoc_ForceNewIteration);
  557. end
  558. else if IsJumpToLabel(taicpu(Next)) and
  559. GetNextInstruction(Next, Next_Label) then
  560. begin
  561. { If we have JMP .lbl, and the label after it has all of its
  562. references tracked, then this is probably an if-else style of
  563. block and we can keep tracking. If the label for this jump
  564. then appears later and is fully tracked, then it's the end
  565. of the if-else blocks and the code paths converge (thus
  566. marking the end of the cross-jump) }
  567. if (Next_Label.typ = ait_label) then
  568. begin
  569. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  570. begin
  571. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  572. Next := Next_Label;
  573. { CrossJump gets set to false by LabelAccountedFor if the
  574. list is completely emptied (as it indicates that all
  575. code paths have converged). We could avoid this nuance
  576. by moving the TrackJump call to before the
  577. LabelAccountedFor call, but this is slower in situations
  578. where LabelAccountedFor would return False due to the
  579. creation of a new object that is not used and destroyed
  580. soon after. }
  581. CrossJump := True;
  582. Continue;
  583. end;
  584. end
  585. else if (Next_Label.typ <> ait_marker) then
  586. { We just did a RemoveDeadCodeAfterJump, so either we find
  587. a label, the end of the procedure or some kind of marker}
  588. InternalError(2022041720);
  589. end;
  590. Result := False;
  591. Exit;
  592. end
  593. else
  594. begin
  595. if not Assigned(JumpTracking) then
  596. begin
  597. { Cross-label optimisations often causes other optimisations
  598. to perform worse because they're not given the chance to
  599. optimise locally. In this case, don't do the cross-label
  600. optimisations yet, but flag them as a potential possibility
  601. for the next iteration of Pass 1 }
  602. if not NotFirstIteration then
  603. Include(OptsToCheck, aoc_ForceNewIteration);
  604. end
  605. else if IsJumpToLabel(taicpu(Next)) then
  606. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  607. else
  608. { Conditional jumps should always be a jump to label }
  609. InternalError(2022041701);
  610. CrossJump := True;
  611. Continue;
  612. end;
  613. if Next.typ = ait_label then
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if LabelAccountedFor(tai_label(Next).labsym) then
  626. Continue;
  627. { If we reach here, we're at a label that hasn't been seen before
  628. (or JumpTracking was nil) }
  629. Break;
  630. end;
  631. until not Result or
  632. not (cs_opt_level3 in current_settings.optimizerswitches) or
  633. not (Next.typ in [ait_label, ait_instruction]) or
  634. RegInInstruction(reg,Next);
  635. end;
  636. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  637. begin
  638. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  639. begin
  640. Result:=GetNextInstruction(Current,Next);
  641. exit;
  642. end;
  643. Next:=tai(Current.Next);
  644. Result:=false;
  645. while assigned(Next) do
  646. begin
  647. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  648. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  649. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  650. exit
  651. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  652. begin
  653. Result:=true;
  654. exit;
  655. end;
  656. Next:=tai(Next.Next);
  657. end;
  658. end;
  659. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  660. begin
  661. Result:=RegReadByInstruction(reg,hp);
  662. end;
  663. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  664. var
  665. p: taicpu;
  666. opcount: longint;
  667. begin
  668. RegReadByInstruction := false;
  669. if hp.typ <> ait_instruction then
  670. exit;
  671. p := taicpu(hp);
  672. case p.opcode of
  673. A_CALL:
  674. regreadbyinstruction := true;
  675. A_IMUL:
  676. case p.ops of
  677. 1:
  678. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  679. (
  680. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  681. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  682. );
  683. 2,3:
  684. regReadByInstruction :=
  685. reginop(reg,p.oper[0]^) or
  686. reginop(reg,p.oper[1]^);
  687. else
  688. InternalError(2019112801);
  689. end;
  690. A_MUL:
  691. begin
  692. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  693. (
  694. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  695. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  696. );
  697. end;
  698. A_IDIV,A_DIV:
  699. begin
  700. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  701. (
  702. (getregtype(reg)=R_INTREGISTER) and
  703. (
  704. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  705. )
  706. );
  707. end;
  708. else
  709. begin
  710. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  711. begin
  712. RegReadByInstruction := false;
  713. exit;
  714. end;
  715. for opcount := 0 to p.ops-1 do
  716. if (p.oper[opCount]^.typ = top_ref) and
  717. RegInRef(reg,p.oper[opcount]^.ref^) then
  718. begin
  719. RegReadByInstruction := true;
  720. exit
  721. end;
  722. { special handling for SSE MOVSD }
  723. if (p.opcode=A_MOVSD) and (p.ops>0) then
  724. begin
  725. if p.ops<>2 then
  726. internalerror(2017042702);
  727. regReadByInstruction := reginop(reg,p.oper[0]^) or
  728. (
  729. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  730. );
  731. exit;
  732. end;
  733. with insprop[p.opcode] do
  734. begin
  735. case getregtype(reg) of
  736. R_INTREGISTER:
  737. begin
  738. case getsupreg(reg) of
  739. RS_EAX:
  740. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  741. begin
  742. RegReadByInstruction := true;
  743. exit
  744. end;
  745. RS_ECX:
  746. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  747. begin
  748. RegReadByInstruction := true;
  749. exit
  750. end;
  751. RS_EDX:
  752. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  753. begin
  754. RegReadByInstruction := true;
  755. exit
  756. end;
  757. RS_EBX:
  758. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  759. begin
  760. RegReadByInstruction := true;
  761. exit
  762. end;
  763. RS_ESP:
  764. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  765. begin
  766. RegReadByInstruction := true;
  767. exit
  768. end;
  769. RS_EBP:
  770. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  771. begin
  772. RegReadByInstruction := true;
  773. exit
  774. end;
  775. RS_ESI:
  776. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  777. begin
  778. RegReadByInstruction := true;
  779. exit
  780. end;
  781. RS_EDI:
  782. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  783. begin
  784. RegReadByInstruction := true;
  785. exit
  786. end;
  787. end;
  788. end;
  789. R_MMREGISTER:
  790. begin
  791. case getsupreg(reg) of
  792. RS_XMM0:
  793. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  794. begin
  795. RegReadByInstruction := true;
  796. exit
  797. end;
  798. end;
  799. end;
  800. else
  801. ;
  802. end;
  803. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  804. begin
  805. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  806. begin
  807. case p.condition of
  808. C_A,C_NBE, { CF=0 and ZF=0 }
  809. C_BE,C_NA: { CF=1 or ZF=1 }
  810. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  811. C_AE,C_NB,C_NC, { CF=0 }
  812. C_B,C_NAE,C_C: { CF=1 }
  813. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  814. C_NE,C_NZ, { ZF=0 }
  815. C_E,C_Z: { ZF=1 }
  816. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  817. C_G,C_NLE, { ZF=0 and SF=OF }
  818. C_LE,C_NG: { ZF=1 or SF<>OF }
  819. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  820. C_GE,C_NL, { SF=OF }
  821. C_L,C_NGE: { SF<>OF }
  822. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  823. C_NO, { OF=0 }
  824. C_O: { OF=1 }
  825. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  826. C_NP,C_PO, { PF=0 }
  827. C_P,C_PE: { PF=1 }
  828. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  829. C_NS, { SF=0 }
  830. C_S: { SF=1 }
  831. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  832. else
  833. internalerror(2017042701);
  834. end;
  835. if RegReadByInstruction then
  836. exit;
  837. end;
  838. case getsubreg(reg) of
  839. R_SUBW,R_SUBD,R_SUBQ:
  840. RegReadByInstruction :=
  841. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  842. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  843. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  844. R_SUBFLAGCARRY:
  845. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  846. R_SUBFLAGPARITY:
  847. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  848. R_SUBFLAGAUXILIARY:
  849. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGZERO:
  851. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGSIGN:
  853. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGOVERFLOW:
  855. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGINTERRUPT:
  857. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGDIRECTION:
  859. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. else
  861. internalerror(2017042601);
  862. end;
  863. exit;
  864. end;
  865. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  866. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  867. (p.oper[0]^.reg=p.oper[1]^.reg) then
  868. exit;
  869. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  870. begin
  871. RegReadByInstruction := true;
  872. exit
  873. end;
  874. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  875. begin
  876. RegReadByInstruction := true;
  877. exit
  878. end;
  879. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  880. begin
  881. RegReadByInstruction := true;
  882. exit
  883. end;
  884. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  885. begin
  886. RegReadByInstruction := true;
  887. exit
  888. end;
  889. end;
  890. end;
  891. end;
  892. end;
  893. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  894. begin
  895. result:=false;
  896. if p1.typ<>ait_instruction then
  897. exit;
  898. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  899. exit(true);
  900. if (getregtype(reg)=R_INTREGISTER) and
  901. { change information for xmm movsd are not correct }
  902. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  903. begin
  904. { Handle instructions that behave differently depending on the size and operand count }
  905. case taicpu(p1).opcode of
  906. A_MUL, A_DIV, A_IDIV:
  907. if taicpu(p1).opsize = S_B then
  908. Result := (getsupreg(Reg) = RS_EAX)
  909. else
  910. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  911. A_IMUL:
  912. if taicpu(p1).ops = 1 then
  913. begin
  914. if taicpu(p1).opsize = S_B then
  915. Result := (getsupreg(Reg) = RS_EAX)
  916. else
  917. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  918. end;
  919. { If ops are greater than 1, call inherited method }
  920. else
  921. case getsupreg(reg) of
  922. { RS_EAX = RS_RAX on x86-64 }
  923. RS_EAX:
  924. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  925. RS_ECX:
  926. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. RS_EDX:
  928. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_EBX:
  930. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_ESP:
  932. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_EBP:
  934. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_ESI:
  936. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_EDI:
  938. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. else
  940. ;
  941. end;
  942. end;
  943. if result then
  944. exit;
  945. end
  946. else if getregtype(reg)=R_MMREGISTER then
  947. begin
  948. case getsupreg(reg) of
  949. RS_XMM0:
  950. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. else
  952. ;
  953. end;
  954. if result then
  955. exit;
  956. end
  957. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  958. begin
  959. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  960. exit(true);
  961. case getsubreg(reg) of
  962. R_SUBFLAGCARRY:
  963. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  964. R_SUBFLAGPARITY:
  965. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. R_SUBFLAGAUXILIARY:
  967. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGZERO:
  969. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGSIGN:
  971. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGOVERFLOW:
  973. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGINTERRUPT:
  975. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGDIRECTION:
  977. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBW,R_SUBD,R_SUBQ:
  979. { Everything except the direction bits }
  980. Result:=
  981. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  982. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  983. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  984. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  985. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  986. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  987. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. else
  989. ;
  990. end;
  991. if result then
  992. exit;
  993. end
  994. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  995. exit(true);
  996. Result:=inherited RegInInstruction(Reg, p1);
  997. end;
  998. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  999. const
  1000. WriteOps: array[0..3] of set of TInsChange =
  1001. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1002. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1003. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1004. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1005. var
  1006. OperIdx: Integer;
  1007. begin
  1008. Result := False;
  1009. if p1.typ <> ait_instruction then
  1010. exit;
  1011. with insprop[taicpu(p1).opcode] do
  1012. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1013. begin
  1014. case getsubreg(reg) of
  1015. R_SUBW,R_SUBD,R_SUBQ:
  1016. Result :=
  1017. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1018. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1019. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1020. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1021. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1022. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1023. R_SUBFLAGCARRY:
  1024. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1025. R_SUBFLAGPARITY:
  1026. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGAUXILIARY:
  1028. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGZERO:
  1030. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGSIGN:
  1032. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGOVERFLOW:
  1034. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGINTERRUPT:
  1036. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGDIRECTION:
  1038. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. else
  1040. internalerror(2017042602);
  1041. end;
  1042. exit;
  1043. end;
  1044. case taicpu(p1).opcode of
  1045. A_CALL:
  1046. { We could potentially set Result to False if the register in
  1047. question is non-volatile for the subroutine's calling convention,
  1048. but this would require detecting the calling convention in use and
  1049. also assuming that the routine doesn't contain malformed assembly
  1050. language, for example... so it could only be done under -O4 as it
  1051. would be considered a side-effect. [Kit] }
  1052. Result := True;
  1053. A_MOVSD:
  1054. { special handling for SSE MOVSD }
  1055. if (taicpu(p1).ops>0) then
  1056. begin
  1057. if taicpu(p1).ops<>2 then
  1058. internalerror(2017042703);
  1059. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1060. end;
  1061. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1062. so fix it here (FK)
  1063. }
  1064. A_VMOVSS,
  1065. A_VMOVSD:
  1066. begin
  1067. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1068. exit;
  1069. end;
  1070. A_MUL, A_DIV, A_IDIV:
  1071. begin
  1072. if taicpu(p1).opsize = S_B then
  1073. Result := (getsupreg(Reg) = RS_EAX)
  1074. else
  1075. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1076. end;
  1077. A_IMUL:
  1078. begin
  1079. if taicpu(p1).ops = 1 then
  1080. begin
  1081. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1082. end
  1083. else
  1084. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1085. Exit;
  1086. end;
  1087. else
  1088. ;
  1089. end;
  1090. if Result then
  1091. exit;
  1092. with insprop[taicpu(p1).opcode] do
  1093. begin
  1094. if getregtype(reg)=R_INTREGISTER then
  1095. begin
  1096. case getsupreg(reg) of
  1097. RS_EAX:
  1098. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1099. begin
  1100. Result := True;
  1101. exit
  1102. end;
  1103. RS_ECX:
  1104. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1105. begin
  1106. Result := True;
  1107. exit
  1108. end;
  1109. RS_EDX:
  1110. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1111. begin
  1112. Result := True;
  1113. exit
  1114. end;
  1115. RS_EBX:
  1116. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1117. begin
  1118. Result := True;
  1119. exit
  1120. end;
  1121. RS_ESP:
  1122. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1123. begin
  1124. Result := True;
  1125. exit
  1126. end;
  1127. RS_EBP:
  1128. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1129. begin
  1130. Result := True;
  1131. exit
  1132. end;
  1133. RS_ESI:
  1134. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1135. begin
  1136. Result := True;
  1137. exit
  1138. end;
  1139. RS_EDI:
  1140. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1141. begin
  1142. Result := True;
  1143. exit
  1144. end;
  1145. end;
  1146. end;
  1147. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1148. if (WriteOps[OperIdx]*Ch<>[]) and
  1149. { The register doesn't get modified inside a reference }
  1150. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1151. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1152. begin
  1153. Result := true;
  1154. exit
  1155. end;
  1156. end;
  1157. end;
  1158. {$ifdef DEBUG_AOPTCPU}
  1159. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1160. begin
  1161. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1162. end;
  1163. function debug_tostr(i: tcgint): string; inline;
  1164. begin
  1165. Result := tostr(i);
  1166. end;
  1167. function debug_hexstr(i: tcgint): string;
  1168. begin
  1169. Result := '0x';
  1170. case i of
  1171. 0..$FF:
  1172. Result := Result + hexstr(i, 2);
  1173. $100..$FFFF:
  1174. Result := Result + hexstr(i, 4);
  1175. $10000..$FFFFFF:
  1176. Result := Result + hexstr(i, 6);
  1177. $1000000..$FFFFFFFF:
  1178. Result := Result + hexstr(i, 8);
  1179. else
  1180. Result := Result + hexstr(i, 16);
  1181. end;
  1182. end;
  1183. function debug_regname(r: TRegister): string; inline;
  1184. begin
  1185. Result := '%' + std_regname(r);
  1186. end;
  1187. { Debug output function - creates a string representation of an operator }
  1188. function debug_operstr(oper: TOper): string;
  1189. begin
  1190. case oper.typ of
  1191. top_const:
  1192. Result := '$' + debug_tostr(oper.val);
  1193. top_reg:
  1194. Result := debug_regname(oper.reg);
  1195. top_ref:
  1196. begin
  1197. if oper.ref^.offset <> 0 then
  1198. Result := debug_tostr(oper.ref^.offset) + '('
  1199. else
  1200. Result := '(';
  1201. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1202. begin
  1203. Result := Result + debug_regname(oper.ref^.base);
  1204. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1205. Result := Result + ',' + debug_regname(oper.ref^.index);
  1206. end
  1207. else
  1208. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1209. Result := Result + debug_regname(oper.ref^.index);
  1210. if (oper.ref^.scalefactor > 1) then
  1211. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1212. else
  1213. Result := Result + ')';
  1214. end;
  1215. else
  1216. Result := '[UNKNOWN]';
  1217. end;
  1218. end;
  1219. function debug_op2str(opcode: tasmop): string; inline;
  1220. begin
  1221. Result := std_op2str[opcode];
  1222. end;
  1223. function debug_opsize2str(opsize: topsize): string; inline;
  1224. begin
  1225. Result := gas_opsize2str[opsize];
  1226. end;
  1227. {$else DEBUG_AOPTCPU}
  1228. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1229. begin
  1230. end;
  1231. function debug_tostr(i: tcgint): string; inline;
  1232. begin
  1233. Result := '';
  1234. end;
  1235. function debug_hexstr(i: tcgint): string; inline;
  1236. begin
  1237. Result := '';
  1238. end;
  1239. function debug_regname(r: TRegister): string; inline;
  1240. begin
  1241. Result := '';
  1242. end;
  1243. function debug_operstr(oper: TOper): string; inline;
  1244. begin
  1245. Result := '';
  1246. end;
  1247. function debug_op2str(opcode: tasmop): string; inline;
  1248. begin
  1249. Result := '';
  1250. end;
  1251. function debug_opsize2str(opsize: topsize): string; inline;
  1252. begin
  1253. Result := '';
  1254. end;
  1255. {$endif DEBUG_AOPTCPU}
  1256. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1257. begin
  1258. {$ifdef x86_64}
  1259. { Always fine on x86-64 }
  1260. Result := True;
  1261. {$else x86_64}
  1262. Result :=
  1263. {$ifdef i8086}
  1264. (current_settings.cputype >= cpu_386) and
  1265. {$endif i8086}
  1266. (
  1267. { Always accept if optimising for size }
  1268. (cs_opt_size in current_settings.optimizerswitches) or
  1269. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1270. (current_settings.optimizecputype >= cpu_Pentium2)
  1271. );
  1272. {$endif x86_64}
  1273. end;
  1274. { Attempts to allocate a volatile integer register for use between p and hp,
  1275. using AUsedRegs for the current register usage information. Returns NR_NO
  1276. if no free register could be found }
  1277. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1278. var
  1279. RegSet: TCPURegisterSet;
  1280. CurrentSuperReg: Integer;
  1281. CurrentReg: TRegister;
  1282. Currentp: tai;
  1283. Breakout: Boolean;
  1284. begin
  1285. Result := NR_NO;
  1286. RegSet :=
  1287. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1288. current_procinfo.saved_regs_int;
  1289. (*
  1290. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1291. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1292. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1293. *)
  1294. for CurrentSuperReg in RegSet do
  1295. begin
  1296. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1297. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1298. {$if defined(i386) or defined(i8086)}
  1299. { If the target size is 8-bit, make sure we can actually encode it }
  1300. and (
  1301. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1302. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1303. )
  1304. {$endif i386 or i8086}
  1305. then
  1306. begin
  1307. Currentp := p;
  1308. Breakout := False;
  1309. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1310. begin
  1311. case Currentp.typ of
  1312. ait_instruction:
  1313. begin
  1314. if RegInInstruction(CurrentReg, Currentp) then
  1315. begin
  1316. Breakout := True;
  1317. Break;
  1318. end;
  1319. { Cannot allocate across an unconditional jump }
  1320. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1321. Exit;
  1322. end;
  1323. ait_marker:
  1324. { Don't try anything more if a marker is hit }
  1325. Exit;
  1326. ait_regalloc:
  1327. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1328. begin
  1329. Breakout := True;
  1330. Break;
  1331. end;
  1332. else
  1333. ;
  1334. end;
  1335. end;
  1336. if Breakout then
  1337. { Try the next register }
  1338. Continue;
  1339. { We have a free register available }
  1340. Result := CurrentReg;
  1341. if not DontAlloc then
  1342. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1343. Exit;
  1344. end;
  1345. end;
  1346. end;
  1347. { Attempts to allocate a volatile MM register for use between p and hp,
  1348. using AUsedRegs for the current register usage information. Returns NR_NO
  1349. if no free register could be found }
  1350. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1351. var
  1352. RegSet: TCPURegisterSet;
  1353. CurrentSuperReg: Integer;
  1354. CurrentReg: TRegister;
  1355. Currentp: tai;
  1356. Breakout: Boolean;
  1357. begin
  1358. Result := NR_NO;
  1359. RegSet :=
  1360. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1361. current_procinfo.saved_regs_mm;
  1362. for CurrentSuperReg in RegSet do
  1363. begin
  1364. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1365. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1366. begin
  1367. Currentp := p;
  1368. Breakout := False;
  1369. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1370. begin
  1371. case Currentp.typ of
  1372. ait_instruction:
  1373. begin
  1374. if RegInInstruction(CurrentReg, Currentp) then
  1375. begin
  1376. Breakout := True;
  1377. Break;
  1378. end;
  1379. { Cannot allocate across an unconditional jump }
  1380. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1381. Exit;
  1382. end;
  1383. ait_marker:
  1384. { Don't try anything more if a marker is hit }
  1385. Exit;
  1386. ait_regalloc:
  1387. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1388. begin
  1389. Breakout := True;
  1390. Break;
  1391. end;
  1392. else
  1393. ;
  1394. end;
  1395. end;
  1396. if Breakout then
  1397. { Try the next register }
  1398. Continue;
  1399. { We have a free register available }
  1400. Result := CurrentReg;
  1401. if not DontAlloc then
  1402. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1403. Exit;
  1404. end;
  1405. end;
  1406. end;
  1407. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1408. begin
  1409. if not SuperRegistersEqual(reg1,reg2) then
  1410. exit(false);
  1411. if getregtype(reg1)<>R_INTREGISTER then
  1412. exit(true); {because SuperRegisterEqual is true}
  1413. case getsubreg(reg1) of
  1414. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1415. higher, it preserves the high bits, so the new value depends on
  1416. reg2's previous value. In other words, it is equivalent to doing:
  1417. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1418. R_SUBL:
  1419. exit(getsubreg(reg2)=R_SUBL);
  1420. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1421. higher, it actually does a:
  1422. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1423. R_SUBH:
  1424. exit(getsubreg(reg2)=R_SUBH);
  1425. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1426. bits of reg2:
  1427. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1428. R_SUBW:
  1429. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1430. { a write to R_SUBD always overwrites every other subregister,
  1431. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1432. R_SUBD,
  1433. R_SUBQ:
  1434. exit(true);
  1435. else
  1436. internalerror(2017042801);
  1437. end;
  1438. end;
  1439. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1440. begin
  1441. if not SuperRegistersEqual(reg1,reg2) then
  1442. exit(false);
  1443. if getregtype(reg1)<>R_INTREGISTER then
  1444. exit(true); {because SuperRegisterEqual is true}
  1445. case getsubreg(reg1) of
  1446. R_SUBL:
  1447. exit(getsubreg(reg2)<>R_SUBH);
  1448. R_SUBH:
  1449. exit(getsubreg(reg2)<>R_SUBL);
  1450. R_SUBW,
  1451. R_SUBD,
  1452. R_SUBQ:
  1453. exit(true);
  1454. else
  1455. internalerror(2017042802);
  1456. end;
  1457. end;
  1458. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1459. var
  1460. hp1 : tai;
  1461. l : TCGInt;
  1462. begin
  1463. result:=false;
  1464. if not(GetNextInstruction(p, hp1)) then
  1465. exit;
  1466. { changes the code sequence
  1467. shr/sar const1, x
  1468. shl const2, x
  1469. to
  1470. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1471. if (taicpu(p).oper[0]^.typ = top_const) and
  1472. MatchInstruction(hp1,A_SHL,[]) and
  1473. (taicpu(hp1).oper[0]^.typ = top_const) and
  1474. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1475. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1476. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1477. begin
  1478. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1479. not(cs_opt_size in current_settings.optimizerswitches) then
  1480. begin
  1481. { shr/sar const1, %reg
  1482. shl const2, %reg
  1483. with const1 > const2 }
  1484. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1485. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1486. taicpu(hp1).opcode := A_AND;
  1487. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1488. case taicpu(p).opsize Of
  1489. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1490. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1491. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1492. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1493. else
  1494. Internalerror(2017050703)
  1495. end;
  1496. end
  1497. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1498. not(cs_opt_size in current_settings.optimizerswitches) then
  1499. begin
  1500. { shr/sar const1, %reg
  1501. shl const2, %reg
  1502. with const1 < const2 }
  1503. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1504. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1505. taicpu(p).opcode := A_AND;
  1506. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1507. case taicpu(p).opsize Of
  1508. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1509. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1510. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1511. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1512. else
  1513. Internalerror(2017050702)
  1514. end;
  1515. end
  1516. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1517. begin
  1518. { shr/sar const1, %reg
  1519. shl const2, %reg
  1520. with const1 = const2 }
  1521. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1522. taicpu(p).opcode := A_AND;
  1523. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1524. case taicpu(p).opsize Of
  1525. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1526. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1527. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1528. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1529. else
  1530. Internalerror(2017050701)
  1531. end;
  1532. RemoveInstruction(hp1);
  1533. end;
  1534. end;
  1535. end;
  1536. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1537. var
  1538. opsize : topsize;
  1539. hp1, hp2 : tai;
  1540. tmpref : treference;
  1541. ShiftValue : Cardinal;
  1542. BaseValue : TCGInt;
  1543. begin
  1544. result:=false;
  1545. opsize:=taicpu(p).opsize;
  1546. { changes certain "imul const, %reg"'s to lea sequences }
  1547. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1548. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1549. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1550. if (taicpu(p).oper[0]^.val = 1) then
  1551. if (taicpu(p).ops = 2) then
  1552. { remove "imul $1, reg" }
  1553. begin
  1554. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1555. Result := RemoveCurrentP(p);
  1556. end
  1557. else
  1558. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1559. begin
  1560. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1561. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1562. asml.InsertAfter(hp1, p);
  1563. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1564. RemoveCurrentP(p, hp1);
  1565. Result := True;
  1566. end
  1567. else if ((taicpu(p).ops <= 2) or
  1568. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1569. not(cs_opt_size in current_settings.optimizerswitches) and
  1570. (not(GetNextInstruction(p, hp1)) or
  1571. not((tai(hp1).typ = ait_instruction) and
  1572. ((taicpu(hp1).opcode=A_Jcc) and
  1573. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1574. begin
  1575. {
  1576. imul X, reg1, reg2 to
  1577. lea (reg1,reg1,Y), reg2
  1578. shl ZZ,reg2
  1579. imul XX, reg1 to
  1580. lea (reg1,reg1,YY), reg1
  1581. shl ZZ,reg2
  1582. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1583. it does not exist as a separate optimization target in FPC though.
  1584. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1585. at most two zeros
  1586. }
  1587. reference_reset(tmpref,1,[]);
  1588. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1589. begin
  1590. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1591. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1592. TmpRef.base := taicpu(p).oper[1]^.reg;
  1593. TmpRef.index := taicpu(p).oper[1]^.reg;
  1594. if not(BaseValue in [3,5,9]) then
  1595. Internalerror(2018110101);
  1596. TmpRef.ScaleFactor := BaseValue-1;
  1597. if (taicpu(p).ops = 2) then
  1598. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1599. else
  1600. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1601. AsmL.InsertAfter(hp1,p);
  1602. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1603. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1604. RemoveCurrentP(p, hp1);
  1605. if ShiftValue>0 then
  1606. begin
  1607. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1608. AsmL.InsertAfter(hp2,hp1);
  1609. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1610. end;
  1611. Result := True;
  1612. end;
  1613. end;
  1614. end;
  1615. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1616. begin
  1617. Result := False;
  1618. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1619. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1620. begin
  1621. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1622. taicpu(p).opcode := A_MOV;
  1623. Result := True;
  1624. end;
  1625. end;
  1626. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1627. var
  1628. p: taicpu absolute hp; { Implicit typecast }
  1629. i: Integer;
  1630. begin
  1631. Result := False;
  1632. if not assigned(hp) or
  1633. (hp.typ <> ait_instruction) then
  1634. Exit;
  1635. Prefetch(insprop[p.opcode]);
  1636. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1637. with insprop[p.opcode] do
  1638. begin
  1639. case getsubreg(reg) of
  1640. R_SUBW,R_SUBD,R_SUBQ:
  1641. Result:=
  1642. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1643. uncommon flags are checked first }
  1644. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1645. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1646. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1647. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1648. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1649. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1650. R_SUBFLAGCARRY:
  1651. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1652. R_SUBFLAGPARITY:
  1653. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1654. R_SUBFLAGAUXILIARY:
  1655. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGZERO:
  1657. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGSIGN:
  1659. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGOVERFLOW:
  1661. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGINTERRUPT:
  1663. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGDIRECTION:
  1665. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1666. else
  1667. internalerror(2017050501);
  1668. end;
  1669. exit;
  1670. end;
  1671. { Handle special cases first }
  1672. case p.opcode of
  1673. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1674. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1675. begin
  1676. Result :=
  1677. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1678. (p.oper[1]^.typ = top_reg) and
  1679. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1680. (
  1681. (p.oper[0]^.typ = top_const) or
  1682. (
  1683. (p.oper[0]^.typ = top_reg) and
  1684. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1685. ) or (
  1686. (p.oper[0]^.typ = top_ref) and
  1687. not RegInRef(reg,p.oper[0]^.ref^)
  1688. )
  1689. );
  1690. end;
  1691. A_MUL, A_IMUL:
  1692. Result :=
  1693. (
  1694. (p.ops=3) and { IMUL only }
  1695. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1696. (
  1697. (
  1698. (p.oper[1]^.typ=top_reg) and
  1699. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1700. ) or (
  1701. (p.oper[1]^.typ=top_ref) and
  1702. not RegInRef(reg,p.oper[1]^.ref^)
  1703. )
  1704. )
  1705. ) or (
  1706. (
  1707. (p.ops=1) and
  1708. (
  1709. (
  1710. (
  1711. (p.oper[0]^.typ=top_reg) and
  1712. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1713. )
  1714. ) or (
  1715. (p.oper[0]^.typ=top_ref) and
  1716. not RegInRef(reg,p.oper[0]^.ref^)
  1717. )
  1718. ) and (
  1719. (
  1720. (p.opsize=S_B) and
  1721. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1722. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1723. ) or (
  1724. (p.opsize=S_W) and
  1725. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1726. ) or (
  1727. (p.opsize=S_L) and
  1728. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1729. {$ifdef x86_64}
  1730. ) or (
  1731. (p.opsize=S_Q) and
  1732. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1733. {$endif x86_64}
  1734. )
  1735. )
  1736. )
  1737. );
  1738. A_CBW:
  1739. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1740. {$ifndef x86_64}
  1741. A_LDS:
  1742. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1743. A_LES:
  1744. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1745. {$endif not x86_64}
  1746. A_LFS:
  1747. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1748. A_LGS:
  1749. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1750. A_LSS:
  1751. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1753. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1754. A_LODSB:
  1755. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1756. A_LODSW:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1758. {$ifdef x86_64}
  1759. A_LODSQ:
  1760. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1761. {$endif x86_64}
  1762. A_LODSD:
  1763. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1764. A_FSTSW, A_FNSTSW:
  1765. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1766. else
  1767. begin
  1768. with insprop[p.opcode] do
  1769. begin
  1770. if (
  1771. { xor %reg,%reg etc. is classed as a new value }
  1772. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1773. MatchOpType(p, top_reg, top_reg) and
  1774. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1775. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1776. ) then
  1777. begin
  1778. Result := True;
  1779. Exit;
  1780. end;
  1781. { Make sure the entire register is overwritten }
  1782. if (getregtype(reg) = R_INTREGISTER) then
  1783. begin
  1784. if (p.ops > 0) then
  1785. begin
  1786. if RegInOp(reg, p.oper[0]^) then
  1787. begin
  1788. if (p.oper[0]^.typ = top_ref) then
  1789. begin
  1790. if RegInRef(reg, p.oper[0]^.ref^) then
  1791. begin
  1792. Result := False;
  1793. Exit;
  1794. end;
  1795. end
  1796. else if (p.oper[0]^.typ = top_reg) then
  1797. begin
  1798. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1799. begin
  1800. Result := False;
  1801. Exit;
  1802. end
  1803. else if ([Ch_WOp1]*Ch<>[]) then
  1804. begin
  1805. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1806. Result := True
  1807. else
  1808. begin
  1809. Result := False;
  1810. Exit;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. if (p.ops > 1) then
  1816. begin
  1817. if RegInOp(reg, p.oper[1]^) then
  1818. begin
  1819. if (p.oper[1]^.typ = top_ref) then
  1820. begin
  1821. if RegInRef(reg, p.oper[1]^.ref^) then
  1822. begin
  1823. Result := False;
  1824. Exit;
  1825. end;
  1826. end
  1827. else if (p.oper[1]^.typ = top_reg) then
  1828. begin
  1829. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1830. begin
  1831. Result := False;
  1832. Exit;
  1833. end
  1834. else if ([Ch_WOp2]*Ch<>[]) then
  1835. begin
  1836. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1837. Result := True
  1838. else
  1839. begin
  1840. Result := False;
  1841. Exit;
  1842. end;
  1843. end;
  1844. end;
  1845. end;
  1846. if (p.ops > 2) then
  1847. begin
  1848. if RegInOp(reg, p.oper[2]^) then
  1849. begin
  1850. if (p.oper[2]^.typ = top_ref) then
  1851. begin
  1852. if RegInRef(reg, p.oper[2]^.ref^) then
  1853. begin
  1854. Result := False;
  1855. Exit;
  1856. end;
  1857. end
  1858. else if (p.oper[2]^.typ = top_reg) then
  1859. begin
  1860. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1861. begin
  1862. Result := False;
  1863. Exit;
  1864. end
  1865. else if ([Ch_WOp3]*Ch<>[]) then
  1866. begin
  1867. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1868. Result := True
  1869. else
  1870. begin
  1871. Result := False;
  1872. Exit;
  1873. end;
  1874. end;
  1875. end;
  1876. end;
  1877. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1878. begin
  1879. if (p.oper[3]^.typ = top_ref) then
  1880. begin
  1881. if RegInRef(reg, p.oper[3]^.ref^) then
  1882. begin
  1883. Result := False;
  1884. Exit;
  1885. end;
  1886. end
  1887. else if (p.oper[3]^.typ = top_reg) then
  1888. begin
  1889. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1890. begin
  1891. Result := False;
  1892. Exit;
  1893. end
  1894. else if ([Ch_WOp4]*Ch<>[]) then
  1895. begin
  1896. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1897. Result := True
  1898. else
  1899. begin
  1900. Result := False;
  1901. Exit;
  1902. end;
  1903. end;
  1904. end;
  1905. end;
  1906. end;
  1907. end;
  1908. end;
  1909. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1910. case getsupreg(reg) of
  1911. RS_EAX:
  1912. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1913. begin
  1914. Result := True;
  1915. Exit;
  1916. end;
  1917. RS_ECX:
  1918. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1919. begin
  1920. Result := True;
  1921. Exit;
  1922. end;
  1923. RS_EDX:
  1924. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1925. begin
  1926. Result := True;
  1927. Exit;
  1928. end;
  1929. RS_EBX:
  1930. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1931. begin
  1932. Result := True;
  1933. Exit;
  1934. end;
  1935. RS_ESP:
  1936. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1937. begin
  1938. Result := True;
  1939. Exit;
  1940. end;
  1941. RS_EBP:
  1942. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1943. begin
  1944. Result := True;
  1945. Exit;
  1946. end;
  1947. RS_ESI:
  1948. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1949. begin
  1950. Result := True;
  1951. Exit;
  1952. end;
  1953. RS_EDI:
  1954. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1955. begin
  1956. Result := True;
  1957. Exit;
  1958. end;
  1959. else
  1960. ;
  1961. end;
  1962. end;
  1963. end;
  1964. end;
  1965. end;
  1966. end;
  1967. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1968. var
  1969. hp2,hp3 : tai;
  1970. begin
  1971. { some x86-64 issue a NOP before the real exit code }
  1972. if MatchInstruction(p,A_NOP,[]) then
  1973. GetNextInstruction(p,p);
  1974. result:=assigned(p) and (p.typ=ait_instruction) and
  1975. ((taicpu(p).opcode = A_RET) or
  1976. ((taicpu(p).opcode=A_LEAVE) and
  1977. GetNextInstruction(p,hp2) and
  1978. MatchInstruction(hp2,A_RET,[S_NO])
  1979. ) or
  1980. (((taicpu(p).opcode=A_LEA) and
  1981. MatchOpType(taicpu(p),top_ref,top_reg) and
  1982. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1983. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1984. ) and
  1985. GetNextInstruction(p,hp2) and
  1986. MatchInstruction(hp2,A_RET,[S_NO])
  1987. ) or
  1988. ((((taicpu(p).opcode=A_MOV) and
  1989. MatchOpType(taicpu(p),top_reg,top_reg) and
  1990. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1991. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1992. ((taicpu(p).opcode=A_LEA) and
  1993. MatchOpType(taicpu(p),top_ref,top_reg) and
  1994. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1995. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1996. )
  1997. ) and
  1998. GetNextInstruction(p,hp2) and
  1999. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2000. MatchOpType(taicpu(hp2),top_reg) and
  2001. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2002. GetNextInstruction(hp2,hp3) and
  2003. MatchInstruction(hp3,A_RET,[S_NO])
  2004. )
  2005. );
  2006. end;
  2007. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2008. begin
  2009. isFoldableArithOp := False;
  2010. case hp1.opcode of
  2011. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2012. isFoldableArithOp :=
  2013. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2014. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2015. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2016. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2017. (taicpu(hp1).oper[1]^.reg = reg);
  2018. A_INC,A_DEC,A_NEG,A_NOT:
  2019. isFoldableArithOp :=
  2020. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2021. (taicpu(hp1).oper[0]^.reg = reg);
  2022. else
  2023. ;
  2024. end;
  2025. end;
  2026. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2027. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2028. var
  2029. hp2: tai;
  2030. begin
  2031. hp2 := p;
  2032. repeat
  2033. hp2 := tai(hp2.previous);
  2034. if assigned(hp2) and
  2035. (hp2.typ = ait_regalloc) and
  2036. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2037. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2038. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2039. begin
  2040. RemoveInstruction(hp2);
  2041. break;
  2042. end;
  2043. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2044. end;
  2045. begin
  2046. case current_procinfo.procdef.returndef.typ of
  2047. arraydef,recorddef,pointerdef,
  2048. stringdef,enumdef,procdef,objectdef,errordef,
  2049. filedef,setdef,procvardef,
  2050. classrefdef,forwarddef:
  2051. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2052. orddef:
  2053. if current_procinfo.procdef.returndef.size <> 0 then
  2054. begin
  2055. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2056. { for int64/qword }
  2057. if current_procinfo.procdef.returndef.size = 8 then
  2058. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2059. end;
  2060. else
  2061. ;
  2062. end;
  2063. end;
  2064. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2065. var
  2066. hp1,hp2 : tai;
  2067. begin
  2068. result:=false;
  2069. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2070. begin
  2071. { vmova* reg1,reg1
  2072. =>
  2073. <nop> }
  2074. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2075. begin
  2076. RemoveCurrentP(p);
  2077. result:=true;
  2078. exit;
  2079. end;
  2080. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2081. (hp1.typ = ait_instruction) and
  2082. (
  2083. { Under -O2 and below, the instructions are always adjacent }
  2084. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2085. (taicpu(hp1).ops <= 1) or
  2086. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2087. { If reg1 = reg3, reg1 must not be modified in between }
  2088. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2089. ) then
  2090. begin
  2091. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2092. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2093. begin
  2094. { vmova* reg1,reg2
  2095. ...
  2096. vmova* reg2,reg3
  2097. dealloc reg2
  2098. =>
  2099. vmova* reg1,reg3 }
  2100. TransferUsedRegs(TmpUsedRegs);
  2101. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2102. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2103. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2104. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2105. begin
  2106. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2107. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2108. TransferUsedRegs(TmpUsedRegs);
  2109. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2110. RemoveInstruction(hp1);
  2111. result:=true;
  2112. exit;
  2113. end;
  2114. { special case:
  2115. vmova* reg1,<op>
  2116. ...
  2117. vmova* <op>,reg1
  2118. =>
  2119. vmova* reg1,<op> }
  2120. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2121. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2122. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2123. ) then
  2124. begin
  2125. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2126. RemoveInstruction(hp1);
  2127. result:=true;
  2128. exit;
  2129. end
  2130. end
  2131. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2132. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2133. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2134. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2135. ) and
  2136. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2137. begin
  2138. { vmova* reg1,reg2
  2139. ...
  2140. vmovs* reg2,<op>
  2141. dealloc reg2
  2142. =>
  2143. vmovs* reg1,<op> }
  2144. TransferUsedRegs(TmpUsedRegs);
  2145. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2146. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2147. begin
  2148. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2149. taicpu(p).opcode:=taicpu(hp1).opcode;
  2150. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2151. TransferUsedRegs(TmpUsedRegs);
  2152. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2153. RemoveInstruction(hp1);
  2154. result:=true;
  2155. exit;
  2156. end
  2157. end;
  2158. if MatchInstruction(hp1,[A_VFMADDPD,
  2159. A_VFMADD132PD,
  2160. A_VFMADD132PS,
  2161. A_VFMADD132SD,
  2162. A_VFMADD132SS,
  2163. A_VFMADD213PD,
  2164. A_VFMADD213PS,
  2165. A_VFMADD213SD,
  2166. A_VFMADD213SS,
  2167. A_VFMADD231PD,
  2168. A_VFMADD231PS,
  2169. A_VFMADD231SD,
  2170. A_VFMADD231SS,
  2171. A_VFMADDSUB132PD,
  2172. A_VFMADDSUB132PS,
  2173. A_VFMADDSUB213PD,
  2174. A_VFMADDSUB213PS,
  2175. A_VFMADDSUB231PD,
  2176. A_VFMADDSUB231PS,
  2177. A_VFMSUB132PD,
  2178. A_VFMSUB132PS,
  2179. A_VFMSUB132SD,
  2180. A_VFMSUB132SS,
  2181. A_VFMSUB213PD,
  2182. A_VFMSUB213PS,
  2183. A_VFMSUB213SD,
  2184. A_VFMSUB213SS,
  2185. A_VFMSUB231PD,
  2186. A_VFMSUB231PS,
  2187. A_VFMSUB231SD,
  2188. A_VFMSUB231SS,
  2189. A_VFMSUBADD132PD,
  2190. A_VFMSUBADD132PS,
  2191. A_VFMSUBADD213PD,
  2192. A_VFMSUBADD213PS,
  2193. A_VFMSUBADD231PD,
  2194. A_VFMSUBADD231PS,
  2195. A_VFNMADD132PD,
  2196. A_VFNMADD132PS,
  2197. A_VFNMADD132SD,
  2198. A_VFNMADD132SS,
  2199. A_VFNMADD213PD,
  2200. A_VFNMADD213PS,
  2201. A_VFNMADD213SD,
  2202. A_VFNMADD213SS,
  2203. A_VFNMADD231PD,
  2204. A_VFNMADD231PS,
  2205. A_VFNMADD231SD,
  2206. A_VFNMADD231SS,
  2207. A_VFNMSUB132PD,
  2208. A_VFNMSUB132PS,
  2209. A_VFNMSUB132SD,
  2210. A_VFNMSUB132SS,
  2211. A_VFNMSUB213PD,
  2212. A_VFNMSUB213PS,
  2213. A_VFNMSUB213SD,
  2214. A_VFNMSUB213SS,
  2215. A_VFNMSUB231PD,
  2216. A_VFNMSUB231PS,
  2217. A_VFNMSUB231SD,
  2218. A_VFNMSUB231SS],[S_NO]) and
  2219. { we mix single and double opperations here because we assume that the compiler
  2220. generates vmovapd only after double operations and vmovaps only after single operations }
  2221. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2222. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2223. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2224. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2225. begin
  2226. TransferUsedRegs(TmpUsedRegs);
  2227. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2228. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2229. begin
  2230. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2231. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2232. RemoveCurrentP(p)
  2233. else
  2234. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2235. RemoveInstruction(hp2);
  2236. end;
  2237. end
  2238. else if (hp1.typ = ait_instruction) and
  2239. (((taicpu(p).opcode=A_MOVAPS) and
  2240. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2241. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2242. ((taicpu(p).opcode=A_MOVAPD) and
  2243. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2244. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2245. ) and
  2246. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2247. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2248. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2249. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2250. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2251. { change
  2252. movapX reg,reg2
  2253. addsX/subsX/... reg3, reg2
  2254. movapX reg2,reg
  2255. to
  2256. addsX/subsX/... reg3,reg
  2257. }
  2258. begin
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2261. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2264. debug_op2str(taicpu(p).opcode)+' '+
  2265. debug_op2str(taicpu(hp1).opcode)+' '+
  2266. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2267. { we cannot eliminate the first move if
  2268. the operations uses the same register for source and dest }
  2269. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2270. { Remember that hp1 is not necessarily the immediate
  2271. next instruction }
  2272. RemoveCurrentP(p);
  2273. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2274. RemoveInstruction(hp2);
  2275. result:=true;
  2276. end;
  2277. end
  2278. else if (hp1.typ = ait_instruction) and
  2279. (((taicpu(p).opcode=A_VMOVAPD) and
  2280. (taicpu(hp1).opcode=A_VCOMISD)) or
  2281. ((taicpu(p).opcode=A_VMOVAPS) and
  2282. ((taicpu(hp1).opcode=A_VCOMISS))
  2283. )
  2284. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2285. { change
  2286. movapX reg,reg1
  2287. vcomisX reg1,reg1
  2288. to
  2289. vcomisX reg,reg
  2290. }
  2291. begin
  2292. TransferUsedRegs(TmpUsedRegs);
  2293. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2294. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2295. begin
  2296. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2297. debug_op2str(taicpu(p).opcode)+' '+
  2298. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2299. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2300. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2301. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2302. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2303. RemoveCurrentP(p);
  2304. result:=true;
  2305. exit;
  2306. end;
  2307. end
  2308. end;
  2309. end;
  2310. end;
  2311. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2312. var
  2313. hp1 : tai;
  2314. begin
  2315. result:=false;
  2316. { replace
  2317. V<Op>X %mreg1,%mreg2,%mreg3
  2318. VMovX %mreg3,%mreg4
  2319. dealloc %mreg3
  2320. by
  2321. V<Op>X %mreg1,%mreg2,%mreg4
  2322. ?
  2323. }
  2324. if GetNextInstruction(p,hp1) and
  2325. { we mix single and double operations here because we assume that the compiler
  2326. generates vmovapd only after double operations and vmovaps only after single operations }
  2327. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2328. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2329. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2330. begin
  2331. TransferUsedRegs(TmpUsedRegs);
  2332. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2333. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2334. begin
  2335. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2336. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2337. RemoveInstruction(hp1);
  2338. result:=true;
  2339. end;
  2340. end;
  2341. end;
  2342. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2343. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2344. begin
  2345. Result := False;
  2346. { For safety reasons, only check for exact register matches }
  2347. { Check base register }
  2348. if (ref.base = AOldReg) then
  2349. begin
  2350. ref.base := ANewReg;
  2351. Result := True;
  2352. end;
  2353. { Check index register }
  2354. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2355. begin
  2356. ref.index := ANewReg;
  2357. Result := True;
  2358. end;
  2359. end;
  2360. { Replaces all references to AOldReg in an operand to ANewReg }
  2361. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2362. var
  2363. OldSupReg, NewSupReg: TSuperRegister;
  2364. OldSubReg, NewSubReg: TSubRegister;
  2365. OldRegType: TRegisterType;
  2366. ThisOper: POper;
  2367. begin
  2368. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2369. Result := False;
  2370. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2371. InternalError(2020011801);
  2372. OldSupReg := getsupreg(AOldReg);
  2373. OldSubReg := getsubreg(AOldReg);
  2374. OldRegType := getregtype(AOldReg);
  2375. NewSupReg := getsupreg(ANewReg);
  2376. NewSubReg := getsubreg(ANewReg);
  2377. if OldRegType <> getregtype(ANewReg) then
  2378. InternalError(2020011802);
  2379. if OldSubReg <> NewSubReg then
  2380. InternalError(2020011803);
  2381. case ThisOper^.typ of
  2382. top_reg:
  2383. if (
  2384. (ThisOper^.reg = AOldReg) or
  2385. (
  2386. (OldRegType = R_INTREGISTER) and
  2387. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2388. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2389. (
  2390. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2391. {$ifndef x86_64}
  2392. and (
  2393. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2394. don't have an 8-bit representation }
  2395. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2396. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2397. )
  2398. {$endif x86_64}
  2399. )
  2400. )
  2401. ) then
  2402. begin
  2403. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2404. Result := True;
  2405. end;
  2406. top_ref:
  2407. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2408. Result := True;
  2409. else
  2410. ;
  2411. end;
  2412. end;
  2413. { Replaces all references to AOldReg in an instruction to ANewReg }
  2414. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2415. const
  2416. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2417. var
  2418. OperIdx: Integer;
  2419. begin
  2420. Result := False;
  2421. for OperIdx := 0 to p.ops - 1 do
  2422. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2423. begin
  2424. { The shift and rotate instructions can only use CL }
  2425. if not (
  2426. (OperIdx = 0) and
  2427. { This second condition just helps to avoid unnecessarily
  2428. calling MatchInstruction for 10 different opcodes }
  2429. (p.oper[0]^.reg = NR_CL) and
  2430. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2431. ) then
  2432. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2433. end
  2434. else if p.oper[OperIdx]^.typ = top_ref then
  2435. { It's okay to replace registers in references that get written to }
  2436. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2437. end;
  2438. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2439. begin
  2440. Result :=
  2441. (ref^.index = NR_NO) and
  2442. (
  2443. {$ifdef x86_64}
  2444. (
  2445. (ref^.base = NR_RIP) and
  2446. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2447. ) or
  2448. {$endif x86_64}
  2449. (ref^.refaddr = addr_full) or
  2450. (ref^.base = NR_STACK_POINTER_REG) or
  2451. (ref^.base = current_procinfo.framepointer)
  2452. );
  2453. end;
  2454. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2455. var
  2456. l: asizeint;
  2457. begin
  2458. Result := False;
  2459. { Should have been checked previously }
  2460. if p.opcode <> A_LEA then
  2461. InternalError(2020072501);
  2462. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2463. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2464. not(cs_opt_size in current_settings.optimizerswitches) then
  2465. exit;
  2466. with p.oper[0]^.ref^ do
  2467. begin
  2468. if (base <> p.oper[1]^.reg) or
  2469. (index <> NR_NO) or
  2470. assigned(symbol) then
  2471. exit;
  2472. l:=offset;
  2473. if (l=1) and UseIncDec then
  2474. begin
  2475. p.opcode:=A_INC;
  2476. p.loadreg(0,p.oper[1]^.reg);
  2477. p.ops:=1;
  2478. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2479. end
  2480. else if (l=-1) and UseIncDec then
  2481. begin
  2482. p.opcode:=A_DEC;
  2483. p.loadreg(0,p.oper[1]^.reg);
  2484. p.ops:=1;
  2485. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2486. end
  2487. else
  2488. begin
  2489. if (l<0) and (l<>-2147483648) then
  2490. begin
  2491. p.opcode:=A_SUB;
  2492. p.loadConst(0,-l);
  2493. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2494. end
  2495. else
  2496. begin
  2497. p.opcode:=A_ADD;
  2498. p.loadConst(0,l);
  2499. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2500. end;
  2501. end;
  2502. end;
  2503. Result := True;
  2504. end;
  2505. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2506. var
  2507. CurrentReg, ReplaceReg: TRegister;
  2508. begin
  2509. Result := False;
  2510. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2511. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2512. case hp.opcode of
  2513. A_FSTSW, A_FNSTSW,
  2514. A_IN, A_INS, A_OUT, A_OUTS,
  2515. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2516. { These routines have explicit operands, but they are restricted in
  2517. what they can be (e.g. IN and OUT can only read from AL, AX or
  2518. EAX. }
  2519. Exit;
  2520. A_IMUL:
  2521. begin
  2522. { The 1-operand version writes to implicit registers
  2523. The 2-operand version reads from the first operator, and reads
  2524. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2525. the 3-operand version reads from a register that it doesn't write to
  2526. }
  2527. case hp.ops of
  2528. 1:
  2529. if (
  2530. (
  2531. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2532. ) or
  2533. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2534. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2535. begin
  2536. Result := True;
  2537. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2538. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2539. end;
  2540. 2:
  2541. { Only modify the first parameter }
  2542. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2543. begin
  2544. Result := True;
  2545. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2546. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2547. end;
  2548. 3:
  2549. { Only modify the second parameter }
  2550. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2551. begin
  2552. Result := True;
  2553. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2554. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2555. end;
  2556. else
  2557. InternalError(2020012901);
  2558. end;
  2559. end;
  2560. else
  2561. if (hp.ops > 0) and
  2562. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2563. begin
  2564. Result := True;
  2565. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2566. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2567. end;
  2568. end;
  2569. end;
  2570. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2571. var
  2572. hp2: tai;
  2573. p_SourceReg, p_TargetReg: TRegister;
  2574. begin
  2575. Result := False;
  2576. { Backward optimisation. If we have:
  2577. func. %reg1,%reg2
  2578. mov %reg2,%reg3
  2579. (dealloc %reg2)
  2580. Change to:
  2581. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2582. Perform similar optimisations with 1, 3 and 4-operand instructions
  2583. that only have one output.
  2584. }
  2585. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2586. begin
  2587. p_SourceReg := taicpu(p).oper[0]^.reg;
  2588. p_TargetReg := taicpu(p).oper[1]^.reg;
  2589. TransferUsedRegs(TmpUsedRegs);
  2590. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2591. GetLastInstruction(p, hp2) and
  2592. (hp2.typ = ait_instruction) and
  2593. { Have to make sure it's an instruction that only reads from
  2594. the first operands and only writes (not reads or modifies) to
  2595. the last one; in essence, a pure function such as BSR, POPCNT
  2596. or ANDN }
  2597. (
  2598. (
  2599. (taicpu(hp2).ops = 1) and
  2600. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2601. ) or
  2602. (
  2603. (taicpu(hp2).ops = 2) and
  2604. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2605. ) or
  2606. (
  2607. (taicpu(hp2).ops = 3) and
  2608. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2609. ) or
  2610. (
  2611. (taicpu(hp2).ops = 4) and
  2612. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2613. )
  2614. ) and
  2615. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2616. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2617. begin
  2618. case taicpu(hp2).opcode of
  2619. A_FSTSW, A_FNSTSW,
  2620. A_IN, A_INS, A_OUT, A_OUTS,
  2621. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2622. { These routines have explicit operands, but they are restricted in
  2623. what they can be (e.g. IN and OUT can only read from AL, AX or
  2624. EAX. }
  2625. ;
  2626. else
  2627. begin
  2628. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2629. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2630. if not RegInInstruction(p_TargetReg, hp2) then
  2631. begin
  2632. { Since we're allocating from an earlier point, we
  2633. need to remove the register from the tracking }
  2634. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2635. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2636. end;
  2637. RemoveCurrentp(p, hp1);
  2638. { If the Func was another MOV instruction, we might get
  2639. "mov %reg,%reg" that doesn't get removed in Pass 2
  2640. otherwise, so deal with it here (also do something
  2641. similar with lea (%reg),%reg}
  2642. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2643. begin
  2644. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2645. if p = hp2 then
  2646. RemoveCurrentp(p)
  2647. else
  2648. RemoveInstruction(hp2);
  2649. end;
  2650. Result := True;
  2651. Exit;
  2652. end;
  2653. end;
  2654. end;
  2655. end;
  2656. end;
  2657. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2658. begin
  2659. Result := False;
  2660. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2661. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2662. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2663. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2664. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2665. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2666. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2667. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2668. begin
  2669. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2670. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2671. Result := True;
  2672. end;
  2673. end;
  2674. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2675. var
  2676. hp1, hp2, hp3, hp4: tai;
  2677. DoOptimisation, TempBool: Boolean;
  2678. {$ifdef x86_64}
  2679. NewConst: TCGInt;
  2680. {$endif x86_64}
  2681. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2682. begin
  2683. if taicpu(hp1).opcode = signed_movop then
  2684. begin
  2685. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2686. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2687. end
  2688. else
  2689. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2690. end;
  2691. function TryConstMerge(var p1, p2: tai): Boolean;
  2692. var
  2693. ThisRef: TReference;
  2694. begin
  2695. Result := False;
  2696. ThisRef := taicpu(p2).oper[1]^.ref^;
  2697. { Only permit writes to the stack, since we can guarantee alignment with that }
  2698. if (ThisRef.index = NR_NO) and
  2699. (
  2700. (ThisRef.base = NR_STACK_POINTER_REG) or
  2701. (ThisRef.base = current_procinfo.framepointer)
  2702. ) then
  2703. begin
  2704. case taicpu(p).opsize of
  2705. S_B:
  2706. begin
  2707. { Word writes must be on a 2-byte boundary }
  2708. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2709. begin
  2710. { Reduce offset of second reference to see if it is sequential with the first }
  2711. Dec(ThisRef.offset, 1);
  2712. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2713. begin
  2714. { Make sure the constants aren't represented as a
  2715. negative number, as these won't merge properly }
  2716. taicpu(p1).opsize := S_W;
  2717. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2718. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2719. RemoveInstruction(p2);
  2720. Result := True;
  2721. end;
  2722. end;
  2723. end;
  2724. S_W:
  2725. begin
  2726. { Longword writes must be on a 4-byte boundary }
  2727. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2728. begin
  2729. { Reduce offset of second reference to see if it is sequential with the first }
  2730. Dec(ThisRef.offset, 2);
  2731. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2732. begin
  2733. { Make sure the constants aren't represented as a
  2734. negative number, as these won't merge properly }
  2735. taicpu(p1).opsize := S_L;
  2736. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2737. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2738. RemoveInstruction(p2);
  2739. Result := True;
  2740. end;
  2741. end;
  2742. end;
  2743. {$ifdef x86_64}
  2744. S_L:
  2745. begin
  2746. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2747. see if the constants can be encoded this way. }
  2748. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2749. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2750. { Quadword writes must be on an 8-byte boundary }
  2751. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2752. begin
  2753. { Reduce offset of second reference to see if it is sequential with the first }
  2754. Dec(ThisRef.offset, 4);
  2755. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2756. begin
  2757. { Make sure the constants aren't represented as a
  2758. negative number, as these won't merge properly }
  2759. taicpu(p1).opsize := S_Q;
  2760. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2761. taicpu(p1).oper[0]^.val := NewConst;
  2762. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2763. RemoveInstruction(p2);
  2764. Result := True;
  2765. end;
  2766. end;
  2767. end;
  2768. {$endif x86_64}
  2769. else
  2770. ;
  2771. end;
  2772. end;
  2773. end;
  2774. var
  2775. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2776. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2777. NewSize: topsize; NewOffset: asizeint;
  2778. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2779. SourceRef, TargetRef: TReference;
  2780. MovAligned, MovUnaligned: TAsmOp;
  2781. ThisRef: TReference;
  2782. JumpTracking: TLinkedList;
  2783. begin
  2784. Result:=false;
  2785. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2786. { remove mov reg1,reg1? }
  2787. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2788. then
  2789. begin
  2790. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2791. { take care of the register (de)allocs following p }
  2792. RemoveCurrentP(p, hp1);
  2793. Result:=true;
  2794. exit;
  2795. end;
  2796. { All the next optimisations require a next instruction }
  2797. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2798. Exit;
  2799. { Prevent compiler warnings }
  2800. p_TargetReg := NR_NO;
  2801. if taicpu(p).oper[1]^.typ = top_reg then
  2802. begin
  2803. { Saves on a large number of dereferences }
  2804. p_TargetReg := taicpu(p).oper[1]^.reg;
  2805. { Look for:
  2806. mov %reg1,%reg2
  2807. ??? %reg2,r/m
  2808. Change to:
  2809. mov %reg1,%reg2
  2810. ??? %reg1,r/m
  2811. }
  2812. if taicpu(p).oper[0]^.typ = top_reg then
  2813. begin
  2814. if RegReadByInstruction(p_TargetReg, hp1) and
  2815. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2816. begin
  2817. { A change has occurred, just not in p }
  2818. Result := True;
  2819. TransferUsedRegs(TmpUsedRegs);
  2820. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2821. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2822. { Just in case something didn't get modified (e.g. an
  2823. implicit register) }
  2824. not RegReadByInstruction(p_TargetReg, hp1) then
  2825. begin
  2826. { We can remove the original MOV }
  2827. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2828. RemoveCurrentp(p, hp1);
  2829. { UsedRegs got updated by RemoveCurrentp }
  2830. Result := True;
  2831. Exit;
  2832. end;
  2833. { If we know a MOV instruction has become a null operation, we might as well
  2834. get rid of it now to save time. }
  2835. if (taicpu(hp1).opcode = A_MOV) and
  2836. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2837. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2838. { Just being a register is enough to confirm it's a null operation }
  2839. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2840. begin
  2841. Result := True;
  2842. { Speed-up to reduce a pipeline stall... if we had something like...
  2843. movl %eax,%edx
  2844. movw %dx,%ax
  2845. ... the second instruction would change to movw %ax,%ax, but
  2846. given that it is now %ax that's active rather than %eax,
  2847. penalties might occur due to a partial register write, so instead,
  2848. change it to a MOVZX instruction when optimising for speed.
  2849. }
  2850. if not (cs_opt_size in current_settings.optimizerswitches) and
  2851. IsMOVZXAcceptable and
  2852. (taicpu(hp1).opsize < taicpu(p).opsize)
  2853. {$ifdef x86_64}
  2854. { operations already implicitly set the upper 64 bits to zero }
  2855. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2856. {$endif x86_64}
  2857. then
  2858. begin
  2859. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2860. case taicpu(p).opsize of
  2861. S_W:
  2862. if taicpu(hp1).opsize = S_B then
  2863. taicpu(hp1).opsize := S_BL
  2864. else
  2865. InternalError(2020012911);
  2866. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2867. case taicpu(hp1).opsize of
  2868. S_B:
  2869. taicpu(hp1).opsize := S_BL;
  2870. S_W:
  2871. taicpu(hp1).opsize := S_WL;
  2872. else
  2873. InternalError(2020012912);
  2874. end;
  2875. else
  2876. InternalError(2020012910);
  2877. end;
  2878. taicpu(hp1).opcode := A_MOVZX;
  2879. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2880. end
  2881. else
  2882. begin
  2883. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2884. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2885. RemoveInstruction(hp1);
  2886. { The instruction after what was hp1 is now the immediate next instruction,
  2887. so we can continue to make optimisations if it's present }
  2888. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2889. Exit;
  2890. hp1 := hp2;
  2891. end;
  2892. end;
  2893. end;
  2894. end;
  2895. end;
  2896. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2897. overwrites the original destination register. e.g.
  2898. movl ###,%reg2d
  2899. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2900. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2901. }
  2902. if (taicpu(p).oper[1]^.typ = top_reg) and
  2903. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2904. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2905. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2906. begin
  2907. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2908. begin
  2909. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2910. case taicpu(p).oper[0]^.typ of
  2911. top_const:
  2912. { We have something like:
  2913. movb $x, %regb
  2914. movzbl %regb,%regd
  2915. Change to:
  2916. movl $x, %regd
  2917. }
  2918. begin
  2919. case taicpu(hp1).opsize of
  2920. S_BW:
  2921. begin
  2922. convert_mov_value(A_MOVSX, $FF);
  2923. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2924. taicpu(p).opsize := S_W;
  2925. end;
  2926. S_BL:
  2927. begin
  2928. convert_mov_value(A_MOVSX, $FF);
  2929. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2930. taicpu(p).opsize := S_L;
  2931. end;
  2932. S_WL:
  2933. begin
  2934. convert_mov_value(A_MOVSX, $FFFF);
  2935. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2936. taicpu(p).opsize := S_L;
  2937. end;
  2938. {$ifdef x86_64}
  2939. S_BQ:
  2940. begin
  2941. convert_mov_value(A_MOVSX, $FF);
  2942. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2943. taicpu(p).opsize := S_Q;
  2944. end;
  2945. S_WQ:
  2946. begin
  2947. convert_mov_value(A_MOVSX, $FFFF);
  2948. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2949. taicpu(p).opsize := S_Q;
  2950. end;
  2951. S_LQ:
  2952. begin
  2953. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2954. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2955. taicpu(p).opsize := S_Q;
  2956. end;
  2957. {$endif x86_64}
  2958. else
  2959. { If hp1 was a MOV instruction, it should have been
  2960. optimised already }
  2961. InternalError(2020021001);
  2962. end;
  2963. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result := True;
  2966. Exit;
  2967. end;
  2968. top_ref:
  2969. begin
  2970. { We have something like:
  2971. movb mem, %regb
  2972. movzbl %regb,%regd
  2973. Change to:
  2974. movzbl mem, %regd
  2975. }
  2976. ThisRef := taicpu(p).oper[0]^.ref^;
  2977. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2978. begin
  2979. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2980. taicpu(hp1).loadref(0, ThisRef);
  2981. { Make sure any registers in the references are properly tracked }
  2982. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2983. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2984. if (ThisRef.index <> NR_NO) then
  2985. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2986. RemoveCurrentP(p, hp1);
  2987. Result := True;
  2988. Exit;
  2989. end;
  2990. end;
  2991. else
  2992. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2993. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2994. Exit;
  2995. end;
  2996. end
  2997. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2998. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2999. optimised }
  3000. else
  3001. begin
  3002. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3003. RemoveCurrentP(p, hp1);
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. end;
  3008. if (taicpu(hp1).opcode = A_AND) and
  3009. (taicpu(p).oper[1]^.typ = top_reg) and
  3010. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3011. begin
  3012. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3013. begin
  3014. case taicpu(p).opsize of
  3015. S_L:
  3016. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3017. begin
  3018. { Optimize out:
  3019. mov x, %reg
  3020. and ffffffffh, %reg
  3021. }
  3022. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3023. RemoveInstruction(hp1);
  3024. Result:=true;
  3025. exit;
  3026. end;
  3027. S_Q: { TODO: Confirm if this is even possible }
  3028. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3029. begin
  3030. { Optimize out:
  3031. mov x, %reg
  3032. and ffffffffffffffffh, %reg
  3033. }
  3034. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3035. RemoveInstruction(hp1);
  3036. Result:=true;
  3037. exit;
  3038. end;
  3039. else
  3040. ;
  3041. end;
  3042. if (
  3043. (taicpu(p).oper[0]^.typ=top_reg) or
  3044. (
  3045. (taicpu(p).oper[0]^.typ=top_ref) and
  3046. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3047. )
  3048. ) and
  3049. GetNextInstruction(hp1,hp2) and
  3050. MatchInstruction(hp2,A_TEST,[]) and
  3051. (
  3052. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3053. (
  3054. { If the register being tested is smaller than the one
  3055. that received a bitwise AND, permit it if the constant
  3056. fits into the smaller size }
  3057. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3058. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3059. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3060. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3061. (
  3062. (
  3063. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3064. (taicpu(hp1).oper[0]^.val <= $FF)
  3065. ) or
  3066. (
  3067. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3068. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3069. {$ifdef x86_64}
  3070. ) or
  3071. (
  3072. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3073. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3074. {$endif x86_64}
  3075. )
  3076. )
  3077. )
  3078. ) and
  3079. (
  3080. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3081. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3082. ) and
  3083. GetNextInstruction(hp2,hp3) and
  3084. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3085. (taicpu(hp3).condition in [C_E,C_NE]) then
  3086. begin
  3087. TransferUsedRegs(TmpUsedRegs);
  3088. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3089. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3090. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3091. begin
  3092. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3093. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3094. taicpu(hp1).opcode:=A_TEST;
  3095. { Shrink the TEST instruction down to the smallest possible size }
  3096. case taicpu(hp1).oper[0]^.val of
  3097. 0..255:
  3098. if (taicpu(hp1).opsize <> S_B)
  3099. {$ifndef x86_64}
  3100. and (
  3101. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3102. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3103. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3104. )
  3105. {$endif x86_64}
  3106. then
  3107. begin
  3108. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3109. { Only print debug message if the TEST instruction
  3110. is a different size before and after }
  3111. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3112. taicpu(hp1).opsize := S_B;
  3113. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3114. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3115. end;
  3116. 256..65535:
  3117. if (taicpu(hp1).opsize <> S_W) then
  3118. begin
  3119. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3120. { Only print debug message if the TEST instruction
  3121. is a different size before and after }
  3122. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3123. taicpu(hp1).opsize := S_W;
  3124. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3125. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3126. end;
  3127. {$ifdef x86_64}
  3128. 65536..$7FFFFFFF:
  3129. if (taicpu(hp1).opsize <> S_L) then
  3130. begin
  3131. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3132. { Only print debug message if the TEST instruction
  3133. is a different size before and after }
  3134. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3135. taicpu(hp1).opsize := S_L;
  3136. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3137. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3138. end;
  3139. {$endif x86_64}
  3140. else
  3141. ;
  3142. end;
  3143. RemoveInstruction(hp2);
  3144. RemoveCurrentP(p, hp1);
  3145. Result:=true;
  3146. exit;
  3147. end;
  3148. end;
  3149. end
  3150. else if IsMOVZXAcceptable and
  3151. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3152. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3153. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3154. then
  3155. begin
  3156. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3157. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3158. case taicpu(p).opsize of
  3159. S_B:
  3160. if (taicpu(hp1).oper[0]^.val = $ff) then
  3161. begin
  3162. { Convert:
  3163. movb x, %regl movb x, %regl
  3164. andw ffh, %regw andl ffh, %regd
  3165. To:
  3166. movzbw x, %regd movzbl x, %regd
  3167. (Identical registers, just different sizes)
  3168. }
  3169. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3170. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3171. case taicpu(hp1).opsize of
  3172. S_W: NewSize := S_BW;
  3173. S_L: NewSize := S_BL;
  3174. {$ifdef x86_64}
  3175. S_Q: NewSize := S_BQ;
  3176. {$endif x86_64}
  3177. else
  3178. InternalError(2018011510);
  3179. end;
  3180. end
  3181. else
  3182. NewSize := S_NO;
  3183. S_W:
  3184. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3185. begin
  3186. { Convert:
  3187. movw x, %regw
  3188. andl ffffh, %regd
  3189. To:
  3190. movzwl x, %regd
  3191. (Identical registers, just different sizes)
  3192. }
  3193. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3194. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3195. case taicpu(hp1).opsize of
  3196. S_L: NewSize := S_WL;
  3197. {$ifdef x86_64}
  3198. S_Q: NewSize := S_WQ;
  3199. {$endif x86_64}
  3200. else
  3201. InternalError(2018011511);
  3202. end;
  3203. end
  3204. else
  3205. NewSize := S_NO;
  3206. else
  3207. NewSize := S_NO;
  3208. end;
  3209. if NewSize <> S_NO then
  3210. begin
  3211. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3212. { The actual optimization }
  3213. taicpu(p).opcode := A_MOVZX;
  3214. taicpu(p).changeopsize(NewSize);
  3215. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3216. { Safeguard if "and" is followed by a conditional command }
  3217. TransferUsedRegs(TmpUsedRegs);
  3218. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3219. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3220. begin
  3221. { At this point, the "and" command is effectively equivalent to
  3222. "test %reg,%reg". This will be handled separately by the
  3223. Peephole Optimizer. [Kit] }
  3224. DebugMsg(SPeepholeOptimization + PreMessage +
  3225. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3226. end
  3227. else
  3228. begin
  3229. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3230. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3231. RemoveInstruction(hp1);
  3232. end;
  3233. Result := True;
  3234. Exit;
  3235. end;
  3236. end;
  3237. end;
  3238. if (taicpu(hp1).opcode = A_OR) and
  3239. (taicpu(p).oper[1]^.typ = top_reg) and
  3240. MatchOperand(taicpu(p).oper[0]^, 0) and
  3241. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3242. begin
  3243. { mov 0, %reg
  3244. or ###,%reg
  3245. Change to (only if the flags are not used):
  3246. mov ###,%reg
  3247. }
  3248. TransferUsedRegs(TmpUsedRegs);
  3249. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3250. DoOptimisation := True;
  3251. { Even if the flags are used, we might be able to do the optimisation
  3252. if the conditions are predictable }
  3253. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3254. begin
  3255. { Only perform if ### = %reg (the same register) or equal to 0,
  3256. so %reg is guaranteed to still have a value of zero }
  3257. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3258. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3259. begin
  3260. hp2 := hp1;
  3261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3262. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3263. GetNextInstruction(hp2, hp3) do
  3264. begin
  3265. { Don't continue modifying if the flags state is getting changed }
  3266. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3267. Break;
  3268. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3269. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3270. begin
  3271. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3272. begin
  3273. { Condition is always true }
  3274. case taicpu(hp3).opcode of
  3275. A_Jcc:
  3276. begin
  3277. { Check for jump shortcuts before we destroy the condition }
  3278. hp4 := hp3;
  3279. DoJumpOptimizations(hp3, TempBool);
  3280. { Make sure hp3 hasn't changed }
  3281. if (hp4 = hp3) then
  3282. begin
  3283. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3284. MakeUnconditional(taicpu(hp3));
  3285. end;
  3286. Result := True;
  3287. end;
  3288. A_CMOVcc:
  3289. begin
  3290. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3291. taicpu(hp3).opcode := A_MOV;
  3292. taicpu(hp3).condition := C_None;
  3293. Result := True;
  3294. end;
  3295. A_SETcc:
  3296. begin
  3297. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3298. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3299. taicpu(hp3).opcode := A_MOV;
  3300. taicpu(hp3).ops := 2;
  3301. taicpu(hp3).condition := C_None;
  3302. taicpu(hp3).opsize := S_B;
  3303. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3304. taicpu(hp3).loadconst(0, 1);
  3305. Result := True;
  3306. end;
  3307. else
  3308. InternalError(2021090701);
  3309. end;
  3310. end
  3311. 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
  3312. begin
  3313. { Condition is always false }
  3314. case taicpu(hp3).opcode of
  3315. A_Jcc:
  3316. begin
  3317. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3318. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3319. RemoveInstruction(hp3);
  3320. Result := True;
  3321. { Since hp3 was deleted, hp2 must not be updated }
  3322. Continue;
  3323. end;
  3324. A_CMOVcc:
  3325. begin
  3326. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3327. RemoveInstruction(hp3);
  3328. Result := True;
  3329. { Since hp3 was deleted, hp2 must not be updated }
  3330. Continue;
  3331. end;
  3332. A_SETcc:
  3333. begin
  3334. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3335. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3336. taicpu(hp3).opcode := A_MOV;
  3337. taicpu(hp3).ops := 2;
  3338. taicpu(hp3).condition := C_None;
  3339. taicpu(hp3).opsize := S_B;
  3340. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3341. taicpu(hp3).loadconst(0, 0);
  3342. Result := True;
  3343. end;
  3344. else
  3345. InternalError(2021090702);
  3346. end;
  3347. end
  3348. else
  3349. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3350. DoOptimisation := False;
  3351. end;
  3352. hp2 := hp3;
  3353. end;
  3354. { Flags are still in use - don't optimise }
  3355. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3356. DoOptimisation := False;
  3357. end
  3358. else
  3359. DoOptimisation := False;
  3360. end;
  3361. if DoOptimisation then
  3362. begin
  3363. {$ifdef x86_64}
  3364. { OR only supports 32-bit sign-extended constants for 64-bit
  3365. instructions, so compensate for this if the constant is
  3366. encoded as a value greater than or equal to 2^31 }
  3367. if (taicpu(hp1).opsize = S_Q) and
  3368. (taicpu(hp1).oper[0]^.typ = top_const) and
  3369. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3370. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3371. {$endif x86_64}
  3372. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3373. taicpu(hp1).opcode := A_MOV;
  3374. RemoveCurrentP(p, hp1);
  3375. Result := True;
  3376. Exit;
  3377. end;
  3378. end;
  3379. { Next instruction is also a MOV ? }
  3380. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3381. begin
  3382. if MatchOpType(taicpu(p), top_const, top_ref) and
  3383. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3384. TryConstMerge(p, hp1) then
  3385. begin
  3386. Result := True;
  3387. { In case we have four byte writes in a row, check for 2 more
  3388. right now so we don't have to wait for another iteration of
  3389. pass 1
  3390. }
  3391. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3392. case taicpu(p).opsize of
  3393. S_W:
  3394. begin
  3395. if GetNextInstruction(p, hp1) and
  3396. MatchInstruction(hp1, A_MOV, [S_B]) and
  3397. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3398. GetNextInstruction(hp1, hp2) and
  3399. MatchInstruction(hp2, A_MOV, [S_B]) and
  3400. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3401. { Try to merge the two bytes }
  3402. TryConstMerge(hp1, hp2) then
  3403. { Now try to merge the two words (hp2 will get deleted) }
  3404. TryConstMerge(p, hp1);
  3405. end;
  3406. S_L:
  3407. begin
  3408. { Though this only really benefits x86_64 and not i386, it
  3409. gets a potential optimisation done faster and hence
  3410. reduces the number of times OptPass1MOV is entered }
  3411. if GetNextInstruction(p, hp1) and
  3412. MatchInstruction(hp1, A_MOV, [S_W]) and
  3413. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3414. GetNextInstruction(hp1, hp2) and
  3415. MatchInstruction(hp2, A_MOV, [S_W]) and
  3416. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3417. { Try to merge the two words }
  3418. TryConstMerge(hp1, hp2) then
  3419. { This will always fail on i386, so don't bother
  3420. calling it unless we're doing x86_64 }
  3421. {$ifdef x86_64}
  3422. { Now try to merge the two longwords (hp2 will get deleted) }
  3423. TryConstMerge(p, hp1)
  3424. {$endif x86_64}
  3425. ;
  3426. end;
  3427. else
  3428. ;
  3429. end;
  3430. Exit;
  3431. end;
  3432. if (taicpu(p).oper[1]^.typ = top_reg) and
  3433. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3434. begin
  3435. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3436. TransferUsedRegs(TmpUsedRegs);
  3437. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3438. { we have
  3439. mov x, %treg
  3440. mov %treg, y
  3441. }
  3442. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3443. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3444. { we've got
  3445. mov x, %treg
  3446. mov %treg, y
  3447. with %treg is not used after }
  3448. case taicpu(p).oper[0]^.typ Of
  3449. { top_reg is covered by DeepMOVOpt }
  3450. top_const:
  3451. begin
  3452. { change
  3453. mov const, %treg
  3454. mov %treg, y
  3455. to
  3456. mov const, y
  3457. }
  3458. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3459. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3460. begin
  3461. if taicpu(hp1).oper[1]^.typ=top_reg then
  3462. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3463. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3464. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3465. RemoveInstruction(hp1);
  3466. Result:=true;
  3467. Exit;
  3468. end;
  3469. end;
  3470. top_ref:
  3471. case taicpu(hp1).oper[1]^.typ of
  3472. top_reg:
  3473. begin
  3474. { change
  3475. mov mem, %treg
  3476. mov %treg, %reg
  3477. to
  3478. mov mem, %reg"
  3479. }
  3480. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3481. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3482. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3483. RemoveInstruction(hp1);
  3484. Result:=true;
  3485. Exit;
  3486. end;
  3487. top_ref:
  3488. begin
  3489. {$ifdef x86_64}
  3490. { Look for the following to simplify:
  3491. mov x(mem1), %reg
  3492. mov %reg, y(mem2)
  3493. mov x+8(mem1), %reg
  3494. mov %reg, y+8(mem2)
  3495. Change to:
  3496. movdqu x(mem1), %xmmreg
  3497. movdqu %xmmreg, y(mem2)
  3498. ...but only as long as the memory blocks don't overlap
  3499. }
  3500. SourceRef := taicpu(p).oper[0]^.ref^;
  3501. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3502. if (taicpu(p).opsize = S_Q) and
  3503. GetNextInstruction(hp1, hp2) and
  3504. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3505. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3506. begin
  3507. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3509. Inc(SourceRef.offset, 8);
  3510. if UseAVX then
  3511. begin
  3512. MovAligned := A_VMOVDQA;
  3513. MovUnaligned := A_VMOVDQU;
  3514. end
  3515. else
  3516. begin
  3517. MovAligned := A_MOVDQA;
  3518. MovUnaligned := A_MOVDQU;
  3519. end;
  3520. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3521. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3522. begin
  3523. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3524. Inc(TargetRef.offset, 8);
  3525. if GetNextInstruction(hp2, hp3) and
  3526. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3527. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3528. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3529. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3530. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3531. begin
  3532. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3533. if NewMMReg <> NR_NO then
  3534. begin
  3535. { Remember that the offsets are 8 ahead }
  3536. if ((SourceRef.offset mod 16) = 8) and
  3537. (
  3538. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3539. (SourceRef.base = current_procinfo.framepointer) or
  3540. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3541. ) then
  3542. taicpu(p).opcode := MovAligned
  3543. else
  3544. taicpu(p).opcode := MovUnaligned;
  3545. taicpu(p).opsize := S_XMM;
  3546. taicpu(p).oper[1]^.reg := NewMMReg;
  3547. if ((TargetRef.offset mod 16) = 8) and
  3548. (
  3549. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3550. (TargetRef.base = current_procinfo.framepointer) or
  3551. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3552. ) then
  3553. taicpu(hp1).opcode := MovAligned
  3554. else
  3555. taicpu(hp1).opcode := MovUnaligned;
  3556. taicpu(hp1).opsize := S_XMM;
  3557. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3558. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3559. RemoveInstruction(hp2);
  3560. RemoveInstruction(hp3);
  3561. Result := True;
  3562. Exit;
  3563. end;
  3564. end;
  3565. end
  3566. else
  3567. begin
  3568. { See if the next references are 8 less rather than 8 greater }
  3569. Dec(SourceRef.offset, 16); { -8 the other way }
  3570. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3571. begin
  3572. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3573. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3574. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3575. GetNextInstruction(hp2, hp3) and
  3576. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3577. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3578. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3579. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3580. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3581. begin
  3582. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3583. if NewMMReg <> NR_NO then
  3584. begin
  3585. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3586. if ((SourceRef.offset mod 16) = 0) and
  3587. (
  3588. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3589. (SourceRef.base = current_procinfo.framepointer) or
  3590. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3591. ) then
  3592. taicpu(hp2).opcode := MovAligned
  3593. else
  3594. taicpu(hp2).opcode := MovUnaligned;
  3595. taicpu(hp2).opsize := S_XMM;
  3596. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3597. if ((TargetRef.offset mod 16) = 0) and
  3598. (
  3599. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3600. (TargetRef.base = current_procinfo.framepointer) or
  3601. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3602. ) then
  3603. taicpu(hp3).opcode := MovAligned
  3604. else
  3605. taicpu(hp3).opcode := MovUnaligned;
  3606. taicpu(hp3).opsize := S_XMM;
  3607. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3608. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3609. RemoveInstruction(hp1);
  3610. RemoveCurrentP(p, hp2);
  3611. Result := True;
  3612. Exit;
  3613. end;
  3614. end;
  3615. end;
  3616. end;
  3617. end;
  3618. {$endif x86_64}
  3619. end;
  3620. else
  3621. { The write target should be a reg or a ref }
  3622. InternalError(2021091601);
  3623. end;
  3624. else
  3625. ;
  3626. end
  3627. else
  3628. { %treg is used afterwards, but all eventualities
  3629. other than the first MOV instruction being a constant
  3630. are covered by DeepMOVOpt, so only check for that }
  3631. if (taicpu(p).oper[0]^.typ = top_const) and
  3632. (
  3633. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3634. not (cs_opt_size in current_settings.optimizerswitches) or
  3635. (taicpu(hp1).opsize = S_B)
  3636. ) and
  3637. (
  3638. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3639. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3640. ) then
  3641. begin
  3642. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3643. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3644. end;
  3645. end;
  3646. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3647. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3648. { mov reg1, mem1 or mov mem1, reg1
  3649. mov mem2, reg2 mov reg2, mem2}
  3650. begin
  3651. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3652. { mov reg1, mem1 or mov mem1, reg1
  3653. mov mem2, reg1 mov reg2, mem1}
  3654. begin
  3655. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3656. { Removes the second statement from
  3657. mov reg1, mem1/reg2
  3658. mov mem1/reg2, reg1 }
  3659. begin
  3660. if taicpu(p).oper[0]^.typ=top_reg then
  3661. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3662. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3663. RemoveInstruction(hp1);
  3664. Result:=true;
  3665. exit;
  3666. end
  3667. else
  3668. begin
  3669. TransferUsedRegs(TmpUsedRegs);
  3670. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3671. if (taicpu(p).oper[1]^.typ = top_ref) and
  3672. { mov reg1, mem1
  3673. mov mem2, reg1 }
  3674. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3675. GetNextInstruction(hp1, hp2) and
  3676. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3677. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3678. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3679. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3680. { change to
  3681. mov reg1, mem1 mov reg1, mem1
  3682. mov mem2, reg1 cmp reg1, mem2
  3683. cmp mem1, reg1
  3684. }
  3685. begin
  3686. RemoveInstruction(hp2);
  3687. taicpu(hp1).opcode := A_CMP;
  3688. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3689. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3690. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3691. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3692. end;
  3693. end;
  3694. end
  3695. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3696. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3697. begin
  3698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3699. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3700. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3701. end
  3702. else
  3703. begin
  3704. TransferUsedRegs(TmpUsedRegs);
  3705. if GetNextInstruction(hp1, hp2) and
  3706. MatchOpType(taicpu(p),top_ref,top_reg) and
  3707. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3708. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3709. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3710. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3711. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3712. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3713. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3714. { mov mem1, %reg1
  3715. mov %reg1, mem2
  3716. mov mem2, reg2
  3717. to:
  3718. mov mem1, reg2
  3719. mov reg2, mem2}
  3720. begin
  3721. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3722. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3723. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3724. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3725. RemoveInstruction(hp2);
  3726. Result := True;
  3727. end
  3728. {$ifdef i386}
  3729. { this is enabled for i386 only, as the rules to create the reg sets below
  3730. are too complicated for x86-64, so this makes this code too error prone
  3731. on x86-64
  3732. }
  3733. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3734. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3735. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3736. { mov mem1, reg1 mov mem1, reg1
  3737. mov reg1, mem2 mov reg1, mem2
  3738. mov mem2, reg2 mov mem2, reg1
  3739. to: to:
  3740. mov mem1, reg1 mov mem1, reg1
  3741. mov mem1, reg2 mov reg1, mem2
  3742. mov reg1, mem2
  3743. or (if mem1 depends on reg1
  3744. and/or if mem2 depends on reg2)
  3745. to:
  3746. mov mem1, reg1
  3747. mov reg1, mem2
  3748. mov reg1, reg2
  3749. }
  3750. begin
  3751. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3752. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3753. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3754. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3755. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3756. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3757. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3758. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3759. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3760. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3761. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3762. end
  3763. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3764. begin
  3765. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3766. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3767. end
  3768. else
  3769. begin
  3770. RemoveInstruction(hp2);
  3771. end
  3772. {$endif i386}
  3773. ;
  3774. end;
  3775. end
  3776. { movl [mem1],reg1
  3777. movl [mem1],reg2
  3778. to
  3779. movl [mem1],reg1
  3780. movl reg1,reg2
  3781. }
  3782. else if not CheckMovMov2MovMov2(p, hp1) and
  3783. { movl const1,[mem1]
  3784. movl [mem1],reg1
  3785. to
  3786. movl const1,reg1
  3787. movl reg1,[mem1]
  3788. }
  3789. MatchOpType(Taicpu(p),top_const,top_ref) and
  3790. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3792. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3793. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3794. begin
  3795. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3796. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3797. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3798. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3799. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3800. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3801. Result:=true;
  3802. exit;
  3803. end;
  3804. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3805. { Change:
  3806. movl %reg1,%reg2
  3807. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3808. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3809. To:
  3810. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3811. movl x(%reg1),%reg1
  3812. movl %reg1,%regX
  3813. }
  3814. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3815. begin
  3816. p_SourceReg := taicpu(p).oper[0]^.reg;
  3817. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3818. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3819. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3820. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3821. GetNextInstruction(hp1, hp2) and
  3822. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3823. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3824. begin
  3825. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3826. if RegInRef(p_TargetReg, SourceRef) and
  3827. { If %reg1 also appears in the second reference, then it will
  3828. not refer to the same memory block as the first reference }
  3829. not RegInRef(p_SourceReg, SourceRef) then
  3830. begin
  3831. { Check to see if the references match if %reg2 is changed to %reg1 }
  3832. if SourceRef.base = p_TargetReg then
  3833. SourceRef.base := p_SourceReg;
  3834. if SourceRef.index = p_TargetReg then
  3835. SourceRef.index := p_SourceReg;
  3836. { RefsEqual also checks to ensure both references are non-volatile }
  3837. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3838. begin
  3839. taicpu(hp2).loadreg(0, p_SourceReg);
  3840. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3841. Result := True;
  3842. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3843. begin
  3844. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3845. RemoveCurrentP(p, hp1);
  3846. Exit;
  3847. end
  3848. else
  3849. begin
  3850. { Check to see if %reg2 is no longer in use }
  3851. TransferUsedRegs(TmpUsedRegs);
  3852. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3853. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3854. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3855. begin
  3856. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3857. RemoveCurrentP(p, hp1);
  3858. Exit;
  3859. end;
  3860. end;
  3861. { If we reach this point, p and hp1 weren't actually modified,
  3862. so we can do a bit more work on this pass }
  3863. end;
  3864. end;
  3865. end;
  3866. end;
  3867. end;
  3868. {$ifdef x86_64}
  3869. { Change:
  3870. movl %reg1l,%reg2l
  3871. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3872. To:
  3873. movl %reg1l,%reg2l
  3874. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3875. If %reg1 = %reg3, convert to:
  3876. movl %reg1l,%reg2l
  3877. andl %reg1l,%reg1l
  3878. }
  3879. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3880. MatchOpType(taicpu(p), top_reg, top_reg) and
  3881. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3882. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3883. begin
  3884. TransferUsedRegs(TmpUsedRegs);
  3885. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3886. taicpu(hp1).opsize := S_L;
  3887. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3888. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3889. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3890. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3891. begin
  3892. { %reg1 = %reg3 }
  3893. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3894. taicpu(hp1).opcode := A_AND;
  3895. end
  3896. else
  3897. begin
  3898. { %reg1 <> %reg3 }
  3899. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3900. end;
  3901. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3902. begin
  3903. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3904. RemoveCurrentP(p, hp1);
  3905. Result := True;
  3906. Exit;
  3907. end
  3908. else
  3909. begin
  3910. { Initial instruction wasn't actually changed }
  3911. Include(OptsToCheck, aoc_ForceNewIteration);
  3912. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3913. appears below since %reg1 has technically changed }
  3914. if taicpu(hp1).opcode = A_AND then
  3915. Exit;
  3916. end;
  3917. end;
  3918. {$endif x86_64}
  3919. { search further than the next instruction for a mov (as long as it's not a jump) }
  3920. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3921. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3922. (taicpu(p).oper[1]^.typ = top_reg) and
  3923. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3924. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3925. begin
  3926. { we work with hp2 here, so hp1 can be still used later on when
  3927. checking for GetNextInstruction_p }
  3928. hp3 := hp1;
  3929. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3930. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3931. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3932. TransferUsedRegs(TmpUsedRegs);
  3933. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3934. if NotFirstIteration then
  3935. JumpTracking := TLinkedList.Create
  3936. else
  3937. JumpTracking := nil;
  3938. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3939. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3940. (hp2.typ=ait_instruction) do
  3941. begin
  3942. case taicpu(hp2).opcode of
  3943. A_POP:
  3944. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3945. begin
  3946. if not CrossJump and
  3947. not RegUsedBetween(p_TargetReg, p, hp2) then
  3948. begin
  3949. { We can remove the original MOV since the register
  3950. wasn't used between it and its popping from the stack }
  3951. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3952. RemoveCurrentp(p, hp1);
  3953. Result := True;
  3954. JumpTracking.Free;
  3955. Exit;
  3956. end;
  3957. { Can't go any further }
  3958. Break;
  3959. end;
  3960. A_MOV:
  3961. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3962. ((taicpu(p).oper[0]^.typ=top_const) or
  3963. ((taicpu(p).oper[0]^.typ=top_reg) and
  3964. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3965. )
  3966. ) then
  3967. begin
  3968. { we have
  3969. mov x, %treg
  3970. mov %treg, y
  3971. }
  3972. { We don't need to call UpdateUsedRegs for every instruction between
  3973. p and hp2 because the register we're concerned about will not
  3974. become deallocated (otherwise GetNextInstructionUsingReg would
  3975. have stopped at an earlier instruction). [Kit] }
  3976. TempRegUsed :=
  3977. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3978. RegReadByInstruction(p_TargetReg, hp3) or
  3979. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3980. case taicpu(p).oper[0]^.typ Of
  3981. top_reg:
  3982. begin
  3983. { change
  3984. mov %reg, %treg
  3985. mov %treg, y
  3986. to
  3987. mov %reg, y
  3988. }
  3989. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3990. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3991. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3992. begin
  3993. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3994. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3995. if TempRegUsed then
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3998. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3999. { Set the start of the next GetNextInstructionUsingRegCond search
  4000. to start at the entry right before hp2 (which is about to be removed) }
  4001. hp3 := tai(hp2.Previous);
  4002. RemoveInstruction(hp2);
  4003. Include(OptsToCheck, aoc_ForceNewIteration);
  4004. { See if there's more we can optimise }
  4005. Continue;
  4006. end
  4007. else
  4008. begin
  4009. RemoveInstruction(hp2);
  4010. { We can remove the original MOV too }
  4011. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4012. RemoveCurrentP(p, hp1);
  4013. Result:=true;
  4014. JumpTracking.Free;
  4015. Exit;
  4016. end;
  4017. end
  4018. else
  4019. begin
  4020. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4021. taicpu(hp2).loadReg(0, p_SourceReg);
  4022. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4023. { Check to see if the register also appears in the reference }
  4024. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4025. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4026. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4027. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4028. begin
  4029. { Don't remove the first instruction if the temporary register is in use }
  4030. if not TempRegUsed then
  4031. begin
  4032. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4033. RemoveCurrentP(p, hp1);
  4034. Result:=true;
  4035. JumpTracking.Free;
  4036. Exit;
  4037. end;
  4038. { No need to set Result to True here. If there's another instruction later
  4039. on that can be optimised, it will be detected when the main Pass 1 loop
  4040. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4041. hp3 := hp2;
  4042. Continue;
  4043. end;
  4044. end;
  4045. end;
  4046. top_const:
  4047. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4048. begin
  4049. { change
  4050. mov const, %treg
  4051. mov %treg, y
  4052. to
  4053. mov const, y
  4054. }
  4055. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4056. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4057. begin
  4058. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4059. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4060. if TempRegUsed then
  4061. begin
  4062. { Don't remove the first instruction if the temporary register is in use }
  4063. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4064. { No need to set Result to True. If there's another instruction later on
  4065. that can be optimised, it will be detected when the main Pass 1 loop
  4066. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4067. end
  4068. else
  4069. begin
  4070. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4071. RemoveCurrentP(p, hp1);
  4072. Result:=true;
  4073. Exit;
  4074. end;
  4075. end;
  4076. end;
  4077. else
  4078. Internalerror(2019103001);
  4079. end;
  4080. end
  4081. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4082. begin
  4083. if not CrossJump and
  4084. not RegUsedBetween(p_TargetReg, p, hp2) and
  4085. not RegReadByInstruction(p_TargetReg, hp2) then
  4086. begin
  4087. { Register is not used before it is overwritten }
  4088. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4089. RemoveCurrentp(p, hp1);
  4090. Result := True;
  4091. Exit;
  4092. end;
  4093. if (taicpu(p).oper[0]^.typ = top_const) and
  4094. (taicpu(hp2).oper[0]^.typ = top_const) then
  4095. begin
  4096. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4097. begin
  4098. { Same value - register hasn't changed }
  4099. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4100. RemoveInstruction(hp2);
  4101. Include(OptsToCheck, aoc_ForceNewIteration);
  4102. { See if there's more we can optimise }
  4103. Continue;
  4104. end;
  4105. end;
  4106. {$ifdef x86_64}
  4107. end
  4108. { Change:
  4109. movl %reg1l,%reg2l
  4110. ...
  4111. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4112. To:
  4113. movl %reg1l,%reg2l
  4114. ...
  4115. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4116. If %reg1 = %reg3, convert to:
  4117. movl %reg1l,%reg2l
  4118. ...
  4119. andl %reg1l,%reg1l
  4120. }
  4121. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4122. (taicpu(p).oper[0]^.typ = top_reg) and
  4123. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4124. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4125. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4126. begin
  4127. TempRegUsed :=
  4128. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4129. RegReadByInstruction(p_TargetReg, hp3) or
  4130. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4131. taicpu(hp2).opsize := S_L;
  4132. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4133. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4134. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4135. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4136. begin
  4137. { %reg1 = %reg3 }
  4138. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4139. taicpu(hp2).opcode := A_AND;
  4140. end
  4141. else
  4142. begin
  4143. { %reg1 <> %reg3 }
  4144. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4145. end;
  4146. if not TempRegUsed then
  4147. begin
  4148. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4149. RemoveCurrentP(p, hp1);
  4150. Result := True;
  4151. Exit;
  4152. end
  4153. else
  4154. begin
  4155. { Initial instruction wasn't actually changed }
  4156. Include(OptsToCheck, aoc_ForceNewIteration);
  4157. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4158. appears below since %reg1 has technically changed }
  4159. if taicpu(hp2).opcode = A_AND then
  4160. Break;
  4161. end;
  4162. {$endif x86_64}
  4163. end
  4164. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4165. GetNextInstruction(hp2, hp4) and
  4166. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4167. { Optimise the following first:
  4168. movl [mem1],reg1
  4169. movl [mem1],reg2
  4170. to
  4171. movl [mem1],reg1
  4172. movl reg1,reg2
  4173. If [mem1] contains the target register and reg1 is the
  4174. the source register, this optimisation will get missed
  4175. and produce less efficient code later on.
  4176. }
  4177. if CheckMovMov2MovMov2(hp2, hp4) then
  4178. { Initial instruction wasn't actually changed }
  4179. Include(OptsToCheck, aoc_ForceNewIteration);
  4180. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4181. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4182. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4183. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4184. begin
  4185. {
  4186. Change from:
  4187. mov ###, %reg
  4188. ...
  4189. movs/z %reg,%reg (Same register, just different sizes)
  4190. To:
  4191. movs/z ###, %reg (Longer version)
  4192. ...
  4193. (remove)
  4194. }
  4195. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4196. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4197. { Keep the first instruction as mov if ### is a constant }
  4198. if taicpu(p).oper[0]^.typ = top_const then
  4199. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4200. else
  4201. begin
  4202. taicpu(p).opcode := taicpu(hp2).opcode;
  4203. taicpu(p).opsize := taicpu(hp2).opsize;
  4204. end;
  4205. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4206. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4207. RemoveInstruction(hp2);
  4208. Result := True;
  4209. JumpTracking.Free;
  4210. Exit;
  4211. end;
  4212. else
  4213. { Move down to the if-block below };
  4214. end;
  4215. { Also catches MOV/S/Z instructions that aren't modified }
  4216. if taicpu(p).oper[0]^.typ = top_reg then
  4217. begin
  4218. p_SourceReg := taicpu(p).oper[0]^.reg;
  4219. if
  4220. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4221. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4222. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4223. begin
  4224. Result := True;
  4225. { Just in case something didn't get modified (e.g. an
  4226. implicit register). Also, if it does read from this
  4227. register, then there's no longer an advantage to
  4228. changing the register on subsequent instructions.}
  4229. if not RegReadByInstruction(p_TargetReg, hp2) then
  4230. begin
  4231. { If a conditional jump was crossed, do not delete
  4232. the original MOV no matter what }
  4233. if not CrossJump and
  4234. { RegEndOfLife returns True if the register is
  4235. deallocated before the next instruction or has
  4236. been loaded with a new value }
  4237. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4238. begin
  4239. { We can remove the original MOV }
  4240. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4241. RemoveCurrentp(p, hp1);
  4242. JumpTracking.Free;
  4243. Result := True;
  4244. Exit;
  4245. end;
  4246. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4247. begin
  4248. { See if there's more we can optimise }
  4249. hp3 := hp2;
  4250. Continue;
  4251. end;
  4252. end;
  4253. end;
  4254. end;
  4255. { Break out of the while loop under normal circumstances }
  4256. Break;
  4257. end;
  4258. JumpTracking.Free;
  4259. end;
  4260. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4261. (taicpu(p).oper[1]^.typ = top_reg) and
  4262. (taicpu(p).opsize = S_L) and
  4263. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4264. (hp2.typ = ait_instruction) and
  4265. (taicpu(hp2).opcode = A_AND) and
  4266. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4267. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4268. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4269. ) then
  4270. begin
  4271. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4272. begin
  4273. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4274. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4275. begin
  4276. { Optimize out:
  4277. mov x, %reg
  4278. and ffffffffh, %reg
  4279. }
  4280. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4281. RemoveInstruction(hp2);
  4282. Result:=true;
  4283. exit;
  4284. end;
  4285. end;
  4286. end;
  4287. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4288. x >= RetOffset) as it doesn't do anything (it writes either to a
  4289. parameter or to the temporary storage room for the function
  4290. result)
  4291. }
  4292. if IsExitCode(hp1) and
  4293. (taicpu(p).oper[1]^.typ = top_ref) and
  4294. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4295. (
  4296. (
  4297. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4298. not (
  4299. assigned(current_procinfo.procdef.funcretsym) and
  4300. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4301. )
  4302. ) or
  4303. { Also discard writes to the stack that are below the base pointer,
  4304. as this is temporary storage rather than a function result on the
  4305. stack, say. }
  4306. (
  4307. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4308. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4309. )
  4310. ) then
  4311. begin
  4312. RemoveCurrentp(p, hp1);
  4313. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4314. RemoveLastDeallocForFuncRes(p);
  4315. Result:=true;
  4316. exit;
  4317. end;
  4318. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4319. begin
  4320. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4321. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4322. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4323. begin
  4324. { change
  4325. mov reg1, mem1
  4326. test/cmp x, mem1
  4327. to
  4328. mov reg1, mem1
  4329. test/cmp x, reg1
  4330. }
  4331. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4332. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4333. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4334. Result := True;
  4335. Exit;
  4336. end;
  4337. if DoMovCmpMemOpt(p, hp1) then
  4338. begin
  4339. Result := True;
  4340. Exit;
  4341. end;
  4342. end;
  4343. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4344. { If the flags register is in use, don't change the instruction to an
  4345. ADD otherwise this will scramble the flags. [Kit] }
  4346. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4347. begin
  4348. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4349. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4350. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4351. ) or
  4352. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4353. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4354. )
  4355. ) then
  4356. { mov reg1,ref
  4357. lea reg2,[reg1,reg2]
  4358. to
  4359. add reg2,ref}
  4360. begin
  4361. TransferUsedRegs(TmpUsedRegs);
  4362. { reg1 may not be used afterwards }
  4363. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4364. begin
  4365. Taicpu(hp1).opcode:=A_ADD;
  4366. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4367. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4368. RemoveCurrentp(p, hp1);
  4369. result:=true;
  4370. exit;
  4371. end;
  4372. end;
  4373. { If the LEA instruction can be converted into an arithmetic instruction,
  4374. it may be possible to then fold it in the next optimisation, otherwise
  4375. there's nothing more that can be optimised here. }
  4376. if not ConvertLEA(taicpu(hp1)) then
  4377. Exit;
  4378. end;
  4379. if (taicpu(p).oper[1]^.typ = top_reg) and
  4380. (hp1.typ = ait_instruction) and
  4381. GetNextInstruction(hp1, hp2) and
  4382. MatchInstruction(hp2,A_MOV,[]) and
  4383. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4384. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4385. (
  4386. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4387. {$ifdef x86_64}
  4388. or
  4389. (
  4390. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4391. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4392. )
  4393. {$endif x86_64}
  4394. ) then
  4395. begin
  4396. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4397. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4398. { change movsX/movzX reg/ref, reg2
  4399. add/sub/or/... reg3/$const, reg2
  4400. mov reg2 reg/ref
  4401. dealloc reg2
  4402. to
  4403. add/sub/or/... reg3/$const, reg/ref }
  4404. begin
  4405. TransferUsedRegs(TmpUsedRegs);
  4406. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4407. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4408. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4409. begin
  4410. { by example:
  4411. movswl %si,%eax movswl %si,%eax p
  4412. decl %eax addl %edx,%eax hp1
  4413. movw %ax,%si movw %ax,%si hp2
  4414. ->
  4415. movswl %si,%eax movswl %si,%eax p
  4416. decw %eax addw %edx,%eax hp1
  4417. movw %ax,%si movw %ax,%si hp2
  4418. }
  4419. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4420. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4421. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4422. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4423. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4424. {
  4425. ->
  4426. movswl %si,%eax movswl %si,%eax p
  4427. decw %si addw %dx,%si hp1
  4428. movw %ax,%si movw %ax,%si hp2
  4429. }
  4430. case taicpu(hp1).ops of
  4431. 1:
  4432. begin
  4433. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4434. if taicpu(hp1).oper[0]^.typ=top_reg then
  4435. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4436. end;
  4437. 2:
  4438. begin
  4439. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4440. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4441. (taicpu(hp1).opcode<>A_SHL) and
  4442. (taicpu(hp1).opcode<>A_SHR) and
  4443. (taicpu(hp1).opcode<>A_SAR) then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. else
  4447. internalerror(2008042701);
  4448. end;
  4449. {
  4450. ->
  4451. decw %si addw %dx,%si p
  4452. }
  4453. RemoveInstruction(hp2);
  4454. RemoveCurrentP(p, hp1);
  4455. Result:=True;
  4456. Exit;
  4457. end;
  4458. end;
  4459. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4460. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4461. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4462. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4463. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4464. )
  4465. {$ifdef i386}
  4466. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4467. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4468. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4469. {$endif i386}
  4470. then
  4471. { change movsX/movzX reg/ref, reg2
  4472. add/sub/or/... regX/$const, reg2
  4473. mov reg2, reg3
  4474. dealloc reg2
  4475. to
  4476. movsX/movzX reg/ref, reg3
  4477. add/sub/or/... reg3/$const, reg3
  4478. }
  4479. begin
  4480. TransferUsedRegs(TmpUsedRegs);
  4481. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4482. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4483. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4484. begin
  4485. { by example:
  4486. movswl %si,%eax movswl %si,%eax p
  4487. decl %eax addl %edx,%eax hp1
  4488. movw %ax,%si movw %ax,%si hp2
  4489. ->
  4490. movswl %si,%eax movswl %si,%eax p
  4491. decw %eax addw %edx,%eax hp1
  4492. movw %ax,%si movw %ax,%si hp2
  4493. }
  4494. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4495. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4496. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4497. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4498. { limit size of constants as well to avoid assembler errors, but
  4499. check opsize to avoid overflow when left shifting the 1 }
  4500. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4501. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4502. {$ifdef x86_64}
  4503. { Be careful of, for example:
  4504. movl %reg1,%reg2
  4505. addl %reg3,%reg2
  4506. movq %reg2,%reg4
  4507. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4508. }
  4509. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4510. begin
  4511. taicpu(hp2).changeopsize(S_L);
  4512. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4513. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4514. end;
  4515. {$endif x86_64}
  4516. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4517. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4518. if taicpu(p).oper[0]^.typ=top_reg then
  4519. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4520. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4521. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4522. {
  4523. ->
  4524. movswl %si,%eax movswl %si,%eax p
  4525. decw %si addw %dx,%si hp1
  4526. movw %ax,%si movw %ax,%si hp2
  4527. }
  4528. case taicpu(hp1).ops of
  4529. 1:
  4530. begin
  4531. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4532. if taicpu(hp1).oper[0]^.typ=top_reg then
  4533. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4534. end;
  4535. 2:
  4536. begin
  4537. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4538. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4539. (taicpu(hp1).opcode<>A_SHL) and
  4540. (taicpu(hp1).opcode<>A_SHR) and
  4541. (taicpu(hp1).opcode<>A_SAR) then
  4542. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4543. end;
  4544. else
  4545. internalerror(2018111801);
  4546. end;
  4547. {
  4548. ->
  4549. decw %si addw %dx,%si p
  4550. }
  4551. RemoveInstruction(hp2);
  4552. end;
  4553. end;
  4554. end;
  4555. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4556. GetNextInstruction(hp1, hp2) and
  4557. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4558. MatchOperand(Taicpu(p).oper[0]^,0) and
  4559. (Taicpu(p).oper[1]^.typ = top_reg) and
  4560. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4561. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4562. { mov reg1,0
  4563. bts reg1,operand1 --> mov reg1,operand2
  4564. or reg1,operand2 bts reg1,operand1}
  4565. begin
  4566. Taicpu(hp2).opcode:=A_MOV;
  4567. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4568. asml.remove(hp1);
  4569. insertllitem(hp2,hp2.next,hp1);
  4570. RemoveCurrentp(p, hp1);
  4571. Result:=true;
  4572. exit;
  4573. end;
  4574. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4575. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4576. GetNextInstruction(hp1, hp2) and
  4577. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4578. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4579. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4580. { change
  4581. mov reg1,reg2
  4582. sub reg3,reg2
  4583. cmp reg3,reg1
  4584. into
  4585. mov reg1,reg2
  4586. sub reg3,reg2
  4587. }
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4590. RemoveInstruction(hp2);
  4591. Result:=true;
  4592. exit;
  4593. end;
  4594. {
  4595. mov ref,reg0
  4596. <op> reg0,reg1
  4597. dealloc reg0
  4598. to
  4599. <op> ref,reg1
  4600. }
  4601. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4602. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4603. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4604. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4605. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4606. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4607. begin
  4608. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4609. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4610. RemoveCurrentp(p, hp1);
  4611. Result:=true;
  4612. exit;
  4613. end;
  4614. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4615. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4616. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4617. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4618. begin
  4619. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4620. {$ifdef x86_64}
  4621. { Convert:
  4622. movq x(ref),%reg64
  4623. shrq y,%reg64
  4624. To:
  4625. movl x+4(ref),%reg32
  4626. shrl y-32,%reg32 (Remove if y = 32)
  4627. }
  4628. if (taicpu(p).opsize = S_Q) and
  4629. (taicpu(hp1).opcode = A_SHR) and
  4630. (taicpu(hp1).oper[0]^.val >= 32) then
  4631. begin
  4632. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4633. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4634. { Convert to 32-bit }
  4635. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4636. taicpu(p).opsize := S_L;
  4637. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4638. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4639. if (taicpu(hp1).oper[0]^.val = 32) then
  4640. begin
  4641. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4642. RemoveInstruction(hp1);
  4643. end
  4644. else
  4645. begin
  4646. { This will potentially open up more arithmetic operations since
  4647. the peephole optimizer now has a big hint that only the lower
  4648. 32 bits are currently in use (and opcodes are smaller in size) }
  4649. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4650. taicpu(hp1).opsize := S_L;
  4651. Dec(taicpu(hp1).oper[0]^.val, 32);
  4652. DebugMsg(SPeepholeOptimization + PreMessage +
  4653. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4654. end;
  4655. Result := True;
  4656. Exit;
  4657. end;
  4658. {$endif x86_64}
  4659. { Convert:
  4660. movl x(ref),%reg
  4661. shrl $24,%reg
  4662. To:
  4663. movzbl x+3(ref),%reg
  4664. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4665. Also accept sar instead of shr, but convert to movsx instead of movzx
  4666. }
  4667. if taicpu(hp1).opcode = A_SHR then
  4668. MovUnaligned := A_MOVZX
  4669. else
  4670. MovUnaligned := A_MOVSX;
  4671. NewSize := S_NO;
  4672. NewOffset := 0;
  4673. case taicpu(p).opsize of
  4674. S_B:
  4675. { No valid combinations };
  4676. S_W:
  4677. if (taicpu(hp1).oper[0]^.val = 8) then
  4678. begin
  4679. NewSize := S_BW;
  4680. NewOffset := 1;
  4681. end;
  4682. S_L:
  4683. case taicpu(hp1).oper[0]^.val of
  4684. 16:
  4685. begin
  4686. NewSize := S_WL;
  4687. NewOffset := 2;
  4688. end;
  4689. 24:
  4690. begin
  4691. NewSize := S_BL;
  4692. NewOffset := 3;
  4693. end;
  4694. else
  4695. ;
  4696. end;
  4697. {$ifdef x86_64}
  4698. S_Q:
  4699. case taicpu(hp1).oper[0]^.val of
  4700. 32:
  4701. begin
  4702. if taicpu(hp1).opcode = A_SAR then
  4703. begin
  4704. { 32-bit to 64-bit is a distinct instruction }
  4705. MovUnaligned := A_MOVSXD;
  4706. NewSize := S_LQ;
  4707. NewOffset := 4;
  4708. end
  4709. else
  4710. { Should have been handled by MovShr2Mov above }
  4711. InternalError(2022081811);
  4712. end;
  4713. 48:
  4714. begin
  4715. NewSize := S_WQ;
  4716. NewOffset := 6;
  4717. end;
  4718. 56:
  4719. begin
  4720. NewSize := S_BQ;
  4721. NewOffset := 7;
  4722. end;
  4723. else
  4724. ;
  4725. end;
  4726. {$endif x86_64}
  4727. else
  4728. InternalError(2022081810);
  4729. end;
  4730. if (NewSize <> S_NO) and
  4731. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4732. begin
  4733. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4734. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4735. debug_op2str(MovUnaligned);
  4736. {$ifdef x86_64}
  4737. if MovUnaligned <> A_MOVSXD then
  4738. { Don't add size suffix for MOVSXD }
  4739. {$endif x86_64}
  4740. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4741. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4742. taicpu(p).opcode := MovUnaligned;
  4743. taicpu(p).opsize := NewSize;
  4744. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4745. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4746. RemoveInstruction(hp1);
  4747. Result := True;
  4748. Exit;
  4749. end;
  4750. end;
  4751. { Backward optimisation shared with OptPass2MOV }
  4752. if FuncMov2Func(p, hp1) then
  4753. begin
  4754. Result := True;
  4755. Exit;
  4756. end;
  4757. end;
  4758. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4759. var
  4760. hp1 : tai;
  4761. begin
  4762. Result:=false;
  4763. if taicpu(p).ops <> 2 then
  4764. exit;
  4765. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4766. GetNextInstruction(p,hp1) then
  4767. begin
  4768. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4769. (taicpu(hp1).ops = 2) then
  4770. begin
  4771. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4772. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4773. { movXX reg1, mem1 or movXX mem1, reg1
  4774. movXX mem2, reg2 movXX reg2, mem2}
  4775. begin
  4776. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4777. { movXX reg1, mem1 or movXX mem1, reg1
  4778. movXX mem2, reg1 movXX reg2, mem1}
  4779. begin
  4780. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4781. begin
  4782. { Removes the second statement from
  4783. movXX reg1, mem1/reg2
  4784. movXX mem1/reg2, reg1
  4785. }
  4786. if taicpu(p).oper[0]^.typ=top_reg then
  4787. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4788. { Removes the second statement from
  4789. movXX mem1/reg1, reg2
  4790. movXX reg2, mem1/reg1
  4791. }
  4792. if (taicpu(p).oper[1]^.typ=top_reg) and
  4793. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4794. begin
  4795. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4796. RemoveInstruction(hp1);
  4797. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4798. Result:=true;
  4799. exit;
  4800. end
  4801. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4802. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4803. begin
  4804. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4805. RemoveInstruction(hp1);
  4806. Result:=true;
  4807. exit;
  4808. end;
  4809. end
  4810. end;
  4811. end;
  4812. end;
  4813. end;
  4814. end;
  4815. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4816. var
  4817. hp1 : tai;
  4818. begin
  4819. result:=false;
  4820. { replace
  4821. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4822. MovX %mreg2,%mreg1
  4823. dealloc %mreg2
  4824. by
  4825. <Op>X %mreg2,%mreg1
  4826. ?
  4827. }
  4828. if GetNextInstruction(p,hp1) and
  4829. { we mix single and double opperations here because we assume that the compiler
  4830. generates vmovapd only after double operations and vmovaps only after single operations }
  4831. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4832. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4833. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4834. (taicpu(p).oper[0]^.typ=top_reg) then
  4835. begin
  4836. TransferUsedRegs(TmpUsedRegs);
  4837. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4838. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4839. begin
  4840. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4841. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4842. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4843. RemoveInstruction(hp1);
  4844. result:=true;
  4845. end;
  4846. end;
  4847. end;
  4848. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4849. var
  4850. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4851. JumpLabel, JumpLabel_dist: TAsmLabel;
  4852. FirstValue, SecondValue: TCGInt;
  4853. function OptimizeJump(var InputP: tai): Boolean;
  4854. var
  4855. TempBool: Boolean;
  4856. begin
  4857. Result := False;
  4858. TempBool := True;
  4859. if DoJumpOptimizations(InputP, TempBool) or
  4860. not TempBool then
  4861. begin
  4862. Result := True;
  4863. if Assigned(InputP) then
  4864. begin
  4865. { CollapseZeroDistJump will be set to the label or an align
  4866. before it after the jump if it optimises, whether or not
  4867. the label is live or dead }
  4868. if (InputP.typ = ait_align) or
  4869. (
  4870. (InputP.typ = ait_label) and
  4871. not (tai_label(InputP).labsym.is_used)
  4872. ) then
  4873. GetNextInstruction(InputP, InputP);
  4874. end;
  4875. Exit;
  4876. end;
  4877. end;
  4878. begin
  4879. Result := False;
  4880. if (taicpu(p).oper[0]^.typ = top_const) and
  4881. (taicpu(p).oper[0]^.val <> -1) then
  4882. begin
  4883. { Convert unsigned maximum constants to -1 to aid optimisation }
  4884. case taicpu(p).opsize of
  4885. S_B:
  4886. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4887. begin
  4888. taicpu(p).oper[0]^.val := -1;
  4889. Result := True;
  4890. Exit;
  4891. end;
  4892. S_W:
  4893. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4894. begin
  4895. taicpu(p).oper[0]^.val := -1;
  4896. Result := True;
  4897. Exit;
  4898. end;
  4899. S_L:
  4900. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4901. begin
  4902. taicpu(p).oper[0]^.val := -1;
  4903. Result := True;
  4904. Exit;
  4905. end;
  4906. {$ifdef x86_64}
  4907. S_Q:
  4908. { Storing anything greater than $7FFFFFFF is not possible so do
  4909. nothing };
  4910. {$endif x86_64}
  4911. else
  4912. InternalError(2021121001);
  4913. end;
  4914. end;
  4915. if GetNextInstruction(p, hp1) and
  4916. TrySwapMovCmp(p, hp1) then
  4917. begin
  4918. Result := True;
  4919. Exit;
  4920. end;
  4921. p_label := nil;
  4922. JumpLabel := nil;
  4923. if MatchInstruction(hp1, A_Jcc, []) then
  4924. begin
  4925. if OptimizeJump(hp1) then
  4926. begin
  4927. Result := True;
  4928. if Assigned(hp1) then
  4929. begin
  4930. { CollapseZeroDistJump will be set to the label or an align
  4931. before it after the jump if it optimises, whether or not
  4932. the label is live or dead }
  4933. if (hp1.typ = ait_align) or
  4934. (
  4935. (hp1.typ = ait_label) and
  4936. not (tai_label(hp1).labsym.is_used)
  4937. ) then
  4938. GetNextInstruction(hp1, hp1);
  4939. end;
  4940. TransferUsedRegs(TmpUsedRegs);
  4941. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4942. if not Assigned(hp1) or
  4943. (
  4944. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4945. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4946. ) then
  4947. begin
  4948. { No more conditional jumps; conditional statement is no longer required }
  4949. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4950. RemoveCurrentP(p);
  4951. end;
  4952. Exit;
  4953. end;
  4954. if IsJumpToLabel(taicpu(hp1)) then
  4955. begin
  4956. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4957. if Assigned(JumpLabel) then
  4958. p_label := getlabelwithsym(JumpLabel);
  4959. end;
  4960. end;
  4961. { Search for:
  4962. test $x,(reg/ref)
  4963. jne @lbl1
  4964. test $y,(reg/ref) (same register or reference)
  4965. jne @lbl1
  4966. Change to:
  4967. test $(x or y),(reg/ref)
  4968. jne @lbl1
  4969. (Note, this doesn't work with je instead of jne)
  4970. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4971. Also search for:
  4972. test $x,(reg/ref)
  4973. je @lbl1
  4974. ...
  4975. test $y,(reg/ref)
  4976. je/jne @lbl2
  4977. If (x or y) = x, then the second jump is deterministic
  4978. }
  4979. if (
  4980. (
  4981. (taicpu(p).oper[0]^.typ = top_const) or
  4982. (
  4983. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4984. (taicpu(p).oper[0]^.typ = top_reg) and
  4985. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4986. )
  4987. ) and
  4988. MatchInstruction(hp1, A_JCC, [])
  4989. ) then
  4990. begin
  4991. if (taicpu(p).oper[0]^.typ = top_reg) and
  4992. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4993. FirstValue := -1
  4994. else
  4995. FirstValue := taicpu(p).oper[0]^.val;
  4996. { If we have several test/jne's in a row, it might be the case that
  4997. the second label doesn't go to the same location, but the one
  4998. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4999. so accommodate for this with a while loop.
  5000. }
  5001. hp1_last := hp1;
  5002. while (
  5003. (
  5004. (taicpu(p).oper[1]^.typ = top_reg) and
  5005. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5006. ) or GetNextInstruction(hp1_last, p_dist)
  5007. ) and (p_dist.typ = ait_instruction) do
  5008. begin
  5009. if (
  5010. (
  5011. (taicpu(p_dist).opcode = A_TEST) and
  5012. (
  5013. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5014. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5015. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5016. )
  5017. ) or
  5018. (
  5019. { cmp 0,%reg = test %reg,%reg }
  5020. (taicpu(p_dist).opcode = A_CMP) and
  5021. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5022. )
  5023. ) and
  5024. { Make sure the destination operands are actually the same }
  5025. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5026. GetNextInstruction(p_dist, hp1_dist) and
  5027. MatchInstruction(hp1_dist, A_JCC, []) then
  5028. begin
  5029. if OptimizeJump(hp1_dist) then
  5030. begin
  5031. Result := True;
  5032. Exit;
  5033. end;
  5034. if
  5035. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5036. (
  5037. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5038. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5039. ) then
  5040. SecondValue := -1
  5041. else
  5042. SecondValue := taicpu(p_dist).oper[0]^.val;
  5043. { If both of the TEST constants are identical, delete the
  5044. second TEST that is unnecessary (be careful though, just
  5045. in case the flags are modified in between) }
  5046. if (FirstValue = SecondValue) then
  5047. begin
  5048. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5049. begin
  5050. { Since the second jump's condition is a subset of the first, we
  5051. know it will never branch because the first jump dominates it.
  5052. Get it out of the way now rather than wait for the jump
  5053. optimisations for a speed boost. }
  5054. if IsJumpToLabel(taicpu(hp1_dist)) then
  5055. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5056. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5057. RemoveInstruction(hp1_dist);
  5058. Result := True;
  5059. end
  5060. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5061. begin
  5062. { If the inverse of the first condition is a subset of the second,
  5063. the second one will definitely branch if the first one doesn't }
  5064. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5065. { We can remove the TEST instruction too }
  5066. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5067. RemoveInstruction(p_dist);
  5068. MakeUnconditional(taicpu(hp1_dist));
  5069. RemoveDeadCodeAfterJump(hp1_dist);
  5070. { Since the jump is now unconditional, we can't
  5071. continue any further with this particular
  5072. optimisation. The original TEST is still intact
  5073. though, so there might be something else we can
  5074. do }
  5075. Include(OptsToCheck, aoc_ForceNewIteration);
  5076. Break;
  5077. end;
  5078. if Result or
  5079. { If a jump wasn't removed or made unconditional, only
  5080. remove the identical TEST instruction if the flags
  5081. weren't modified }
  5082. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5083. begin
  5084. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5085. RemoveInstruction(p_dist);
  5086. { If the jump was removed or made unconditional, we
  5087. don't need to allocate NR_DEFAULTFLAGS over the
  5088. entire range }
  5089. if not Result then
  5090. begin
  5091. { Mark the flags as 'in use' over the entire range }
  5092. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5093. { Speed gain - continue search from the Jcc instruction }
  5094. hp1_last := hp1_dist;
  5095. { Only the TEST instruction was removed, and the
  5096. original was unchanged, so we can safely do
  5097. another iteration of the while loop }
  5098. Include(OptsToCheck, aoc_ForceNewIteration);
  5099. Continue;
  5100. end;
  5101. Exit;
  5102. end;
  5103. end;
  5104. hp1_last := nil;
  5105. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5106. (
  5107. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5108. { Always adjacent under -O2 and under }
  5109. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5110. (
  5111. GetNextInstruction(hp1, hp1_last) and
  5112. (hp1_last = p_dist)
  5113. )
  5114. ) and
  5115. (
  5116. (
  5117. { Test the following variant:
  5118. test $x,(reg/ref)
  5119. jne @lbl1
  5120. test $y,(reg/ref)
  5121. je @lbl2
  5122. @lbl1:
  5123. Becomes:
  5124. test $(x or y),(reg/ref)
  5125. je @lbl2
  5126. @lbl1: (may become a dead label)
  5127. }
  5128. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5129. GetNextInstruction(hp1_dist, hp1_last) and
  5130. (hp1_last = p_label)
  5131. ) or
  5132. (
  5133. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5134. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5135. then the second jump will never branch, so it can also be
  5136. removed regardless of where it goes }
  5137. (
  5138. (FirstValue = -1) or
  5139. (SecondValue = -1) or
  5140. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5141. )
  5142. )
  5143. ) then
  5144. begin
  5145. { Same jump location... can be a register since nothing's changed }
  5146. { If any of the entries are equivalent to test %reg,%reg, then the
  5147. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5148. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5149. if (hp1_last = p_label) then
  5150. begin
  5151. { Variant }
  5152. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5153. RemoveInstruction(p_dist);
  5154. if Assigned(JumpLabel) then
  5155. JumpLabel.decrefs;
  5156. RemoveInstruction(hp1);
  5157. end
  5158. else
  5159. begin
  5160. { Only remove the second test if no jumps or other conditional instructions follow }
  5161. TransferUsedRegs(TmpUsedRegs);
  5162. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5163. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5164. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5165. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5166. begin
  5167. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5168. RemoveInstruction(p_dist);
  5169. { Remove the first jump, not the second, to keep
  5170. any register deallocations between the second
  5171. TEST/JNE pair in the same place. Aids future
  5172. optimisation. }
  5173. if Assigned(JumpLabel) then
  5174. JumpLabel.decrefs;
  5175. RemoveInstruction(hp1);
  5176. end
  5177. else
  5178. begin
  5179. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5180. if IsJumpToLabel(taicpu(hp1_dist)) then
  5181. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5182. { Remove second jump in this instance }
  5183. RemoveInstruction(hp1_dist);
  5184. end;
  5185. end;
  5186. Result := True;
  5187. Exit;
  5188. end;
  5189. end;
  5190. if { If -O2 and under, it may stop on any old instruction }
  5191. (cs_opt_level3 in current_settings.optimizerswitches) and
  5192. (taicpu(p).oper[1]^.typ = top_reg) and
  5193. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5194. begin
  5195. hp1_last := p_dist;
  5196. Continue;
  5197. end;
  5198. Break;
  5199. end;
  5200. end;
  5201. { Search for:
  5202. test %reg,%reg
  5203. j(c1) @lbl1
  5204. ...
  5205. @lbl:
  5206. test %reg,%reg (same register)
  5207. j(c2) @lbl2
  5208. If c2 is a subset of c1, change to:
  5209. test %reg,%reg
  5210. j(c1) @lbl2
  5211. (@lbl1 may become a dead label as a result)
  5212. }
  5213. if (taicpu(p).oper[1]^.typ = top_reg) and
  5214. (taicpu(p).oper[0]^.typ = top_reg) and
  5215. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5216. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5217. Assigned(p_label) and
  5218. GetNextInstruction(p_label, p_dist) and
  5219. MatchInstruction(p_dist, A_TEST, []) and
  5220. { It's fine if the second test uses smaller sub-registers }
  5221. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5222. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5223. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5224. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5225. GetNextInstruction(p_dist, hp1_dist) and
  5226. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5227. begin
  5228. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5229. if JumpLabel = JumpLabel_dist then
  5230. { This is an infinite loop }
  5231. Exit;
  5232. { Best optimisation when the first condition is a subset (or equal) of the second }
  5233. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5234. begin
  5235. { Any registers used here will already be allocated }
  5236. if Assigned(JumpLabel) then
  5237. JumpLabel.DecRefs;
  5238. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5239. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5240. Result := True;
  5241. Exit;
  5242. end;
  5243. end;
  5244. end;
  5245. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5246. var
  5247. hp1, hp2: tai;
  5248. ActiveReg: TRegister;
  5249. OldOffset: asizeint;
  5250. ThisConst: TCGInt;
  5251. function RegDeallocated: Boolean;
  5252. begin
  5253. TransferUsedRegs(TmpUsedRegs);
  5254. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5255. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5256. end;
  5257. begin
  5258. result:=false;
  5259. hp1 := nil;
  5260. { replace
  5261. addX const,%reg1
  5262. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5263. dealloc %reg1
  5264. by
  5265. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5266. }
  5267. if MatchOpType(taicpu(p),top_const,top_reg) then
  5268. begin
  5269. ActiveReg := taicpu(p).oper[1]^.reg;
  5270. { Ensures the entire register was updated }
  5271. if (taicpu(p).opsize >= S_L) and
  5272. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5273. MatchInstruction(hp1,A_LEA,[]) and
  5274. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5275. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5276. (
  5277. { Cover the case where the register in the reference is also the destination register }
  5278. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5279. (
  5280. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5281. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5282. RegDeallocated
  5283. )
  5284. ) then
  5285. begin
  5286. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5287. {$push}
  5288. {$R-}{$Q-}
  5289. { Explicitly disable overflow checking for these offset calculation
  5290. as those do not matter for the final result }
  5291. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5292. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5293. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5294. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5295. {$pop}
  5296. {$ifdef x86_64}
  5297. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5298. begin
  5299. { Overflow; abort }
  5300. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5301. end
  5302. else
  5303. {$endif x86_64}
  5304. begin
  5305. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5306. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5307. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5308. RemoveCurrentP(p, hp1)
  5309. else
  5310. RemoveCurrentP(p);
  5311. result:=true;
  5312. Exit;
  5313. end;
  5314. end;
  5315. if (
  5316. { Save calling GetNextInstructionUsingReg again }
  5317. Assigned(hp1) or
  5318. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5319. ) and
  5320. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5321. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5322. begin
  5323. if taicpu(hp1).oper[0]^.typ = top_const then
  5324. begin
  5325. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5326. if taicpu(hp1).opcode = A_ADD then
  5327. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5328. else
  5329. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5330. Result := True;
  5331. { Handle any overflows }
  5332. case taicpu(p).opsize of
  5333. S_B:
  5334. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5335. S_W:
  5336. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5337. S_L:
  5338. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5339. {$ifdef x86_64}
  5340. S_Q:
  5341. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5342. { Overflow; abort }
  5343. Result := False
  5344. else
  5345. taicpu(p).oper[0]^.val := ThisConst;
  5346. {$endif x86_64}
  5347. else
  5348. InternalError(2021102610);
  5349. end;
  5350. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5351. if Result then
  5352. begin
  5353. if (taicpu(p).oper[0]^.val < 0) and
  5354. (
  5355. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5356. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5357. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5358. ) then
  5359. begin
  5360. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5361. taicpu(p).opcode := A_SUB;
  5362. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5363. end
  5364. else
  5365. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5366. RemoveInstruction(hp1);
  5367. end;
  5368. end
  5369. else
  5370. begin
  5371. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5372. TransferUsedRegs(TmpUsedRegs);
  5373. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5374. hp2 := p;
  5375. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5376. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5377. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5378. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5379. begin
  5380. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5381. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5382. Asml.Remove(p);
  5383. Asml.InsertAfter(p, hp1);
  5384. p := hp1;
  5385. Result := True;
  5386. Exit;
  5387. end;
  5388. end;
  5389. end;
  5390. if DoArithCombineOpt(p) then
  5391. Result:=true;
  5392. end;
  5393. end;
  5394. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5395. var
  5396. hp1, hp2: tai;
  5397. ref: Integer;
  5398. saveref: treference;
  5399. offsetcalc: Int64;
  5400. TempReg: TRegister;
  5401. Multiple: TCGInt;
  5402. Adjacent, IntermediateRegDiscarded: Boolean;
  5403. begin
  5404. Result:=false;
  5405. { play save and throw an error if LEA uses a seg register prefix,
  5406. this is most likely an error somewhere else }
  5407. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5408. internalerror(2022022001);
  5409. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5410. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5411. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5412. (
  5413. { do not mess with leas accessing the stack pointer
  5414. unless it's a null operation }
  5415. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5416. (
  5417. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5418. (taicpu(p).oper[0]^.ref^.offset = 0)
  5419. )
  5420. ) and
  5421. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5422. begin
  5423. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5424. begin
  5425. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5426. begin
  5427. taicpu(p).opcode := A_MOV;
  5428. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5429. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5430. end
  5431. else
  5432. begin
  5433. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5434. RemoveCurrentP(p);
  5435. end;
  5436. Result:=true;
  5437. exit;
  5438. end
  5439. else if (
  5440. { continue to use lea to adjust the stack pointer,
  5441. it is the recommended way, but only if not optimizing for size }
  5442. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5443. (cs_opt_size in current_settings.optimizerswitches)
  5444. ) and
  5445. { If the flags register is in use, don't change the instruction
  5446. to an ADD otherwise this will scramble the flags. [Kit] }
  5447. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5448. ConvertLEA(taicpu(p)) then
  5449. begin
  5450. Result:=true;
  5451. exit;
  5452. end;
  5453. end;
  5454. { Don't optimise if the stack or frame pointer is the destination register }
  5455. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5456. Exit;
  5457. if GetNextInstruction(p,hp1) and
  5458. (hp1.typ=ait_instruction) then
  5459. begin
  5460. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5461. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5462. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5463. begin
  5464. TransferUsedRegs(TmpUsedRegs);
  5465. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5466. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5467. begin
  5468. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5469. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5470. RemoveInstruction(hp1);
  5471. result:=true;
  5472. exit;
  5473. end;
  5474. end;
  5475. { changes
  5476. lea <ref1>, reg1
  5477. <op> ...,<ref. with reg1>,...
  5478. to
  5479. <op> ...,<ref1>,... }
  5480. { find a reference which uses reg1 }
  5481. 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
  5482. ref:=0
  5483. 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
  5484. ref:=1
  5485. else
  5486. ref:=-1;
  5487. if (ref<>-1) and
  5488. { reg1 must be either the base or the index }
  5489. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5490. begin
  5491. { reg1 can be removed from the reference }
  5492. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5493. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5494. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5495. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5496. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5497. else
  5498. Internalerror(2019111201);
  5499. { check if the can insert all data of the lea into the second instruction }
  5500. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5501. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5502. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5503. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5504. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5505. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5506. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5507. {$ifdef x86_64}
  5508. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5509. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5510. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5511. )
  5512. {$endif x86_64}
  5513. then
  5514. begin
  5515. { reg1 might not used by the second instruction after it is remove from the reference }
  5516. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5517. begin
  5518. TransferUsedRegs(TmpUsedRegs);
  5519. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5520. { reg1 is not updated so it might not be used afterwards }
  5521. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5522. begin
  5523. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5524. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5525. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5526. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5527. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5528. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5529. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5530. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5531. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5532. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5533. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5534. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5535. RemoveCurrentP(p, hp1);
  5536. result:=true;
  5537. exit;
  5538. end
  5539. end;
  5540. end;
  5541. { recover }
  5542. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5543. end;
  5544. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5545. if Adjacent or
  5546. { Check further ahead (up to 2 instructions ahead for -O2) }
  5547. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5548. begin
  5549. { Check common LEA/LEA conditions }
  5550. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5551. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5552. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5553. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5554. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5555. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5556. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5557. (
  5558. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5559. calling it (since it calls GetNextInstruction) }
  5560. Adjacent or
  5561. (
  5562. (
  5563. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5564. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5565. ) and (
  5566. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5567. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5568. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5569. )
  5570. )
  5571. ) then
  5572. begin
  5573. TransferUsedRegs(TmpUsedRegs);
  5574. hp2 := p;
  5575. repeat
  5576. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5577. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5578. IntermediateRegDiscarded :=
  5579. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5580. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5581. { changes
  5582. lea offset1(regX,scale), reg1
  5583. lea offset2(reg1,reg1), reg2
  5584. to
  5585. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5586. and
  5587. lea offset1(regX,scale1), reg1
  5588. lea offset2(reg1,scale2), reg2
  5589. to
  5590. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5591. and
  5592. lea offset1(regX,scale1), reg1
  5593. lea offset2(reg3,reg1,scale2), reg2
  5594. to
  5595. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5596. ... so long as the final scale does not exceed 8
  5597. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5598. }
  5599. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5600. (
  5601. { Don't optimise if size is a concern and the intermediate register remains in use }
  5602. IntermediateRegDiscarded or
  5603. not (cs_opt_size in current_settings.optimizerswitches)
  5604. ) and
  5605. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5606. (
  5607. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5608. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5609. ) and (
  5610. (
  5611. { lea (reg1,scale2), reg2 variant }
  5612. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5613. (
  5614. Adjacent or
  5615. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5616. ) and
  5617. (
  5618. (
  5619. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5620. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5621. ) or (
  5622. { lea (regX,regX), reg1 variant }
  5623. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5624. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5625. )
  5626. )
  5627. ) or (
  5628. { lea (reg1,reg1), reg1 variant }
  5629. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5630. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5631. )
  5632. ) then
  5633. begin
  5634. { Make everything homogeneous to make calculations easier }
  5635. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5636. begin
  5637. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5638. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5639. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5640. else
  5641. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5642. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5643. end;
  5644. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5645. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5646. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5647. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5648. begin
  5649. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5650. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5651. begin
  5652. { Put the register to change in the index register }
  5653. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5654. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5655. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5656. end;
  5657. { Change lea (reg,reg) to lea(,reg,2) }
  5658. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5659. begin
  5660. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5661. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5662. end;
  5663. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5664. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5665. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5666. { Just to prevent miscalculations }
  5667. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5668. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5669. else
  5670. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5671. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5672. if IntermediateRegDiscarded then
  5673. begin
  5674. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5675. RemoveCurrentP(p);
  5676. end
  5677. else
  5678. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5679. result:=true;
  5680. exit;
  5681. end;
  5682. end;
  5683. { changes
  5684. lea offset1(regX), reg1
  5685. lea offset2(reg1), reg2
  5686. to
  5687. lea offset1+offset2(regX), reg2 }
  5688. if (
  5689. { Don't optimise if size is a concern and the intermediate register remains in use }
  5690. IntermediateRegDiscarded or
  5691. not (cs_opt_size in current_settings.optimizerswitches)
  5692. ) and
  5693. (
  5694. (
  5695. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5696. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5697. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5698. ) or (
  5699. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5700. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5701. (
  5702. (
  5703. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5704. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5705. ) or (
  5706. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5707. (
  5708. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5709. (
  5710. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5711. (
  5712. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5713. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5714. )
  5715. )
  5716. )
  5717. )
  5718. )
  5719. )
  5720. ) then
  5721. begin
  5722. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5723. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5724. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5725. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5726. begin
  5727. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5728. begin
  5729. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5730. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5731. { if the register is used as index and base, we have to increase for base as well
  5732. and adapt base }
  5733. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5734. begin
  5735. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5736. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5737. end;
  5738. end
  5739. else
  5740. begin
  5741. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5742. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5743. end;
  5744. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5745. begin
  5746. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5747. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5748. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5749. end;
  5750. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5751. if IntermediateRegDiscarded then
  5752. begin
  5753. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5754. RemoveCurrentP(p);
  5755. end
  5756. else
  5757. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5758. result:=true;
  5759. exit;
  5760. end;
  5761. end;
  5762. end;
  5763. { Change:
  5764. leal/q $x(%reg1),%reg2
  5765. ...
  5766. shll/q $y,%reg2
  5767. To:
  5768. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5769. }
  5770. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5771. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5772. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5773. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5774. (taicpu(hp1).oper[0]^.val <= 3) then
  5775. begin
  5776. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5777. TransferUsedRegs(TmpUsedRegs);
  5778. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5779. if
  5780. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5781. (this works even if scalefactor is zero) }
  5782. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5783. { Ensure offset doesn't go out of bounds }
  5784. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5785. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5786. (
  5787. (
  5788. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5789. (
  5790. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5791. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5792. (
  5793. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5794. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5795. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5796. )
  5797. )
  5798. ) or (
  5799. (
  5800. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5801. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5802. ) and
  5803. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5804. )
  5805. ) then
  5806. begin
  5807. repeat
  5808. with taicpu(p).oper[0]^.ref^ do
  5809. begin
  5810. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5811. if index = base then
  5812. begin
  5813. if Multiple > 4 then
  5814. { Optimisation will no longer work because resultant
  5815. scale factor will exceed 8 }
  5816. Break;
  5817. base := NR_NO;
  5818. scalefactor := 2;
  5819. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5820. end
  5821. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5822. begin
  5823. { Scale factor only works on the index register }
  5824. index := base;
  5825. base := NR_NO;
  5826. end;
  5827. { For safety }
  5828. if scalefactor <= 1 then
  5829. begin
  5830. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5831. scalefactor := Multiple;
  5832. end
  5833. else
  5834. begin
  5835. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5836. scalefactor := scalefactor * Multiple;
  5837. end;
  5838. offset := offset * Multiple;
  5839. end;
  5840. RemoveInstruction(hp1);
  5841. Result := True;
  5842. Exit;
  5843. { This repeat..until loop exists for the benefit of Break }
  5844. until True;
  5845. end;
  5846. end;
  5847. end;
  5848. end;
  5849. end;
  5850. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5851. var
  5852. hp1 : tai;
  5853. SubInstr: Boolean;
  5854. ThisConst: TCGInt;
  5855. const
  5856. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5857. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5858. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5859. begin
  5860. Result := False;
  5861. if taicpu(p).oper[0]^.typ <> top_const then
  5862. { Should have been confirmed before calling }
  5863. InternalError(2021102601);
  5864. SubInstr := (taicpu(p).opcode = A_SUB);
  5865. if GetLastInstruction(p, hp1) and
  5866. (hp1.typ = ait_instruction) and
  5867. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5868. begin
  5869. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5870. { Bad size }
  5871. InternalError(2022042001);
  5872. case taicpu(hp1).opcode Of
  5873. A_INC:
  5874. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5875. begin
  5876. if SubInstr then
  5877. ThisConst := taicpu(p).oper[0]^.val - 1
  5878. else
  5879. ThisConst := taicpu(p).oper[0]^.val + 1;
  5880. end
  5881. else
  5882. Exit;
  5883. A_DEC:
  5884. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5885. begin
  5886. if SubInstr then
  5887. ThisConst := taicpu(p).oper[0]^.val + 1
  5888. else
  5889. ThisConst := taicpu(p).oper[0]^.val - 1;
  5890. end
  5891. else
  5892. Exit;
  5893. A_SUB:
  5894. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5895. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5896. begin
  5897. if SubInstr then
  5898. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5899. else
  5900. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5901. end
  5902. else
  5903. Exit;
  5904. A_ADD:
  5905. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5906. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5907. begin
  5908. if SubInstr then
  5909. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5910. else
  5911. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5912. end
  5913. else
  5914. Exit;
  5915. else
  5916. Exit;
  5917. end;
  5918. { Check that the values are in range }
  5919. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5920. { Overflow; abort }
  5921. Exit;
  5922. if (ThisConst = 0) then
  5923. begin
  5924. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5925. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5926. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5927. RemoveInstruction(hp1);
  5928. hp1 := tai(p.next);
  5929. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5930. if not GetLastInstruction(hp1, p) then
  5931. p := hp1;
  5932. end
  5933. else
  5934. begin
  5935. if taicpu(hp1).opercnt=1 then
  5936. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5937. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5938. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5939. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5940. else
  5941. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5942. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5943. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5944. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5945. RemoveInstruction(hp1);
  5946. taicpu(p).loadconst(0, ThisConst);
  5947. end;
  5948. Result := True;
  5949. end;
  5950. end;
  5951. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5952. begin
  5953. Result := False;
  5954. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5955. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5956. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5957. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5958. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5959. (
  5960. (
  5961. (taicpu(hp1).opcode = A_TEST)
  5962. ) or (
  5963. (taicpu(hp1).opcode = A_CMP) and
  5964. { A sanity check more than anything }
  5965. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5966. )
  5967. ) then
  5968. begin
  5969. { change
  5970. mov mem, %reg
  5971. ...
  5972. cmp/test x, %reg / test %reg,%reg
  5973. (reg deallocated)
  5974. to
  5975. cmp/test x, mem / cmp 0, mem
  5976. }
  5977. TransferUsedRegs(TmpUsedRegs);
  5978. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5979. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5980. begin
  5981. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5982. if (taicpu(hp1).opcode = A_TEST) and
  5983. (
  5984. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5985. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5986. ) then
  5987. begin
  5988. taicpu(hp1).opcode := A_CMP;
  5989. taicpu(hp1).loadconst(0, 0);
  5990. end;
  5991. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5992. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5993. RemoveCurrentP(p);
  5994. if (p <> hp1) then
  5995. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5996. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5997. { Make sure the flags are allocated across the CMP instruction }
  5998. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5999. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6000. Result := True;
  6001. Exit;
  6002. end;
  6003. end;
  6004. end;
  6005. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6006. var
  6007. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6008. ThisReg, SecondReg: TRegister;
  6009. JumpLoc: TAsmLabel;
  6010. NewSize: TOpSize;
  6011. begin
  6012. Result := False;
  6013. {
  6014. Convert:
  6015. j<c> .L1
  6016. .L2:
  6017. mov 1,reg
  6018. jmp .L3 (or ret, although it might not be a RET yet)
  6019. .L1:
  6020. mov 0,reg
  6021. jmp .L3 (or ret)
  6022. ( As long as .L3 <> .L1 or .L2)
  6023. To:
  6024. mov 0,reg
  6025. set<not(c)> reg
  6026. jmp .L3 (or ret)
  6027. .L2:
  6028. mov 1,reg
  6029. jmp .L3 (or ret)
  6030. .L1:
  6031. mov 0,reg
  6032. jmp .L3 (or ret)
  6033. }
  6034. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6035. Exit;
  6036. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6037. if GetNextInstruction(hp_label, hp2) and
  6038. MatchInstruction(hp2,A_MOV,[]) and
  6039. (taicpu(hp2).oper[0]^.typ = top_const) and
  6040. (
  6041. (
  6042. (taicpu(hp2).oper[1]^.typ = top_reg)
  6043. {$ifdef i386}
  6044. { Under i386, ESI, EDI, EBP and ESP
  6045. don't have an 8-bit representation }
  6046. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6047. {$endif i386}
  6048. ) or (
  6049. {$ifdef i386}
  6050. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6051. {$endif i386}
  6052. (taicpu(hp2).opsize = S_B)
  6053. )
  6054. ) and
  6055. GetNextInstruction(hp2, hp3) and
  6056. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6057. (
  6058. (taicpu(hp3).opcode=A_RET) or
  6059. (
  6060. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6061. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6062. )
  6063. ) and
  6064. GetNextInstruction(hp3, hp4) and
  6065. (hp4.typ=ait_label) and
  6066. (tai_label(hp4).labsym=JumpLoc) and
  6067. (
  6068. not (cs_opt_size in current_settings.optimizerswitches) or
  6069. { If the initial jump is the label's only reference, then it will
  6070. become a dead label if the other conditions are met and hence
  6071. remove at least 2 instructions, including a jump }
  6072. (JumpLoc.getrefs = 1)
  6073. ) and
  6074. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6075. that will be optimised out }
  6076. GetNextInstruction(hp4, hp5) and
  6077. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6078. (taicpu(hp5).oper[0]^.typ = top_const) and
  6079. (
  6080. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6081. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6082. ) and
  6083. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6084. GetNextInstruction(hp5,hp6) and
  6085. (
  6086. (hp6.typ<>ait_label) or
  6087. SkipLabels(hp6, hp6)
  6088. ) and
  6089. (hp6.typ=ait_instruction) then
  6090. begin
  6091. { First, let's look at the two jumps that are hp3 and hp6 }
  6092. if not
  6093. (
  6094. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6095. (
  6096. (taicpu(hp6).opcode=A_RET) or
  6097. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6098. )
  6099. ) then
  6100. { If condition is False, then the JMP/RET instructions matched conventionally }
  6101. begin
  6102. { See if one of the jumps can be instantly converted into a RET }
  6103. if (taicpu(hp3).opcode=A_JMP) then
  6104. begin
  6105. { Reuse hp5 }
  6106. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6107. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6108. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6109. Exit;
  6110. if MatchInstruction(hp5, A_RET, []) then
  6111. begin
  6112. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6113. ConvertJumpToRET(hp3, hp5);
  6114. Result := True;
  6115. end
  6116. else
  6117. Exit;
  6118. end;
  6119. if (taicpu(hp6).opcode=A_JMP) then
  6120. begin
  6121. { Reuse hp5 }
  6122. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6123. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6124. Exit;
  6125. if MatchInstruction(hp5, A_RET, []) then
  6126. begin
  6127. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6128. ConvertJumpToRET(hp6, hp5);
  6129. Result := True;
  6130. end
  6131. else
  6132. Exit;
  6133. end;
  6134. if not
  6135. (
  6136. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6137. (
  6138. (taicpu(hp6).opcode=A_RET) or
  6139. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6140. )
  6141. ) then
  6142. { Still doesn't match }
  6143. Exit;
  6144. end;
  6145. if (taicpu(hp2).oper[0]^.val = 1) then
  6146. begin
  6147. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6148. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6149. end
  6150. else
  6151. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6152. if taicpu(hp2).opsize=S_B then
  6153. begin
  6154. if taicpu(hp2).oper[1]^.typ = top_reg then
  6155. begin
  6156. SecondReg := taicpu(hp2).oper[1]^.reg;
  6157. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6158. end
  6159. else
  6160. begin
  6161. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6162. SecondReg := NR_NO;
  6163. end;
  6164. hp_pos := p;
  6165. hp_allocstart := hp4;
  6166. end
  6167. else
  6168. begin
  6169. { Will be a register because the size can't be S_B otherwise }
  6170. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6171. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6172. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6173. if (cs_opt_size in current_settings.optimizerswitches) then
  6174. begin
  6175. { Favour using MOVZX when optimising for size }
  6176. case taicpu(hp2).opsize of
  6177. S_W:
  6178. NewSize := S_BW;
  6179. S_L:
  6180. NewSize := S_BL;
  6181. {$ifdef x86_64}
  6182. S_Q:
  6183. begin
  6184. NewSize := S_BL;
  6185. { Will implicitly zero-extend to 64-bit }
  6186. setsubreg(SecondReg, R_SUBD);
  6187. end;
  6188. {$endif x86_64}
  6189. else
  6190. InternalError(2022101301);
  6191. end;
  6192. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6193. { Inserting it right before p will guarantee that the flags are also tracked }
  6194. Asml.InsertBefore(hp5, p);
  6195. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6196. hp_pos := hp5;
  6197. hp_allocstart := hp4;
  6198. end
  6199. else
  6200. begin
  6201. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6202. { Inserting it right before p will guarantee that the flags are also tracked }
  6203. Asml.InsertBefore(hp5, p);
  6204. hp_pos := p;
  6205. hp_allocstart := hp5;
  6206. end;
  6207. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6208. end;
  6209. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6210. taicpu(hp4).condition := taicpu(p).condition;
  6211. asml.InsertBefore(hp4, hp_pos);
  6212. if taicpu(hp3).is_jmp then
  6213. begin
  6214. JumpLoc.decrefs;
  6215. MakeUnconditional(taicpu(p));
  6216. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6217. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6218. end
  6219. else
  6220. ConvertJumpToRET(p, hp3);
  6221. if SecondReg <> NR_NO then
  6222. { Ensure the destination register is allocated over this region }
  6223. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6224. if (JumpLoc.getrefs = 0) then
  6225. RemoveDeadCodeAfterJump(hp3);
  6226. Result:=true;
  6227. exit;
  6228. end;
  6229. end;
  6230. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6231. var
  6232. hp1, hp2: tai;
  6233. ActiveReg: TRegister;
  6234. OldOffset: asizeint;
  6235. ThisConst: TCGInt;
  6236. function RegDeallocated: Boolean;
  6237. begin
  6238. TransferUsedRegs(TmpUsedRegs);
  6239. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6240. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6241. end;
  6242. begin
  6243. Result:=false;
  6244. hp1 := nil;
  6245. { replace
  6246. subX const,%reg1
  6247. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6248. dealloc %reg1
  6249. by
  6250. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6251. }
  6252. if MatchOpType(taicpu(p),top_const,top_reg) then
  6253. begin
  6254. ActiveReg := taicpu(p).oper[1]^.reg;
  6255. { Ensures the entire register was updated }
  6256. if (taicpu(p).opsize >= S_L) and
  6257. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6258. MatchInstruction(hp1,A_LEA,[]) and
  6259. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6260. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6261. (
  6262. { Cover the case where the register in the reference is also the destination register }
  6263. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6264. (
  6265. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6266. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6267. RegDeallocated
  6268. )
  6269. ) then
  6270. begin
  6271. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6272. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6273. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6274. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6275. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6276. {$ifdef x86_64}
  6277. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6278. begin
  6279. { Overflow; abort }
  6280. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6281. end
  6282. else
  6283. {$endif x86_64}
  6284. begin
  6285. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6286. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6287. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6288. RemoveCurrentP(p, hp1)
  6289. else
  6290. RemoveCurrentP(p);
  6291. result:=true;
  6292. Exit;
  6293. end;
  6294. end;
  6295. if (
  6296. { Save calling GetNextInstructionUsingReg again }
  6297. Assigned(hp1) or
  6298. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6299. ) and
  6300. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6301. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6302. begin
  6303. if taicpu(hp1).oper[0]^.typ = top_const then
  6304. begin
  6305. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6306. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6307. Result := True;
  6308. { Handle any overflows }
  6309. case taicpu(p).opsize of
  6310. S_B:
  6311. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6312. S_W:
  6313. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6314. S_L:
  6315. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6316. {$ifdef x86_64}
  6317. S_Q:
  6318. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6319. { Overflow; abort }
  6320. Result := False
  6321. else
  6322. taicpu(p).oper[0]^.val := ThisConst;
  6323. {$endif x86_64}
  6324. else
  6325. InternalError(2021102611);
  6326. end;
  6327. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6328. if Result then
  6329. begin
  6330. if (taicpu(p).oper[0]^.val < 0) and
  6331. (
  6332. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6333. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6334. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6335. ) then
  6336. begin
  6337. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6338. taicpu(p).opcode := A_SUB;
  6339. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6340. end
  6341. else
  6342. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6343. RemoveInstruction(hp1);
  6344. end;
  6345. end
  6346. else
  6347. begin
  6348. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6349. TransferUsedRegs(TmpUsedRegs);
  6350. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6351. hp2 := p;
  6352. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6353. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6354. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6355. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6356. begin
  6357. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6358. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6359. Asml.Remove(p);
  6360. Asml.InsertAfter(p, hp1);
  6361. p := hp1;
  6362. Result := True;
  6363. Exit;
  6364. end;
  6365. end;
  6366. end;
  6367. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6368. { * change "sub/add const1, reg" or "dec reg" followed by
  6369. "sub const2, reg" to one "sub ..., reg" }
  6370. {$ifdef i386}
  6371. if (taicpu(p).oper[0]^.val = 2) and
  6372. (ActiveReg = NR_ESP) and
  6373. { Don't do the sub/push optimization if the sub }
  6374. { comes from setting up the stack frame (JM) }
  6375. (not(GetLastInstruction(p,hp1)) or
  6376. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6377. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6378. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6379. begin
  6380. hp1 := tai(p.next);
  6381. while Assigned(hp1) and
  6382. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6383. not RegReadByInstruction(NR_ESP,hp1) and
  6384. not RegModifiedByInstruction(NR_ESP,hp1) do
  6385. hp1 := tai(hp1.next);
  6386. if Assigned(hp1) and
  6387. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6388. begin
  6389. taicpu(hp1).changeopsize(S_L);
  6390. if taicpu(hp1).oper[0]^.typ=top_reg then
  6391. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6392. hp1 := tai(p.next);
  6393. RemoveCurrentp(p, hp1);
  6394. Result:=true;
  6395. exit;
  6396. end;
  6397. end;
  6398. {$endif i386}
  6399. if DoArithCombineOpt(p) then
  6400. Result:=true;
  6401. end;
  6402. end;
  6403. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6404. var
  6405. TmpBool1,TmpBool2 : Boolean;
  6406. tmpref : treference;
  6407. hp1,hp2: tai;
  6408. mask, shiftval: tcgint;
  6409. begin
  6410. Result:=false;
  6411. { All these optimisations work on "shl/sal const,%reg" }
  6412. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6413. Exit;
  6414. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6415. (taicpu(p).oper[0]^.val <= 3) then
  6416. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6417. begin
  6418. { should we check the next instruction? }
  6419. TmpBool1 := True;
  6420. { have we found an add/sub which could be
  6421. integrated in the lea? }
  6422. TmpBool2 := False;
  6423. reference_reset(tmpref,2,[]);
  6424. TmpRef.index := taicpu(p).oper[1]^.reg;
  6425. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6426. while TmpBool1 and
  6427. GetNextInstruction(p, hp1) and
  6428. (tai(hp1).typ = ait_instruction) and
  6429. ((((taicpu(hp1).opcode = A_ADD) or
  6430. (taicpu(hp1).opcode = A_SUB)) and
  6431. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6432. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6433. (((taicpu(hp1).opcode = A_INC) or
  6434. (taicpu(hp1).opcode = A_DEC)) and
  6435. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6436. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6437. ((taicpu(hp1).opcode = A_LEA) and
  6438. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6439. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6440. (not GetNextInstruction(hp1,hp2) or
  6441. not instrReadsFlags(hp2)) Do
  6442. begin
  6443. TmpBool1 := False;
  6444. if taicpu(hp1).opcode=A_LEA then
  6445. begin
  6446. if (TmpRef.base = NR_NO) and
  6447. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6448. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6449. { Segment register isn't a concern here }
  6450. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6451. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6452. begin
  6453. TmpBool1 := True;
  6454. TmpBool2 := True;
  6455. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6456. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6457. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6458. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6459. RemoveInstruction(hp1);
  6460. end
  6461. end
  6462. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6463. begin
  6464. TmpBool1 := True;
  6465. TmpBool2 := True;
  6466. case taicpu(hp1).opcode of
  6467. A_ADD:
  6468. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6469. A_SUB:
  6470. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6471. else
  6472. internalerror(2019050536);
  6473. end;
  6474. RemoveInstruction(hp1);
  6475. end
  6476. else
  6477. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6478. (((taicpu(hp1).opcode = A_ADD) and
  6479. (TmpRef.base = NR_NO)) or
  6480. (taicpu(hp1).opcode = A_INC) or
  6481. (taicpu(hp1).opcode = A_DEC)) then
  6482. begin
  6483. TmpBool1 := True;
  6484. TmpBool2 := True;
  6485. case taicpu(hp1).opcode of
  6486. A_ADD:
  6487. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6488. A_INC:
  6489. inc(TmpRef.offset);
  6490. A_DEC:
  6491. dec(TmpRef.offset);
  6492. else
  6493. internalerror(2019050535);
  6494. end;
  6495. RemoveInstruction(hp1);
  6496. end;
  6497. end;
  6498. if TmpBool2
  6499. {$ifndef x86_64}
  6500. or
  6501. ((current_settings.optimizecputype < cpu_Pentium2) and
  6502. (taicpu(p).oper[0]^.val <= 3) and
  6503. not(cs_opt_size in current_settings.optimizerswitches))
  6504. {$endif x86_64}
  6505. then
  6506. begin
  6507. if not(TmpBool2) and
  6508. (taicpu(p).oper[0]^.val=1) then
  6509. begin
  6510. taicpu(p).opcode := A_ADD;
  6511. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6512. end
  6513. else
  6514. begin
  6515. taicpu(p).opcode := A_LEA;
  6516. taicpu(p).loadref(0, TmpRef);
  6517. end;
  6518. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6519. Result := True;
  6520. end;
  6521. end
  6522. {$ifndef x86_64}
  6523. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6524. begin
  6525. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6526. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6527. (unlike shl, which is only Tairable in the U pipe) }
  6528. if taicpu(p).oper[0]^.val=1 then
  6529. begin
  6530. taicpu(p).opcode := A_ADD;
  6531. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6532. Result := True;
  6533. end
  6534. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6535. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6536. else if (taicpu(p).opsize = S_L) and
  6537. (taicpu(p).oper[0]^.val<= 3) then
  6538. begin
  6539. reference_reset(tmpref,2,[]);
  6540. TmpRef.index := taicpu(p).oper[1]^.reg;
  6541. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6542. taicpu(p).opcode := A_LEA;
  6543. taicpu(p).loadref(0, TmpRef);
  6544. Result := True;
  6545. end;
  6546. end
  6547. {$endif x86_64}
  6548. else if
  6549. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6550. (
  6551. (
  6552. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6553. SetAndTest(hp1, hp2)
  6554. {$ifdef x86_64}
  6555. ) or
  6556. (
  6557. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6558. GetNextInstruction(hp1, hp2) and
  6559. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6560. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6561. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6562. {$endif x86_64}
  6563. )
  6564. ) and
  6565. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6566. begin
  6567. { Change:
  6568. shl x, %reg1
  6569. mov -(1<<x), %reg2
  6570. and %reg2, %reg1
  6571. Or:
  6572. shl x, %reg1
  6573. and -(1<<x), %reg1
  6574. To just:
  6575. shl x, %reg1
  6576. Since the and operation only zeroes bits that are already zero from the shl operation
  6577. }
  6578. case taicpu(p).oper[0]^.val of
  6579. 8:
  6580. mask:=$FFFFFFFFFFFFFF00;
  6581. 16:
  6582. mask:=$FFFFFFFFFFFF0000;
  6583. 32:
  6584. mask:=$FFFFFFFF00000000;
  6585. 63:
  6586. { Constant pre-calculated to prevent overflow errors with Int64 }
  6587. mask:=$8000000000000000;
  6588. else
  6589. begin
  6590. if taicpu(p).oper[0]^.val >= 64 then
  6591. { Shouldn't happen realistically, since the register
  6592. is guaranteed to be set to zero at this point }
  6593. mask := 0
  6594. else
  6595. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6596. end;
  6597. end;
  6598. if taicpu(hp1).oper[0]^.val = mask then
  6599. begin
  6600. { Everything checks out, perform the optimisation, as long as
  6601. the FLAGS register isn't being used}
  6602. TransferUsedRegs(TmpUsedRegs);
  6603. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6604. {$ifdef x86_64}
  6605. if (hp1 <> hp2) then
  6606. begin
  6607. { "shl/mov/and" version }
  6608. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6609. { Don't do the optimisation if the FLAGS register is in use }
  6610. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6611. begin
  6612. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6613. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6614. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6615. begin
  6616. RemoveInstruction(hp1);
  6617. Result := True;
  6618. end;
  6619. { Only set Result to True if the 'mov' instruction was removed }
  6620. RemoveInstruction(hp2);
  6621. end;
  6622. end
  6623. else
  6624. {$endif x86_64}
  6625. begin
  6626. { "shl/and" version }
  6627. { Don't do the optimisation if the FLAGS register is in use }
  6628. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6629. begin
  6630. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6631. RemoveInstruction(hp1);
  6632. Result := True;
  6633. end;
  6634. end;
  6635. Exit;
  6636. end
  6637. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6638. begin
  6639. { Even if the mask doesn't allow for its removal, we might be
  6640. able to optimise the mask for the "shl/and" version, which
  6641. may permit other peephole optimisations }
  6642. {$ifdef DEBUG_AOPTCPU}
  6643. mask := taicpu(hp1).oper[0]^.val and mask;
  6644. if taicpu(hp1).oper[0]^.val <> mask then
  6645. begin
  6646. DebugMsg(
  6647. SPeepholeOptimization +
  6648. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6649. ' to $' + debug_tostr(mask) +
  6650. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6651. taicpu(hp1).oper[0]^.val := mask;
  6652. end;
  6653. {$else DEBUG_AOPTCPU}
  6654. { If debugging is off, just set the operand even if it's the same }
  6655. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6656. {$endif DEBUG_AOPTCPU}
  6657. end;
  6658. end;
  6659. {
  6660. change
  6661. shl/sal const,reg
  6662. <op> ...(...,reg,1),...
  6663. into
  6664. <op> ...(...,reg,1 shl const),...
  6665. if const in 1..3
  6666. }
  6667. if MatchOpType(taicpu(p), top_const, top_reg) and
  6668. (taicpu(p).oper[0]^.val in [1..3]) and
  6669. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6670. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6671. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6672. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6673. MatchOpType(taicpu(hp1),top_ref))
  6674. ) and
  6675. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6676. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6677. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6678. begin
  6679. TransferUsedRegs(TmpUsedRegs);
  6680. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6681. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6682. begin
  6683. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6684. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6685. RemoveCurrentP(p);
  6686. Result:=true;
  6687. exit;
  6688. end;
  6689. end;
  6690. if MatchOpType(taicpu(p), top_const, top_reg) and
  6691. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6692. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6693. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6694. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6695. begin
  6696. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6697. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6698. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6699. {$ifdef x86_64}
  6700. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6701. {$endif x86_64}
  6702. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6703. begin
  6704. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6705. taicpu(hp1).opcode:=A_MOV;
  6706. taicpu(hp1).oper[0]^.val:=0;
  6707. end
  6708. else
  6709. begin
  6710. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6711. taicpu(hp1).oper[0]^.val:=shiftval;
  6712. end;
  6713. RemoveCurrentP(p);
  6714. Result:=true;
  6715. exit;
  6716. end;
  6717. end;
  6718. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6719. begin
  6720. case shr_size of
  6721. S_B:
  6722. { No valid combinations }
  6723. Result := False;
  6724. S_W:
  6725. Result := (Shift >= 8) and (movz_size = S_BW);
  6726. S_L:
  6727. Result :=
  6728. (Shift >= 24) { Any opsize is valid for this shift } or
  6729. ((Shift >= 16) and (movz_size = S_WL));
  6730. {$ifdef x86_64}
  6731. S_Q:
  6732. Result :=
  6733. (Shift >= 56) { Any opsize is valid for this shift } or
  6734. ((Shift >= 48) and (movz_size = S_WL));
  6735. {$endif x86_64}
  6736. else
  6737. InternalError(2022081510);
  6738. end;
  6739. end;
  6740. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6741. var
  6742. hp1, hp2: tai;
  6743. Shift: TCGInt;
  6744. LimitSize: Topsize;
  6745. DoNotMerge: Boolean;
  6746. begin
  6747. Result := False;
  6748. { All these optimisations work on "shr const,%reg" }
  6749. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6750. Exit;
  6751. DoNotMerge := False;
  6752. Shift := taicpu(p).oper[0]^.val;
  6753. LimitSize := taicpu(p).opsize;
  6754. hp1 := p;
  6755. repeat
  6756. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6757. Exit;
  6758. case taicpu(hp1).opcode of
  6759. A_TEST, A_CMP, A_Jcc:
  6760. { Skip over conditional jumps and relevant comparisons }
  6761. Continue;
  6762. A_MOVZX:
  6763. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6764. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6765. begin
  6766. { Since the original register is being read as is, subsequent
  6767. SHRs must not be merged at this point }
  6768. DoNotMerge := True;
  6769. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6770. begin
  6771. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6772. begin
  6773. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6774. taicpu(hp1).opcode := A_MOV;
  6775. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6776. case taicpu(hp1).opsize of
  6777. S_BW:
  6778. taicpu(hp1).opsize := S_W;
  6779. S_BL, S_WL:
  6780. taicpu(hp1).opsize := S_L;
  6781. else
  6782. InternalError(2022081503);
  6783. end;
  6784. { p itself hasn't changed, so no need to set Result to True }
  6785. Include(OptsToCheck, aoc_ForceNewIteration);
  6786. { See if there's anything afterwards that can be
  6787. optimised, since the input register hasn't changed }
  6788. Continue;
  6789. end;
  6790. { NOTE: If the MOVZX instruction reads and writes the same
  6791. register, defer this to the post-peephole optimisation stage }
  6792. Exit;
  6793. end;
  6794. end;
  6795. A_SHL, A_SAL, A_SHR:
  6796. if (taicpu(hp1).opsize <= LimitSize) and
  6797. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6798. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6799. begin
  6800. { Make sure the sizes don't exceed the register size limit
  6801. (measured by the shift value falling below the limit) }
  6802. if taicpu(hp1).opsize < LimitSize then
  6803. LimitSize := taicpu(hp1).opsize;
  6804. if taicpu(hp1).opcode = A_SHR then
  6805. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6806. else
  6807. begin
  6808. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6809. DoNotMerge := True;
  6810. end;
  6811. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6812. Exit;
  6813. { Since we've established that the combined shift is within
  6814. limits, we can actually combine the adjacent SHR
  6815. instructions even if they're different sizes }
  6816. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6817. begin
  6818. hp2 := tai(hp1.Previous);
  6819. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6820. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6821. RemoveInstruction(hp1);
  6822. hp1 := hp2;
  6823. { Though p has changed, only the constant has, and its
  6824. effects can still be detected on the next iteration of
  6825. the repeat..until loop }
  6826. Include(OptsToCheck, aoc_ForceNewIteration);
  6827. end;
  6828. { Move onto the next instruction }
  6829. Continue;
  6830. end;
  6831. else
  6832. ;
  6833. end;
  6834. Break;
  6835. until False;
  6836. end;
  6837. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6838. var
  6839. CurrentRef: TReference;
  6840. FullReg: TRegister;
  6841. hp1, hp2: tai;
  6842. begin
  6843. Result := False;
  6844. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6845. Exit;
  6846. { We assume you've checked if the operand is actually a reference by
  6847. this point. If it isn't, you'll most likely get an access violation }
  6848. CurrentRef := first_mov.oper[1]^.ref^;
  6849. { Memory must be aligned }
  6850. if (CurrentRef.offset mod 4) <> 0 then
  6851. Exit;
  6852. Inc(CurrentRef.offset);
  6853. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6854. if MatchOperand(second_mov.oper[0]^, 0) and
  6855. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6856. GetNextInstruction(second_mov, hp1) and
  6857. (hp1.typ = ait_instruction) and
  6858. (taicpu(hp1).opcode = A_MOV) and
  6859. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6860. (taicpu(hp1).oper[0]^.val = 0) then
  6861. begin
  6862. Inc(CurrentRef.offset);
  6863. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6864. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6865. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6866. begin
  6867. case taicpu(hp1).opsize of
  6868. S_B:
  6869. if GetNextInstruction(hp1, hp2) and
  6870. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6871. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6872. (taicpu(hp2).oper[0]^.val = 0) then
  6873. begin
  6874. Inc(CurrentRef.offset);
  6875. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6876. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6877. (taicpu(hp2).opsize = S_B) then
  6878. begin
  6879. RemoveInstruction(hp1);
  6880. RemoveInstruction(hp2);
  6881. first_mov.opsize := S_L;
  6882. if first_mov.oper[0]^.typ = top_reg then
  6883. begin
  6884. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6885. { Reuse second_mov as a MOVZX instruction }
  6886. second_mov.opcode := A_MOVZX;
  6887. second_mov.opsize := S_BL;
  6888. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6889. second_mov.loadreg(1, FullReg);
  6890. first_mov.oper[0]^.reg := FullReg;
  6891. asml.Remove(second_mov);
  6892. asml.InsertBefore(second_mov, first_mov);
  6893. end
  6894. else
  6895. { It's a value }
  6896. begin
  6897. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6898. RemoveInstruction(second_mov);
  6899. end;
  6900. Result := True;
  6901. Exit;
  6902. end;
  6903. end;
  6904. S_W:
  6905. begin
  6906. RemoveInstruction(hp1);
  6907. first_mov.opsize := S_L;
  6908. if first_mov.oper[0]^.typ = top_reg then
  6909. begin
  6910. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6911. { Reuse second_mov as a MOVZX instruction }
  6912. second_mov.opcode := A_MOVZX;
  6913. second_mov.opsize := S_BL;
  6914. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6915. second_mov.loadreg(1, FullReg);
  6916. first_mov.oper[0]^.reg := FullReg;
  6917. asml.Remove(second_mov);
  6918. asml.InsertBefore(second_mov, first_mov);
  6919. end
  6920. else
  6921. { It's a value }
  6922. begin
  6923. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6924. RemoveInstruction(second_mov);
  6925. end;
  6926. Result := True;
  6927. Exit;
  6928. end;
  6929. else
  6930. ;
  6931. end;
  6932. end;
  6933. end;
  6934. end;
  6935. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6936. { returns true if a "continue" should be done after this optimization }
  6937. var
  6938. hp1, hp2, hp3: tai;
  6939. begin
  6940. Result := false;
  6941. hp3 := nil;
  6942. if MatchOpType(taicpu(p),top_ref) and
  6943. GetNextInstruction(p, hp1) and
  6944. (hp1.typ = ait_instruction) and
  6945. (((taicpu(hp1).opcode = A_FLD) and
  6946. (taicpu(p).opcode = A_FSTP)) or
  6947. ((taicpu(p).opcode = A_FISTP) and
  6948. (taicpu(hp1).opcode = A_FILD))) and
  6949. MatchOpType(taicpu(hp1),top_ref) and
  6950. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6951. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6952. begin
  6953. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6954. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6955. GetNextInstruction(hp1, hp2) and
  6956. (((hp2.typ = ait_instruction) and
  6957. IsExitCode(hp2) and
  6958. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6959. not(assigned(current_procinfo.procdef.funcretsym) and
  6960. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6961. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6962. { fstp <temp>
  6963. fld <temp>
  6964. <dealloc> <temp>
  6965. }
  6966. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6967. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6968. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6969. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6970. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6971. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6972. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6973. )
  6974. )
  6975. ) then
  6976. begin
  6977. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6978. RemoveInstruction(hp1);
  6979. RemoveCurrentP(p, hp2);
  6980. { first case: exit code }
  6981. if hp2.typ = ait_instruction then
  6982. RemoveLastDeallocForFuncRes(p);
  6983. Result := true;
  6984. end
  6985. else
  6986. { we can do this only in fast math mode as fstp is rounding ...
  6987. ... still disabled as it breaks the compiler and/or rtl }
  6988. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6989. { ... or if another fstp equal to the first one follows }
  6990. GetNextInstruction(hp1,hp2) and
  6991. (hp2.typ = ait_instruction) and
  6992. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6993. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6994. begin
  6995. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6996. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6997. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6998. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6999. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7000. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7001. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7002. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7003. ) then
  7004. begin
  7005. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7006. RemoveCurrentP(p,hp2);
  7007. RemoveInstruction(hp1);
  7008. Result := true;
  7009. end
  7010. else if { fst can't store an extended/comp value }
  7011. (taicpu(p).opsize <> S_FX) and
  7012. (taicpu(p).opsize <> S_IQ) then
  7013. begin
  7014. if (taicpu(p).opcode = A_FSTP) then
  7015. taicpu(p).opcode := A_FST
  7016. else
  7017. taicpu(p).opcode := A_FIST;
  7018. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7019. RemoveInstruction(hp1);
  7020. Result := true;
  7021. end;
  7022. end;
  7023. end;
  7024. end;
  7025. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7026. var
  7027. hp1, hp2, hp3: tai;
  7028. begin
  7029. result:=false;
  7030. if MatchOpType(taicpu(p),top_reg) and
  7031. GetNextInstruction(p, hp1) and
  7032. (hp1.typ = Ait_Instruction) and
  7033. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7034. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7035. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7036. { change to
  7037. fld reg fxxx reg,st
  7038. fxxxp st, st1 (hp1)
  7039. Remark: non commutative operations must be reversed!
  7040. }
  7041. begin
  7042. case taicpu(hp1).opcode Of
  7043. A_FMULP,A_FADDP,
  7044. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7045. begin
  7046. case taicpu(hp1).opcode Of
  7047. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7048. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7049. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7050. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7051. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7052. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7053. else
  7054. internalerror(2019050534);
  7055. end;
  7056. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7057. taicpu(hp1).oper[1]^.reg := NR_ST;
  7058. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7059. RemoveCurrentP(p, hp1);
  7060. Result:=true;
  7061. exit;
  7062. end;
  7063. else
  7064. ;
  7065. end;
  7066. end
  7067. else
  7068. if MatchOpType(taicpu(p),top_ref) and
  7069. GetNextInstruction(p, hp2) and
  7070. (hp2.typ = Ait_Instruction) and
  7071. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7072. (taicpu(p).opsize in [S_FS, S_FL]) and
  7073. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7074. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7075. if GetLastInstruction(p, hp1) and
  7076. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7077. MatchOpType(taicpu(hp1),top_ref) and
  7078. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7079. if ((taicpu(hp2).opcode = A_FMULP) or
  7080. (taicpu(hp2).opcode = A_FADDP)) then
  7081. { change to
  7082. fld/fst mem1 (hp1) fld/fst mem1
  7083. fld mem1 (p) fadd/
  7084. faddp/ fmul st, st
  7085. fmulp st, st1 (hp2) }
  7086. begin
  7087. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7088. RemoveCurrentP(p, hp1);
  7089. if (taicpu(hp2).opcode = A_FADDP) then
  7090. taicpu(hp2).opcode := A_FADD
  7091. else
  7092. taicpu(hp2).opcode := A_FMUL;
  7093. taicpu(hp2).oper[1]^.reg := NR_ST;
  7094. end
  7095. else
  7096. { change to
  7097. fld/fst mem1 (hp1) fld/fst mem1
  7098. fld mem1 (p) fld st
  7099. }
  7100. begin
  7101. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7102. taicpu(p).changeopsize(S_FL);
  7103. taicpu(p).loadreg(0,NR_ST);
  7104. end
  7105. else
  7106. begin
  7107. case taicpu(hp2).opcode Of
  7108. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7109. { change to
  7110. fld/fst mem1 (hp1) fld/fst mem1
  7111. fld mem2 (p) fxxx mem2
  7112. fxxxp st, st1 (hp2) }
  7113. begin
  7114. case taicpu(hp2).opcode Of
  7115. A_FADDP: taicpu(p).opcode := A_FADD;
  7116. A_FMULP: taicpu(p).opcode := A_FMUL;
  7117. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7118. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7119. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7120. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7121. else
  7122. internalerror(2019050533);
  7123. end;
  7124. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7125. RemoveInstruction(hp2);
  7126. end
  7127. else
  7128. ;
  7129. end
  7130. end
  7131. end;
  7132. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7133. begin
  7134. Result := condition_in(cond1, cond2) or
  7135. { Not strictly subsets due to the actual flags checked, but because we're
  7136. comparing integers, E is a subset of AE and GE and their aliases }
  7137. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7138. end;
  7139. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7140. var
  7141. v: TCGInt;
  7142. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7143. FirstMatch, TempBool: Boolean;
  7144. NewReg: TRegister;
  7145. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7146. begin
  7147. Result:=false;
  7148. { All these optimisations need a next instruction }
  7149. if not GetNextInstruction(p, hp1) then
  7150. Exit;
  7151. { Search for:
  7152. cmp ###,###
  7153. j(c1) @lbl1
  7154. ...
  7155. @lbl:
  7156. cmp ###,### (same comparison as above)
  7157. j(c2) @lbl2
  7158. If c1 is a subset of c2, change to:
  7159. cmp ###,###
  7160. j(c1) @lbl2
  7161. (@lbl1 may become a dead label as a result)
  7162. }
  7163. { Also handle cases where there are multiple jumps in a row }
  7164. p_jump := hp1;
  7165. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7166. begin
  7167. if IsJumpToLabel(taicpu(p_jump)) then
  7168. begin
  7169. { Do jump optimisations first in case the condition becomes
  7170. unnecessary }
  7171. TempBool := True;
  7172. if DoJumpOptimizations(p_jump, TempBool) or
  7173. not TempBool then
  7174. begin
  7175. if Assigned(p_jump) then
  7176. begin
  7177. { CollapseZeroDistJump will be set to the label or an align
  7178. before it after the jump if it optimises, whether or not
  7179. the label is live or dead }
  7180. if (p_jump.typ = ait_align) or
  7181. (
  7182. (p_jump.typ = ait_label) and
  7183. not (tai_label(p_jump).labsym.is_used)
  7184. ) then
  7185. GetNextInstruction(p_jump, p_jump);
  7186. end;
  7187. TransferUsedRegs(TmpUsedRegs);
  7188. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7189. if not Assigned(p_jump) or
  7190. (
  7191. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7192. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7193. ) then
  7194. begin
  7195. { No more conditional jumps; conditional statement is no longer required }
  7196. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7197. RemoveCurrentP(p);
  7198. Result := True;
  7199. Exit;
  7200. end;
  7201. hp1 := p_jump;
  7202. Include(OptsToCheck, aoc_ForceNewIteration);
  7203. Continue;
  7204. end;
  7205. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7206. if GetNextInstruction(p_jump, hp2) and
  7207. (
  7208. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7209. not TempBool
  7210. ) then
  7211. begin
  7212. hp1 := p_jump;
  7213. Include(OptsToCheck, aoc_ForceNewIteration);
  7214. Continue;
  7215. end;
  7216. p_label := nil;
  7217. if Assigned(JumpLabel) then
  7218. p_label := getlabelwithsym(JumpLabel);
  7219. if Assigned(p_label) and
  7220. GetNextInstruction(p_label, p_dist) and
  7221. MatchInstruction(p_dist, A_CMP, []) and
  7222. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7223. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7224. GetNextInstruction(p_dist, hp1_dist) and
  7225. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7226. begin
  7227. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7228. if JumpLabel = JumpLabel_dist then
  7229. { This is an infinite loop }
  7230. Exit;
  7231. { Best optimisation when the first condition is a subset (or equal) of the second }
  7232. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7233. begin
  7234. { Any registers used here will already be allocated }
  7235. if Assigned(JumpLabel) then
  7236. JumpLabel.DecRefs;
  7237. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7238. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7239. Result := True;
  7240. { Don't exit yet. Since p and p_jump haven't actually been
  7241. removed, we can check for more on this iteration }
  7242. end
  7243. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7244. GetNextInstruction(hp1_dist, hp1_label) and
  7245. (hp1_label.typ = ait_label) then
  7246. begin
  7247. JumpLabel_far := tai_label(hp1_label).labsym;
  7248. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7249. { This is an infinite loop }
  7250. Exit;
  7251. if Assigned(JumpLabel_far) then
  7252. begin
  7253. { In this situation, if the first jump branches, the second one will never,
  7254. branch so change the destination label to after the second jump }
  7255. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7256. if Assigned(JumpLabel) then
  7257. JumpLabel.DecRefs;
  7258. JumpLabel_far.IncRefs;
  7259. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7260. Result := True;
  7261. { Don't exit yet. Since p and p_jump haven't actually been
  7262. removed, we can check for more on this iteration }
  7263. Continue;
  7264. end;
  7265. end;
  7266. end;
  7267. end;
  7268. { Search for:
  7269. cmp ###,###
  7270. j(c1) @lbl1
  7271. cmp ###,### (same as first)
  7272. Remove second cmp
  7273. }
  7274. if GetNextInstruction(p_jump, hp2) and
  7275. (
  7276. (
  7277. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7278. (
  7279. (
  7280. MatchOpType(taicpu(p), top_const, top_reg) and
  7281. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7282. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7283. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7284. ) or (
  7285. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7286. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7287. )
  7288. )
  7289. ) or (
  7290. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7291. MatchOperand(taicpu(p).oper[0]^, 0) and
  7292. (taicpu(p).oper[1]^.typ = top_reg) and
  7293. MatchInstruction(hp2, A_TEST, []) and
  7294. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7295. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7296. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7297. )
  7298. ) then
  7299. begin
  7300. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7301. RemoveInstruction(hp2);
  7302. Result := True;
  7303. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7304. end;
  7305. GetNextInstruction(p_jump, p_jump);
  7306. end;
  7307. if (
  7308. { Don't call GetNextInstruction again if we already have it }
  7309. (hp1 = p_jump) or
  7310. GetNextInstruction(p, hp1)
  7311. ) and
  7312. MatchInstruction(hp1, A_Jcc, []) and
  7313. IsJumpToLabel(taicpu(hp1)) and
  7314. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7315. GetNextInstruction(hp1, hp2) then
  7316. begin
  7317. {
  7318. cmp x, y (or "cmp y, x")
  7319. je @lbl
  7320. mov x, y
  7321. @lbl:
  7322. (x and y can be constants, registers or references)
  7323. Change to:
  7324. mov x, y (x and y will always be equal in the end)
  7325. @lbl: (may beceome a dead label)
  7326. Also:
  7327. cmp x, y (or "cmp y, x")
  7328. jne @lbl
  7329. mov x, y
  7330. @lbl:
  7331. (x and y can be constants, registers or references)
  7332. Change to:
  7333. Absolutely nothing! (Except @lbl if it's still live)
  7334. }
  7335. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7336. (
  7337. (
  7338. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7339. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7340. ) or (
  7341. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7342. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7343. )
  7344. ) and
  7345. GetNextInstruction(hp2, hp1_label) and
  7346. (hp1_label.typ = ait_label) and
  7347. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7348. begin
  7349. tai_label(hp1_label).labsym.DecRefs;
  7350. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7351. begin
  7352. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7353. RemoveInstruction(hp2);
  7354. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7355. end
  7356. else
  7357. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7358. RemoveInstruction(hp1);
  7359. RemoveCurrentp(p, hp2);
  7360. Result := True;
  7361. Exit;
  7362. end;
  7363. {
  7364. Try to optimise the following:
  7365. cmp $x,### ($x and $y can be registers or constants)
  7366. je @lbl1 (only reference)
  7367. cmp $y,### (### are identical)
  7368. @Lbl:
  7369. sete %reg1
  7370. Change to:
  7371. cmp $x,###
  7372. sete %reg2 (allocate new %reg2)
  7373. cmp $y,###
  7374. sete %reg1
  7375. orb %reg2,%reg1
  7376. (dealloc %reg2)
  7377. This adds an instruction (so don't perform under -Os), but it removes
  7378. a conditional branch.
  7379. }
  7380. if not (cs_opt_size in current_settings.optimizerswitches) and
  7381. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7382. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7383. { The first operand of CMP instructions can only be a register or
  7384. immediate anyway, so no need to check }
  7385. GetNextInstruction(hp2, p_label) and
  7386. (p_label.typ = ait_label) and
  7387. (tai_label(p_label).labsym.getrefs = 1) and
  7388. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7389. GetNextInstruction(p_label, p_dist) and
  7390. MatchInstruction(p_dist, A_SETcc, []) and
  7391. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7392. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7393. begin
  7394. TransferUsedRegs(TmpUsedRegs);
  7395. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7396. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7397. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7398. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7399. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7400. { Get the instruction after the SETcc instruction so we can
  7401. allocate a new register over the entire range }
  7402. GetNextInstruction(p_dist, hp1_dist) then
  7403. begin
  7404. { Register can appear in p if it's not used afterwards, so only
  7405. allocate between hp1 and hp1_dist }
  7406. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7407. if NewReg <> NR_NO then
  7408. begin
  7409. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7410. { Change the jump instruction into a SETcc instruction }
  7411. taicpu(hp1).opcode := A_SETcc;
  7412. taicpu(hp1).opsize := S_B;
  7413. taicpu(hp1).loadreg(0, NewReg);
  7414. { This is now a dead label }
  7415. tai_label(p_label).labsym.decrefs;
  7416. { Prefer adding before the next instruction so the FLAGS
  7417. register is deallicated first }
  7418. AsmL.InsertBefore(
  7419. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7420. hp1_dist
  7421. );
  7422. Result := True;
  7423. { Don't exit yet, as p wasn't changed and hp1, while
  7424. modified, is still intact and might be optimised by the
  7425. SETcc optimisation below }
  7426. end;
  7427. end;
  7428. end;
  7429. end;
  7430. if taicpu(p).oper[0]^.typ = top_const then
  7431. begin
  7432. if (taicpu(p).oper[0]^.val = 0) and
  7433. (taicpu(p).oper[1]^.typ = top_reg) and
  7434. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7435. begin
  7436. hp2 := p;
  7437. FirstMatch := True;
  7438. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7439. anything meaningful once it's converted to "test %reg,%reg";
  7440. additionally, some jumps will always (or never) branch, so
  7441. evaluate every jump immediately following the
  7442. comparison, optimising the conditions if possible.
  7443. Similarly with SETcc... those that are always set to 0 or 1
  7444. are changed to MOV instructions }
  7445. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7446. (
  7447. GetNextInstruction(hp2, hp1) and
  7448. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7449. ) do
  7450. begin
  7451. FirstMatch := False;
  7452. case taicpu(hp1).condition of
  7453. C_B, C_C, C_NAE, C_O:
  7454. { For B/NAE:
  7455. Will never branch since an unsigned integer can never be below zero
  7456. For C/O:
  7457. Result cannot overflow because 0 is being subtracted
  7458. }
  7459. begin
  7460. if taicpu(hp1).opcode = A_Jcc then
  7461. begin
  7462. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7463. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7464. RemoveInstruction(hp1);
  7465. { Since hp1 was deleted, hp2 must not be updated }
  7466. Continue;
  7467. end
  7468. else
  7469. begin
  7470. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7471. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7472. taicpu(hp1).opcode := A_MOV;
  7473. taicpu(hp1).ops := 2;
  7474. taicpu(hp1).condition := C_None;
  7475. taicpu(hp1).opsize := S_B;
  7476. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7477. taicpu(hp1).loadconst(0, 0);
  7478. end;
  7479. end;
  7480. C_BE, C_NA:
  7481. begin
  7482. { Will only branch if equal to zero }
  7483. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7484. taicpu(hp1).condition := C_E;
  7485. end;
  7486. C_A, C_NBE:
  7487. begin
  7488. { Will only branch if not equal to zero }
  7489. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7490. taicpu(hp1).condition := C_NE;
  7491. end;
  7492. C_AE, C_NB, C_NC, C_NO:
  7493. begin
  7494. { Will always branch }
  7495. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7496. if taicpu(hp1).opcode = A_Jcc then
  7497. begin
  7498. MakeUnconditional(taicpu(hp1));
  7499. { Any jumps/set that follow will now be dead code }
  7500. RemoveDeadCodeAfterJump(taicpu(hp1));
  7501. Break;
  7502. end
  7503. else
  7504. begin
  7505. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7506. taicpu(hp1).opcode := A_MOV;
  7507. taicpu(hp1).ops := 2;
  7508. taicpu(hp1).condition := C_None;
  7509. taicpu(hp1).opsize := S_B;
  7510. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7511. taicpu(hp1).loadconst(0, 1);
  7512. end;
  7513. end;
  7514. C_None:
  7515. InternalError(2020012201);
  7516. C_P, C_PE, C_NP, C_PO:
  7517. { We can't handle parity checks and they should never be generated
  7518. after a general-purpose CMP (it's used in some floating-point
  7519. comparisons that don't use CMP) }
  7520. InternalError(2020012202);
  7521. else
  7522. { Zero/Equality, Sign, their complements and all of the
  7523. signed comparisons do not need to be converted };
  7524. end;
  7525. hp2 := hp1;
  7526. end;
  7527. { Convert the instruction to a TEST }
  7528. taicpu(p).opcode := A_TEST;
  7529. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7530. Result := True;
  7531. Exit;
  7532. end
  7533. else if (taicpu(p).oper[0]^.val = 1) and
  7534. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7535. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7536. begin
  7537. { Convert; To:
  7538. cmp $1,r/m cmp $0,r/m
  7539. jl @lbl jle @lbl
  7540. (Also do inverted conditions)
  7541. }
  7542. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7543. taicpu(p).oper[0]^.val := 0;
  7544. if taicpu(hp1).condition in [C_L, C_NGE] then
  7545. taicpu(hp1).condition := C_LE
  7546. else
  7547. taicpu(hp1).condition := C_NLE;
  7548. { If the instruction is now "cmp $0,%reg", convert it to a
  7549. TEST (and effectively do the work of the "cmp $0,%reg" in
  7550. the block above)
  7551. }
  7552. if (taicpu(p).oper[1]^.typ = top_reg) then
  7553. begin
  7554. taicpu(p).opcode := A_TEST;
  7555. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7556. end;
  7557. Result := True;
  7558. Exit;
  7559. end
  7560. else if (taicpu(p).oper[1]^.typ = top_reg)
  7561. {$ifdef x86_64}
  7562. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7563. {$endif x86_64}
  7564. then
  7565. begin
  7566. { cmp register,$8000 neg register
  7567. je target --> jo target
  7568. .... only if register is deallocated before jump.}
  7569. case Taicpu(p).opsize of
  7570. S_B: v:=$80;
  7571. S_W: v:=$8000;
  7572. S_L: v:=qword($80000000);
  7573. else
  7574. internalerror(2013112905);
  7575. end;
  7576. if (taicpu(p).oper[0]^.val=v) and
  7577. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7578. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7579. begin
  7580. TransferUsedRegs(TmpUsedRegs);
  7581. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7582. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7583. begin
  7584. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7585. Taicpu(p).opcode:=A_NEG;
  7586. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7587. Taicpu(p).clearop(1);
  7588. Taicpu(p).ops:=1;
  7589. if Taicpu(hp1).condition=C_E then
  7590. Taicpu(hp1).condition:=C_O
  7591. else
  7592. Taicpu(hp1).condition:=C_NO;
  7593. Result:=true;
  7594. exit;
  7595. end;
  7596. end;
  7597. end;
  7598. end;
  7599. if TrySwapMovCmp(p, hp1) then
  7600. begin
  7601. Result := True;
  7602. Exit;
  7603. end;
  7604. end;
  7605. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7606. var
  7607. hp1: tai;
  7608. begin
  7609. {
  7610. remove the second (v)pxor from
  7611. pxor reg,reg
  7612. ...
  7613. pxor reg,reg
  7614. }
  7615. Result:=false;
  7616. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7617. MatchOpType(taicpu(p),top_reg,top_reg) and
  7618. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7619. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7620. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7621. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7622. begin
  7623. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7624. RemoveInstruction(hp1);
  7625. Result:=true;
  7626. Exit;
  7627. end
  7628. {
  7629. replace
  7630. pxor reg1,reg1
  7631. movapd/s reg1,reg2
  7632. dealloc reg1
  7633. by
  7634. pxor reg2,reg2
  7635. }
  7636. else if GetNextInstruction(p,hp1) and
  7637. { we mix single and double opperations here because we assume that the compiler
  7638. generates vmovapd only after double operations and vmovaps only after single operations }
  7639. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7640. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7641. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7642. (taicpu(p).oper[0]^.typ=top_reg) then
  7643. begin
  7644. TransferUsedRegs(TmpUsedRegs);
  7645. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7646. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7647. begin
  7648. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7649. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7650. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7651. RemoveInstruction(hp1);
  7652. result:=true;
  7653. end;
  7654. end;
  7655. end;
  7656. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7657. var
  7658. hp1: tai;
  7659. begin
  7660. {
  7661. remove the second (v)pxor from
  7662. (v)pxor reg,reg
  7663. ...
  7664. (v)pxor reg,reg
  7665. }
  7666. Result:=false;
  7667. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7668. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7669. begin
  7670. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7671. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7672. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7673. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7674. begin
  7675. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7676. RemoveInstruction(hp1);
  7677. Result:=true;
  7678. Exit;
  7679. end;
  7680. {$ifdef x86_64}
  7681. {
  7682. replace
  7683. vpxor reg1,reg1,reg1
  7684. vmov reg,mem
  7685. by
  7686. movq $0,mem
  7687. }
  7688. if GetNextInstruction(p,hp1) and
  7689. MatchInstruction(hp1,A_VMOVSD,[]) and
  7690. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7691. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7692. begin
  7693. TransferUsedRegs(TmpUsedRegs);
  7694. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7695. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7696. begin
  7697. taicpu(hp1).loadconst(0,0);
  7698. taicpu(hp1).opcode:=A_MOV;
  7699. taicpu(hp1).opsize:=S_Q;
  7700. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7701. RemoveCurrentP(p);
  7702. result:=true;
  7703. Exit;
  7704. end;
  7705. end;
  7706. {$endif x86_64}
  7707. end
  7708. {
  7709. replace
  7710. vpxor reg1,reg1,reg2
  7711. by
  7712. vpxor reg2,reg2,reg2
  7713. to avoid unncessary data dependencies
  7714. }
  7715. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7716. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7717. begin
  7718. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7719. { avoid unncessary data dependency }
  7720. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7721. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7722. result:=true;
  7723. exit;
  7724. end;
  7725. Result:=OptPass1VOP(p);
  7726. end;
  7727. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7728. var
  7729. hp1 : tai;
  7730. begin
  7731. result:=false;
  7732. { replace
  7733. IMul const,%mreg1,%mreg2
  7734. Mov %reg2,%mreg3
  7735. dealloc %mreg3
  7736. by
  7737. Imul const,%mreg1,%mreg23
  7738. }
  7739. if (taicpu(p).ops=3) and
  7740. GetNextInstruction(p,hp1) and
  7741. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7742. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7743. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7744. begin
  7745. TransferUsedRegs(TmpUsedRegs);
  7746. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7747. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7748. begin
  7749. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7750. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7751. RemoveInstruction(hp1);
  7752. result:=true;
  7753. end;
  7754. end;
  7755. end;
  7756. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7757. var
  7758. hp1 : tai;
  7759. begin
  7760. result:=false;
  7761. { replace
  7762. IMul %reg0,%reg1,%reg2
  7763. Mov %reg2,%reg3
  7764. dealloc %reg2
  7765. by
  7766. Imul %reg0,%reg1,%reg3
  7767. }
  7768. if GetNextInstruction(p,hp1) and
  7769. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7770. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7771. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7772. begin
  7773. TransferUsedRegs(TmpUsedRegs);
  7774. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7775. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7776. begin
  7777. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7778. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7779. RemoveInstruction(hp1);
  7780. result:=true;
  7781. end;
  7782. end;
  7783. end;
  7784. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7785. var
  7786. hp1: tai;
  7787. begin
  7788. Result:=false;
  7789. { get rid of
  7790. (v)cvtss2sd reg0,<reg1,>reg2
  7791. (v)cvtss2sd reg2,<reg2,>reg0
  7792. }
  7793. if GetNextInstruction(p,hp1) and
  7794. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7795. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7796. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7797. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7798. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7799. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7800. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7801. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7802. )
  7803. ) then
  7804. begin
  7805. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7806. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7807. begin
  7808. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7809. RemoveCurrentP(p);
  7810. RemoveInstruction(hp1);
  7811. end
  7812. else
  7813. begin
  7814. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7815. if taicpu(hp1).opcode=A_CVTSD2SS then
  7816. begin
  7817. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7818. taicpu(p).opcode:=A_MOVAPS;
  7819. end
  7820. else
  7821. begin
  7822. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7823. taicpu(p).opcode:=A_VMOVAPS;
  7824. end;
  7825. taicpu(p).ops:=2;
  7826. RemoveInstruction(hp1);
  7827. end;
  7828. Result:=true;
  7829. Exit;
  7830. end;
  7831. end;
  7832. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7833. var
  7834. hp1, hp2, hp3, hp4, hp5: tai;
  7835. ThisReg: TRegister;
  7836. begin
  7837. Result := False;
  7838. if not GetNextInstruction(p,hp1) then
  7839. Exit;
  7840. {
  7841. convert
  7842. j<c> .L1
  7843. mov 1,reg
  7844. jmp .L2
  7845. .L1
  7846. mov 0,reg
  7847. .L2
  7848. into
  7849. mov 0,reg
  7850. set<not(c)> reg
  7851. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7852. would destroy the flag contents
  7853. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7854. executed at the same time as a previous comparison.
  7855. set<not(c)> reg
  7856. movzx reg, reg
  7857. }
  7858. if MatchInstruction(hp1,A_MOV,[]) and
  7859. (taicpu(hp1).oper[0]^.typ = top_const) and
  7860. (
  7861. (
  7862. (taicpu(hp1).oper[1]^.typ = top_reg)
  7863. {$ifdef i386}
  7864. { Under i386, ESI, EDI, EBP and ESP
  7865. don't have an 8-bit representation }
  7866. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7867. {$endif i386}
  7868. ) or (
  7869. {$ifdef i386}
  7870. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7871. {$endif i386}
  7872. (taicpu(hp1).opsize = S_B)
  7873. )
  7874. ) and
  7875. GetNextInstruction(hp1,hp2) and
  7876. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7877. GetNextInstruction(hp2,hp3) and
  7878. (hp3.typ=ait_label) and
  7879. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7880. GetNextInstruction(hp3,hp4) and
  7881. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7882. (taicpu(hp4).oper[0]^.typ = top_const) and
  7883. (
  7884. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7885. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7886. ) and
  7887. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7888. GetNextInstruction(hp4,hp5) and
  7889. (hp5.typ=ait_label) and
  7890. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7891. begin
  7892. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7893. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7894. tai_label(hp3).labsym.DecRefs;
  7895. { If this isn't the only reference to the middle label, we can
  7896. still make a saving - only that the first jump and everything
  7897. that follows will remain. }
  7898. if (tai_label(hp3).labsym.getrefs = 0) then
  7899. begin
  7900. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7901. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7902. else
  7903. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7904. { remove jump, first label and second MOV (also catching any aligns) }
  7905. repeat
  7906. if not GetNextInstruction(hp2, hp3) then
  7907. InternalError(2021040810);
  7908. RemoveInstruction(hp2);
  7909. hp2 := hp3;
  7910. until hp2 = hp5;
  7911. { Don't decrement reference count before the removal loop
  7912. above, otherwise GetNextInstruction won't stop on the
  7913. the label }
  7914. tai_label(hp5).labsym.DecRefs;
  7915. end
  7916. else
  7917. begin
  7918. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7919. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7920. else
  7921. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7922. end;
  7923. taicpu(p).opcode:=A_SETcc;
  7924. taicpu(p).opsize:=S_B;
  7925. taicpu(p).is_jmp:=False;
  7926. if taicpu(hp1).opsize=S_B then
  7927. begin
  7928. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7929. if taicpu(hp1).oper[1]^.typ = top_reg then
  7930. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7931. RemoveInstruction(hp1);
  7932. end
  7933. else
  7934. begin
  7935. { Will be a register because the size can't be S_B otherwise }
  7936. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7937. taicpu(p).loadreg(0, ThisReg);
  7938. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7939. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7940. begin
  7941. case taicpu(hp1).opsize of
  7942. S_W:
  7943. taicpu(hp1).opsize := S_BW;
  7944. S_L:
  7945. taicpu(hp1).opsize := S_BL;
  7946. {$ifdef x86_64}
  7947. S_Q:
  7948. begin
  7949. taicpu(hp1).opsize := S_BL;
  7950. { Change the destination register to 32-bit }
  7951. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7952. end;
  7953. {$endif x86_64}
  7954. else
  7955. InternalError(2021040820);
  7956. end;
  7957. taicpu(hp1).opcode := A_MOVZX;
  7958. taicpu(hp1).loadreg(0, ThisReg);
  7959. end
  7960. else
  7961. begin
  7962. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7963. { hp1 is already a MOV instruction with the correct register }
  7964. taicpu(hp1).loadconst(0, 0);
  7965. { Inserting it right before p will guarantee that the flags are also tracked }
  7966. asml.Remove(hp1);
  7967. asml.InsertBefore(hp1, p);
  7968. end;
  7969. end;
  7970. Result:=true;
  7971. exit;
  7972. end
  7973. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  7974. Result := TryJccStcClcOpt(p, hp1)
  7975. else if (hp1.typ = ait_label) then
  7976. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7977. end;
  7978. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7979. var
  7980. hp1, hp2, hp3: tai;
  7981. SourceRef, TargetRef: TReference;
  7982. CurrentReg: TRegister;
  7983. begin
  7984. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7985. if not UseAVX then
  7986. InternalError(2021100501);
  7987. Result := False;
  7988. { Look for the following to simplify:
  7989. vmovdqa/u x(mem1), %xmmreg
  7990. vmovdqa/u %xmmreg, y(mem2)
  7991. vmovdqa/u x+16(mem1), %xmmreg
  7992. vmovdqa/u %xmmreg, y+16(mem2)
  7993. Change to:
  7994. vmovdqa/u x(mem1), %ymmreg
  7995. vmovdqa/u %ymmreg, y(mem2)
  7996. vpxor %ymmreg, %ymmreg, %ymmreg
  7997. ( The VPXOR instruction is to zero the upper half, thus removing the
  7998. need to call the potentially expensive VZEROUPPER instruction. Other
  7999. peephole optimisations can remove VPXOR if it's unnecessary )
  8000. }
  8001. TransferUsedRegs(TmpUsedRegs);
  8002. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8003. { NOTE: In the optimisations below, if the references dictate that an
  8004. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8005. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8006. if (taicpu(p).opsize = S_XMM) and
  8007. MatchOpType(taicpu(p), top_ref, top_reg) and
  8008. GetNextInstruction(p, hp1) and
  8009. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8010. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8011. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8012. begin
  8013. SourceRef := taicpu(p).oper[0]^.ref^;
  8014. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8015. if GetNextInstruction(hp1, hp2) and
  8016. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8017. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8018. begin
  8019. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8020. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8021. Inc(SourceRef.offset, 16);
  8022. { Reuse the register in the first block move }
  8023. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8024. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8025. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8026. begin
  8027. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8028. Inc(TargetRef.offset, 16);
  8029. if GetNextInstruction(hp2, hp3) and
  8030. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8031. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8032. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8033. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8034. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8035. begin
  8036. { Update the register tracking to the new size }
  8037. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8038. { Remember that the offsets are 16 ahead }
  8039. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8040. if not (
  8041. ((SourceRef.offset mod 32) = 16) and
  8042. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8043. ) then
  8044. taicpu(p).opcode := A_VMOVDQU;
  8045. taicpu(p).opsize := S_YMM;
  8046. taicpu(p).oper[1]^.reg := CurrentReg;
  8047. if not (
  8048. ((TargetRef.offset mod 32) = 16) and
  8049. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8050. ) then
  8051. taicpu(hp1).opcode := A_VMOVDQU;
  8052. taicpu(hp1).opsize := S_YMM;
  8053. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8054. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8055. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8056. if (pi_uses_ymm in current_procinfo.flags) then
  8057. RemoveInstruction(hp2)
  8058. else
  8059. begin
  8060. taicpu(hp2).opcode := A_VPXOR;
  8061. taicpu(hp2).opsize := S_YMM;
  8062. taicpu(hp2).loadreg(0, CurrentReg);
  8063. taicpu(hp2).loadreg(1, CurrentReg);
  8064. taicpu(hp2).loadreg(2, CurrentReg);
  8065. taicpu(hp2).ops := 3;
  8066. end;
  8067. RemoveInstruction(hp3);
  8068. Result := True;
  8069. Exit;
  8070. end;
  8071. end
  8072. else
  8073. begin
  8074. { See if the next references are 16 less rather than 16 greater }
  8075. Dec(SourceRef.offset, 32); { -16 the other way }
  8076. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8077. begin
  8078. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8079. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8080. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8081. GetNextInstruction(hp2, hp3) and
  8082. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8083. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8084. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8085. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8086. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8087. begin
  8088. { Update the register tracking to the new size }
  8089. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8090. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8091. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8092. if not(
  8093. ((SourceRef.offset mod 32) = 0) and
  8094. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8095. ) then
  8096. taicpu(hp2).opcode := A_VMOVDQU;
  8097. taicpu(hp2).opsize := S_YMM;
  8098. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8099. if not (
  8100. ((TargetRef.offset mod 32) = 0) and
  8101. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8102. ) then
  8103. taicpu(hp3).opcode := A_VMOVDQU;
  8104. taicpu(hp3).opsize := S_YMM;
  8105. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8106. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8107. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8108. if (pi_uses_ymm in current_procinfo.flags) then
  8109. RemoveInstruction(hp1)
  8110. else
  8111. begin
  8112. taicpu(hp1).opcode := A_VPXOR;
  8113. taicpu(hp1).opsize := S_YMM;
  8114. taicpu(hp1).loadreg(0, CurrentReg);
  8115. taicpu(hp1).loadreg(1, CurrentReg);
  8116. taicpu(hp1).loadreg(2, CurrentReg);
  8117. taicpu(hp1).ops := 3;
  8118. Asml.Remove(hp1);
  8119. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8120. end;
  8121. RemoveCurrentP(p, hp2);
  8122. Result := True;
  8123. Exit;
  8124. end;
  8125. end;
  8126. end;
  8127. end;
  8128. end;
  8129. end;
  8130. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8131. var
  8132. hp2, hp3, first_assignment: tai;
  8133. IncCount, OperIdx: Integer;
  8134. OrigLabel: TAsmLabel;
  8135. begin
  8136. Count := 0;
  8137. Result := False;
  8138. first_assignment := nil;
  8139. if (LoopCount >= 20) then
  8140. begin
  8141. { Guard against infinite loops }
  8142. Exit;
  8143. end;
  8144. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8145. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8146. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8147. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8148. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8149. Exit;
  8150. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8151. {
  8152. change
  8153. jmp .L1
  8154. ...
  8155. .L1:
  8156. mov ##, ## ( multiple movs possible )
  8157. jmp/ret
  8158. into
  8159. mov ##, ##
  8160. jmp/ret
  8161. }
  8162. if not Assigned(hp1) then
  8163. begin
  8164. hp1 := GetLabelWithSym(OrigLabel);
  8165. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8166. Exit;
  8167. end;
  8168. hp2 := hp1;
  8169. while Assigned(hp2) do
  8170. begin
  8171. if Assigned(hp2) and (hp2.typ = ait_label) then
  8172. SkipLabels(hp2,hp2);
  8173. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8174. Break;
  8175. case taicpu(hp2).opcode of
  8176. A_MOVSD:
  8177. begin
  8178. if taicpu(hp2).ops = 0 then
  8179. { Wrong MOVSD }
  8180. Break;
  8181. Inc(Count);
  8182. if Count >= 5 then
  8183. { Too many to be worthwhile }
  8184. Break;
  8185. GetNextInstruction(hp2, hp2);
  8186. Continue;
  8187. end;
  8188. A_MOV,
  8189. A_MOVD,
  8190. A_MOVQ,
  8191. A_MOVSX,
  8192. {$ifdef x86_64}
  8193. A_MOVSXD,
  8194. {$endif x86_64}
  8195. A_MOVZX,
  8196. A_MOVAPS,
  8197. A_MOVUPS,
  8198. A_MOVSS,
  8199. A_MOVAPD,
  8200. A_MOVUPD,
  8201. A_MOVDQA,
  8202. A_MOVDQU,
  8203. A_VMOVSS,
  8204. A_VMOVAPS,
  8205. A_VMOVUPS,
  8206. A_VMOVSD,
  8207. A_VMOVAPD,
  8208. A_VMOVUPD,
  8209. A_VMOVDQA,
  8210. A_VMOVDQU:
  8211. begin
  8212. Inc(Count);
  8213. if Count >= 5 then
  8214. { Too many to be worthwhile }
  8215. Break;
  8216. GetNextInstruction(hp2, hp2);
  8217. Continue;
  8218. end;
  8219. A_JMP:
  8220. begin
  8221. { Guard against infinite loops }
  8222. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8223. Exit;
  8224. { Analyse this jump first in case it also duplicates assignments }
  8225. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8226. begin
  8227. { Something did change! }
  8228. Result := True;
  8229. Inc(Count, IncCount);
  8230. if Count >= 5 then
  8231. begin
  8232. { Too many to be worthwhile }
  8233. Exit;
  8234. end;
  8235. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8236. Break;
  8237. end;
  8238. Result := True;
  8239. Break;
  8240. end;
  8241. A_RET:
  8242. begin
  8243. Result := True;
  8244. Break;
  8245. end;
  8246. else
  8247. Break;
  8248. end;
  8249. end;
  8250. if Result then
  8251. begin
  8252. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8253. if Count = 0 then
  8254. begin
  8255. Result := False;
  8256. Exit;
  8257. end;
  8258. hp3 := p;
  8259. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8260. while True do
  8261. begin
  8262. if Assigned(hp1) and (hp1.typ = ait_label) then
  8263. SkipLabels(hp1,hp1);
  8264. if (hp1.typ <> ait_instruction) then
  8265. InternalError(2021040720);
  8266. case taicpu(hp1).opcode of
  8267. A_JMP:
  8268. begin
  8269. { Change the original jump to the new destination }
  8270. OrigLabel.decrefs;
  8271. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8272. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8273. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8274. if not Assigned(first_assignment) then
  8275. InternalError(2021040810)
  8276. else
  8277. p := first_assignment;
  8278. Exit;
  8279. end;
  8280. A_RET:
  8281. begin
  8282. { Now change the jump into a RET instruction }
  8283. ConvertJumpToRET(p, hp1);
  8284. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8285. if not Assigned(first_assignment) then
  8286. InternalError(2021040811)
  8287. else
  8288. p := first_assignment;
  8289. Exit;
  8290. end;
  8291. else
  8292. begin
  8293. { Duplicate the MOV instruction }
  8294. hp3:=tai(hp1.getcopy);
  8295. if first_assignment = nil then
  8296. first_assignment := hp3;
  8297. asml.InsertBefore(hp3, p);
  8298. { Make sure the compiler knows about any final registers written here }
  8299. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8300. with taicpu(hp3).oper[OperIdx]^ do
  8301. begin
  8302. case typ of
  8303. top_ref:
  8304. begin
  8305. if (ref^.base <> NR_NO) and
  8306. (getsupreg(ref^.base) <> RS_ESP) and
  8307. (getsupreg(ref^.base) <> RS_EBP)
  8308. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8309. then
  8310. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8311. if (ref^.index <> NR_NO) and
  8312. (getsupreg(ref^.index) <> RS_ESP) and
  8313. (getsupreg(ref^.index) <> RS_EBP)
  8314. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8315. (ref^.index <> ref^.base) then
  8316. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8317. end;
  8318. top_reg:
  8319. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8320. else
  8321. ;
  8322. end;
  8323. end;
  8324. end;
  8325. end;
  8326. if not GetNextInstruction(hp1, hp1) then
  8327. { Should have dropped out earlier }
  8328. InternalError(2021040710);
  8329. end;
  8330. end;
  8331. end;
  8332. const
  8333. WriteOp: array[0..3] of set of TInsChange = (
  8334. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8335. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8336. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8337. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8338. RegWriteFlags: array[0..7] of set of TInsChange = (
  8339. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8340. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8341. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8342. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8343. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8344. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8345. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8346. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8347. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8348. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8349. var
  8350. hp2: tai;
  8351. X: Integer;
  8352. begin
  8353. { If we have something like:
  8354. op ###,###
  8355. mov ###,###
  8356. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8357. interfere in regards to what they write to.
  8358. NOTE: p must be a 2-operand instruction
  8359. }
  8360. Result := False;
  8361. if (hp1.typ <> ait_instruction) or
  8362. taicpu(hp1).is_jmp or
  8363. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8364. Exit;
  8365. { NOP is a pipeline fence, likely marking the beginning of the function
  8366. epilogue, so drop out. Similarly, drop out if POP or RET are
  8367. encountered }
  8368. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8369. Exit;
  8370. if (taicpu(hp1).opcode = A_MOVSD) and
  8371. (taicpu(hp1).ops = 0) then
  8372. { Wrong MOVSD }
  8373. Exit;
  8374. { Check for writes to specific registers first }
  8375. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8376. for X := 0 to 7 do
  8377. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8378. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8379. Exit;
  8380. for X := 0 to taicpu(hp1).ops - 1 do
  8381. begin
  8382. { Check to see if this operand writes to something }
  8383. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8384. { And matches something in the CMP/TEST instruction }
  8385. (
  8386. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8387. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8388. (
  8389. { If it's a register, make sure the register written to doesn't
  8390. appear in the cmp instruction as part of a reference }
  8391. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8392. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8393. )
  8394. ) then
  8395. Exit;
  8396. end;
  8397. { Check p to make sure it doesn't write to something that affects hp1 }
  8398. { Check for writes to specific registers first }
  8399. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8400. for X := 0 to 7 do
  8401. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8402. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8403. Exit;
  8404. for X := 0 to taicpu(p).ops - 1 do
  8405. begin
  8406. { Check to see if this operand writes to something }
  8407. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8408. { And matches something in hp1 }
  8409. (taicpu(p).oper[X]^.typ = top_reg) and
  8410. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8411. Exit;
  8412. end;
  8413. { The instruction can be safely moved }
  8414. asml.Remove(hp1);
  8415. { Try to insert after the last instructions where the FLAGS register is not
  8416. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8417. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8418. asml.InsertBefore(hp1, hp2)
  8419. { Failing that, try to insert after the last instructions where the
  8420. FLAGS register is not yet in use }
  8421. else if GetLastInstruction(p, hp2) and
  8422. (
  8423. (hp2.typ <> ait_instruction) or
  8424. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8425. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8426. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8427. ) then
  8428. asml.InsertAfter(hp1, hp2)
  8429. else
  8430. { Note, if p.Previous is nil (even if it should logically never be the
  8431. case), FindRegAllocBackward immediately exits with False and so we
  8432. safely land here (we can't just pass p because FindRegAllocBackward
  8433. immediately exits on an instruction). [Kit] }
  8434. asml.InsertBefore(hp1, p);
  8435. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8436. { We can't trust UsedRegs because we're looking backwards, although we
  8437. know the registers are allocated after p at the very least, so manually
  8438. create tai_regalloc objects if needed }
  8439. for X := 0 to taicpu(hp1).ops - 1 do
  8440. case taicpu(hp1).oper[X]^.typ of
  8441. top_reg:
  8442. begin
  8443. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8444. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8445. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8446. end;
  8447. top_ref:
  8448. begin
  8449. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8450. begin
  8451. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8452. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8453. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8454. end;
  8455. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8456. begin
  8457. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8458. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8459. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8460. end;
  8461. end;
  8462. else
  8463. ;
  8464. end;
  8465. Result := True;
  8466. end;
  8467. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8468. var
  8469. hp2: tai;
  8470. X: Integer;
  8471. begin
  8472. { If we have something like:
  8473. cmp ###,%reg1
  8474. mov 0,%reg2
  8475. And no modified registers are shared, move the instruction to before
  8476. the comparison as this means it can be optimised without worrying
  8477. about the FLAGS register. (CMP/MOV is generated by
  8478. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8479. As long as the second instruction doesn't use the flags or one of the
  8480. registers used by CMP or TEST (also check any references that use the
  8481. registers), then it can be moved prior to the comparison.
  8482. }
  8483. Result := False;
  8484. if not TrySwapMovOp(p, hp1) then
  8485. Exit;
  8486. if taicpu(hp1).opcode = A_LEA then
  8487. { The flags will be overwritten by the CMP/TEST instruction }
  8488. ConvertLEA(taicpu(hp1));
  8489. Result := True;
  8490. { Can we move it one further back? }
  8491. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8492. { Check to see if CMP/TEST is a comparison against zero }
  8493. (
  8494. (
  8495. (taicpu(p).opcode = A_CMP) and
  8496. MatchOperand(taicpu(p).oper[0]^, 0)
  8497. ) or
  8498. (
  8499. (taicpu(p).opcode = A_TEST) and
  8500. (
  8501. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8502. MatchOperand(taicpu(p).oper[0]^, -1)
  8503. )
  8504. )
  8505. ) and
  8506. { These instructions set the zero flag if the result is zero }
  8507. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8508. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8509. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8510. TrySwapMovOp(hp2, hp1);
  8511. end;
  8512. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8513. var
  8514. hp1, hp2, p_dist, hp1_dist: tai;
  8515. JumpLabel: TAsmLabel;
  8516. Tmp: string;
  8517. begin
  8518. Result := False;
  8519. { Look for:
  8520. stc/clc
  8521. j(c) .L1
  8522. ...
  8523. .L1:
  8524. set(n)cb %reg
  8525. (flags deallocated)
  8526. j(c) .L2
  8527. Change to:
  8528. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8529. j(c) .L2
  8530. }
  8531. if not GetNextInstruction(p, hp1) then
  8532. Exit;
  8533. if (hp1.typ = ait_instruction) and
  8534. IsJumpToLabel(taicpu(hp1)) then
  8535. begin
  8536. { Optimise the J(c); stc/clc optimisation first since this will
  8537. get missed if the main optimisation takes place }
  8538. if (taicpu(hp1).opcode = A_JCC) and
  8539. GetNextInstruction(hp1, hp2) and
  8540. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8541. TryJccStcClcOpt(hp1, hp2) then
  8542. begin
  8543. Result := True;
  8544. Exit;
  8545. end;
  8546. hp2 := nil; { Suppress compiler warning }
  8547. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8548. if Assigned(JumpLabel) and
  8549. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8550. GetNextInstruction(hp2, p_dist) and
  8551. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8552. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8553. begin
  8554. case taicpu(p_dist).opcode of
  8555. A_Jcc:
  8556. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8557. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8558. begin
  8559. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8560. JumpLabel.decrefs;
  8561. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8562. RemoveCurrentP(p, hp1);
  8563. Result := True;
  8564. Exit;
  8565. end
  8566. else if GetNextInstruction(p_dist, hp1_dist) and
  8567. (hp1_dist.typ = ait_label) then
  8568. begin
  8569. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8570. JumpLabel.decrefs;
  8571. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8572. RemoveCurrentP(p, hp1);
  8573. Result := True;
  8574. Exit;
  8575. end;
  8576. A_SETcc:
  8577. if { Make sure the flags aren't used again }
  8578. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8579. GetNextInstruction(hp2, hp1_dist) and
  8580. IsJumpToLabel(taicpu(hp1_dist)) and
  8581. { Make sure the carry flag doesn't appear in the jump conditions }
  8582. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8583. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8584. { This works if hp1_dist or both are regular JMP instructions }
  8585. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  8586. begin
  8587. taicpu(p).allocate_oper(2);
  8588. taicpu(p).ops := 2;
  8589. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8590. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8591. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8592. taicpu(p).opcode := A_MOV;
  8593. taicpu(p).opsize := S_B;
  8594. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8595. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8596. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8597. JumpLabel.decrefs;
  8598. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8599. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8600. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp1) and
  8601. (tai_regalloc(hp1).ratype = ra_alloc) then
  8602. begin
  8603. Asml.Remove(hp1);
  8604. Asml.InsertAfter(hp1, p);
  8605. end;
  8606. Result := True;
  8607. Exit;
  8608. end;
  8609. else
  8610. ;
  8611. end;
  8612. end;
  8613. end;
  8614. end;
  8615. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8616. var
  8617. hp2, hp3: tai;
  8618. TempBool: Boolean;
  8619. begin
  8620. Result := False;
  8621. {
  8622. j(c) .L1
  8623. stc/clc
  8624. .L1:
  8625. jc/jnc .L2
  8626. (Flags deallocated)
  8627. Change to:
  8628. j)c) .L1
  8629. jmp .L2
  8630. .L1:
  8631. jc/jnc .L2
  8632. Then call DoJumpOptimizations to convert to:
  8633. j(nc) .L2
  8634. .L1: (may become a dead label)
  8635. jc/jnc .L2
  8636. }
  8637. if GetNextInstruction(hp1, hp2) and
  8638. (hp2.typ = ait_label) and
  8639. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8640. GetNextInstruction(hp2, hp3) and
  8641. MatchInstruction(hp3, A_Jcc, []) and
  8642. (
  8643. (
  8644. (taicpu(hp3).condition = C_C) and
  8645. (taicpu(hp1).opcode = A_STC)
  8646. ) or (
  8647. (taicpu(hp3).condition = C_NC) and
  8648. (taicpu(hp1).opcode = A_CLC)
  8649. )
  8650. ) and
  8651. { Make sure the flags aren't used again }
  8652. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8653. begin
  8654. tai_label(hp2).labsym.DecRefs;
  8655. taicpu(hp1).allocate_oper(1);
  8656. taicpu(hp1).ops := 1;
  8657. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8658. taicpu(hp1).opcode := A_JMP;
  8659. taicpu(hp1).is_jmp := True;
  8660. TempBool := True; { Prevent compiler warnings }
  8661. if DoJumpOptimizations(p, TempBool) then
  8662. Result := True
  8663. else
  8664. Include(OptsToCheck, aoc_ForceNewIteration);
  8665. end;
  8666. end;
  8667. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8668. function IsXCHGAcceptable: Boolean; inline;
  8669. begin
  8670. { Always accept if optimising for size }
  8671. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8672. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8673. than 3, so it becomes a saving compared to three MOVs with two of
  8674. them able to execute simultaneously. [Kit] }
  8675. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8676. end;
  8677. var
  8678. NewRef: TReference;
  8679. hp1, hp2, hp3, hp4: Tai;
  8680. {$ifndef x86_64}
  8681. OperIdx: Integer;
  8682. {$endif x86_64}
  8683. NewInstr : Taicpu;
  8684. NewAligh : Tai_align;
  8685. DestLabel: TAsmLabel;
  8686. TempTracking: TAllUsedRegs;
  8687. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8688. var
  8689. NextInstr: tai;
  8690. begin
  8691. Result := False;
  8692. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8693. if not GetNextInstruction(InputInstr, NextInstr) or
  8694. (
  8695. { The FLAGS register isn't always tracked properly, so do not
  8696. perform this optimisation if a conditional statement follows }
  8697. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8698. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8699. ) then
  8700. begin
  8701. reference_reset(NewRef, 1, []);
  8702. NewRef.base := taicpu(p).oper[0]^.reg;
  8703. NewRef.scalefactor := 1;
  8704. if taicpu(InputInstr).opcode = A_ADD then
  8705. begin
  8706. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8707. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8708. end
  8709. else
  8710. begin
  8711. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8712. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8713. end;
  8714. taicpu(p).opcode := A_LEA;
  8715. taicpu(p).loadref(0, NewRef);
  8716. RemoveInstruction(InputInstr);
  8717. Result := True;
  8718. end;
  8719. end;
  8720. begin
  8721. Result:=false;
  8722. { This optimisation adds an instruction, so only do it for speed }
  8723. if not (cs_opt_size in current_settings.optimizerswitches) and
  8724. MatchOpType(taicpu(p), top_const, top_reg) and
  8725. (taicpu(p).oper[0]^.val = 0) then
  8726. begin
  8727. { To avoid compiler warning }
  8728. DestLabel := nil;
  8729. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8730. InternalError(2021040750);
  8731. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8732. Exit;
  8733. case hp1.typ of
  8734. ait_label:
  8735. begin
  8736. { Change:
  8737. mov $0,%reg mov $0,%reg
  8738. @Lbl1: @Lbl1:
  8739. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8740. je @Lbl2 jne @Lbl2
  8741. To: To:
  8742. mov $0,%reg mov $0,%reg
  8743. jmp @Lbl2 jmp @Lbl3
  8744. (align) (align)
  8745. @Lbl1: @Lbl1:
  8746. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8747. je @Lbl2 je @Lbl2
  8748. @Lbl3: <-- Only if label exists
  8749. (Not if it's optimised for size)
  8750. }
  8751. if not GetNextInstruction(hp1, hp2) then
  8752. Exit;
  8753. if (hp2.typ = ait_instruction) and
  8754. (
  8755. { Register sizes must exactly match }
  8756. (
  8757. (taicpu(hp2).opcode = A_CMP) and
  8758. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8759. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8760. ) or (
  8761. (taicpu(hp2).opcode = A_TEST) and
  8762. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8763. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8764. )
  8765. ) and GetNextInstruction(hp2, hp3) and
  8766. (hp3.typ = ait_instruction) and
  8767. (taicpu(hp3).opcode = A_JCC) and
  8768. (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
  8769. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8770. begin
  8771. { Check condition of jump }
  8772. { Always true? }
  8773. if condition_in(C_E, taicpu(hp3).condition) then
  8774. begin
  8775. { Copy label symbol and obtain matching label entry for the
  8776. conditional jump, as this will be our destination}
  8777. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8778. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8779. Result := True;
  8780. end
  8781. { Always false? }
  8782. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8783. begin
  8784. { This is only worth it if there's a jump to take }
  8785. case hp2.typ of
  8786. ait_instruction:
  8787. begin
  8788. if taicpu(hp2).opcode = A_JMP then
  8789. begin
  8790. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8791. { An unconditional jump follows the conditional jump which will always be false,
  8792. so use this jump's destination for the new jump }
  8793. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8794. Result := True;
  8795. end
  8796. else if taicpu(hp2).opcode = A_JCC then
  8797. begin
  8798. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8799. if condition_in(C_E, taicpu(hp2).condition) then
  8800. begin
  8801. { A second conditional jump follows the conditional jump which will always be false,
  8802. while the second jump is always True, so use this jump's destination for the new jump }
  8803. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8804. Result := True;
  8805. end;
  8806. { Don't risk it if the jump isn't always true (Result remains False) }
  8807. end;
  8808. end;
  8809. else
  8810. { If anything else don't optimise };
  8811. end;
  8812. end;
  8813. if Result then
  8814. begin
  8815. { Just so we have something to insert as a paremeter}
  8816. reference_reset(NewRef, 1, []);
  8817. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8818. { Now actually load the correct parameter (this also
  8819. increases the reference count) }
  8820. NewInstr.loadsymbol(0, DestLabel, 0);
  8821. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8822. begin
  8823. { Get instruction before original label (may not be p under -O3) }
  8824. if not GetLastInstruction(hp1, hp2) then
  8825. { Shouldn't fail here }
  8826. InternalError(2021040701);
  8827. end
  8828. else
  8829. hp2 := p;
  8830. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8831. AsmL.InsertAfter(NewInstr, hp2);
  8832. { Add new alignment field }
  8833. (* AsmL.InsertAfter(
  8834. cai_align.create_max(
  8835. current_settings.alignment.jumpalign,
  8836. current_settings.alignment.jumpalignskipmax
  8837. ),
  8838. NewInstr
  8839. ); *)
  8840. end;
  8841. Exit;
  8842. end;
  8843. end;
  8844. else
  8845. ;
  8846. end;
  8847. end;
  8848. if not GetNextInstruction(p, hp1) then
  8849. Exit;
  8850. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8851. and DoMovCmpMemOpt(p, hp1) then
  8852. begin
  8853. Result := True;
  8854. Exit;
  8855. end
  8856. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8857. begin
  8858. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8859. further, but we can't just put this jump optimisation in pass 1
  8860. because it tends to perform worse when conditional jumps are
  8861. nearby (e.g. when converting CMOV instructions). [Kit] }
  8862. CopyUsedRegs(TempTracking);
  8863. UpdateUsedRegs(tai(p.Next));
  8864. if OptPass2JMP(hp1) then
  8865. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8866. Result := OptPass1MOV(p);
  8867. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8868. returned True and the instruction is still a MOV, thus checking
  8869. the optimisations below }
  8870. { If OptPass2JMP returned False, no optimisations were done to
  8871. the jump and there are no further optimisations that can be done
  8872. to the MOV instruction on this pass }
  8873. { Restore register state }
  8874. RestoreUsedRegs(TempTracking);
  8875. ReleaseUsedRegs(TempTracking);
  8876. end
  8877. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8878. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8879. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8880. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8881. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8882. begin
  8883. { Change:
  8884. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8885. addl/q $x,%reg2 subl/q $x,%reg2
  8886. To:
  8887. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8888. }
  8889. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8890. { be lazy, checking separately for sub would be slightly better }
  8891. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8892. begin
  8893. TransferUsedRegs(TmpUsedRegs);
  8894. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8895. if TryMovArith2Lea(hp1) then
  8896. begin
  8897. Result := True;
  8898. Exit;
  8899. end
  8900. end
  8901. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8902. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8903. { Same as above, but also adds or subtracts to %reg2 in between.
  8904. It's still valid as long as the flags aren't in use }
  8905. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8906. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8907. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8908. { be lazy, checking separately for sub would be slightly better }
  8909. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8910. begin
  8911. TransferUsedRegs(TmpUsedRegs);
  8912. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8913. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8914. if TryMovArith2Lea(hp2) then
  8915. begin
  8916. Result := True;
  8917. Exit;
  8918. end;
  8919. end;
  8920. end
  8921. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8922. {$ifdef x86_64}
  8923. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8924. {$else x86_64}
  8925. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8926. {$endif x86_64}
  8927. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8928. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8929. { mov reg1, reg2 mov reg1, reg2
  8930. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8931. begin
  8932. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8933. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8934. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8935. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8936. TransferUsedRegs(TmpUsedRegs);
  8937. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8938. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8939. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8940. then
  8941. begin
  8942. RemoveCurrentP(p, hp1);
  8943. Result:=true;
  8944. end;
  8945. exit;
  8946. end
  8947. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8948. IsXCHGAcceptable and
  8949. { XCHG doesn't support 8-byte registers }
  8950. (taicpu(p).opsize <> S_B) and
  8951. MatchInstruction(hp1, A_MOV, []) and
  8952. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8953. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8954. GetNextInstruction(hp1, hp2) and
  8955. MatchInstruction(hp2, A_MOV, []) and
  8956. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8957. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8958. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8959. begin
  8960. { mov %reg1,%reg2
  8961. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8962. mov %reg2,%reg3
  8963. (%reg2 not used afterwards)
  8964. Note that xchg takes 3 cycles to execute, and generally mov's take
  8965. only one cycle apiece, but the first two mov's can be executed in
  8966. parallel, only taking 2 cycles overall. Older processors should
  8967. therefore only optimise for size. [Kit]
  8968. }
  8969. TransferUsedRegs(TmpUsedRegs);
  8970. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8971. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8972. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8973. begin
  8974. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8975. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8976. taicpu(hp1).opcode := A_XCHG;
  8977. RemoveCurrentP(p, hp1);
  8978. RemoveInstruction(hp2);
  8979. Result := True;
  8980. Exit;
  8981. end;
  8982. end
  8983. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8984. MatchInstruction(hp1, A_SAR, []) then
  8985. begin
  8986. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8987. begin
  8988. { the use of %edx also covers the opsize being S_L }
  8989. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8990. begin
  8991. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8992. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8993. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8994. begin
  8995. { Change:
  8996. movl %eax,%edx
  8997. sarl $31,%edx
  8998. To:
  8999. cltd
  9000. }
  9001. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9002. RemoveInstruction(hp1);
  9003. taicpu(p).opcode := A_CDQ;
  9004. taicpu(p).opsize := S_NO;
  9005. taicpu(p).clearop(1);
  9006. taicpu(p).clearop(0);
  9007. taicpu(p).ops:=0;
  9008. Result := True;
  9009. end
  9010. else if (cs_opt_size in current_settings.optimizerswitches) and
  9011. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9012. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9013. begin
  9014. { Change:
  9015. movl %edx,%eax
  9016. sarl $31,%edx
  9017. To:
  9018. movl %edx,%eax
  9019. cltd
  9020. Note that this creates a dependency between the two instructions,
  9021. so only perform if optimising for size.
  9022. }
  9023. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9024. taicpu(hp1).opcode := A_CDQ;
  9025. taicpu(hp1).opsize := S_NO;
  9026. taicpu(hp1).clearop(1);
  9027. taicpu(hp1).clearop(0);
  9028. taicpu(hp1).ops:=0;
  9029. end;
  9030. {$ifndef x86_64}
  9031. end
  9032. { Don't bother if CMOV is supported, because a more optimal
  9033. sequence would have been generated for the Abs() intrinsic }
  9034. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9035. { the use of %eax also covers the opsize being S_L }
  9036. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9037. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9038. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9039. GetNextInstruction(hp1, hp2) and
  9040. MatchInstruction(hp2, A_XOR, [S_L]) and
  9041. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9042. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9043. GetNextInstruction(hp2, hp3) and
  9044. MatchInstruction(hp3, A_SUB, [S_L]) and
  9045. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9046. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9047. begin
  9048. { Change:
  9049. movl %eax,%edx
  9050. sarl $31,%eax
  9051. xorl %eax,%edx
  9052. subl %eax,%edx
  9053. (Instruction that uses %edx)
  9054. (%eax deallocated)
  9055. (%edx deallocated)
  9056. To:
  9057. cltd
  9058. xorl %edx,%eax <-- Note the registers have swapped
  9059. subl %edx,%eax
  9060. (Instruction that uses %eax) <-- %eax rather than %edx
  9061. }
  9062. TransferUsedRegs(TmpUsedRegs);
  9063. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9065. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9066. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9067. begin
  9068. if GetNextInstruction(hp3, hp4) and
  9069. not RegModifiedByInstruction(NR_EDX, hp4) and
  9070. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9071. begin
  9072. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9073. taicpu(p).opcode := A_CDQ;
  9074. taicpu(p).clearop(1);
  9075. taicpu(p).clearop(0);
  9076. taicpu(p).ops:=0;
  9077. RemoveInstruction(hp1);
  9078. taicpu(hp2).loadreg(0, NR_EDX);
  9079. taicpu(hp2).loadreg(1, NR_EAX);
  9080. taicpu(hp3).loadreg(0, NR_EDX);
  9081. taicpu(hp3).loadreg(1, NR_EAX);
  9082. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9083. { Convert references in the following instruction (hp4) from %edx to %eax }
  9084. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9085. with taicpu(hp4).oper[OperIdx]^ do
  9086. case typ of
  9087. top_reg:
  9088. if getsupreg(reg) = RS_EDX then
  9089. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9090. top_ref:
  9091. begin
  9092. if getsupreg(reg) = RS_EDX then
  9093. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9094. if getsupreg(reg) = RS_EDX then
  9095. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9096. end;
  9097. else
  9098. ;
  9099. end;
  9100. end;
  9101. end;
  9102. {$else x86_64}
  9103. end;
  9104. end
  9105. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9106. { the use of %rdx also covers the opsize being S_Q }
  9107. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9108. begin
  9109. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9110. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9111. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9112. begin
  9113. { Change:
  9114. movq %rax,%rdx
  9115. sarq $63,%rdx
  9116. To:
  9117. cqto
  9118. }
  9119. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9120. RemoveInstruction(hp1);
  9121. taicpu(p).opcode := A_CQO;
  9122. taicpu(p).opsize := S_NO;
  9123. taicpu(p).clearop(1);
  9124. taicpu(p).clearop(0);
  9125. taicpu(p).ops:=0;
  9126. Result := True;
  9127. end
  9128. else if (cs_opt_size in current_settings.optimizerswitches) and
  9129. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9130. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9131. begin
  9132. { Change:
  9133. movq %rdx,%rax
  9134. sarq $63,%rdx
  9135. To:
  9136. movq %rdx,%rax
  9137. cqto
  9138. Note that this creates a dependency between the two instructions,
  9139. so only perform if optimising for size.
  9140. }
  9141. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9142. taicpu(hp1).opcode := A_CQO;
  9143. taicpu(hp1).opsize := S_NO;
  9144. taicpu(hp1).clearop(1);
  9145. taicpu(hp1).clearop(0);
  9146. taicpu(hp1).ops:=0;
  9147. {$endif x86_64}
  9148. end;
  9149. end;
  9150. end
  9151. else if MatchInstruction(hp1, A_MOV, []) and
  9152. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9153. { Though "GetNextInstruction" could be factored out, along with
  9154. the instructions that depend on hp2, it is an expensive call that
  9155. should be delayed for as long as possible, hence we do cheaper
  9156. checks first that are likely to be False. [Kit] }
  9157. begin
  9158. if (
  9159. (
  9160. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9161. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9162. (
  9163. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9164. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9165. )
  9166. ) or
  9167. (
  9168. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9169. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9170. (
  9171. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9172. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9173. )
  9174. )
  9175. ) and
  9176. GetNextInstruction(hp1, hp2) and
  9177. MatchInstruction(hp2, A_SAR, []) and
  9178. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9179. begin
  9180. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9181. begin
  9182. { Change:
  9183. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9184. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9185. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9186. To:
  9187. movl r/m,%eax <- Note the change in register
  9188. cltd
  9189. }
  9190. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9191. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9192. taicpu(p).loadreg(1, NR_EAX);
  9193. taicpu(hp1).opcode := A_CDQ;
  9194. taicpu(hp1).clearop(1);
  9195. taicpu(hp1).clearop(0);
  9196. taicpu(hp1).ops:=0;
  9197. RemoveInstruction(hp2);
  9198. (*
  9199. {$ifdef x86_64}
  9200. end
  9201. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9202. { This code sequence does not get generated - however it might become useful
  9203. if and when 128-bit signed integer types make an appearance, so the code
  9204. is kept here for when it is eventually needed. [Kit] }
  9205. (
  9206. (
  9207. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9208. (
  9209. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9210. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9211. )
  9212. ) or
  9213. (
  9214. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9215. (
  9216. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9217. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9218. )
  9219. )
  9220. ) and
  9221. GetNextInstruction(hp1, hp2) and
  9222. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9223. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9224. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9225. begin
  9226. { Change:
  9227. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9228. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9229. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9230. To:
  9231. movq r/m,%rax <- Note the change in register
  9232. cqto
  9233. }
  9234. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9235. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9236. taicpu(p).loadreg(1, NR_RAX);
  9237. taicpu(hp1).opcode := A_CQO;
  9238. taicpu(hp1).clearop(1);
  9239. taicpu(hp1).clearop(0);
  9240. taicpu(hp1).ops:=0;
  9241. RemoveInstruction(hp2);
  9242. {$endif x86_64}
  9243. *)
  9244. end;
  9245. end;
  9246. {$ifdef x86_64}
  9247. end
  9248. else if (taicpu(p).opsize = S_L) and
  9249. (taicpu(p).oper[1]^.typ = top_reg) and
  9250. (
  9251. MatchInstruction(hp1, A_MOV,[]) and
  9252. (taicpu(hp1).opsize = S_L) and
  9253. (taicpu(hp1).oper[1]^.typ = top_reg)
  9254. ) and (
  9255. GetNextInstruction(hp1, hp2) and
  9256. (tai(hp2).typ=ait_instruction) and
  9257. (taicpu(hp2).opsize = S_Q) and
  9258. (
  9259. (
  9260. MatchInstruction(hp2, A_ADD,[]) and
  9261. (taicpu(hp2).opsize = S_Q) and
  9262. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9263. (
  9264. (
  9265. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9266. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9267. ) or (
  9268. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9269. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9270. )
  9271. )
  9272. ) or (
  9273. MatchInstruction(hp2, A_LEA,[]) and
  9274. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9275. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9276. (
  9277. (
  9278. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9279. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9280. ) or (
  9281. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9282. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9283. )
  9284. ) and (
  9285. (
  9286. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9287. ) or (
  9288. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9289. )
  9290. )
  9291. )
  9292. )
  9293. ) and (
  9294. GetNextInstruction(hp2, hp3) and
  9295. MatchInstruction(hp3, A_SHR,[]) and
  9296. (taicpu(hp3).opsize = S_Q) and
  9297. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9298. (taicpu(hp3).oper[0]^.val = 1) and
  9299. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9300. ) then
  9301. begin
  9302. { Change movl x, reg1d movl x, reg1d
  9303. movl y, reg2d movl y, reg2d
  9304. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9305. shrq $1, reg1q shrq $1, reg1q
  9306. ( reg1d and reg2d can be switched around in the first two instructions )
  9307. To movl x, reg1d
  9308. addl y, reg1d
  9309. rcrl $1, reg1d
  9310. This corresponds to the common expression (x + y) shr 1, where
  9311. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9312. smaller code, but won't account for x + y causing an overflow). [Kit]
  9313. }
  9314. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9315. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9316. { Change first MOV command to have the same register as the final output }
  9317. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9318. else
  9319. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9320. { Change second MOV command to an ADD command. This is easier than
  9321. converting the existing command because it means we don't have to
  9322. touch 'y', which might be a complicated reference, and also the
  9323. fact that the third command might either be ADD or LEA. [Kit] }
  9324. taicpu(hp1).opcode := A_ADD;
  9325. { Delete old ADD/LEA instruction }
  9326. RemoveInstruction(hp2);
  9327. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9328. taicpu(hp3).opcode := A_RCR;
  9329. taicpu(hp3).changeopsize(S_L);
  9330. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9331. {$endif x86_64}
  9332. end;
  9333. if FuncMov2Func(p, hp1) then
  9334. begin
  9335. Result := True;
  9336. Exit;
  9337. end;
  9338. end;
  9339. {$push}
  9340. {$q-}{$r-}
  9341. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9342. var
  9343. ThisReg: TRegister;
  9344. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9345. TargetSubReg: TSubRegister;
  9346. hp1, hp2: tai;
  9347. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9348. { Store list of found instructions so we don't have to call
  9349. GetNextInstructionUsingReg multiple times }
  9350. InstrList: array of taicpu;
  9351. InstrMax, Index: Integer;
  9352. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9353. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9354. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9355. WorkingValue: TCgInt;
  9356. PreMessage: string;
  9357. { Data flow analysis }
  9358. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9359. BitwiseOnly, OrXorUsed,
  9360. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9361. function CheckOverflowConditions: Boolean;
  9362. begin
  9363. Result := True;
  9364. if (TestValSignedMax > SignedUpperLimit) then
  9365. UpperSignedOverflow := True;
  9366. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9367. LowerSignedOverflow := True;
  9368. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9369. LowerUnsignedOverflow := True;
  9370. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9371. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9372. begin
  9373. { Absolute overflow }
  9374. Result := False;
  9375. Exit;
  9376. end;
  9377. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9378. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9379. ShiftDownOverflow := True;
  9380. if (TestValMin < 0) or (TestValMax < 0) then
  9381. begin
  9382. LowerUnsignedOverflow := True;
  9383. UpperUnsignedOverflow := True;
  9384. end;
  9385. end;
  9386. function AdjustInitialLoadAndSize: Boolean;
  9387. begin
  9388. Result := False;
  9389. if not p_removed then
  9390. begin
  9391. if TargetSize = MinSize then
  9392. begin
  9393. { Convert the input MOVZX to a MOV }
  9394. if (taicpu(p).oper[0]^.typ = top_reg) and
  9395. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9396. begin
  9397. { Or remove it completely! }
  9398. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9399. RemoveCurrentP(p);
  9400. p_removed := True;
  9401. end
  9402. else
  9403. begin
  9404. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9405. taicpu(p).opcode := A_MOV;
  9406. taicpu(p).oper[1]^.reg := ThisReg;
  9407. taicpu(p).opsize := TargetSize;
  9408. end;
  9409. Result := True;
  9410. end
  9411. else if TargetSize <> MaxSize then
  9412. begin
  9413. case MaxSize of
  9414. S_L:
  9415. if TargetSize = S_W then
  9416. begin
  9417. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9418. taicpu(p).opsize := S_BW;
  9419. taicpu(p).oper[1]^.reg := ThisReg;
  9420. Result := True;
  9421. end
  9422. else
  9423. InternalError(2020112341);
  9424. S_W:
  9425. if TargetSize = S_L then
  9426. begin
  9427. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9428. taicpu(p).opsize := S_BL;
  9429. taicpu(p).oper[1]^.reg := ThisReg;
  9430. Result := True;
  9431. end
  9432. else
  9433. InternalError(2020112342);
  9434. else
  9435. ;
  9436. end;
  9437. end
  9438. else if not hp1_removed and not RegInUse then
  9439. begin
  9440. { If we have something like:
  9441. movzbl (oper),%regd
  9442. add x, %regd
  9443. movzbl %regb, %regd
  9444. We can reduce the register size to the input of the final
  9445. movzbl instruction. Overflows won't have any effect.
  9446. }
  9447. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9448. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9449. begin
  9450. TargetSize := S_B;
  9451. setsubreg(ThisReg, R_SUBL);
  9452. Result := True;
  9453. end
  9454. else if (taicpu(p).opsize = S_WL) and
  9455. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9456. begin
  9457. TargetSize := S_W;
  9458. setsubreg(ThisReg, R_SUBW);
  9459. Result := True;
  9460. end;
  9461. if Result then
  9462. begin
  9463. { Convert the input MOVZX to a MOV }
  9464. if (taicpu(p).oper[0]^.typ = top_reg) and
  9465. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9466. begin
  9467. { Or remove it completely! }
  9468. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9469. RemoveCurrentP(p);
  9470. p_removed := True;
  9471. end
  9472. else
  9473. begin
  9474. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9475. taicpu(p).opcode := A_MOV;
  9476. taicpu(p).oper[1]^.reg := ThisReg;
  9477. taicpu(p).opsize := TargetSize;
  9478. end;
  9479. end;
  9480. end;
  9481. end;
  9482. end;
  9483. procedure AdjustFinalLoad;
  9484. begin
  9485. if not LowerUnsignedOverflow then
  9486. begin
  9487. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9488. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9489. begin
  9490. { Convert the output MOVZX to a MOV }
  9491. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9492. begin
  9493. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9494. if (MinSize = S_B) or
  9495. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9496. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9497. begin
  9498. { Remove it completely! }
  9499. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9500. { Be careful; if p = hp1 and p was also removed, p
  9501. will become a dangling pointer }
  9502. if p = hp1 then
  9503. begin
  9504. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9505. p_removed := True;
  9506. end
  9507. else
  9508. RemoveInstruction(hp1);
  9509. hp1_removed := True;
  9510. end;
  9511. end
  9512. else
  9513. begin
  9514. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9515. taicpu(hp1).opcode := A_MOV;
  9516. taicpu(hp1).oper[0]^.reg := ThisReg;
  9517. taicpu(hp1).opsize := TargetSize;
  9518. end;
  9519. end
  9520. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9521. begin
  9522. { Need to change the size of the output }
  9523. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9524. taicpu(hp1).oper[0]^.reg := ThisReg;
  9525. taicpu(hp1).opsize := S_BL;
  9526. end;
  9527. end;
  9528. end;
  9529. function CompressInstructions: Boolean;
  9530. var
  9531. LocalIndex: Integer;
  9532. begin
  9533. Result := False;
  9534. { The objective here is to try to find a combination that
  9535. removes one of the MOV/Z instructions. }
  9536. if (
  9537. (taicpu(p).oper[0]^.typ <> top_reg) or
  9538. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9539. ) and
  9540. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9541. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9542. begin
  9543. { Make a preference to remove the second MOVZX instruction }
  9544. case taicpu(hp1).opsize of
  9545. S_BL, S_WL:
  9546. begin
  9547. TargetSize := S_L;
  9548. TargetSubReg := R_SUBD;
  9549. end;
  9550. S_BW:
  9551. begin
  9552. TargetSize := S_W;
  9553. TargetSubReg := R_SUBW;
  9554. end;
  9555. else
  9556. InternalError(2020112302);
  9557. end;
  9558. end
  9559. else
  9560. begin
  9561. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9562. begin
  9563. { Exceeded lower bound but not upper bound }
  9564. TargetSize := MaxSize;
  9565. end
  9566. else if not LowerUnsignedOverflow then
  9567. begin
  9568. { Size didn't exceed lower bound }
  9569. TargetSize := MinSize;
  9570. end
  9571. else
  9572. Exit;
  9573. end;
  9574. case TargetSize of
  9575. S_B:
  9576. TargetSubReg := R_SUBL;
  9577. S_W:
  9578. TargetSubReg := R_SUBW;
  9579. S_L:
  9580. TargetSubReg := R_SUBD;
  9581. else
  9582. InternalError(2020112350);
  9583. end;
  9584. { Update the register to its new size }
  9585. setsubreg(ThisReg, TargetSubReg);
  9586. RegInUse := False;
  9587. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9588. begin
  9589. { Check to see if the active register is used afterwards;
  9590. if not, we can change it and make a saving. }
  9591. TransferUsedRegs(TmpUsedRegs);
  9592. { The target register may be marked as in use to cross
  9593. a jump to a distant label, so exclude it }
  9594. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9595. hp2 := p;
  9596. repeat
  9597. { Explicitly check for the excluded register (don't include the first
  9598. instruction as it may be reading from here }
  9599. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9600. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9601. begin
  9602. RegInUse := True;
  9603. Break;
  9604. end;
  9605. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9606. if not GetNextInstruction(hp2, hp2) then
  9607. InternalError(2020112340);
  9608. until (hp2 = hp1);
  9609. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9610. { We might still be able to get away with this }
  9611. RegInUse := not
  9612. (
  9613. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9614. (hp2.typ = ait_instruction) and
  9615. (
  9616. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9617. instruction that doesn't actually contain ThisReg }
  9618. (cs_opt_level3 in current_settings.optimizerswitches) or
  9619. RegInInstruction(ThisReg, hp2)
  9620. ) and
  9621. RegLoadedWithNewValue(ThisReg, hp2)
  9622. );
  9623. if not RegInUse then
  9624. begin
  9625. { Force the register size to the same as this instruction so it can be removed}
  9626. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9627. begin
  9628. TargetSize := S_L;
  9629. TargetSubReg := R_SUBD;
  9630. end
  9631. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9632. begin
  9633. TargetSize := S_W;
  9634. TargetSubReg := R_SUBW;
  9635. end;
  9636. ThisReg := taicpu(hp1).oper[1]^.reg;
  9637. setsubreg(ThisReg, TargetSubReg);
  9638. RegChanged := True;
  9639. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9640. TransferUsedRegs(TmpUsedRegs);
  9641. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9642. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9643. if p = hp1 then
  9644. begin
  9645. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9646. p_removed := True;
  9647. end
  9648. else
  9649. RemoveInstruction(hp1);
  9650. hp1_removed := True;
  9651. { Instruction will become "mov %reg,%reg" }
  9652. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9653. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9654. begin
  9655. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9656. RemoveCurrentP(p);
  9657. p_removed := True;
  9658. end
  9659. else
  9660. taicpu(p).oper[1]^.reg := ThisReg;
  9661. Result := True;
  9662. end
  9663. else
  9664. begin
  9665. if TargetSize <> MaxSize then
  9666. begin
  9667. { Since the register is in use, we have to force it to
  9668. MaxSize otherwise part of it may become undefined later on }
  9669. TargetSize := MaxSize;
  9670. case TargetSize of
  9671. S_B:
  9672. TargetSubReg := R_SUBL;
  9673. S_W:
  9674. TargetSubReg := R_SUBW;
  9675. S_L:
  9676. TargetSubReg := R_SUBD;
  9677. else
  9678. InternalError(2020112351);
  9679. end;
  9680. setsubreg(ThisReg, TargetSubReg);
  9681. end;
  9682. AdjustFinalLoad;
  9683. end;
  9684. end
  9685. else
  9686. AdjustFinalLoad;
  9687. Result := AdjustInitialLoadAndSize or Result;
  9688. { Now go through every instruction we found and change the
  9689. size. If TargetSize = MaxSize, then almost no changes are
  9690. needed and Result can remain False if it hasn't been set
  9691. yet.
  9692. If RegChanged is True, then the register requires changing
  9693. and so the point about TargetSize = MaxSize doesn't apply. }
  9694. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9695. begin
  9696. for LocalIndex := 0 to InstrMax do
  9697. begin
  9698. { If p_removed is true, then the original MOV/Z was removed
  9699. and removing the AND instruction may not be safe if it
  9700. appears first }
  9701. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9702. InternalError(2020112310);
  9703. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9704. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9705. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9706. InstrList[LocalIndex].opsize := TargetSize;
  9707. end;
  9708. Result := True;
  9709. end;
  9710. end;
  9711. begin
  9712. Result := False;
  9713. p_removed := False;
  9714. hp1_removed := False;
  9715. ThisReg := taicpu(p).oper[1]^.reg;
  9716. { Check for:
  9717. movs/z ###,%ecx (or %cx or %rcx)
  9718. ...
  9719. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9720. (dealloc %ecx)
  9721. Change to:
  9722. mov ###,%cl (if ### = %cl, then remove completely)
  9723. ...
  9724. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9725. }
  9726. if (getsupreg(ThisReg) = RS_ECX) and
  9727. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9728. (hp1.typ = ait_instruction) and
  9729. (
  9730. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9731. instruction that doesn't actually contain ECX }
  9732. (cs_opt_level3 in current_settings.optimizerswitches) or
  9733. RegInInstruction(NR_ECX, hp1) or
  9734. (
  9735. { It's common for the shift/rotate's read/write register to be
  9736. initialised in between, so under -O2 and under, search ahead
  9737. one more instruction
  9738. }
  9739. GetNextInstruction(hp1, hp1) and
  9740. (hp1.typ = ait_instruction) and
  9741. RegInInstruction(NR_ECX, hp1)
  9742. )
  9743. ) and
  9744. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9745. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9746. begin
  9747. TransferUsedRegs(TmpUsedRegs);
  9748. hp2 := p;
  9749. repeat
  9750. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9751. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9752. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9753. begin
  9754. case taicpu(p).opsize of
  9755. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9756. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9757. begin
  9758. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9759. RemoveCurrentP(p);
  9760. end
  9761. else
  9762. begin
  9763. taicpu(p).opcode := A_MOV;
  9764. taicpu(p).opsize := S_B;
  9765. taicpu(p).oper[1]^.reg := NR_CL;
  9766. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9767. end;
  9768. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9769. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9770. begin
  9771. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9772. RemoveCurrentP(p);
  9773. end
  9774. else
  9775. begin
  9776. taicpu(p).opcode := A_MOV;
  9777. taicpu(p).opsize := S_W;
  9778. taicpu(p).oper[1]^.reg := NR_CX;
  9779. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9780. end;
  9781. {$ifdef x86_64}
  9782. S_LQ:
  9783. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9784. begin
  9785. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9786. RemoveCurrentP(p);
  9787. end
  9788. else
  9789. begin
  9790. taicpu(p).opcode := A_MOV;
  9791. taicpu(p).opsize := S_L;
  9792. taicpu(p).oper[1]^.reg := NR_ECX;
  9793. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9794. end;
  9795. {$endif x86_64}
  9796. else
  9797. InternalError(2021120401);
  9798. end;
  9799. Result := True;
  9800. Exit;
  9801. end;
  9802. end;
  9803. { This is anything but quick! }
  9804. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9805. Exit;
  9806. SetLength(InstrList, 0);
  9807. InstrMax := -1;
  9808. case taicpu(p).opsize of
  9809. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9810. begin
  9811. {$if defined(i386) or defined(i8086)}
  9812. { If the target size is 8-bit, make sure we can actually encode it }
  9813. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9814. Exit;
  9815. {$endif i386 or i8086}
  9816. LowerLimit := $FF;
  9817. SignedLowerLimit := $7F;
  9818. SignedLowerLimitBottom := -128;
  9819. MinSize := S_B;
  9820. if taicpu(p).opsize = S_BW then
  9821. begin
  9822. MaxSize := S_W;
  9823. UpperLimit := $FFFF;
  9824. SignedUpperLimit := $7FFF;
  9825. SignedUpperLimitBottom := -32768;
  9826. end
  9827. else
  9828. begin
  9829. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9830. MaxSize := S_L;
  9831. UpperLimit := $FFFFFFFF;
  9832. SignedUpperLimit := $7FFFFFFF;
  9833. SignedUpperLimitBottom := -2147483648;
  9834. end;
  9835. end;
  9836. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9837. begin
  9838. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9839. LowerLimit := $FFFF;
  9840. SignedLowerLimit := $7FFF;
  9841. SignedLowerLimitBottom := -32768;
  9842. UpperLimit := $FFFFFFFF;
  9843. SignedUpperLimit := $7FFFFFFF;
  9844. SignedUpperLimitBottom := -2147483648;
  9845. MinSize := S_W;
  9846. MaxSize := S_L;
  9847. end;
  9848. {$ifdef x86_64}
  9849. S_LQ:
  9850. begin
  9851. { Both the lower and upper limits are set to 32-bit. If a limit
  9852. is breached, then optimisation is impossible }
  9853. LowerLimit := $FFFFFFFF;
  9854. SignedLowerLimit := $7FFFFFFF;
  9855. SignedLowerLimitBottom := -2147483648;
  9856. UpperLimit := $FFFFFFFF;
  9857. SignedUpperLimit := $7FFFFFFF;
  9858. SignedUpperLimitBottom := -2147483648;
  9859. MinSize := S_L;
  9860. MaxSize := S_L;
  9861. end;
  9862. {$endif x86_64}
  9863. else
  9864. InternalError(2020112301);
  9865. end;
  9866. TestValMin := 0;
  9867. TestValMax := LowerLimit;
  9868. TestValSignedMax := SignedLowerLimit;
  9869. TryShiftDownLimit := LowerLimit;
  9870. TryShiftDown := S_NO;
  9871. ShiftDownOverflow := False;
  9872. RegChanged := False;
  9873. BitwiseOnly := True;
  9874. OrXorUsed := False;
  9875. UpperSignedOverflow := False;
  9876. LowerSignedOverflow := False;
  9877. UpperUnsignedOverflow := False;
  9878. LowerUnsignedOverflow := False;
  9879. hp1 := p;
  9880. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9881. (hp1.typ = ait_instruction) and
  9882. (
  9883. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9884. instruction that doesn't actually contain ThisReg }
  9885. (cs_opt_level3 in current_settings.optimizerswitches) or
  9886. { This allows this Movx optimisation to work through the SETcc instructions
  9887. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9888. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9889. skip over these SETcc instructions). }
  9890. (taicpu(hp1).opcode = A_SETcc) or
  9891. RegInInstruction(ThisReg, hp1)
  9892. ) do
  9893. begin
  9894. case taicpu(hp1).opcode of
  9895. A_INC,A_DEC:
  9896. begin
  9897. { Has to be an exact match on the register }
  9898. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9899. Break;
  9900. if taicpu(hp1).opcode = A_INC then
  9901. begin
  9902. Inc(TestValMin);
  9903. Inc(TestValMax);
  9904. Inc(TestValSignedMax);
  9905. end
  9906. else
  9907. begin
  9908. Dec(TestValMin);
  9909. Dec(TestValMax);
  9910. Dec(TestValSignedMax);
  9911. end;
  9912. end;
  9913. A_TEST, A_CMP:
  9914. begin
  9915. if (
  9916. { Too high a risk of non-linear behaviour that breaks DFA
  9917. here, unless it's cmp $0,%reg, which is equivalent to
  9918. test %reg,%reg }
  9919. OrXorUsed and
  9920. (taicpu(hp1).opcode = A_CMP) and
  9921. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9922. ) or
  9923. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9924. { Has to be an exact match on the register }
  9925. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9926. (
  9927. { Permit "test %reg,%reg" }
  9928. (taicpu(hp1).opcode = A_TEST) and
  9929. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9930. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9931. ) or
  9932. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9933. { Make sure the comparison value is not smaller than the
  9934. smallest allowed signed value for the minimum size (e.g.
  9935. -128 for 8-bit) }
  9936. not (
  9937. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9938. { Is it in the negative range? }
  9939. (
  9940. (taicpu(hp1).oper[0]^.val < 0) and
  9941. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9942. )
  9943. ) then
  9944. Break;
  9945. { Check to see if the active register is used afterwards }
  9946. TransferUsedRegs(TmpUsedRegs);
  9947. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9948. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9949. begin
  9950. { Make sure the comparison or any previous instructions
  9951. hasn't pushed the test values outside of the range of
  9952. MinSize }
  9953. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9954. begin
  9955. { Exceeded lower bound but not upper bound }
  9956. Exit;
  9957. end
  9958. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9959. begin
  9960. { Size didn't exceed lower bound }
  9961. TargetSize := MinSize;
  9962. end
  9963. else
  9964. Break;
  9965. case TargetSize of
  9966. S_B:
  9967. TargetSubReg := R_SUBL;
  9968. S_W:
  9969. TargetSubReg := R_SUBW;
  9970. S_L:
  9971. TargetSubReg := R_SUBD;
  9972. else
  9973. InternalError(2021051002);
  9974. end;
  9975. if TargetSize <> MaxSize then
  9976. begin
  9977. { Update the register to its new size }
  9978. setsubreg(ThisReg, TargetSubReg);
  9979. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9980. taicpu(hp1).oper[1]^.reg := ThisReg;
  9981. taicpu(hp1).opsize := TargetSize;
  9982. { Convert the input MOVZX to a MOV if necessary }
  9983. AdjustInitialLoadAndSize;
  9984. if (InstrMax >= 0) then
  9985. begin
  9986. for Index := 0 to InstrMax do
  9987. begin
  9988. { If p_removed is true, then the original MOV/Z was removed
  9989. and removing the AND instruction may not be safe if it
  9990. appears first }
  9991. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9992. InternalError(2020112311);
  9993. if InstrList[Index].oper[0]^.typ = top_reg then
  9994. InstrList[Index].oper[0]^.reg := ThisReg;
  9995. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9996. InstrList[Index].opsize := MinSize;
  9997. end;
  9998. end;
  9999. Result := True;
  10000. end;
  10001. Exit;
  10002. end;
  10003. end;
  10004. A_SETcc:
  10005. begin
  10006. { This allows this Movx optimisation to work through the SETcc instructions
  10007. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10008. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10009. skip over these SETcc instructions). }
  10010. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10011. { Of course, break out if the current register is used }
  10012. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10013. Break
  10014. else
  10015. { We must use Continue so the instruction doesn't get added
  10016. to InstrList }
  10017. Continue;
  10018. end;
  10019. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10020. begin
  10021. if
  10022. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10023. { Has to be an exact match on the register }
  10024. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10025. (
  10026. (
  10027. (taicpu(hp1).oper[0]^.typ = top_const) and
  10028. (
  10029. (
  10030. (taicpu(hp1).opcode = A_SHL) and
  10031. (
  10032. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10033. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10034. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10035. )
  10036. ) or (
  10037. (taicpu(hp1).opcode <> A_SHL) and
  10038. (
  10039. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10040. { Is it in the negative range? }
  10041. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10042. )
  10043. )
  10044. )
  10045. ) or (
  10046. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10047. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10048. )
  10049. ) then
  10050. Break;
  10051. { Only process OR and XOR if there are only bitwise operations,
  10052. since otherwise they can too easily fool the data flow
  10053. analysis (they can cause non-linear behaviour) }
  10054. case taicpu(hp1).opcode of
  10055. A_ADD:
  10056. begin
  10057. if OrXorUsed then
  10058. { Too high a risk of non-linear behaviour that breaks DFA here }
  10059. Break
  10060. else
  10061. BitwiseOnly := False;
  10062. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10063. begin
  10064. TestValMin := TestValMin * 2;
  10065. TestValMax := TestValMax * 2;
  10066. TestValSignedMax := TestValSignedMax * 2;
  10067. end
  10068. else
  10069. begin
  10070. WorkingValue := taicpu(hp1).oper[0]^.val;
  10071. TestValMin := TestValMin + WorkingValue;
  10072. TestValMax := TestValMax + WorkingValue;
  10073. TestValSignedMax := TestValSignedMax + WorkingValue;
  10074. end;
  10075. end;
  10076. A_SUB:
  10077. begin
  10078. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10079. begin
  10080. TestValMin := 0;
  10081. TestValMax := 0;
  10082. TestValSignedMax := 0;
  10083. end
  10084. else
  10085. begin
  10086. if OrXorUsed then
  10087. { Too high a risk of non-linear behaviour that breaks DFA here }
  10088. Break
  10089. else
  10090. BitwiseOnly := False;
  10091. WorkingValue := taicpu(hp1).oper[0]^.val;
  10092. TestValMin := TestValMin - WorkingValue;
  10093. TestValMax := TestValMax - WorkingValue;
  10094. TestValSignedMax := TestValSignedMax - WorkingValue;
  10095. end;
  10096. end;
  10097. A_AND:
  10098. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10099. begin
  10100. { we might be able to go smaller if AND appears first }
  10101. if InstrMax = -1 then
  10102. case MinSize of
  10103. S_B:
  10104. ;
  10105. S_W:
  10106. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10107. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10108. begin
  10109. TryShiftDown := S_B;
  10110. TryShiftDownLimit := $FF;
  10111. end;
  10112. S_L:
  10113. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10114. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10115. begin
  10116. TryShiftDown := S_B;
  10117. TryShiftDownLimit := $FF;
  10118. end
  10119. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10120. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10121. begin
  10122. TryShiftDown := S_W;
  10123. TryShiftDownLimit := $FFFF;
  10124. end;
  10125. else
  10126. InternalError(2020112320);
  10127. end;
  10128. WorkingValue := taicpu(hp1).oper[0]^.val;
  10129. TestValMin := TestValMin and WorkingValue;
  10130. TestValMax := TestValMax and WorkingValue;
  10131. TestValSignedMax := TestValSignedMax and WorkingValue;
  10132. end;
  10133. A_OR:
  10134. begin
  10135. if not BitwiseOnly then
  10136. Break;
  10137. OrXorUsed := True;
  10138. WorkingValue := taicpu(hp1).oper[0]^.val;
  10139. TestValMin := TestValMin or WorkingValue;
  10140. TestValMax := TestValMax or WorkingValue;
  10141. TestValSignedMax := TestValSignedMax or WorkingValue;
  10142. end;
  10143. A_XOR:
  10144. begin
  10145. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10146. begin
  10147. TestValMin := 0;
  10148. TestValMax := 0;
  10149. TestValSignedMax := 0;
  10150. end
  10151. else
  10152. begin
  10153. if not BitwiseOnly then
  10154. Break;
  10155. OrXorUsed := True;
  10156. WorkingValue := taicpu(hp1).oper[0]^.val;
  10157. TestValMin := TestValMin xor WorkingValue;
  10158. TestValMax := TestValMax xor WorkingValue;
  10159. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10160. end;
  10161. end;
  10162. A_SHL:
  10163. begin
  10164. BitwiseOnly := False;
  10165. WorkingValue := taicpu(hp1).oper[0]^.val;
  10166. TestValMin := TestValMin shl WorkingValue;
  10167. TestValMax := TestValMax shl WorkingValue;
  10168. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10169. end;
  10170. A_SHR,
  10171. { The first instruction was MOVZX, so the value won't be negative }
  10172. A_SAR:
  10173. begin
  10174. if InstrMax <> -1 then
  10175. BitwiseOnly := False
  10176. else
  10177. { we might be able to go smaller if SHR appears first }
  10178. case MinSize of
  10179. S_B:
  10180. ;
  10181. S_W:
  10182. if (taicpu(hp1).oper[0]^.val >= 8) then
  10183. begin
  10184. TryShiftDown := S_B;
  10185. TryShiftDownLimit := $FF;
  10186. TryShiftDownSignedLimit := $7F;
  10187. TryShiftDownSignedLimitLower := -128;
  10188. end;
  10189. S_L:
  10190. if (taicpu(hp1).oper[0]^.val >= 24) then
  10191. begin
  10192. TryShiftDown := S_B;
  10193. TryShiftDownLimit := $FF;
  10194. TryShiftDownSignedLimit := $7F;
  10195. TryShiftDownSignedLimitLower := -128;
  10196. end
  10197. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10198. begin
  10199. TryShiftDown := S_W;
  10200. TryShiftDownLimit := $FFFF;
  10201. TryShiftDownSignedLimit := $7FFF;
  10202. TryShiftDownSignedLimitLower := -32768;
  10203. end;
  10204. else
  10205. InternalError(2020112321);
  10206. end;
  10207. WorkingValue := taicpu(hp1).oper[0]^.val;
  10208. if taicpu(hp1).opcode = A_SAR then
  10209. begin
  10210. TestValMin := SarInt64(TestValMin, WorkingValue);
  10211. TestValMax := SarInt64(TestValMax, WorkingValue);
  10212. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10213. end
  10214. else
  10215. begin
  10216. TestValMin := TestValMin shr WorkingValue;
  10217. TestValMax := TestValMax shr WorkingValue;
  10218. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10219. end;
  10220. end;
  10221. else
  10222. InternalError(2020112303);
  10223. end;
  10224. end;
  10225. (*
  10226. A_IMUL:
  10227. case taicpu(hp1).ops of
  10228. 2:
  10229. begin
  10230. if not MatchOpType(hp1, top_reg, top_reg) or
  10231. { Has to be an exact match on the register }
  10232. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10233. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10234. Break;
  10235. TestValMin := TestValMin * TestValMin;
  10236. TestValMax := TestValMax * TestValMax;
  10237. TestValSignedMax := TestValSignedMax * TestValMax;
  10238. end;
  10239. 3:
  10240. begin
  10241. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10242. { Has to be an exact match on the register }
  10243. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10244. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10245. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10246. { Is it in the negative range? }
  10247. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10248. Break;
  10249. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10250. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10251. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10252. end;
  10253. else
  10254. Break;
  10255. end;
  10256. A_IDIV:
  10257. case taicpu(hp1).ops of
  10258. 3:
  10259. begin
  10260. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10261. { Has to be an exact match on the register }
  10262. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10263. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10264. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10265. { Is it in the negative range? }
  10266. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10267. Break;
  10268. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10269. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10270. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10271. end;
  10272. else
  10273. Break;
  10274. end;
  10275. *)
  10276. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10277. begin
  10278. { If there are no instructions in between, then we might be able to make a saving }
  10279. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10280. Break;
  10281. { We have something like:
  10282. movzbw %dl,%dx
  10283. ...
  10284. movswl %dx,%edx
  10285. Change the latter to a zero-extension then enter the
  10286. A_MOVZX case branch.
  10287. }
  10288. {$ifdef x86_64}
  10289. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10290. begin
  10291. { this becomes a zero extension from 32-bit to 64-bit, but
  10292. the upper 32 bits are already zero, so just delete the
  10293. instruction }
  10294. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10295. RemoveInstruction(hp1);
  10296. Result := True;
  10297. Exit;
  10298. end
  10299. else
  10300. {$endif x86_64}
  10301. begin
  10302. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10303. taicpu(hp1).opcode := A_MOVZX;
  10304. {$ifdef x86_64}
  10305. case taicpu(hp1).opsize of
  10306. S_BQ:
  10307. begin
  10308. taicpu(hp1).opsize := S_BL;
  10309. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10310. end;
  10311. S_WQ:
  10312. begin
  10313. taicpu(hp1).opsize := S_WL;
  10314. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10315. end;
  10316. S_LQ:
  10317. begin
  10318. taicpu(hp1).opcode := A_MOV;
  10319. taicpu(hp1).opsize := S_L;
  10320. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10321. { In this instance, we need to break out because the
  10322. instruction is no longer MOVZX or MOVSXD }
  10323. Result := True;
  10324. Exit;
  10325. end;
  10326. else
  10327. ;
  10328. end;
  10329. {$endif x86_64}
  10330. Result := CompressInstructions;
  10331. Exit;
  10332. end;
  10333. end;
  10334. A_MOVZX:
  10335. begin
  10336. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10337. Break;
  10338. if (InstrMax = -1) then
  10339. begin
  10340. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10341. begin
  10342. { Optimise around i40003 }
  10343. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10344. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10345. {$ifndef x86_64}
  10346. and (
  10347. (taicpu(p).oper[0]^.typ <> top_reg) or
  10348. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10349. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10350. )
  10351. {$endif not x86_64}
  10352. then
  10353. begin
  10354. if (taicpu(p).oper[0]^.typ = top_reg) then
  10355. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10356. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10357. taicpu(p).opsize := S_BL;
  10358. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10359. RemoveInstruction(hp1);
  10360. Result := True;
  10361. Exit;
  10362. end;
  10363. end
  10364. else
  10365. begin
  10366. { Will return false if the second parameter isn't ThisReg
  10367. (can happen on -O2 and under) }
  10368. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10369. begin
  10370. { The two MOVZX instructions are adjacent, so remove the first one }
  10371. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10372. RemoveCurrentP(p);
  10373. Result := True;
  10374. Exit;
  10375. end;
  10376. Break;
  10377. end;
  10378. end;
  10379. Result := CompressInstructions;
  10380. Exit;
  10381. end;
  10382. else
  10383. { This includes ADC, SBB and IDIV }
  10384. Break;
  10385. end;
  10386. if not CheckOverflowConditions then
  10387. Break;
  10388. { Contains highest index (so instruction count - 1) }
  10389. Inc(InstrMax);
  10390. if InstrMax > High(InstrList) then
  10391. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10392. InstrList[InstrMax] := taicpu(hp1);
  10393. end;
  10394. end;
  10395. {$pop}
  10396. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10397. var
  10398. hp1 : tai;
  10399. begin
  10400. Result:=false;
  10401. if (taicpu(p).ops >= 2) and
  10402. ((taicpu(p).oper[0]^.typ = top_const) or
  10403. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10404. (taicpu(p).oper[1]^.typ = top_reg) and
  10405. ((taicpu(p).ops = 2) or
  10406. ((taicpu(p).oper[2]^.typ = top_reg) and
  10407. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10408. GetLastInstruction(p,hp1) and
  10409. MatchInstruction(hp1,A_MOV,[]) and
  10410. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10411. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10412. begin
  10413. TransferUsedRegs(TmpUsedRegs);
  10414. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10415. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10416. { change
  10417. mov reg1,reg2
  10418. imul y,reg2 to imul y,reg1,reg2 }
  10419. begin
  10420. taicpu(p).ops := 3;
  10421. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10422. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10423. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10424. RemoveInstruction(hp1);
  10425. result:=true;
  10426. end;
  10427. end;
  10428. end;
  10429. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10430. var
  10431. ThisLabel: TAsmLabel;
  10432. begin
  10433. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10434. ThisLabel.decrefs;
  10435. taicpu(p).condition := C_None;
  10436. taicpu(p).opcode := A_RET;
  10437. taicpu(p).is_jmp := false;
  10438. taicpu(p).ops := taicpu(ret_p).ops;
  10439. case taicpu(ret_p).ops of
  10440. 0:
  10441. taicpu(p).clearop(0);
  10442. 1:
  10443. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10444. else
  10445. internalerror(2016041301);
  10446. end;
  10447. { If the original label is now dead, it might turn out that the label
  10448. immediately follows p. As a result, everything beyond it, which will
  10449. be just some final register configuration and a RET instruction, is
  10450. now dead code. [Kit] }
  10451. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10452. running RemoveDeadCodeAfterJump for each RET instruction, because
  10453. this optimisation rarely happens and most RETs appear at the end of
  10454. routines where there is nothing that can be stripped. [Kit] }
  10455. if not ThisLabel.is_used then
  10456. RemoveDeadCodeAfterJump(p);
  10457. end;
  10458. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10459. var
  10460. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10461. Unconditional, PotentialModified: Boolean;
  10462. OperPtr: POper;
  10463. NewRef: TReference;
  10464. InstrList: array of taicpu;
  10465. InstrMax, Index: Integer;
  10466. const
  10467. {$ifdef DEBUG_AOPTCPU}
  10468. SNoFlags: shortstring = ' so the flags aren''t modified';
  10469. {$else DEBUG_AOPTCPU}
  10470. SNoFlags = '';
  10471. {$endif DEBUG_AOPTCPU}
  10472. begin
  10473. Result:=false;
  10474. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10475. begin
  10476. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10477. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10478. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10479. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10480. GetNextInstruction(hp1, hp2) and
  10481. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10482. { Change from: To:
  10483. set(C) %reg j(~C) label
  10484. test %reg,%reg/cmp $0,%reg
  10485. je label
  10486. set(C) %reg j(C) label
  10487. test %reg,%reg/cmp $0,%reg
  10488. jne label
  10489. (Also do something similar with sete/setne instead of je/jne)
  10490. }
  10491. begin
  10492. { Before we do anything else, we need to check the instructions
  10493. in between SETcc and TEST to make sure they don't modify the
  10494. FLAGS register - if -O2 or under, there won't be any
  10495. instructions between SET and TEST }
  10496. TransferUsedRegs(TmpUsedRegs);
  10497. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10498. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10499. begin
  10500. next := p;
  10501. SetLength(InstrList, 0);
  10502. InstrMax := -1;
  10503. PotentialModified := False;
  10504. { Make a note of every instruction that modifies the FLAGS
  10505. register }
  10506. while GetNextInstruction(next, next) and (next <> hp1) do
  10507. begin
  10508. if next.typ <> ait_instruction then
  10509. { GetNextInstructionUsingReg should have returned False }
  10510. InternalError(2021051701);
  10511. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10512. begin
  10513. case taicpu(next).opcode of
  10514. A_SETcc,
  10515. A_CMOVcc,
  10516. A_Jcc:
  10517. begin
  10518. if PotentialModified then
  10519. { Not safe because the flags were modified earlier }
  10520. Exit
  10521. else
  10522. { Condition is the same as the initial SETcc, so this is safe
  10523. (don't add to instruction list though) }
  10524. Continue;
  10525. end;
  10526. A_ADD:
  10527. begin
  10528. if (taicpu(next).opsize = S_B) or
  10529. { LEA doesn't support 8-bit operands }
  10530. (taicpu(next).oper[1]^.typ <> top_reg) or
  10531. { Must write to a register }
  10532. (taicpu(next).oper[0]^.typ = top_ref) then
  10533. { Require a constant or a register }
  10534. Exit;
  10535. PotentialModified := True;
  10536. end;
  10537. A_SUB:
  10538. begin
  10539. if (taicpu(next).opsize = S_B) or
  10540. { LEA doesn't support 8-bit operands }
  10541. (taicpu(next).oper[1]^.typ <> top_reg) or
  10542. { Must write to a register }
  10543. (taicpu(next).oper[0]^.typ <> top_const) or
  10544. (taicpu(next).oper[0]^.val = $80000000) then
  10545. { Can't subtract a register with LEA - also
  10546. check that the value isn't -2^31, as this
  10547. can't be negated }
  10548. Exit;
  10549. PotentialModified := True;
  10550. end;
  10551. A_SAL,
  10552. A_SHL:
  10553. begin
  10554. if (taicpu(next).opsize = S_B) or
  10555. { LEA doesn't support 8-bit operands }
  10556. (taicpu(next).oper[1]^.typ <> top_reg) or
  10557. { Must write to a register }
  10558. (taicpu(next).oper[0]^.typ <> top_const) or
  10559. (taicpu(next).oper[0]^.val < 0) or
  10560. (taicpu(next).oper[0]^.val > 3) then
  10561. Exit;
  10562. PotentialModified := True;
  10563. end;
  10564. A_IMUL:
  10565. begin
  10566. if (taicpu(next).ops <> 3) or
  10567. (taicpu(next).oper[1]^.typ <> top_reg) or
  10568. { Must write to a register }
  10569. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10570. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10571. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10572. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10573. Exit
  10574. else
  10575. PotentialModified := True;
  10576. end;
  10577. else
  10578. { Don't know how to change this, so abort }
  10579. Exit;
  10580. end;
  10581. { Contains highest index (so instruction count - 1) }
  10582. Inc(InstrMax);
  10583. if InstrMax > High(InstrList) then
  10584. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10585. InstrList[InstrMax] := taicpu(next);
  10586. end;
  10587. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10588. end;
  10589. if not Assigned(next) or (next <> hp1) then
  10590. { It should be equal to hp1 }
  10591. InternalError(2021051702);
  10592. { Cycle through each instruction and check to see if we can
  10593. change them to versions that don't modify the flags }
  10594. if (InstrMax >= 0) then
  10595. begin
  10596. for Index := 0 to InstrMax do
  10597. case InstrList[Index].opcode of
  10598. A_ADD:
  10599. begin
  10600. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10601. InstrList[Index].opcode := A_LEA;
  10602. reference_reset(NewRef, 1, []);
  10603. NewRef.base := InstrList[Index].oper[1]^.reg;
  10604. if InstrList[Index].oper[0]^.typ = top_reg then
  10605. begin
  10606. NewRef.index := InstrList[Index].oper[0]^.reg;
  10607. NewRef.scalefactor := 1;
  10608. end
  10609. else
  10610. NewRef.offset := InstrList[Index].oper[0]^.val;
  10611. InstrList[Index].loadref(0, NewRef);
  10612. end;
  10613. A_SUB:
  10614. begin
  10615. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10616. InstrList[Index].opcode := A_LEA;
  10617. reference_reset(NewRef, 1, []);
  10618. NewRef.base := InstrList[Index].oper[1]^.reg;
  10619. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10620. InstrList[Index].loadref(0, NewRef);
  10621. end;
  10622. A_SHL,
  10623. A_SAL:
  10624. begin
  10625. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10626. InstrList[Index].opcode := A_LEA;
  10627. reference_reset(NewRef, 1, []);
  10628. NewRef.index := InstrList[Index].oper[1]^.reg;
  10629. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10630. InstrList[Index].loadref(0, NewRef);
  10631. end;
  10632. A_IMUL:
  10633. begin
  10634. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10635. InstrList[Index].opcode := A_LEA;
  10636. reference_reset(NewRef, 1, []);
  10637. NewRef.index := InstrList[Index].oper[1]^.reg;
  10638. case InstrList[Index].oper[0]^.val of
  10639. 2, 4, 8:
  10640. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10641. else {3, 5 and 9}
  10642. begin
  10643. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10644. NewRef.base := InstrList[Index].oper[1]^.reg;
  10645. end;
  10646. end;
  10647. InstrList[Index].loadref(0, NewRef);
  10648. end;
  10649. else
  10650. InternalError(2021051710);
  10651. end;
  10652. end;
  10653. { Mark the FLAGS register as used across this whole block }
  10654. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10655. end;
  10656. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10657. JumpC := taicpu(hp2).condition;
  10658. Unconditional := False;
  10659. if conditions_equal(JumpC, C_E) then
  10660. SetC := inverse_cond(taicpu(p).condition)
  10661. else if conditions_equal(JumpC, C_NE) then
  10662. SetC := taicpu(p).condition
  10663. else
  10664. { We've got something weird here (and inefficent) }
  10665. begin
  10666. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10667. SetC := C_NONE;
  10668. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10669. if condition_in(C_AE, JumpC) then
  10670. Unconditional := True
  10671. else
  10672. { Not sure what to do with this jump - drop out }
  10673. Exit;
  10674. end;
  10675. RemoveInstruction(hp1);
  10676. if Unconditional then
  10677. MakeUnconditional(taicpu(hp2))
  10678. else
  10679. begin
  10680. if SetC = C_NONE then
  10681. InternalError(2018061402);
  10682. taicpu(hp2).SetCondition(SetC);
  10683. end;
  10684. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10685. TmpUsedRegs }
  10686. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10687. begin
  10688. RemoveCurrentp(p, hp2);
  10689. if taicpu(hp2).opcode = A_SETcc then
  10690. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10691. else
  10692. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10693. end
  10694. else
  10695. if taicpu(hp2).opcode = A_SETcc then
  10696. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10697. else
  10698. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10699. Result := True;
  10700. end
  10701. else if
  10702. { Make sure the instructions are adjacent }
  10703. (
  10704. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10705. GetNextInstruction(p, hp1)
  10706. ) and
  10707. MatchInstruction(hp1, A_MOV, [S_B]) and
  10708. { Writing to memory is allowed }
  10709. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10710. begin
  10711. {
  10712. Watch out for sequences such as:
  10713. set(c)b %regb
  10714. movb %regb,(ref)
  10715. movb $0,1(ref)
  10716. movb $0,2(ref)
  10717. movb $0,3(ref)
  10718. Much more efficient to turn it into:
  10719. movl $0,%regl
  10720. set(c)b %regb
  10721. movl %regl,(ref)
  10722. Or:
  10723. set(c)b %regb
  10724. movzbl %regb,%regl
  10725. movl %regl,(ref)
  10726. }
  10727. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10728. GetNextInstruction(hp1, hp2) and
  10729. MatchInstruction(hp2, A_MOV, [S_B]) and
  10730. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10731. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10732. begin
  10733. { Don't do anything else except set Result to True }
  10734. end
  10735. else
  10736. begin
  10737. if taicpu(p).oper[0]^.typ = top_reg then
  10738. begin
  10739. TransferUsedRegs(TmpUsedRegs);
  10740. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10741. end;
  10742. { If it's not a register, it's a memory address }
  10743. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10744. begin
  10745. { Even if the register is still in use, we can minimise the
  10746. pipeline stall by changing the MOV into another SETcc. }
  10747. taicpu(hp1).opcode := A_SETcc;
  10748. taicpu(hp1).condition := taicpu(p).condition;
  10749. if taicpu(hp1).oper[1]^.typ = top_ref then
  10750. begin
  10751. { Swapping the operand pointers like this is probably a
  10752. bit naughty, but it is far faster than using loadoper
  10753. to transfer the reference from oper[1] to oper[0] if
  10754. you take into account the extra procedure calls and
  10755. the memory allocation and deallocation required }
  10756. OperPtr := taicpu(hp1).oper[1];
  10757. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10758. taicpu(hp1).oper[0] := OperPtr;
  10759. end
  10760. else
  10761. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10762. taicpu(hp1).clearop(1);
  10763. taicpu(hp1).ops := 1;
  10764. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10765. end
  10766. else
  10767. begin
  10768. if taicpu(hp1).oper[1]^.typ = top_reg then
  10769. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10770. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10771. RemoveInstruction(hp1);
  10772. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10773. end
  10774. end;
  10775. Result := True;
  10776. end;
  10777. end;
  10778. end;
  10779. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  10780. var
  10781. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  10782. TargetReg: TRegister;
  10783. condition, inverted_condition: TAsmCond;
  10784. FoundMOV: Boolean;
  10785. begin
  10786. Result := False;
  10787. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  10788. create the most optimial instructions possible due to limited
  10789. register availability, and there are situations where two
  10790. complementary "simple" CMOV blocks are created which, after the fact
  10791. can be merged into a "double" block. For example:
  10792. movw $257,%ax
  10793. movw $2,%r8w
  10794. xorl r9d,%r9d
  10795. testw $16,18(%rcx)
  10796. cmovew %ax,%dx
  10797. cmovew %r8w,%bx
  10798. cmovel %r9d,%r14d
  10799. movw $1283,%ax
  10800. movw $4,%r8w
  10801. movl $9,%r9d
  10802. cmovnew %ax,%dx
  10803. cmovnew %r8w,%bx
  10804. cmovnel %r9d,%r14d
  10805. The CMOVNE instructions at the end can be removed, and the
  10806. destination registers copied into the MOV instructions directly
  10807. above them, before finally being moved to before the first CMOVE
  10808. instructions, to produce:
  10809. movw $257,%ax
  10810. movw $2,%r8w
  10811. xorl r9d,%r9d
  10812. testw $16,18(%rcx)
  10813. movw $1283,%dx
  10814. movw $4,%bx
  10815. movl $9,%r14d
  10816. cmovew %ax,%dx
  10817. cmovew %r8w,%bx
  10818. cmovel %r9d,%r14d
  10819. Which can then be later optimised to:
  10820. movw $257,%ax
  10821. movw $2,%r8w
  10822. xorl r9d,%r9d
  10823. movw $1283,%dx
  10824. movw $4,%bx
  10825. movl $9,%r14d
  10826. testw $16,18(%rcx)
  10827. cmovew %ax,%dx
  10828. cmovew %r8w,%bx
  10829. cmovel %r9d,%r14d
  10830. }
  10831. TargetReg := taicpu(hp1).oper[1]^.reg;
  10832. condition := taicpu(hp1).condition;
  10833. inverted_condition := inverse_cond(condition);
  10834. pFirstMov := nil;
  10835. pLastMov := nil;
  10836. pCMOV := nil;
  10837. if (p.typ = ait_instruction) then
  10838. pCond := p
  10839. else if not GetNextInstruction(p, pCond) then
  10840. InternalError(2024012501);
  10841. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  10842. { We should get the CMP or TEST instructeion }
  10843. InternalError(2024012502);
  10844. if (
  10845. (taicpu(hp1).oper[0]^.typ = top_reg) or
  10846. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  10847. ) then
  10848. begin
  10849. { We have to tread carefully here, hence why we're not using
  10850. GetNextInstructionUsingReg... we can only accept MOV and other
  10851. CMOV instructions. Anything else and we must drop out}
  10852. hp2 := hp1;
  10853. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  10854. begin
  10855. if (hp2.typ <> ait_instruction) then
  10856. Exit;
  10857. case taicpu(hp2).opcode of
  10858. A_MOV:
  10859. begin
  10860. if not Assigned(pFirstMov) then
  10861. pFirstMov := hp2;
  10862. pLastMOV := hp2;
  10863. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  10864. { Something different - drop out }
  10865. Exit;
  10866. { Otherwise, leave it for now }
  10867. end;
  10868. A_CMOVcc:
  10869. begin
  10870. if taicpu(hp2).condition = inverted_condition then
  10871. begin
  10872. { We found what we're looking for }
  10873. if taicpu(hp2).oper[1]^.reg = TargetReg then
  10874. begin
  10875. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  10876. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  10877. begin
  10878. pCMOV := hp2;
  10879. Break;
  10880. end
  10881. else
  10882. { Unsafe reference - drop out }
  10883. Exit;
  10884. end;
  10885. end
  10886. else if taicpu(hp2).condition <> condition then
  10887. { Something weird - drop out }
  10888. Exit;
  10889. end;
  10890. else
  10891. { Invalid }
  10892. Exit;
  10893. end;
  10894. end;
  10895. if not Assigned(pCMOV) then
  10896. { No complementary CMOV found }
  10897. Exit;
  10898. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  10899. begin
  10900. { Don't need to do anything special or search for a matching MOV }
  10901. Asml.Remove(pCMOV);
  10902. if RegInInstruction(TargetReg, pCond) then
  10903. { Make sure we don't overwrite the register if it's being used in the condition }
  10904. Asml.InsertAfter(pCMOV, pCond)
  10905. else
  10906. Asml.InsertBefore(pCMOV, pCond);
  10907. taicpu(pCMOV).opcode := A_MOV;
  10908. taicpu(pCMOV).condition := C_None;
  10909. { Don't need to worry about allocating new registers in these cases }
  10910. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  10911. Result := True;
  10912. Exit;
  10913. end
  10914. else
  10915. begin
  10916. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  10917. FoundMOV := False;
  10918. { Search for the MOV that sets the target register }
  10919. hp2 := pFirstMov;
  10920. repeat
  10921. if (taicpu(hp2).opcode = A_MOV) and
  10922. (taicpu(hp2).oper[1]^.typ = top_reg) and
  10923. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  10924. begin
  10925. { Change the destination }
  10926. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  10927. if not FoundMOV then
  10928. begin
  10929. FoundMOV := True;
  10930. { Make sure the register is allocated }
  10931. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  10932. end;
  10933. hp1 := tai(hp2.Previous);
  10934. Asml.Remove(hp2);
  10935. if RegInInstruction(TargetReg, pCond) then
  10936. { Make sure we don't overwrite the register if it's being used in the condition }
  10937. Asml.InsertAfter(hp2, pCond)
  10938. else
  10939. Asml.InsertBefore(hp2, pCond);
  10940. if (hp2 = pLastMov) then
  10941. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  10942. Break;
  10943. hp2 := hp1;
  10944. end;
  10945. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  10946. if FoundMOV then
  10947. { Delete the CMOV }
  10948. RemoveInstruction(pCMOV)
  10949. else
  10950. begin
  10951. { If no MOV was found, we have to actually move and transmute the CMOV }
  10952. Asml.Remove(pCMOV);
  10953. if RegInInstruction(TargetReg, pCond) then
  10954. { Make sure we don't overwrite the register if it's being used in the condition }
  10955. Asml.InsertAfter(pCMOV, pCond)
  10956. else
  10957. Asml.InsertBefore(pCMOV, pCond);
  10958. taicpu(pCMOV).opcode := A_MOV;
  10959. taicpu(pCMOV).condition := C_None;
  10960. end;
  10961. Result := True;
  10962. Exit;
  10963. end;
  10964. end;
  10965. end;
  10966. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  10967. var
  10968. hp1, hp2, pCond: tai;
  10969. begin
  10970. Result := False;
  10971. { Search ahead for CMOV instructions }
  10972. if (cs_opt_level2 in current_settings.optimizerswitches) then
  10973. begin
  10974. hp1 := p;
  10975. hp2 := p;
  10976. pCond := nil; { To prevent compiler warnings }
  10977. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  10978. DEFAULTFLAGS }
  10979. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  10980. (tai_regalloc(pCond).ratype = ra_dealloc) then
  10981. pCond := p;
  10982. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  10983. begin
  10984. if (hp1.typ <> ait_instruction) then
  10985. { Break out on markers and labels etc. }
  10986. Break;
  10987. case taicpu(hp1).opcode of
  10988. A_MOV:
  10989. { Ignore regular MOVs unless they are obviously not related
  10990. to a CMOV block }
  10991. if taicpu(hp1).oper[1]^.typ <> top_reg then
  10992. Break;
  10993. A_CMOVcc:
  10994. if TryCmpCMovOpts(pCond, hp1) then
  10995. begin
  10996. hp1 := hp2;
  10997. { p itself isn't changed, and we're still inside a
  10998. while loop to catch subsequent CMOVs, so just flag
  10999. a new iteration }
  11000. Include(OptsToCheck, aoc_ForceNewIteration);
  11001. Continue;
  11002. end;
  11003. else
  11004. { Drop out if we find anything else }
  11005. Break;
  11006. end;
  11007. hp2 := hp1;
  11008. end;
  11009. end;
  11010. end;
  11011. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11012. var
  11013. hp1, hp2, pCond: tai;
  11014. begin
  11015. Result := False;
  11016. { Search ahead for CMOV instructions }
  11017. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11018. begin
  11019. hp1 := p;
  11020. hp2 := p;
  11021. pCond := nil; { To prevent compiler warnings }
  11022. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11023. DEFAULTFLAGS }
  11024. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11025. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11026. pCond := p;
  11027. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11028. begin
  11029. if (hp1.typ <> ait_instruction) then
  11030. { Break out on markers and labels etc. }
  11031. Break;
  11032. case taicpu(hp1).opcode of
  11033. A_MOV:
  11034. { Ignore regular MOVs unless they are obviously not related
  11035. to a CMOV block }
  11036. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11037. Break;
  11038. A_CMOVcc:
  11039. if TryCmpCMovOpts(pCond, hp1) then
  11040. begin
  11041. hp1 := hp2;
  11042. { p itself isn't changed, and we're still inside a
  11043. while loop to catch subsequent CMOVs, so just flag
  11044. a new iteration }
  11045. Include(OptsToCheck, aoc_ForceNewIteration);
  11046. Continue;
  11047. end;
  11048. else
  11049. { Drop out if we find anything else }
  11050. Break;
  11051. end;
  11052. hp2 := hp1;
  11053. end;
  11054. end;
  11055. end;
  11056. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11057. var
  11058. hp1: tai;
  11059. Count: Integer;
  11060. OrigLabel: TAsmLabel;
  11061. begin
  11062. result := False;
  11063. { Sometimes, the optimisations below can permit this }
  11064. RemoveDeadCodeAfterJump(p);
  11065. 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
  11066. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11067. begin
  11068. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11069. { Also a side-effect of optimisations }
  11070. if CollapseZeroDistJump(p, OrigLabel) then
  11071. begin
  11072. Result := True;
  11073. Exit;
  11074. end;
  11075. hp1 := GetLabelWithSym(OrigLabel);
  11076. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11077. begin
  11078. if taicpu(hp1).opcode = A_RET then
  11079. begin
  11080. {
  11081. change
  11082. jmp .L1
  11083. ...
  11084. .L1:
  11085. ret
  11086. into
  11087. ret
  11088. }
  11089. begin
  11090. ConvertJumpToRET(p, hp1);
  11091. result:=true;
  11092. end;
  11093. end
  11094. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11095. not (cs_opt_size in current_settings.optimizerswitches) and
  11096. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11097. begin
  11098. Result := True;
  11099. Exit;
  11100. end;
  11101. end;
  11102. end;
  11103. end;
  11104. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11105. begin
  11106. Result := assigned(p) and
  11107. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11108. (taicpu(p).oper[1]^.typ = top_reg) and
  11109. (
  11110. (taicpu(p).oper[0]^.typ = top_reg) or
  11111. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11112. it is not expected that this can cause a seg. violation }
  11113. (
  11114. (taicpu(p).oper[0]^.typ = top_ref) and
  11115. { TODO: Can we detect which references become constants at this
  11116. stage so we don't have to do a blanket ban? }
  11117. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11118. (
  11119. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11120. (
  11121. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11122. not RefModified and
  11123. { If the reference also appears in the condition, then we know it's safe, otherwise
  11124. any kind of access violation would have occurred already }
  11125. Assigned(cond_p) and
  11126. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11127. (cond_p.typ = ait_instruction) and
  11128. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11129. { Just consider 2-operand comparison instructions for now to be safe }
  11130. (taicpu(cond_p).ops = 2) and
  11131. (
  11132. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11133. (
  11134. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11135. { Don't risk identical registers but different offsets, as we may have constructs
  11136. such as buffer streams with things like length fields that indicate whether
  11137. any more data follows. And there are probably some contrived examples where
  11138. writing to offsets behind the one being read also lead to access violations }
  11139. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11140. (
  11141. { Check that we're not modifying a register that appears in the reference }
  11142. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11143. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11144. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11145. )
  11146. )
  11147. )
  11148. )
  11149. )
  11150. )
  11151. );
  11152. end;
  11153. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11154. begin
  11155. { Update integer registers, ignoring deallocations }
  11156. repeat
  11157. while assigned(p) and
  11158. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11159. (p.typ = ait_label) or
  11160. ((p.typ = ait_marker) and
  11161. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11162. p := tai(p.next);
  11163. while assigned(p) and
  11164. (p.typ=ait_RegAlloc) Do
  11165. begin
  11166. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11167. begin
  11168. case tai_regalloc(p).ratype of
  11169. ra_alloc :
  11170. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11171. else
  11172. ;
  11173. end;
  11174. end;
  11175. p := tai(p.next);
  11176. end;
  11177. until not(assigned(p)) or
  11178. (not(p.typ in SkipInstr) and
  11179. not((p.typ = ait_label) and
  11180. labelCanBeSkipped(tai_label(p))));
  11181. end;
  11182. {$ifndef 8086}
  11183. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11184. begin
  11185. Result := False;
  11186. EndJump := nil;
  11187. BlockStop := nil;
  11188. while (BlockStart <> fOptimizer.BlockEnd) and
  11189. { stop on labels }
  11190. (BlockStart.typ <> ait_label) do
  11191. begin
  11192. { Keep track of all integer registers that are used }
  11193. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11194. if BlockStart.typ = ait_instruction then
  11195. begin
  11196. if (taicpu(BlockStart).opcode = A_JMP) then
  11197. begin
  11198. if not IsJumpToLabel(taicpu(BlockStart)) or
  11199. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11200. Exit;
  11201. EndJump := BlockStart;
  11202. Break;
  11203. end
  11204. { Check to see if we have a valid MOV instruction instead }
  11205. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11206. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11207. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11208. begin
  11209. Exit;
  11210. end
  11211. else
  11212. { This will be a valid MOV }
  11213. fAllocationRange := BlockStart;
  11214. end;
  11215. OneBeforeBlock := BlockStart;
  11216. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11217. end;
  11218. if (BlockStart = fOptimizer.BlockEnd) then
  11219. Exit;
  11220. BlockStop := BlockStart;
  11221. Result := True;
  11222. end;
  11223. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11224. var
  11225. hp1: tai;
  11226. RefModified: Boolean;
  11227. begin
  11228. Result := 0;
  11229. hp1 := BlockStart;
  11230. RefModified := False; { As long as the condition is inverted, this can be reset }
  11231. while assigned(hp1) and
  11232. (hp1 <> BlockStop) do
  11233. begin
  11234. case hp1.typ of
  11235. ait_instruction:
  11236. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11237. begin
  11238. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11239. begin
  11240. Inc(Result);
  11241. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11242. Assigned(fCondition) and
  11243. { Will have 2 operands }
  11244. (
  11245. (
  11246. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11247. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11248. ) or
  11249. (
  11250. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11251. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11252. )
  11253. ) then
  11254. { It is no longer safe to use the reference in the condition.
  11255. this prevents problems such as:
  11256. mov (%reg),%reg
  11257. mov (%reg),...
  11258. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11259. (fixes #40165)
  11260. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11261. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11262. }
  11263. RefModified := True;
  11264. end
  11265. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11266. { CMOV with constants grows the code size }
  11267. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11268. begin
  11269. { Register was reserved by TryCMOVConst and
  11270. stored on ConstRegs }
  11271. end
  11272. else
  11273. begin
  11274. Result := -1;
  11275. Exit;
  11276. end;
  11277. end
  11278. else
  11279. begin
  11280. Result := -1;
  11281. Exit;
  11282. end;
  11283. else
  11284. { Most likely an align };
  11285. end;
  11286. fOptimizer.GetNextInstruction(hp1, hp1);
  11287. end;
  11288. end;
  11289. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11290. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11291. (this is done as a separate stage because the double types are extensions of the branching type,
  11292. but we can't discount the conditional jump until the last step) }
  11293. procedure EvaluateBranchingType;
  11294. begin
  11295. Inc(CMOVScore);
  11296. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11297. { Too many instructions to be worthwhile }
  11298. fState := tsInvalid;
  11299. end;
  11300. var
  11301. hp1: tai;
  11302. Count: Integer;
  11303. begin
  11304. { Table of valid CMOV block types
  11305. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11306. ---------- --------- --------- --------- --------- ---------
  11307. tsSimple X Yes X X X
  11308. tsDetour = 1st X X X X
  11309. tsBranching <> Mid Yes X X X
  11310. tsDouble End-label Yes * Yes X Yes
  11311. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11312. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11313. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11314. * Only one reference allowed
  11315. }
  11316. hp1 := nil; { To prevent compiler warnings }
  11317. Optimizer.CopyUsedRegs(RegisterTracking);
  11318. fOptimizer := Optimizer;
  11319. fLabel := AFirstLabel;
  11320. CMOVScore := 0;
  11321. ConstCount := 0;
  11322. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11323. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11324. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11325. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11326. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11327. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11328. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11329. fInsertionPoint := p_initialjump;
  11330. fCondition := nil;
  11331. fInitialJump := p_initialjump;
  11332. fFirstMovBlock := p_initialmov;
  11333. fFirstMovBlockStop := nil;
  11334. fSecondJump := nil;
  11335. fSecondMovBlock := nil;
  11336. fSecondMovBlockStop := nil;
  11337. fMidLabel := nil;
  11338. fSecondJump := nil;
  11339. fSecondMovBlock := nil;
  11340. fEndLabel := nil;
  11341. fAllocationRange := nil;
  11342. { Assume it all goes horribly wrong! }
  11343. fState := tsInvalid;
  11344. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11345. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11346. 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
  11347. begin
  11348. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11349. for Count := 0 to 1 do
  11350. with taicpu(fCondition).oper[Count]^ do
  11351. case typ of
  11352. top_reg:
  11353. if getregtype(reg) = R_INTREGISTER then
  11354. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11355. top_ref:
  11356. begin
  11357. if
  11358. {$ifdef x86_64}
  11359. (ref^.base <> NR_RIP) and
  11360. {$endif x86_64}
  11361. (ref^.base <> NR_NO) then
  11362. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11363. if (ref^.index <> NR_NO) then
  11364. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11365. end
  11366. else
  11367. ;
  11368. end;
  11369. { When inserting instructions before hp_prev, try to insert them
  11370. before the allocation of the FLAGS register }
  11371. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11372. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11373. { If not found, set it equal to the condition so it's something sensible }
  11374. fInsertionPoint := fCondition;
  11375. { When dealing with a comparison against zero, take note of the
  11376. instruction before it to see if we can move instructions further
  11377. back in order to benefit PostPeepholeOptTestOr.
  11378. }
  11379. if (
  11380. (
  11381. (taicpu(fCondition).opcode = A_CMP) and
  11382. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11383. ) or
  11384. (
  11385. (taicpu(fCondition).opcode = A_TEST) and
  11386. (
  11387. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11388. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11389. )
  11390. )
  11391. ) and
  11392. Optimizer.GetLastInstruction(fCondition, hp1) then
  11393. begin
  11394. { These instructions set the zero flag if the result is zero }
  11395. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11396. begin
  11397. fInsertionPoint := hp1;
  11398. { Also mark all the registers in this previous instruction
  11399. as 'in use', even if they've just been deallocated }
  11400. for Count := 0 to 1 do
  11401. with taicpu(hp1).oper[Count]^ do
  11402. case typ of
  11403. top_reg:
  11404. if getregtype(reg) = R_INTREGISTER then
  11405. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11406. top_ref:
  11407. begin
  11408. if
  11409. {$ifdef x86_64}
  11410. (ref^.base <> NR_RIP) and
  11411. {$endif x86_64}
  11412. (ref^.base <> NR_NO) then
  11413. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11414. if (ref^.index <> NR_NO) then
  11415. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11416. end
  11417. else
  11418. ;
  11419. end;
  11420. end;
  11421. end;
  11422. end
  11423. else
  11424. fCondition := nil;
  11425. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11426. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11427. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11428. { If not found, set it equal to p so it's something sensible }
  11429. fInsertionPoint := hp1;
  11430. hp1 := p_initialmov;
  11431. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11432. Exit;
  11433. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11434. if (hp1.typ <> ait_label) then { should be on a jump }
  11435. begin
  11436. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11437. { Need a label afterwards }
  11438. Exit;
  11439. end
  11440. else
  11441. fMidLabel := hp1;
  11442. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11443. { Not the correct label }
  11444. fMidLabel := nil;
  11445. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11446. { If there's neither a 2nd jump nor correct label, then it's invalid
  11447. (see above table) }
  11448. Exit;
  11449. { Analyse the first block of MOVs more closely }
  11450. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11451. if Assigned(fSecondJump) then
  11452. begin
  11453. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11454. begin
  11455. fState := tsDetour
  11456. end
  11457. else
  11458. begin
  11459. { Need the correct mid-label for this one }
  11460. if not Assigned(fMidLabel) then
  11461. Exit;
  11462. fState := tsBranching;
  11463. end;
  11464. end
  11465. else
  11466. { No jump. but mid-label is present }
  11467. fState := tsSimple;
  11468. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11469. begin
  11470. { Invalid or too many instructions to be worthwhile }
  11471. fState := tsInvalid;
  11472. Exit;
  11473. end;
  11474. { check further for
  11475. jCC xxx
  11476. <several movs 1>
  11477. jmp yyy
  11478. xxx:
  11479. <several movs 2>
  11480. yyy:
  11481. etc.
  11482. }
  11483. if (fState = tsBranching) and
  11484. { Estimate for required savings for extra jump }
  11485. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11486. { Only one reference is allowed for double blocks }
  11487. (AFirstLabel.getrefs = 1) then
  11488. begin
  11489. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11490. fSecondMovBlock := hp1;
  11491. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11492. begin
  11493. EvaluateBranchingType;
  11494. Exit;
  11495. end;
  11496. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11497. if (hp1.typ <> ait_label) then { should be on a jump }
  11498. begin
  11499. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11500. begin
  11501. { Need a label afterwards }
  11502. EvaluateBranchingType;
  11503. Exit;
  11504. end;
  11505. end
  11506. else
  11507. fEndLabel := hp1;
  11508. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11509. { Second jump doesn't go to the end }
  11510. fEndLabel := nil;
  11511. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11512. begin
  11513. { If there's neither a 3rd jump nor correct end label, then it's
  11514. not a invalid double block, but is a valid single branching
  11515. block (see above table) }
  11516. EvaluateBranchingType;
  11517. Exit;
  11518. end;
  11519. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11520. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11521. { Invalid or too many instructions to be worthwhile }
  11522. Exit;
  11523. Inc(CMOVScore, Count);
  11524. if Assigned(fThirdJump) then
  11525. begin
  11526. if not Assigned(fSecondJump) then
  11527. fState := tsDoubleSecondBranching
  11528. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11529. fState := tsDoubleBranchSame
  11530. else
  11531. fState := tsDoubleBranchDifferent;
  11532. end
  11533. else
  11534. fState := tsDouble;
  11535. end;
  11536. if fState = tsBranching then
  11537. EvaluateBranchingType;
  11538. end;
  11539. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11540. new register to store the constant }
  11541. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11542. var
  11543. RegSize: TSubRegister;
  11544. CurrentVal: TCGInt;
  11545. ANewReg: TRegister;
  11546. X: ShortInt;
  11547. begin
  11548. Result := False;
  11549. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11550. Exit;
  11551. if ConstCount >= MAX_CMOV_REGISTERS then
  11552. { Arrays are full }
  11553. Exit;
  11554. { Remember that CMOV can't encode 8-bit registers }
  11555. case taicpu(p).opsize of
  11556. S_W:
  11557. RegSize := R_SUBW;
  11558. S_L:
  11559. RegSize := R_SUBD;
  11560. {$ifdef x86_64}
  11561. S_Q:
  11562. RegSize := R_SUBQ;
  11563. {$endif x86_64}
  11564. else
  11565. InternalError(2021100401);
  11566. end;
  11567. { See if the value has already been reserved for another CMOV instruction }
  11568. CurrentVal := taicpu(p).oper[0]^.val;
  11569. for X := 0 to ConstCount - 1 do
  11570. if ConstVals[X] = CurrentVal then
  11571. begin
  11572. ConstRegs[ConstCount] := ConstRegs[X];
  11573. ConstSizes[ConstCount] := RegSize;
  11574. ConstVals[ConstCount] := CurrentVal;
  11575. Inc(ConstCount);
  11576. Inc(Count);
  11577. Result := True;
  11578. Exit;
  11579. end;
  11580. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11581. if ANewReg = NR_NO then
  11582. { No free registers }
  11583. Exit;
  11584. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11585. up vying for the same register }
  11586. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11587. ConstRegs[ConstCount] := ANewReg;
  11588. ConstSizes[ConstCount] := RegSize;
  11589. ConstVals[ConstCount] := CurrentVal;
  11590. Inc(ConstCount);
  11591. Inc(Count);
  11592. Result := True;
  11593. end;
  11594. destructor TCMOVTracking.Done;
  11595. begin
  11596. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11597. end;
  11598. procedure TCMOVTracking.Process(out new_p: tai);
  11599. var
  11600. Count, Writes: LongInt;
  11601. RegMatch: Boolean;
  11602. hp1, hp_new: tai;
  11603. inverted_condition, condition: TAsmCond;
  11604. begin
  11605. if (fState in [tsInvalid, tsProcessed]) then
  11606. InternalError(2023110701);
  11607. { Repurpose RegisterTracking to mark registers that we've defined }
  11608. RegisterTracking[R_INTREGISTER].Clear;
  11609. Count := 0;
  11610. Writes := 0;
  11611. condition := taicpu(fInitialJump).condition;
  11612. inverted_condition := inverse_cond(condition);
  11613. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11614. doesn't get CMOVs in this case }
  11615. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11616. begin
  11617. { Include the jump in the flag tracking }
  11618. if Assigned(fThirdJump) then
  11619. begin
  11620. if (fState = tsDoubleBranchSame) then
  11621. begin
  11622. { Will be an unconditional jump, so track to the instruction before it }
  11623. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11624. InternalError(2023110710);
  11625. end
  11626. else
  11627. hp1 := fThirdJump;
  11628. end
  11629. else
  11630. hp1 := fSecondMovBlockStop;
  11631. end
  11632. else
  11633. begin
  11634. { Include a conditional jump in the flag tracking }
  11635. if Assigned(fSecondJump) then
  11636. begin
  11637. if (fState = tsDetour) then
  11638. begin
  11639. { Will be an unconditional jump, so track to the instruction before it }
  11640. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11641. InternalError(2023110711);
  11642. end
  11643. else
  11644. hp1 := fSecondJump;
  11645. end
  11646. else
  11647. hp1 := fFirstMovBlockStop;
  11648. end;
  11649. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11650. { Process the second set of MOVs first, because if a destination
  11651. register is shared between the first and second MOV sets, it is more
  11652. efficient to turn the first one into a MOV instruction and place it
  11653. before the CMP if possible, but we won't know which registers are
  11654. shared until we've processed at least one list, so we might as well
  11655. make it the second one since that won't be modified again. }
  11656. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11657. begin
  11658. hp1 := fSecondMovBlock;
  11659. repeat
  11660. if not Assigned(hp1) then
  11661. InternalError(2018062902);
  11662. if (hp1.typ = ait_instruction) then
  11663. begin
  11664. { Extra safeguard }
  11665. if (taicpu(hp1).opcode <> A_MOV) then
  11666. InternalError(2018062903);
  11667. { Note: tsDoubleBranchDifferent is essentially identical to
  11668. tsBranching and the 2nd block is best left largely
  11669. untouched, but we need to evaluate which registers the MOVs
  11670. write to in order to track what would be complementary CMOV
  11671. pairs that can be further optimised. [Kit] }
  11672. if fState <> tsDoubleBranchDifferent then
  11673. begin
  11674. if taicpu(hp1).oper[0]^.typ = top_const then
  11675. begin
  11676. RegMatch := False;
  11677. for Count := 0 to ConstCount - 1 do
  11678. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11679. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11680. begin
  11681. RegMatch := True;
  11682. { If it's in RegisterTracking, then this register
  11683. is being used more than once and hence has
  11684. already had its value defined (it gets added to
  11685. UsedRegs through AllocRegBetween below) }
  11686. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11687. begin
  11688. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11689. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11690. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11691. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11692. ConstMovs[Count] := hp_new;
  11693. end
  11694. else
  11695. { We just need an instruction between hp_prev and hp1
  11696. where we know the register is marked as in use }
  11697. hp_new := fSecondMovBlock;
  11698. { Keep track of largest write for this register so it can be optimised later }
  11699. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11700. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11701. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11702. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11703. Break;
  11704. end;
  11705. if not RegMatch then
  11706. InternalError(2021100411);
  11707. end;
  11708. taicpu(hp1).opcode := A_CMOVcc;
  11709. taicpu(hp1).condition := condition;
  11710. end;
  11711. { Store these writes to search for duplicates later on }
  11712. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11713. Inc(Writes);
  11714. end;
  11715. fOptimizer.GetNextInstruction(hp1, hp1);
  11716. until (hp1 = fSecondMovBlockStop);
  11717. end;
  11718. { Now do the first set of MOVs }
  11719. hp1 := fFirstMovBlock;
  11720. repeat
  11721. if not Assigned(hp1) then
  11722. InternalError(2018062904);
  11723. if (hp1.typ = ait_instruction) then
  11724. begin
  11725. RegMatch := False;
  11726. { Extra safeguard }
  11727. if (taicpu(hp1).opcode <> A_MOV) then
  11728. InternalError(2018062905);
  11729. { Search through the RegWrites list to see if there are any
  11730. opposing CMOV pairs that write to the same register }
  11731. for Count := 0 to Writes - 1 do
  11732. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11733. begin
  11734. { We have a match. Keep this as a MOV }
  11735. { Move ahead in preparation }
  11736. fOptimizer.GetNextInstruction(hp1, hp1);
  11737. RegMatch := True;
  11738. Break;
  11739. end;
  11740. if RegMatch then
  11741. Continue;
  11742. if taicpu(hp1).oper[0]^.typ = top_const then
  11743. begin
  11744. for Count := 0 to ConstCount - 1 do
  11745. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11746. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11747. begin
  11748. RegMatch := True;
  11749. { If it's in RegisterTracking, then this register is
  11750. being used more than once and hence has already had
  11751. its value defined (it gets added to UsedRegs through
  11752. AllocRegBetween below) }
  11753. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11754. begin
  11755. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11756. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11757. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11758. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11759. ConstMovs[Count] := hp_new;
  11760. end
  11761. else
  11762. { We just need an instruction between hp_prev and hp1
  11763. where we know the register is marked as in use }
  11764. hp_new := fFirstMovBlock;
  11765. { Keep track of largest write for this register so it can be optimised later }
  11766. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11767. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11768. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11769. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11770. Break;
  11771. end;
  11772. if not RegMatch then
  11773. InternalError(2021100412);
  11774. end;
  11775. taicpu(hp1).opcode := A_CMOVcc;
  11776. taicpu(hp1).condition := inverted_condition;
  11777. if (fState = tsDoubleBranchDifferent) then
  11778. begin
  11779. { Store these writes to search for duplicates later on }
  11780. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11781. Inc(Writes);
  11782. end;
  11783. end;
  11784. fOptimizer.GetNextInstruction(hp1, hp1);
  11785. until (hp1 = fFirstMovBlockStop);
  11786. { Update initialisation MOVs to the smallest possible size }
  11787. for Count := 0 to ConstCount - 1 do
  11788. if Assigned(ConstMovs[Count]) then
  11789. begin
  11790. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  11791. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  11792. end;
  11793. case fState of
  11794. tsSimple:
  11795. begin
  11796. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  11797. { No branch to delete }
  11798. end;
  11799. tsDetour:
  11800. begin
  11801. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  11802. { Preserve jump }
  11803. end;
  11804. tsBranching, tsDoubleBranchDifferent:
  11805. begin
  11806. if (fState = tsBranching) then
  11807. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  11808. else
  11809. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  11810. taicpu(fSecondJump).opcode := A_JCC;
  11811. taicpu(fSecondJump).condition := inverted_condition;
  11812. end;
  11813. tsDouble, tsDoubleBranchSame:
  11814. begin
  11815. if (fState = tsDouble) then
  11816. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  11817. else
  11818. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  11819. { Delete second jump }
  11820. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11821. fOptimizer.RemoveInstruction(fSecondJump);
  11822. end;
  11823. tsDoubleSecondBranching:
  11824. begin
  11825. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  11826. { Delete second jump, preserve third jump as conditional }
  11827. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11828. fOptimizer.RemoveInstruction(fSecondJump);
  11829. taicpu(fThirdJump).opcode := A_JCC;
  11830. taicpu(fThirdJump).condition := condition;
  11831. end;
  11832. else
  11833. InternalError(2023110720);
  11834. end;
  11835. { Now we can safely decrement the reference count }
  11836. tasmlabel(fLabel).decrefs;
  11837. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  11838. { Remove the original jump }
  11839. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  11840. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  11841. fState := tsProcessed;
  11842. end;
  11843. {$endif 8086}
  11844. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  11845. var
  11846. hp1,hp2: tai;
  11847. carryadd_opcode : TAsmOp;
  11848. symbol: TAsmSymbol;
  11849. increg, tmpreg: TRegister;
  11850. {$ifndef i8086}
  11851. CMOVTracking: PCMOVTracking;
  11852. hp3,hp4,hp5: tai;
  11853. {$endif i8086}
  11854. begin
  11855. result:=false;
  11856. if GetNextInstruction(p,hp1) then
  11857. begin
  11858. if (hp1.typ=ait_label) then
  11859. begin
  11860. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  11861. Exit;
  11862. end
  11863. else if (hp1.typ<>ait_instruction) then
  11864. Exit;
  11865. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11866. if (
  11867. (
  11868. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  11869. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  11870. (Taicpu(hp1).oper[0]^.val=1)
  11871. ) or
  11872. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  11873. ) and
  11874. GetNextInstruction(hp1,hp2) and
  11875. (hp2.typ = ait_label) and
  11876. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  11877. { jb @@1 cmc
  11878. inc/dec operand --> adc/sbb operand,0
  11879. @@1:
  11880. ... and ...
  11881. jnb @@1
  11882. inc/dec operand --> adc/sbb operand,0
  11883. @@1: }
  11884. begin
  11885. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  11886. begin
  11887. case taicpu(hp1).opcode of
  11888. A_INC,
  11889. A_ADD:
  11890. carryadd_opcode:=A_ADC;
  11891. A_DEC,
  11892. A_SUB:
  11893. carryadd_opcode:=A_SBB;
  11894. else
  11895. InternalError(2021011001);
  11896. end;
  11897. Taicpu(p).clearop(0);
  11898. Taicpu(p).ops:=0;
  11899. Taicpu(p).is_jmp:=false;
  11900. Taicpu(p).opcode:=A_CMC;
  11901. Taicpu(p).condition:=C_NONE;
  11902. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  11903. Taicpu(hp1).ops:=2;
  11904. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11905. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11906. else
  11907. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11908. Taicpu(hp1).loadconst(0,0);
  11909. Taicpu(hp1).opcode:=carryadd_opcode;
  11910. result:=true;
  11911. exit;
  11912. end
  11913. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  11914. begin
  11915. case taicpu(hp1).opcode of
  11916. A_INC,
  11917. A_ADD:
  11918. carryadd_opcode:=A_ADC;
  11919. A_DEC,
  11920. A_SUB:
  11921. carryadd_opcode:=A_SBB;
  11922. else
  11923. InternalError(2021011002);
  11924. end;
  11925. Taicpu(hp1).ops:=2;
  11926. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  11927. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11928. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11929. else
  11930. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11931. Taicpu(hp1).loadconst(0,0);
  11932. Taicpu(hp1).opcode:=carryadd_opcode;
  11933. RemoveCurrentP(p, hp1);
  11934. result:=true;
  11935. exit;
  11936. end
  11937. {
  11938. jcc @@1 setcc tmpreg
  11939. inc/dec/add/sub operand -> (movzx tmpreg)
  11940. @@1: add/sub tmpreg,operand
  11941. While this increases code size slightly, it makes the code much faster if the
  11942. jump is unpredictable
  11943. }
  11944. else if not(cs_opt_size in current_settings.optimizerswitches) then
  11945. begin
  11946. { search for an available register which is volatile }
  11947. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  11948. if increg <> NR_NO then
  11949. begin
  11950. { We don't need to check if tmpreg is in hp1 or not, because
  11951. it will be marked as in use at p (if not, this is
  11952. indictive of a compiler bug). }
  11953. TAsmLabel(symbol).decrefs;
  11954. Taicpu(p).clearop(0);
  11955. Taicpu(p).ops:=1;
  11956. Taicpu(p).is_jmp:=false;
  11957. Taicpu(p).opcode:=A_SETcc;
  11958. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  11959. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  11960. Taicpu(p).loadreg(0,increg);
  11961. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  11962. begin
  11963. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  11964. R_SUBW:
  11965. begin
  11966. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  11967. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  11968. end;
  11969. R_SUBD:
  11970. begin
  11971. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  11972. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  11973. end;
  11974. {$ifdef x86_64}
  11975. R_SUBQ:
  11976. begin
  11977. { MOVZX doesn't have a 64-bit variant, because
  11978. the 32-bit version implicitly zeroes the
  11979. upper 32-bits of the destination register }
  11980. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  11981. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  11982. setsubreg(tmpreg, R_SUBQ);
  11983. end;
  11984. {$endif x86_64}
  11985. else
  11986. Internalerror(2020030601);
  11987. end;
  11988. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  11989. asml.InsertAfter(hp2,p);
  11990. end
  11991. else
  11992. tmpreg := increg;
  11993. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  11994. begin
  11995. Taicpu(hp1).ops:=2;
  11996. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  11997. end;
  11998. Taicpu(hp1).loadreg(0,tmpreg);
  11999. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12000. Result := True;
  12001. { p is no longer a Jcc instruction, so exit }
  12002. Exit;
  12003. end;
  12004. end;
  12005. end;
  12006. { Detect the following:
  12007. jmp<cond> @Lbl1
  12008. jmp @Lbl2
  12009. ...
  12010. @Lbl1:
  12011. ret
  12012. Change to:
  12013. jmp<inv_cond> @Lbl2
  12014. ret
  12015. }
  12016. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12017. begin
  12018. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12019. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12020. MatchInstruction(hp2,A_RET,[S_NO]) then
  12021. begin
  12022. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12023. { Change label address to that of the unconditional jump }
  12024. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12025. TAsmLabel(symbol).DecRefs;
  12026. taicpu(hp1).opcode := A_RET;
  12027. taicpu(hp1).is_jmp := false;
  12028. taicpu(hp1).ops := taicpu(hp2).ops;
  12029. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12030. case taicpu(hp2).ops of
  12031. 0:
  12032. taicpu(hp1).clearop(0);
  12033. 1:
  12034. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12035. else
  12036. internalerror(2016041302);
  12037. end;
  12038. end;
  12039. {$ifndef i8086}
  12040. end
  12041. {
  12042. convert
  12043. j<c> .L1
  12044. mov 1,reg
  12045. jmp .L2
  12046. .L1
  12047. mov 0,reg
  12048. .L2
  12049. into
  12050. mov 0,reg
  12051. set<not(c)> reg
  12052. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12053. would destroy the flag contents
  12054. }
  12055. else if MatchInstruction(hp1,A_MOV,[]) and
  12056. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12057. {$ifdef i386}
  12058. (
  12059. { Under i386, ESI, EDI, EBP and ESP
  12060. don't have an 8-bit representation }
  12061. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12062. ) and
  12063. {$endif i386}
  12064. (taicpu(hp1).oper[0]^.val=1) and
  12065. GetNextInstruction(hp1,hp2) and
  12066. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12067. GetNextInstruction(hp2,hp3) and
  12068. (hp3.typ=ait_label) and
  12069. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12070. (tai_label(hp3).labsym.getrefs=1) and
  12071. GetNextInstruction(hp3,hp4) and
  12072. MatchInstruction(hp4,A_MOV,[]) and
  12073. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12074. (taicpu(hp4).oper[0]^.val=0) and
  12075. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12076. GetNextInstruction(hp4,hp5) and
  12077. (hp5.typ=ait_label) and
  12078. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12079. (tai_label(hp5).labsym.getrefs=1) then
  12080. begin
  12081. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12082. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12083. { remove last label }
  12084. RemoveInstruction(hp5);
  12085. { remove second label }
  12086. RemoveInstruction(hp3);
  12087. { remove jmp }
  12088. RemoveInstruction(hp2);
  12089. if taicpu(hp1).opsize=S_B then
  12090. RemoveInstruction(hp1)
  12091. else
  12092. taicpu(hp1).loadconst(0,0);
  12093. taicpu(hp4).opcode:=A_SETcc;
  12094. taicpu(hp4).opsize:=S_B;
  12095. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12096. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12097. taicpu(hp4).opercnt:=1;
  12098. taicpu(hp4).ops:=1;
  12099. taicpu(hp4).freeop(1);
  12100. RemoveCurrentP(p);
  12101. Result:=true;
  12102. exit;
  12103. end
  12104. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12105. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12106. begin
  12107. { check for
  12108. jCC xxx
  12109. <several movs>
  12110. xxx:
  12111. Also spot:
  12112. Jcc xxx
  12113. <several movs>
  12114. jmp xxx
  12115. Change to:
  12116. <several cmovs with inverted condition>
  12117. jmp xxx (only for the 2nd case)
  12118. }
  12119. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12120. if CMOVTracking^.State <> tsInvalid then
  12121. begin
  12122. CMovTracking^.Process(p);
  12123. Result := True;
  12124. end;
  12125. CMOVTracking^.Done;
  12126. {$endif i8086}
  12127. end;
  12128. end;
  12129. end;
  12130. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12131. var
  12132. hp1,hp2,hp3: tai;
  12133. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12134. NewSize: TOpSize;
  12135. NewRegSize: TSubRegister;
  12136. Limit: TCgInt;
  12137. SwapOper: POper;
  12138. begin
  12139. result:=false;
  12140. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12141. GetNextInstruction(p,hp1) and
  12142. (hp1.typ = ait_instruction);
  12143. if reg_and_hp1_is_instr and
  12144. (
  12145. (taicpu(hp1).opcode <> A_LEA) or
  12146. { If the LEA instruction can be converted into an arithmetic instruction,
  12147. it may be possible to then fold it. }
  12148. (
  12149. { If the flags register is in use, don't change the instruction
  12150. to an ADD otherwise this will scramble the flags. [Kit] }
  12151. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12152. ConvertLEA(taicpu(hp1))
  12153. )
  12154. ) and
  12155. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12156. GetNextInstruction(hp1,hp2) and
  12157. MatchInstruction(hp2,A_MOV,[]) and
  12158. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12159. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12160. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12161. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12162. {$ifdef i386}
  12163. { not all registers have byte size sub registers on i386 }
  12164. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12165. {$endif i386}
  12166. (((taicpu(hp1).ops=2) and
  12167. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12168. ((taicpu(hp1).ops=1) and
  12169. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12170. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12171. begin
  12172. { change movsX/movzX reg/ref, reg2
  12173. add/sub/or/... reg3/$const, reg2
  12174. mov reg2 reg/ref
  12175. to add/sub/or/... reg3/$const, reg/ref }
  12176. { by example:
  12177. movswl %si,%eax movswl %si,%eax p
  12178. decl %eax addl %edx,%eax hp1
  12179. movw %ax,%si movw %ax,%si hp2
  12180. ->
  12181. movswl %si,%eax movswl %si,%eax p
  12182. decw %eax addw %edx,%eax hp1
  12183. movw %ax,%si movw %ax,%si hp2
  12184. }
  12185. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12186. {
  12187. ->
  12188. movswl %si,%eax movswl %si,%eax p
  12189. decw %si addw %dx,%si hp1
  12190. movw %ax,%si movw %ax,%si hp2
  12191. }
  12192. case taicpu(hp1).ops of
  12193. 1:
  12194. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12195. 2:
  12196. begin
  12197. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12198. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12199. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12200. end;
  12201. else
  12202. internalerror(2008042702);
  12203. end;
  12204. {
  12205. ->
  12206. decw %si addw %dx,%si p
  12207. }
  12208. DebugMsg(SPeepholeOptimization + 'var3',p);
  12209. RemoveCurrentP(p, hp1);
  12210. RemoveInstruction(hp2);
  12211. Result := True;
  12212. Exit;
  12213. end;
  12214. if reg_and_hp1_is_instr and
  12215. (taicpu(hp1).opcode = A_MOV) and
  12216. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12217. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12218. {$ifdef x86_64}
  12219. { check for implicit extension to 64 bit }
  12220. or
  12221. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12222. (taicpu(hp1).opsize=S_Q) and
  12223. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12224. )
  12225. {$endif x86_64}
  12226. )
  12227. then
  12228. begin
  12229. { change
  12230. movx %reg1,%reg2
  12231. mov %reg2,%reg3
  12232. dealloc %reg2
  12233. into
  12234. movx %reg,%reg3
  12235. }
  12236. TransferUsedRegs(TmpUsedRegs);
  12237. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12238. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12239. begin
  12240. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12241. {$ifdef x86_64}
  12242. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12243. (taicpu(hp1).opsize=S_Q) then
  12244. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12245. else
  12246. {$endif x86_64}
  12247. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12248. RemoveInstruction(hp1);
  12249. Result := True;
  12250. Exit;
  12251. end;
  12252. end;
  12253. if reg_and_hp1_is_instr and
  12254. ((taicpu(hp1).opcode=A_MOV) or
  12255. (taicpu(hp1).opcode=A_ADD) or
  12256. (taicpu(hp1).opcode=A_SUB) or
  12257. (taicpu(hp1).opcode=A_CMP) or
  12258. (taicpu(hp1).opcode=A_OR) or
  12259. (taicpu(hp1).opcode=A_XOR) or
  12260. (taicpu(hp1).opcode=A_AND)
  12261. ) and
  12262. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12263. begin
  12264. AndTest := (taicpu(hp1).opcode=A_AND) and
  12265. GetNextInstruction(hp1, hp2) and
  12266. (hp2.typ = ait_instruction) and
  12267. (
  12268. (
  12269. (taicpu(hp2).opcode=A_TEST) and
  12270. (
  12271. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12272. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12273. (
  12274. { If the AND and TEST instructions share a constant, this is also valid }
  12275. (taicpu(hp1).oper[0]^.typ = top_const) and
  12276. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12277. )
  12278. ) and
  12279. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12280. ) or
  12281. (
  12282. (taicpu(hp2).opcode=A_CMP) and
  12283. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12284. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12285. )
  12286. );
  12287. { change
  12288. movx (oper),%reg2
  12289. and $x,%reg2
  12290. test %reg2,%reg2
  12291. dealloc %reg2
  12292. into
  12293. op %reg1,%reg3
  12294. if the second op accesses only the bits stored in reg1
  12295. }
  12296. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12297. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12298. (taicpu(hp1).oper[0]^.typ = top_const) and
  12299. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12300. AndTest then
  12301. begin
  12302. { Check if the AND constant is in range }
  12303. case taicpu(p).opsize of
  12304. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12305. begin
  12306. NewSize := S_B;
  12307. Limit := $FF;
  12308. end;
  12309. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12310. begin
  12311. NewSize := S_W;
  12312. Limit := $FFFF;
  12313. end;
  12314. {$ifdef x86_64}
  12315. S_LQ:
  12316. begin
  12317. NewSize := S_L;
  12318. Limit := $FFFFFFFF;
  12319. end;
  12320. {$endif x86_64}
  12321. else
  12322. InternalError(2021120303);
  12323. end;
  12324. if (
  12325. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12326. { Check for negative operands }
  12327. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12328. ) and
  12329. GetNextInstruction(hp2,hp3) and
  12330. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12331. (taicpu(hp3).condition in [C_E,C_NE]) then
  12332. begin
  12333. TransferUsedRegs(TmpUsedRegs);
  12334. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12335. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12336. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12337. begin
  12338. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12339. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12340. taicpu(hp1).opcode := A_TEST;
  12341. taicpu(hp1).opsize := NewSize;
  12342. RemoveInstruction(hp2);
  12343. RemoveCurrentP(p, hp1);
  12344. Result:=true;
  12345. exit;
  12346. end;
  12347. end;
  12348. end;
  12349. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12350. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12351. (taicpu(hp1).opsize=S_B)) or
  12352. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12353. (taicpu(hp1).opsize=S_W))
  12354. {$ifdef x86_64}
  12355. or ((taicpu(p).opsize=S_LQ) and
  12356. (taicpu(hp1).opsize=S_L))
  12357. {$endif x86_64}
  12358. ) and
  12359. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12360. begin
  12361. { change
  12362. movx %reg1,%reg2
  12363. op %reg2,%reg3
  12364. dealloc %reg2
  12365. into
  12366. op %reg1,%reg3
  12367. if the second op accesses only the bits stored in reg1
  12368. }
  12369. TransferUsedRegs(TmpUsedRegs);
  12370. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12371. if AndTest then
  12372. begin
  12373. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12374. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12375. end
  12376. else
  12377. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12378. if not RegUsed then
  12379. begin
  12380. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12381. if taicpu(p).oper[0]^.typ=top_reg then
  12382. begin
  12383. case taicpu(hp1).opsize of
  12384. S_B:
  12385. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12386. S_W:
  12387. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12388. S_L:
  12389. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12390. else
  12391. Internalerror(2020102301);
  12392. end;
  12393. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12394. end
  12395. else
  12396. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12397. RemoveCurrentP(p);
  12398. if AndTest then
  12399. RemoveInstruction(hp2);
  12400. result:=true;
  12401. exit;
  12402. end;
  12403. end
  12404. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12405. (
  12406. { Bitwise operations only }
  12407. (taicpu(hp1).opcode=A_AND) or
  12408. (taicpu(hp1).opcode=A_TEST) or
  12409. (
  12410. (taicpu(hp1).oper[0]^.typ = top_const) and
  12411. (
  12412. (taicpu(hp1).opcode=A_OR) or
  12413. (taicpu(hp1).opcode=A_XOR)
  12414. )
  12415. )
  12416. ) and
  12417. (
  12418. (taicpu(hp1).oper[0]^.typ = top_const) or
  12419. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12420. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12421. ) then
  12422. begin
  12423. { change
  12424. movx %reg2,%reg2
  12425. op const,%reg2
  12426. into
  12427. op const,%reg2 (smaller version)
  12428. movx %reg2,%reg2
  12429. also change
  12430. movx %reg1,%reg2
  12431. and/test (oper),%reg2
  12432. dealloc %reg2
  12433. into
  12434. and/test (oper),%reg1
  12435. }
  12436. case taicpu(p).opsize of
  12437. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12438. begin
  12439. NewSize := S_B;
  12440. NewRegSize := R_SUBL;
  12441. Limit := $FF;
  12442. end;
  12443. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12444. begin
  12445. NewSize := S_W;
  12446. NewRegSize := R_SUBW;
  12447. Limit := $FFFF;
  12448. end;
  12449. {$ifdef x86_64}
  12450. S_LQ:
  12451. begin
  12452. NewSize := S_L;
  12453. NewRegSize := R_SUBD;
  12454. Limit := $FFFFFFFF;
  12455. end;
  12456. {$endif x86_64}
  12457. else
  12458. Internalerror(2021120302);
  12459. end;
  12460. TransferUsedRegs(TmpUsedRegs);
  12461. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12462. if AndTest then
  12463. begin
  12464. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12465. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12466. end
  12467. else
  12468. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12469. if
  12470. (
  12471. (taicpu(p).opcode = A_MOVZX) and
  12472. (
  12473. (taicpu(hp1).opcode=A_AND) or
  12474. (taicpu(hp1).opcode=A_TEST)
  12475. ) and
  12476. not (
  12477. { If both are references, then the final instruction will have
  12478. both operands as references, which is not allowed }
  12479. (taicpu(p).oper[0]^.typ = top_ref) and
  12480. (taicpu(hp1).oper[0]^.typ = top_ref)
  12481. ) and
  12482. not RegUsed
  12483. ) or
  12484. (
  12485. (
  12486. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12487. not RegUsed
  12488. ) and
  12489. (taicpu(p).oper[0]^.typ = top_reg) and
  12490. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12491. (taicpu(hp1).oper[0]^.typ = top_const) and
  12492. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12493. ) then
  12494. begin
  12495. {$if defined(i386) or defined(i8086)}
  12496. { If the target size is 8-bit, make sure we can actually encode it }
  12497. 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
  12498. Exit;
  12499. {$endif i386 or i8086}
  12500. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12501. taicpu(hp1).opsize := NewSize;
  12502. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12503. if AndTest then
  12504. begin
  12505. RemoveInstruction(hp2);
  12506. if not RegUsed then
  12507. begin
  12508. taicpu(hp1).opcode := A_TEST;
  12509. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12510. begin
  12511. { Make sure the reference is the second operand }
  12512. SwapOper := taicpu(hp1).oper[0];
  12513. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12514. taicpu(hp1).oper[1] := SwapOper;
  12515. end;
  12516. end;
  12517. end;
  12518. case taicpu(hp1).oper[0]^.typ of
  12519. top_reg:
  12520. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12521. top_const:
  12522. { For the AND/TEST case }
  12523. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12524. else
  12525. ;
  12526. end;
  12527. if RegUsed then
  12528. begin
  12529. AsmL.Remove(p);
  12530. AsmL.InsertAfter(p, hp1);
  12531. p := hp1;
  12532. end
  12533. else
  12534. RemoveCurrentP(p, hp1);
  12535. result:=true;
  12536. exit;
  12537. end;
  12538. end;
  12539. end;
  12540. if reg_and_hp1_is_instr and
  12541. (taicpu(p).oper[0]^.typ = top_reg) and
  12542. (
  12543. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12544. ) and
  12545. (taicpu(hp1).oper[0]^.typ = top_const) and
  12546. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12547. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12548. { Minimum shift value allowed is the bit difference between the sizes }
  12549. (taicpu(hp1).oper[0]^.val >=
  12550. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12551. 8 * (
  12552. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12553. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12554. )
  12555. ) then
  12556. begin
  12557. { For:
  12558. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12559. shl/sal ##, %reg1
  12560. Remove the movsx/movzx instruction if the shift overwrites the
  12561. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12562. }
  12563. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12564. RemoveCurrentP(p, hp1);
  12565. Result := True;
  12566. Exit;
  12567. end
  12568. else if reg_and_hp1_is_instr and
  12569. (taicpu(p).oper[0]^.typ = top_reg) and
  12570. (
  12571. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12572. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12573. ) and
  12574. (taicpu(hp1).oper[0]^.typ = top_const) and
  12575. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12576. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12577. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12578. (taicpu(hp1).oper[0]^.val <
  12579. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12580. 8 * (
  12581. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12582. )
  12583. ) then
  12584. begin
  12585. { For:
  12586. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12587. sar ##, %reg1 shr ##, %reg1
  12588. Move the shift to before the movx instruction if the shift value
  12589. is not too large.
  12590. }
  12591. asml.Remove(hp1);
  12592. asml.InsertBefore(hp1, p);
  12593. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12594. case taicpu(p).opsize of
  12595. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12596. taicpu(hp1).opsize := S_B;
  12597. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12598. taicpu(hp1).opsize := S_W;
  12599. {$ifdef x86_64}
  12600. S_LQ:
  12601. taicpu(hp1).opsize := S_L;
  12602. {$endif}
  12603. else
  12604. InternalError(2020112401);
  12605. end;
  12606. if (taicpu(hp1).opcode = A_SHR) then
  12607. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12608. else
  12609. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12610. Result := True;
  12611. end;
  12612. if reg_and_hp1_is_instr and
  12613. (taicpu(p).oper[0]^.typ = top_reg) and
  12614. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12615. (
  12616. (taicpu(hp1).opcode = taicpu(p).opcode)
  12617. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12618. {$ifdef x86_64}
  12619. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12620. {$endif x86_64}
  12621. ) then
  12622. begin
  12623. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12624. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12625. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12626. begin
  12627. {
  12628. For example:
  12629. movzbw %al,%ax
  12630. movzwl %ax,%eax
  12631. Compress into:
  12632. movzbl %al,%eax
  12633. }
  12634. RegUsed := False;
  12635. case taicpu(p).opsize of
  12636. S_BW:
  12637. case taicpu(hp1).opsize of
  12638. S_WL:
  12639. begin
  12640. taicpu(p).opsize := S_BL;
  12641. RegUsed := True;
  12642. end;
  12643. {$ifdef x86_64}
  12644. S_WQ:
  12645. begin
  12646. if taicpu(p).opcode = A_MOVZX then
  12647. begin
  12648. taicpu(p).opsize := S_BL;
  12649. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12650. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12651. end
  12652. else
  12653. taicpu(p).opsize := S_BQ;
  12654. RegUsed := True;
  12655. end;
  12656. {$endif x86_64}
  12657. else
  12658. ;
  12659. end;
  12660. {$ifdef x86_64}
  12661. S_BL:
  12662. case taicpu(hp1).opsize of
  12663. S_LQ:
  12664. begin
  12665. if taicpu(p).opcode = A_MOVZX then
  12666. begin
  12667. taicpu(p).opsize := S_BL;
  12668. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12669. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12670. end
  12671. else
  12672. taicpu(p).opsize := S_BQ;
  12673. RegUsed := True;
  12674. end;
  12675. else
  12676. ;
  12677. end;
  12678. S_WL:
  12679. case taicpu(hp1).opsize of
  12680. S_LQ:
  12681. begin
  12682. if taicpu(p).opcode = A_MOVZX then
  12683. begin
  12684. taicpu(p).opsize := S_WL;
  12685. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12686. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12687. end
  12688. else
  12689. taicpu(p).opsize := S_WQ;
  12690. RegUsed := True;
  12691. end;
  12692. else
  12693. ;
  12694. end;
  12695. {$endif x86_64}
  12696. else
  12697. ;
  12698. end;
  12699. if RegUsed then
  12700. begin
  12701. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12702. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12703. RemoveInstruction(hp1);
  12704. Result := True;
  12705. Exit;
  12706. end;
  12707. end;
  12708. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12709. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12710. GetNextInstruction(hp1, hp2) and
  12711. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12712. (
  12713. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12714. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12715. {$ifdef x86_64}
  12716. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12717. {$endif x86_64}
  12718. ) and
  12719. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12720. (
  12721. (
  12722. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12723. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12724. ) or
  12725. (
  12726. { Only allow the operands in reverse order for TEST instructions }
  12727. (taicpu(hp2).opcode = A_TEST) and
  12728. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12729. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12730. )
  12731. ) then
  12732. begin
  12733. {
  12734. For example:
  12735. movzbl %al,%eax
  12736. movzbl (ref),%edx
  12737. andl %edx,%eax
  12738. (%edx deallocated)
  12739. Change to:
  12740. andb (ref),%al
  12741. movzbl %al,%eax
  12742. Rules are:
  12743. - First two instructions have the same opcode and opsize
  12744. - First instruction's operands are the same super-register
  12745. - Second instruction operates on a different register
  12746. - Third instruction is AND, OR, XOR or TEST
  12747. - Third instruction's operands are the destination registers of the first two instructions
  12748. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12749. - Second instruction's destination register is deallocated afterwards
  12750. }
  12751. TransferUsedRegs(TmpUsedRegs);
  12752. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12753. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12754. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12755. begin
  12756. case taicpu(p).opsize of
  12757. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12758. NewSize := S_B;
  12759. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12760. NewSize := S_W;
  12761. {$ifdef x86_64}
  12762. S_LQ:
  12763. NewSize := S_L;
  12764. {$endif x86_64}
  12765. else
  12766. InternalError(2021120301);
  12767. end;
  12768. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12769. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12770. taicpu(hp2).opsize := NewSize;
  12771. RemoveInstruction(hp1);
  12772. { With TEST, it's best to keep the MOVX instruction at the top }
  12773. if (taicpu(hp2).opcode <> A_TEST) then
  12774. begin
  12775. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12776. asml.Remove(p);
  12777. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12778. asml.InsertAfter(p, hp2);
  12779. p := hp2;
  12780. end
  12781. else
  12782. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12783. Result := True;
  12784. Exit;
  12785. end;
  12786. end;
  12787. end;
  12788. if taicpu(p).opcode=A_MOVZX then
  12789. begin
  12790. { removes superfluous And's after movzx's }
  12791. if reg_and_hp1_is_instr and
  12792. (taicpu(hp1).opcode = A_AND) and
  12793. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12794. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12795. {$ifdef x86_64}
  12796. { check for implicit extension to 64 bit }
  12797. or
  12798. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12799. (taicpu(hp1).opsize=S_Q) and
  12800. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12801. )
  12802. {$endif x86_64}
  12803. )
  12804. then
  12805. begin
  12806. case taicpu(p).opsize Of
  12807. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12808. if (taicpu(hp1).oper[0]^.val = $ff) then
  12809. begin
  12810. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12811. RemoveInstruction(hp1);
  12812. Result:=true;
  12813. exit;
  12814. end;
  12815. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12816. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12817. begin
  12818. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12819. RemoveInstruction(hp1);
  12820. Result:=true;
  12821. exit;
  12822. end;
  12823. {$ifdef x86_64}
  12824. S_LQ:
  12825. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12826. begin
  12827. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12828. RemoveInstruction(hp1);
  12829. Result:=true;
  12830. exit;
  12831. end;
  12832. {$endif x86_64}
  12833. else
  12834. ;
  12835. end;
  12836. { we cannot get rid of the and, but can we get rid of the movz ?}
  12837. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12838. begin
  12839. case taicpu(p).opsize Of
  12840. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12841. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12842. begin
  12843. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12844. RemoveCurrentP(p,hp1);
  12845. Result:=true;
  12846. exit;
  12847. end;
  12848. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12849. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12850. begin
  12851. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12852. RemoveCurrentP(p,hp1);
  12853. Result:=true;
  12854. exit;
  12855. end;
  12856. {$ifdef x86_64}
  12857. S_LQ:
  12858. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12859. begin
  12860. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12861. RemoveCurrentP(p,hp1);
  12862. Result:=true;
  12863. exit;
  12864. end;
  12865. {$endif x86_64}
  12866. else
  12867. ;
  12868. end;
  12869. end;
  12870. end;
  12871. { changes some movzx constructs to faster synonyms (all examples
  12872. are given with eax/ax, but are also valid for other registers)}
  12873. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12874. begin
  12875. case taicpu(p).opsize of
  12876. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12877. (the machine code is equivalent to movzbl %al,%eax), but the
  12878. code generator still generates that assembler instruction and
  12879. it is silently converted. This should probably be checked.
  12880. [Kit] }
  12881. S_BW:
  12882. begin
  12883. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12884. (
  12885. not IsMOVZXAcceptable
  12886. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12887. or (
  12888. (cs_opt_size in current_settings.optimizerswitches) and
  12889. (taicpu(p).oper[1]^.reg = NR_AX)
  12890. )
  12891. ) then
  12892. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12893. begin
  12894. DebugMsg(SPeepholeOptimization + 'var7',p);
  12895. taicpu(p).opcode := A_AND;
  12896. taicpu(p).changeopsize(S_W);
  12897. taicpu(p).loadConst(0,$ff);
  12898. Result := True;
  12899. end
  12900. else if not IsMOVZXAcceptable and
  12901. GetNextInstruction(p, hp1) and
  12902. (tai(hp1).typ = ait_instruction) and
  12903. (taicpu(hp1).opcode = A_AND) and
  12904. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12905. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12906. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12907. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12908. begin
  12909. DebugMsg(SPeepholeOptimization + 'var8',p);
  12910. taicpu(p).opcode := A_MOV;
  12911. taicpu(p).changeopsize(S_W);
  12912. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12913. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12914. Result := True;
  12915. end;
  12916. end;
  12917. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12918. S_BL:
  12919. if not IsMOVZXAcceptable then
  12920. begin
  12921. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12922. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12923. begin
  12924. DebugMsg(SPeepholeOptimization + 'var9',p);
  12925. taicpu(p).opcode := A_AND;
  12926. taicpu(p).changeopsize(S_L);
  12927. taicpu(p).loadConst(0,$ff);
  12928. Result := True;
  12929. end
  12930. else if GetNextInstruction(p, hp1) and
  12931. (tai(hp1).typ = ait_instruction) and
  12932. (taicpu(hp1).opcode = A_AND) and
  12933. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12934. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12935. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12936. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12937. begin
  12938. DebugMsg(SPeepholeOptimization + 'var10',p);
  12939. taicpu(p).opcode := A_MOV;
  12940. taicpu(p).changeopsize(S_L);
  12941. { do not use R_SUBWHOLE
  12942. as movl %rdx,%eax
  12943. is invalid in assembler PM }
  12944. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12945. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12946. Result := True;
  12947. end;
  12948. end;
  12949. {$endif i8086}
  12950. S_WL:
  12951. if not IsMOVZXAcceptable then
  12952. begin
  12953. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12954. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12955. begin
  12956. DebugMsg(SPeepholeOptimization + 'var11',p);
  12957. taicpu(p).opcode := A_AND;
  12958. taicpu(p).changeopsize(S_L);
  12959. taicpu(p).loadConst(0,$ffff);
  12960. Result := True;
  12961. end
  12962. else if GetNextInstruction(p, hp1) and
  12963. (tai(hp1).typ = ait_instruction) and
  12964. (taicpu(hp1).opcode = A_AND) and
  12965. (taicpu(hp1).oper[0]^.typ = top_const) and
  12966. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12967. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12968. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12969. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12970. begin
  12971. DebugMsg(SPeepholeOptimization + 'var12',p);
  12972. taicpu(p).opcode := A_MOV;
  12973. taicpu(p).changeopsize(S_L);
  12974. { do not use R_SUBWHOLE
  12975. as movl %rdx,%eax
  12976. is invalid in assembler PM }
  12977. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12978. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12979. Result := True;
  12980. end;
  12981. end;
  12982. else
  12983. InternalError(2017050705);
  12984. end;
  12985. end
  12986. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12987. begin
  12988. if GetNextInstruction(p, hp1) and
  12989. (tai(hp1).typ = ait_instruction) and
  12990. (taicpu(hp1).opcode = A_AND) and
  12991. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12992. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12993. begin
  12994. //taicpu(p).opcode := A_MOV;
  12995. case taicpu(p).opsize Of
  12996. S_BL:
  12997. begin
  12998. DebugMsg(SPeepholeOptimization + 'var13',p);
  12999. taicpu(hp1).changeopsize(S_L);
  13000. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13001. end;
  13002. S_WL:
  13003. begin
  13004. DebugMsg(SPeepholeOptimization + 'var14',p);
  13005. taicpu(hp1).changeopsize(S_L);
  13006. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13007. end;
  13008. S_BW:
  13009. begin
  13010. DebugMsg(SPeepholeOptimization + 'var15',p);
  13011. taicpu(hp1).changeopsize(S_W);
  13012. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13013. end;
  13014. else
  13015. Internalerror(2017050704)
  13016. end;
  13017. Result := True;
  13018. end;
  13019. end;
  13020. end;
  13021. end;
  13022. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13023. var
  13024. hp1, hp2 : tai;
  13025. MaskLength : Cardinal;
  13026. MaskedBits : TCgInt;
  13027. ActiveReg : TRegister;
  13028. begin
  13029. Result:=false;
  13030. { There are no optimisations for reference targets }
  13031. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13032. Exit;
  13033. while GetNextInstruction(p, hp1) and
  13034. (hp1.typ = ait_instruction) do
  13035. begin
  13036. if (taicpu(p).oper[0]^.typ = top_const) then
  13037. begin
  13038. case taicpu(hp1).opcode of
  13039. A_AND:
  13040. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13041. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13042. { the second register must contain the first one, so compare their subreg types }
  13043. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13044. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13045. { change
  13046. and const1, reg
  13047. and const2, reg
  13048. to
  13049. and (const1 and const2), reg
  13050. }
  13051. begin
  13052. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13053. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13054. RemoveCurrentP(p, hp1);
  13055. Result:=true;
  13056. exit;
  13057. end;
  13058. A_CMP:
  13059. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13060. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13061. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13062. { Just check that the condition on the next instruction is compatible }
  13063. GetNextInstruction(hp1, hp2) and
  13064. (hp2.typ = ait_instruction) and
  13065. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13066. then
  13067. { change
  13068. and 2^n, reg
  13069. cmp 2^n, reg
  13070. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13071. to
  13072. and 2^n, reg
  13073. test reg, reg
  13074. j(~c) / set(~c) / cmov(~c)
  13075. }
  13076. begin
  13077. { Keep TEST instruction in, rather than remove it, because
  13078. it may trigger other optimisations such as MovAndTest2Test }
  13079. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13080. taicpu(hp1).opcode := A_TEST;
  13081. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13082. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13083. Result := True;
  13084. Exit;
  13085. end
  13086. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13087. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13088. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13089. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13090. { change
  13091. and $ff/$ff/$ffff, reg
  13092. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13093. dealloc reg
  13094. to
  13095. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13096. }
  13097. begin
  13098. TransferUsedRegs(TmpUsedRegs);
  13099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13100. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13101. begin
  13102. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13103. case taicpu(p).oper[0]^.val of
  13104. $ff:
  13105. begin
  13106. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13107. taicpu(hp1).opsize:=S_B;
  13108. end;
  13109. $ffff:
  13110. begin
  13111. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13112. taicpu(hp1).opsize:=S_W;
  13113. end;
  13114. $ffffffff:
  13115. begin
  13116. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13117. taicpu(hp1).opsize:=S_L;
  13118. end;
  13119. else
  13120. Internalerror(2023030401);
  13121. end;
  13122. RemoveCurrentP(p);
  13123. Result := True;
  13124. Exit;
  13125. end;
  13126. end;
  13127. A_MOVZX:
  13128. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13129. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13130. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13131. (
  13132. (
  13133. (taicpu(p).opsize=S_W) and
  13134. (taicpu(hp1).opsize=S_BW)
  13135. ) or
  13136. (
  13137. (taicpu(p).opsize=S_L) and
  13138. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13139. )
  13140. {$ifdef x86_64}
  13141. or
  13142. (
  13143. (taicpu(p).opsize=S_Q) and
  13144. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13145. )
  13146. {$endif x86_64}
  13147. ) then
  13148. begin
  13149. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13150. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13151. ) or
  13152. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13153. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13154. then
  13155. begin
  13156. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13157. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13158. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13159. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13160. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13161. }
  13162. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13163. RemoveInstruction(hp1);
  13164. { See if there are other optimisations possible }
  13165. Continue;
  13166. end;
  13167. end;
  13168. A_SHL:
  13169. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13170. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13171. begin
  13172. {$ifopt R+}
  13173. {$define RANGE_WAS_ON}
  13174. {$R-}
  13175. {$endif}
  13176. { get length of potential and mask }
  13177. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13178. { really a mask? }
  13179. {$ifdef RANGE_WAS_ON}
  13180. {$R+}
  13181. {$endif}
  13182. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13183. { unmasked part shifted out? }
  13184. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13185. begin
  13186. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13187. RemoveCurrentP(p, hp1);
  13188. Result:=true;
  13189. exit;
  13190. end;
  13191. end;
  13192. A_SHR:
  13193. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13194. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13195. (taicpu(hp1).oper[0]^.val <= 63) then
  13196. begin
  13197. { Does SHR combined with the AND cover all the bits?
  13198. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13199. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13200. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13201. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13202. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13203. begin
  13204. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13205. RemoveCurrentP(p, hp1);
  13206. Result := True;
  13207. Exit;
  13208. end;
  13209. end;
  13210. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13211. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13212. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13213. begin
  13214. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13215. (
  13216. (
  13217. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13218. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13219. ) or (
  13220. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13221. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13222. {$ifdef x86_64}
  13223. ) or (
  13224. (taicpu(hp1).opsize = S_LQ) and
  13225. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13226. {$endif x86_64}
  13227. )
  13228. ) then
  13229. begin
  13230. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13231. begin
  13232. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13233. RemoveInstruction(hp1);
  13234. { See if there are other optimisations possible }
  13235. Continue;
  13236. end;
  13237. { The super-registers are the same though.
  13238. Note that this change by itself doesn't improve
  13239. code speed, but it opens up other optimisations. }
  13240. {$ifdef x86_64}
  13241. { Convert 64-bit register to 32-bit }
  13242. case taicpu(hp1).opsize of
  13243. S_BQ:
  13244. begin
  13245. taicpu(hp1).opsize := S_BL;
  13246. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13247. end;
  13248. S_WQ:
  13249. begin
  13250. taicpu(hp1).opsize := S_WL;
  13251. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13252. end
  13253. else
  13254. ;
  13255. end;
  13256. {$endif x86_64}
  13257. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13258. taicpu(hp1).opcode := A_MOVZX;
  13259. { See if there are other optimisations possible }
  13260. Continue;
  13261. end;
  13262. end;
  13263. else
  13264. ;
  13265. end;
  13266. end
  13267. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13268. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13269. begin
  13270. {$ifdef x86_64}
  13271. if (taicpu(p).opsize = S_Q) then
  13272. begin
  13273. { Never necessary }
  13274. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13275. RemoveCurrentP(p, hp1);
  13276. Result := True;
  13277. Exit;
  13278. end;
  13279. {$endif x86_64}
  13280. { Forward check to determine necessity of and %reg,%reg }
  13281. TransferUsedRegs(TmpUsedRegs);
  13282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13283. { Saves on a bunch of dereferences }
  13284. ActiveReg := taicpu(p).oper[1]^.reg;
  13285. case taicpu(hp1).opcode of
  13286. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13287. if (
  13288. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13289. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13290. ) and
  13291. (
  13292. (taicpu(hp1).opcode <> A_MOV) or
  13293. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13294. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13295. ) and
  13296. not (
  13297. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13298. (taicpu(hp1).opcode = A_MOV) and
  13299. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13300. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13301. ) and
  13302. (
  13303. (
  13304. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13305. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13306. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13307. ) or
  13308. (
  13309. {$ifdef x86_64}
  13310. (
  13311. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13312. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13313. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13314. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13315. ) and
  13316. {$endif x86_64}
  13317. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13318. )
  13319. ) then
  13320. begin
  13321. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13322. RemoveCurrentP(p, hp1);
  13323. Result := True;
  13324. Exit;
  13325. end;
  13326. A_ADD,
  13327. A_AND,
  13328. A_BSF,
  13329. A_BSR,
  13330. A_BTC,
  13331. A_BTR,
  13332. A_BTS,
  13333. A_OR,
  13334. A_SUB,
  13335. A_XOR:
  13336. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13337. if (
  13338. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13339. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13340. ) and
  13341. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13342. begin
  13343. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13344. RemoveCurrentP(p, hp1);
  13345. Result := True;
  13346. Exit;
  13347. end;
  13348. A_CMP,
  13349. A_TEST:
  13350. if (
  13351. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13352. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13353. ) and
  13354. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13355. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13356. begin
  13357. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13358. RemoveCurrentP(p, hp1);
  13359. Result := True;
  13360. Exit;
  13361. end;
  13362. A_BSWAP,
  13363. A_NEG,
  13364. A_NOT:
  13365. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13366. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13367. begin
  13368. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13369. RemoveCurrentP(p, hp1);
  13370. Result := True;
  13371. Exit;
  13372. end;
  13373. else
  13374. ;
  13375. end;
  13376. end;
  13377. if (taicpu(hp1).is_jmp) and
  13378. (taicpu(hp1).opcode<>A_JMP) and
  13379. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13380. begin
  13381. { change
  13382. and x, reg
  13383. jxx
  13384. to
  13385. test x, reg
  13386. jxx
  13387. if reg is deallocated before the
  13388. jump, but only if it's a conditional jump (PFV)
  13389. }
  13390. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13391. taicpu(p).opcode := A_TEST;
  13392. Exit;
  13393. end;
  13394. Break;
  13395. end;
  13396. { Lone AND tests }
  13397. if (taicpu(p).oper[0]^.typ = top_const) then
  13398. begin
  13399. {
  13400. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13401. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13402. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13403. }
  13404. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13405. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13406. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13407. begin
  13408. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13409. if taicpu(p).opsize = S_L then
  13410. begin
  13411. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13412. Result := True;
  13413. end;
  13414. end;
  13415. end;
  13416. { Backward check to determine necessity of and %reg,%reg }
  13417. if (taicpu(p).oper[0]^.typ = top_reg) and
  13418. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13419. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13420. GetLastInstruction(p, hp2) and
  13421. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13422. { Check size of adjacent instruction to determine if the AND is
  13423. effectively a null operation }
  13424. (
  13425. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13426. { Note: Don't include S_Q }
  13427. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13428. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13429. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13430. ) then
  13431. begin
  13432. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13433. { If GetNextInstruction returned False, hp1 will be nil }
  13434. RemoveCurrentP(p, hp1);
  13435. Result := True;
  13436. Exit;
  13437. end;
  13438. end;
  13439. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13440. var
  13441. hp1, hp2: tai;
  13442. NewRef: TReference;
  13443. Distance: Cardinal;
  13444. TempTracking: TAllUsedRegs;
  13445. { This entire nested function is used in an if-statement below, but we
  13446. want to avoid all the used reg transfers and GetNextInstruction calls
  13447. until we really have to check }
  13448. function MemRegisterNotUsedLater: Boolean; inline;
  13449. var
  13450. hp2: tai;
  13451. begin
  13452. TransferUsedRegs(TmpUsedRegs);
  13453. hp2 := p;
  13454. repeat
  13455. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13456. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13457. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13458. end;
  13459. begin
  13460. Result := False;
  13461. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13462. (taicpu(p).oper[1]^.typ = top_reg) then
  13463. begin
  13464. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13465. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13466. (hp1.typ <> ait_instruction) or
  13467. not
  13468. (
  13469. (cs_opt_level3 in current_settings.optimizerswitches) or
  13470. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13471. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13472. ) then
  13473. Exit;
  13474. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13475. addq $x, %rax
  13476. movq %rax, %rdx
  13477. sarq $63, %rdx
  13478. (%rax still in use)
  13479. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13480. leaq $x(%rax),%rdx
  13481. addq $x, %rax
  13482. sarq $63, %rdx
  13483. ...which is okay since it breaks the dependency chain between
  13484. addq and movq, but if OptPass2MOV is called first:
  13485. addq $x, %rax
  13486. cqto
  13487. ...which is better in all ways, taking only 2 cycles to execute
  13488. and much smaller in code size.
  13489. }
  13490. { The extra register tracking is quite strenuous }
  13491. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13492. MatchInstruction(hp1, A_MOV, []) then
  13493. begin
  13494. { Update the register tracking to the MOV instruction }
  13495. CopyUsedRegs(TempTracking);
  13496. hp2 := p;
  13497. repeat
  13498. UpdateUsedRegs(tai(hp2.Next));
  13499. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13500. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13501. OptPass2ADD get called again }
  13502. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13503. begin
  13504. { Reset the tracking to the current instruction }
  13505. RestoreUsedRegs(TempTracking);
  13506. ReleaseUsedRegs(TempTracking);
  13507. Result := True;
  13508. Exit;
  13509. end;
  13510. { Reset the tracking to the current instruction }
  13511. RestoreUsedRegs(TempTracking);
  13512. ReleaseUsedRegs(TempTracking);
  13513. { If OptPass2MOV returned True, we don't need to set Result to
  13514. True if hp1 didn't change because the ADD instruction didn't
  13515. get modified and we'll be evaluating hp1 again when the
  13516. peephole optimizer reaches it }
  13517. end;
  13518. { Change:
  13519. add %reg2,%reg1
  13520. (%reg2 not modified in between)
  13521. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13522. To:
  13523. mov/s/z #(%reg1,%reg2),%reg1
  13524. }
  13525. if (taicpu(p).oper[0]^.typ = top_reg) and
  13526. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13527. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13528. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13529. (
  13530. (
  13531. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13532. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13533. { r/esp cannot be an index }
  13534. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13535. ) or (
  13536. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13537. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13538. )
  13539. ) and (
  13540. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13541. (
  13542. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13543. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13544. MemRegisterNotUsedLater
  13545. )
  13546. ) then
  13547. begin
  13548. if (
  13549. { Instructions are guaranteed to be adjacent on -O2 and under }
  13550. (cs_opt_level3 in current_settings.optimizerswitches) and
  13551. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13552. ) then
  13553. begin
  13554. { If the other register is used in between, move the MOV
  13555. instruction to right after the ADD instruction so a
  13556. saving can still be made }
  13557. Asml.Remove(hp1);
  13558. Asml.InsertAfter(hp1, p);
  13559. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13560. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13561. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13562. RemoveCurrentp(p, hp1);
  13563. end
  13564. else
  13565. begin
  13566. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13567. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13568. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13569. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13570. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13571. { hp1 may not be the immediate next instruction under -O3 }
  13572. RemoveCurrentp(p)
  13573. else
  13574. RemoveCurrentp(p, hp1);
  13575. end;
  13576. Result := True;
  13577. Exit;
  13578. end;
  13579. { Change:
  13580. addl/q $x,%reg1
  13581. movl/q %reg1,%reg2
  13582. To:
  13583. leal/q $x(%reg1),%reg2
  13584. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13585. Breaks the dependency chain.
  13586. }
  13587. if (taicpu(p).oper[0]^.typ = top_const) and
  13588. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13589. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13590. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13591. (
  13592. { Instructions are guaranteed to be adjacent on -O2 and under }
  13593. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13594. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13595. ) then
  13596. begin
  13597. TransferUsedRegs(TmpUsedRegs);
  13598. hp2 := p;
  13599. repeat
  13600. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13601. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13602. if (
  13603. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13604. not (cs_opt_size in current_settings.optimizerswitches) or
  13605. (
  13606. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13607. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13608. )
  13609. ) then
  13610. begin
  13611. { Change the MOV instruction to a LEA instruction, and update the
  13612. first operand }
  13613. reference_reset(NewRef, 1, []);
  13614. NewRef.base := taicpu(p).oper[1]^.reg;
  13615. NewRef.scalefactor := 1;
  13616. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13617. taicpu(hp1).opcode := A_LEA;
  13618. taicpu(hp1).loadref(0, NewRef);
  13619. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13620. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13621. begin
  13622. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13623. { Move what is now the LEA instruction to before the ADD instruction }
  13624. Asml.Remove(hp1);
  13625. Asml.InsertBefore(hp1, p);
  13626. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13627. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13628. p := hp1;
  13629. end
  13630. else
  13631. begin
  13632. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13633. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13634. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13635. { hp1 may not be the immediate next instruction under -O3 }
  13636. RemoveCurrentp(p)
  13637. else
  13638. RemoveCurrentp(p, hp1);
  13639. end;
  13640. Result := True;
  13641. end;
  13642. end;
  13643. end;
  13644. end;
  13645. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13646. var
  13647. SubReg: TSubRegister;
  13648. begin
  13649. Result:=false;
  13650. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13651. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13652. with taicpu(p).oper[0]^.ref^ do
  13653. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13654. begin
  13655. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13656. begin
  13657. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13658. taicpu(p).opcode := A_ADD;
  13659. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13660. Result := True;
  13661. end
  13662. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13663. begin
  13664. if (base <> NR_NO) then
  13665. begin
  13666. if (scalefactor <= 1) then
  13667. begin
  13668. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13669. taicpu(p).opcode := A_ADD;
  13670. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13671. Result := True;
  13672. end;
  13673. end
  13674. else
  13675. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13676. if (scalefactor in [2, 4, 8]) then
  13677. begin
  13678. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13679. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13680. taicpu(p).opcode := A_SHL;
  13681. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13682. Result := True;
  13683. end;
  13684. end;
  13685. end;
  13686. end;
  13687. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13688. var
  13689. hp1, hp2: tai;
  13690. NewRef: TReference;
  13691. Distance: Cardinal;
  13692. TempTracking: TAllUsedRegs;
  13693. begin
  13694. Result := False;
  13695. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13696. MatchOpType(taicpu(p),top_const,top_reg) then
  13697. begin
  13698. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13699. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13700. (hp1.typ <> ait_instruction) or
  13701. not
  13702. (
  13703. (cs_opt_level3 in current_settings.optimizerswitches) or
  13704. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13705. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13706. ) then
  13707. Exit;
  13708. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13709. subq $x, %rax
  13710. movq %rax, %rdx
  13711. sarq $63, %rdx
  13712. (%rax still in use)
  13713. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13714. leaq $-x(%rax),%rdx
  13715. movq $x, %rax
  13716. sarq $63, %rdx
  13717. ...which is okay since it breaks the dependency chain between
  13718. subq and movq, but if OptPass2MOV is called first:
  13719. subq $x, %rax
  13720. cqto
  13721. ...which is better in all ways, taking only 2 cycles to execute
  13722. and much smaller in code size.
  13723. }
  13724. { The extra register tracking is quite strenuous }
  13725. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13726. MatchInstruction(hp1, A_MOV, []) then
  13727. begin
  13728. { Update the register tracking to the MOV instruction }
  13729. CopyUsedRegs(TempTracking);
  13730. hp2 := p;
  13731. repeat
  13732. UpdateUsedRegs(tai(hp2.Next));
  13733. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13734. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13735. OptPass2SUB get called again }
  13736. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13737. begin
  13738. { Reset the tracking to the current instruction }
  13739. RestoreUsedRegs(TempTracking);
  13740. ReleaseUsedRegs(TempTracking);
  13741. Result := True;
  13742. Exit;
  13743. end;
  13744. { Reset the tracking to the current instruction }
  13745. RestoreUsedRegs(TempTracking);
  13746. ReleaseUsedRegs(TempTracking);
  13747. { If OptPass2MOV returned True, we don't need to set Result to
  13748. True if hp1 didn't change because the SUB instruction didn't
  13749. get modified and we'll be evaluating hp1 again when the
  13750. peephole optimizer reaches it }
  13751. end;
  13752. { Change:
  13753. subl/q $x,%reg1
  13754. movl/q %reg1,%reg2
  13755. To:
  13756. leal/q $-x(%reg1),%reg2
  13757. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13758. Breaks the dependency chain and potentially permits the removal of
  13759. a CMP instruction if one follows.
  13760. }
  13761. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13762. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13763. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13764. (
  13765. { Instructions are guaranteed to be adjacent on -O2 and under }
  13766. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13767. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13768. ) then
  13769. begin
  13770. TransferUsedRegs(TmpUsedRegs);
  13771. hp2 := p;
  13772. repeat
  13773. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13774. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13775. if (
  13776. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13777. not (cs_opt_size in current_settings.optimizerswitches) or
  13778. (
  13779. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13780. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13781. )
  13782. ) then
  13783. begin
  13784. { Change the MOV instruction to a LEA instruction, and update the
  13785. first operand }
  13786. reference_reset(NewRef, 1, []);
  13787. NewRef.base := taicpu(p).oper[1]^.reg;
  13788. NewRef.scalefactor := 1;
  13789. NewRef.offset := -taicpu(p).oper[0]^.val;
  13790. taicpu(hp1).opcode := A_LEA;
  13791. taicpu(hp1).loadref(0, NewRef);
  13792. TransferUsedRegs(TmpUsedRegs);
  13793. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13794. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13795. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13796. begin
  13797. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13798. { Move what is now the LEA instruction to before the SUB instruction }
  13799. Asml.Remove(hp1);
  13800. Asml.InsertBefore(hp1, p);
  13801. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13802. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13803. p := hp1;
  13804. end
  13805. else
  13806. begin
  13807. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13808. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13809. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13810. { hp1 may not be the immediate next instruction under -O3 }
  13811. RemoveCurrentp(p)
  13812. else
  13813. RemoveCurrentp(p, hp1);
  13814. end;
  13815. Result := True;
  13816. end;
  13817. end;
  13818. end;
  13819. end;
  13820. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13821. begin
  13822. { we can skip all instructions not messing with the stack pointer }
  13823. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13824. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13825. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13826. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13827. ({(taicpu(hp1).ops=0) or }
  13828. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13829. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13830. ) and }
  13831. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13832. )
  13833. ) do
  13834. GetNextInstruction(hp1,hp1);
  13835. Result:=assigned(hp1);
  13836. end;
  13837. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13838. var
  13839. hp1, hp2, hp3, hp4, hp5: tai;
  13840. begin
  13841. Result:=false;
  13842. hp5:=nil;
  13843. { replace
  13844. leal(q) x(<stackpointer>),<stackpointer>
  13845. call procname
  13846. leal(q) -x(<stackpointer>),<stackpointer>
  13847. ret
  13848. by
  13849. jmp procname
  13850. but do it only on level 4 because it destroys stack back traces
  13851. }
  13852. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13853. MatchOpType(taicpu(p),top_ref,top_reg) and
  13854. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13855. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13856. { the -8 or -24 are not required, but bail out early if possible,
  13857. higher values are unlikely }
  13858. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13859. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13860. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13861. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13862. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13863. GetNextInstruction(p, hp1) and
  13864. { Take a copy of hp1 }
  13865. SetAndTest(hp1, hp4) and
  13866. { trick to skip label }
  13867. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13868. SkipSimpleInstructions(hp1) and
  13869. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13870. GetNextInstruction(hp1, hp2) and
  13871. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13872. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13873. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13874. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13875. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13876. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13877. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13878. { Segment register will be NR_NO }
  13879. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13880. GetNextInstruction(hp2, hp3) and
  13881. { trick to skip label }
  13882. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13883. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13884. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13885. SetAndTest(hp3,hp5) and
  13886. GetNextInstruction(hp3,hp3) and
  13887. MatchInstruction(hp3,A_RET,[S_NO])
  13888. )
  13889. ) and
  13890. (taicpu(hp3).ops=0) then
  13891. begin
  13892. taicpu(hp1).opcode := A_JMP;
  13893. taicpu(hp1).is_jmp := true;
  13894. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13895. RemoveCurrentP(p, hp4);
  13896. RemoveInstruction(hp2);
  13897. RemoveInstruction(hp3);
  13898. if Assigned(hp5) then
  13899. begin
  13900. AsmL.Remove(hp5);
  13901. ASmL.InsertBefore(hp5,hp1)
  13902. end;
  13903. Result:=true;
  13904. end;
  13905. end;
  13906. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13907. {$ifdef x86_64}
  13908. var
  13909. hp1, hp2, hp3, hp4, hp5: tai;
  13910. {$endif x86_64}
  13911. begin
  13912. Result:=false;
  13913. {$ifdef x86_64}
  13914. hp5:=nil;
  13915. { replace
  13916. push %rax
  13917. call procname
  13918. pop %rcx
  13919. ret
  13920. by
  13921. jmp procname
  13922. but do it only on level 4 because it destroys stack back traces
  13923. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13924. for all supported calling conventions
  13925. }
  13926. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13927. MatchOpType(taicpu(p),top_reg) and
  13928. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13929. GetNextInstruction(p, hp1) and
  13930. { Take a copy of hp1 }
  13931. SetAndTest(hp1, hp4) and
  13932. { trick to skip label }
  13933. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13934. SkipSimpleInstructions(hp1) and
  13935. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13936. GetNextInstruction(hp1, hp2) and
  13937. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13938. MatchOpType(taicpu(hp2),top_reg) and
  13939. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13940. GetNextInstruction(hp2, hp3) and
  13941. { trick to skip label }
  13942. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13943. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13944. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13945. SetAndTest(hp3,hp5) and
  13946. GetNextInstruction(hp3,hp3) and
  13947. MatchInstruction(hp3,A_RET,[S_NO])
  13948. )
  13949. ) and
  13950. (taicpu(hp3).ops=0) then
  13951. begin
  13952. taicpu(hp1).opcode := A_JMP;
  13953. taicpu(hp1).is_jmp := true;
  13954. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13955. RemoveCurrentP(p, hp4);
  13956. RemoveInstruction(hp2);
  13957. RemoveInstruction(hp3);
  13958. if Assigned(hp5) then
  13959. begin
  13960. AsmL.Remove(hp5);
  13961. ASmL.InsertBefore(hp5,hp1)
  13962. end;
  13963. Result:=true;
  13964. end;
  13965. {$endif x86_64}
  13966. end;
  13967. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13968. var
  13969. Value, RegName: string;
  13970. hp1: tai;
  13971. begin
  13972. Result:=false;
  13973. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13974. begin
  13975. case taicpu(p).oper[0]^.val of
  13976. 0:
  13977. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13978. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  13979. (
  13980. { See if we can still convert the instruction }
  13981. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  13982. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  13983. ) then
  13984. begin
  13985. { change "mov $0,%reg" into "xor %reg,%reg" }
  13986. taicpu(p).opcode := A_XOR;
  13987. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13988. Result := True;
  13989. {$ifdef x86_64}
  13990. end
  13991. else if (taicpu(p).opsize = S_Q) then
  13992. begin
  13993. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13994. { The actual optimization }
  13995. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13996. taicpu(p).changeopsize(S_L);
  13997. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13998. Result := True;
  13999. end;
  14000. $1..$FFFFFFFF:
  14001. begin
  14002. { Code size reduction by J. Gareth "Kit" Moreton }
  14003. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14004. case taicpu(p).opsize of
  14005. S_Q:
  14006. begin
  14007. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14008. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14009. { The actual optimization }
  14010. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14011. taicpu(p).changeopsize(S_L);
  14012. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14013. Result := True;
  14014. end;
  14015. else
  14016. { Do nothing };
  14017. end;
  14018. {$endif x86_64}
  14019. end;
  14020. -1:
  14021. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14022. if (cs_opt_size in current_settings.optimizerswitches) and
  14023. (taicpu(p).opsize <> S_B) and
  14024. (
  14025. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14026. (
  14027. { See if we can still convert the instruction }
  14028. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14029. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14030. )
  14031. ) then
  14032. begin
  14033. { change "mov $-1,%reg" into "or $-1,%reg" }
  14034. { NOTES:
  14035. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14036. - This operation creates a false dependency on the register, so only do it when optimising for size
  14037. - 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
  14038. }
  14039. taicpu(p).opcode := A_OR;
  14040. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14041. Result := True;
  14042. end;
  14043. else
  14044. { Do nothing };
  14045. end;
  14046. end;
  14047. end;
  14048. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14049. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14050. begin
  14051. Result := False;
  14052. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14053. Exit;
  14054. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14055. so don't bother optimising }
  14056. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14057. Exit;
  14058. if (taicpu(p).oper[0]^.typ <> top_const) or
  14059. { If the value can fit into an 8-bit signed integer, a smaller
  14060. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14061. falls within this range }
  14062. (
  14063. (taicpu(p).oper[0]^.val > -128) and
  14064. (taicpu(p).oper[0]^.val <= 127)
  14065. ) then
  14066. Exit;
  14067. { If we're optimising for size, this is acceptable }
  14068. if (cs_opt_size in current_settings.optimizerswitches) then
  14069. Exit(True);
  14070. if (taicpu(p).oper[1]^.typ = top_reg) and
  14071. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14072. Exit(True);
  14073. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14074. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14075. Exit(True);
  14076. end;
  14077. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14078. var
  14079. hp1: tai;
  14080. Value: TCGInt;
  14081. begin
  14082. Result := False;
  14083. if MatchOpType(taicpu(p), top_const, top_reg) then
  14084. begin
  14085. { Detect:
  14086. andw x, %ax (0 <= x < $8000)
  14087. ...
  14088. movzwl %ax,%eax
  14089. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14090. }
  14091. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14092. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14093. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14094. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14095. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14096. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14097. begin
  14098. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14099. taicpu(hp1).opcode := A_CWDE;
  14100. taicpu(hp1).clearop(0);
  14101. taicpu(hp1).clearop(1);
  14102. taicpu(hp1).ops := 0;
  14103. { A change was made, but not with p, so don't set Result, but
  14104. notify the compiler that a change was made }
  14105. Include(OptsToCheck, aoc_ForceNewIteration);
  14106. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14107. end;
  14108. end;
  14109. { If "not x" is a power of 2 (popcnt = 1), change:
  14110. and $x, %reg/ref
  14111. To:
  14112. btr lb(x), %reg/ref
  14113. }
  14114. if IsBTXAcceptable(p) and
  14115. (
  14116. { Make sure a TEST doesn't follow that plays with the register }
  14117. not GetNextInstruction(p, hp1) or
  14118. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14119. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14120. ) then
  14121. begin
  14122. {$push}{$R-}{$Q-}
  14123. { Value is a sign-extended 32-bit integer - just correct it
  14124. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14125. checks to see if this operand is an immediate. }
  14126. Value := not taicpu(p).oper[0]^.val;
  14127. {$pop}
  14128. {$ifdef x86_64}
  14129. if taicpu(p).opsize = S_L then
  14130. {$endif x86_64}
  14131. Value := Value and $FFFFFFFF;
  14132. if (PopCnt(QWord(Value)) = 1) then
  14133. begin
  14134. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14135. taicpu(p).opcode := A_BTR;
  14136. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14137. Result := True;
  14138. Exit;
  14139. end;
  14140. end;
  14141. end;
  14142. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14143. begin
  14144. Result := False;
  14145. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14146. Exit;
  14147. { Convert:
  14148. movswl %ax,%eax -> cwtl
  14149. movslq %eax,%rax -> cdqe
  14150. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14151. refer to the same opcode and depends only on the assembler's
  14152. current operand-size attribute. [Kit]
  14153. }
  14154. with taicpu(p) do
  14155. case opsize of
  14156. S_WL:
  14157. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14158. begin
  14159. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14160. opcode := A_CWDE;
  14161. clearop(0);
  14162. clearop(1);
  14163. ops := 0;
  14164. Result := True;
  14165. end;
  14166. {$ifdef x86_64}
  14167. S_LQ:
  14168. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14169. begin
  14170. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14171. opcode := A_CDQE;
  14172. clearop(0);
  14173. clearop(1);
  14174. ops := 0;
  14175. Result := True;
  14176. end;
  14177. {$endif x86_64}
  14178. else
  14179. ;
  14180. end;
  14181. end;
  14182. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14183. var
  14184. hp1, hp2: tai;
  14185. IdentityMask, Shift: TCGInt;
  14186. LimitSize: Topsize;
  14187. DoNotMerge: Boolean;
  14188. begin
  14189. Result := False;
  14190. { All these optimisations work on "shr const,%reg" }
  14191. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14192. Exit;
  14193. DoNotMerge := False;
  14194. Shift := taicpu(p).oper[0]^.val;
  14195. LimitSize := taicpu(p).opsize;
  14196. hp1 := p;
  14197. repeat
  14198. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14199. Break;
  14200. { Detect:
  14201. shr x, %reg
  14202. and y, %reg
  14203. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14204. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14205. }
  14206. case taicpu(hp1).opcode of
  14207. A_AND:
  14208. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14209. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14210. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14211. begin
  14212. { Make sure the FLAGS register isn't in use }
  14213. TransferUsedRegs(TmpUsedRegs);
  14214. hp2 := p;
  14215. repeat
  14216. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14217. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14218. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14219. begin
  14220. { Generate the identity mask }
  14221. case taicpu(p).opsize of
  14222. S_B:
  14223. IdentityMask := $FF shr Shift;
  14224. S_W:
  14225. IdentityMask := $FFFF shr Shift;
  14226. S_L:
  14227. IdentityMask := $FFFFFFFF shr Shift;
  14228. {$ifdef x86_64}
  14229. S_Q:
  14230. { We need to force the operands to be unsigned 64-bit
  14231. integers otherwise the wrong value is generated }
  14232. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14233. {$endif x86_64}
  14234. else
  14235. InternalError(2022081501);
  14236. end;
  14237. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14238. begin
  14239. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14240. { All the possible 1 bits are covered, so we can remove the AND }
  14241. hp2 := tai(hp1.Previous);
  14242. RemoveInstruction(hp1);
  14243. { p wasn't actually changed, so don't set Result to True,
  14244. but a change was nonetheless made elsewhere }
  14245. Include(OptsToCheck, aoc_ForceNewIteration);
  14246. { Do another pass in case other AND or MOVZX instructions
  14247. follow }
  14248. hp1 := hp2;
  14249. Continue;
  14250. end;
  14251. end;
  14252. end;
  14253. A_TEST, A_CMP, A_Jcc:
  14254. { Skip over conditional jumps and relevant comparisons }
  14255. Continue;
  14256. A_MOVZX:
  14257. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14258. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14259. begin
  14260. { Since the original register is being read as is, subsequent
  14261. SHRs must not be merged at this point }
  14262. DoNotMerge := True;
  14263. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14264. begin
  14265. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14266. begin
  14267. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14268. { All the possible 1 bits are covered, so we can remove the AND }
  14269. hp2 := tai(hp1.Previous);
  14270. RemoveInstruction(hp1);
  14271. hp1 := hp2;
  14272. end
  14273. else { Different register target }
  14274. begin
  14275. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14276. taicpu(hp1).opcode := A_MOV;
  14277. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14278. case taicpu(hp1).opsize of
  14279. S_BW:
  14280. taicpu(hp1).opsize := S_W;
  14281. S_BL, S_WL:
  14282. taicpu(hp1).opsize := S_L;
  14283. else
  14284. InternalError(2022081503);
  14285. end;
  14286. end;
  14287. end
  14288. else if (Shift > 0) and
  14289. (taicpu(p).opsize = S_W) and
  14290. (taicpu(hp1).opsize = S_WL) and
  14291. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14292. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14293. begin
  14294. { Detect:
  14295. shr x, %ax (x > 0)
  14296. ...
  14297. movzwl %ax,%eax
  14298. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14299. }
  14300. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14301. taicpu(hp1).opcode := A_CWDE;
  14302. taicpu(hp1).clearop(0);
  14303. taicpu(hp1).clearop(1);
  14304. taicpu(hp1).ops := 0;
  14305. end;
  14306. { Move onto the next instruction }
  14307. Continue;
  14308. end;
  14309. A_SHL, A_SAL, A_SHR:
  14310. if (taicpu(hp1).opsize <= LimitSize) and
  14311. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14312. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14313. begin
  14314. { Make sure the sizes don't exceed the register size limit
  14315. (measured by the shift value falling below the limit) }
  14316. if taicpu(hp1).opsize < LimitSize then
  14317. LimitSize := taicpu(hp1).opsize;
  14318. if taicpu(hp1).opcode = A_SHR then
  14319. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14320. else
  14321. begin
  14322. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14323. DoNotMerge := True;
  14324. end;
  14325. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14326. Break;
  14327. { Since we've established that the combined shift is within
  14328. limits, we can actually combine the adjacent SHR
  14329. instructions even if they're different sizes }
  14330. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14331. begin
  14332. hp2 := tai(hp1.Previous);
  14333. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14334. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14335. RemoveInstruction(hp1);
  14336. hp1 := hp2;
  14337. end;
  14338. { Move onto the next instruction }
  14339. Continue;
  14340. end;
  14341. else
  14342. ;
  14343. end;
  14344. Break;
  14345. until False;
  14346. { Detect the following (looking backwards):
  14347. shr %cl,%reg
  14348. shr x, %reg
  14349. Swap the two SHR instructions to minimise a pipeline stall.
  14350. }
  14351. if GetLastInstruction(p, hp1) and
  14352. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14353. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14354. { First operand will be %cl }
  14355. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14356. { Just to be sure }
  14357. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14358. begin
  14359. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14360. { Moving the entries this way ensures the register tracking remains correct }
  14361. Asml.Remove(p);
  14362. Asml.InsertBefore(p, hp1);
  14363. p := hp1;
  14364. { Don't set Result to True because the current instruction is now
  14365. "shr %cl,%reg" and there's nothing more we can do with it }
  14366. end;
  14367. end;
  14368. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14369. var
  14370. hp1, hp2: tai;
  14371. Opposite, SecondOpposite: TAsmOp;
  14372. NewCond: TAsmCond;
  14373. begin
  14374. Result := False;
  14375. { Change:
  14376. add/sub 128,(dest)
  14377. To:
  14378. sub/add -128,(dest)
  14379. This generaally takes fewer bytes to encode because -128 can be stored
  14380. in a signed byte, whereas +128 cannot.
  14381. }
  14382. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14383. begin
  14384. if taicpu(p).opcode = A_ADD then
  14385. Opposite := A_SUB
  14386. else
  14387. Opposite := A_ADD;
  14388. { Be careful if the flags are in use, because the CF flag inverts
  14389. when changing from ADD to SUB and vice versa }
  14390. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14391. GetNextInstruction(p, hp1) then
  14392. begin
  14393. TransferUsedRegs(TmpUsedRegs);
  14394. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14395. hp2 := hp1;
  14396. { Scan ahead to check if everything's safe }
  14397. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14398. begin
  14399. if (hp1.typ <> ait_instruction) then
  14400. { Probably unsafe since the flags are still in use }
  14401. Exit;
  14402. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14403. { Stop searching at an unconditional jump }
  14404. Break;
  14405. if not
  14406. (
  14407. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14408. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14409. ) and
  14410. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14411. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14412. Exit;
  14413. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14414. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14415. { Move to the next instruction }
  14416. GetNextInstruction(hp1, hp1);
  14417. end;
  14418. while Assigned(hp2) and (hp2 <> hp1) do
  14419. begin
  14420. NewCond := C_None;
  14421. case taicpu(hp2).condition of
  14422. C_A, C_NBE:
  14423. NewCond := C_BE;
  14424. C_B, C_C, C_NAE:
  14425. NewCond := C_AE;
  14426. C_AE, C_NB, C_NC:
  14427. NewCond := C_B;
  14428. C_BE, C_NA:
  14429. NewCond := C_A;
  14430. else
  14431. { No change needed };
  14432. end;
  14433. if NewCond <> C_None then
  14434. begin
  14435. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14436. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14437. taicpu(hp2).condition := NewCond;
  14438. end
  14439. else
  14440. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14441. begin
  14442. { Because of the flipping of the carry bit, to ensure
  14443. the operation remains equivalent, ADC becomes SBB
  14444. and vice versa, and the constant is not-inverted.
  14445. If multiple ADCs or SBBs appear in a row, each one
  14446. changed causes the carry bit to invert, so they all
  14447. need to be flipped }
  14448. if taicpu(hp2).opcode = A_ADC then
  14449. SecondOpposite := A_SBB
  14450. else
  14451. SecondOpposite := A_ADC;
  14452. if taicpu(hp2).oper[0]^.typ <> top_const then
  14453. { Should have broken out of this optimisation already }
  14454. InternalError(2021112901);
  14455. 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]^) + ' -> ' +
  14456. 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);
  14457. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14458. taicpu(hp2).opcode := SecondOpposite;
  14459. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14460. end;
  14461. { Move to the next instruction }
  14462. GetNextInstruction(hp2, hp2);
  14463. end;
  14464. if (hp2 <> hp1) then
  14465. InternalError(2021111501);
  14466. end;
  14467. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14468. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14469. taicpu(p).opcode := Opposite;
  14470. taicpu(p).oper[0]^.val := -128;
  14471. { No further optimisations can be made on this instruction, so move
  14472. onto the next one to save time }
  14473. p := tai(p.Next);
  14474. UpdateUsedRegs(p);
  14475. Result := True;
  14476. Exit;
  14477. end;
  14478. { Detect:
  14479. add/sub %reg2,(dest)
  14480. add/sub x, (dest)
  14481. (dest can be a register or a reference)
  14482. Swap the instructions to minimise a pipeline stall. This reverses the
  14483. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14484. optimisations could be made.
  14485. }
  14486. if (taicpu(p).oper[0]^.typ = top_reg) and
  14487. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14488. (
  14489. (
  14490. (taicpu(p).oper[1]^.typ = top_reg) and
  14491. { We can try searching further ahead if we're writing to a register }
  14492. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14493. ) or
  14494. (
  14495. (taicpu(p).oper[1]^.typ = top_ref) and
  14496. GetNextInstruction(p, hp1)
  14497. )
  14498. ) and
  14499. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14500. (taicpu(hp1).oper[0]^.typ = top_const) and
  14501. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14502. begin
  14503. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14504. TransferUsedRegs(TmpUsedRegs);
  14505. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14506. hp2 := p;
  14507. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14508. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14509. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14510. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14511. begin
  14512. asml.remove(hp1);
  14513. asml.InsertBefore(hp1, p);
  14514. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14515. Result := True;
  14516. end;
  14517. end;
  14518. end;
  14519. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14520. var
  14521. hp1: tai;
  14522. begin
  14523. Result:=false;
  14524. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14525. while GetNextInstruction(p, hp1) and
  14526. TrySwapMovCmp(p, hp1) do
  14527. begin
  14528. if MatchInstruction(hp1, A_MOV, []) then
  14529. begin
  14530. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14531. begin
  14532. { A little hacky, but since CMP doesn't read the flags, only
  14533. modify them, it's safe if they get scrambled by MOV -> XOR }
  14534. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14535. Result := PostPeepholeOptMov(hp1);
  14536. {$ifdef x86_64}
  14537. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14538. { Used to shrink instruction size }
  14539. PostPeepholeOptXor(hp1);
  14540. {$endif x86_64}
  14541. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14542. end
  14543. else
  14544. begin
  14545. Result := PostPeepholeOptMov(hp1);
  14546. {$ifdef x86_64}
  14547. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14548. { Used to shrink instruction size }
  14549. PostPeepholeOptXor(hp1);
  14550. {$endif x86_64}
  14551. end;
  14552. end;
  14553. { Enabling this flag is actually a null operation, but it marks
  14554. the code as 'modified' during this pass }
  14555. Include(OptsToCheck, aoc_ForceNewIteration);
  14556. end;
  14557. { change "cmp $0, %reg" to "test %reg, %reg" }
  14558. if MatchOpType(taicpu(p),top_const,top_reg) and
  14559. (taicpu(p).oper[0]^.val = 0) then
  14560. begin
  14561. taicpu(p).opcode := A_TEST;
  14562. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14563. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14564. Result:=true;
  14565. end;
  14566. end;
  14567. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14568. var
  14569. IsTestConstX, IsValid : Boolean;
  14570. hp1,hp2 : tai;
  14571. begin
  14572. Result:=false;
  14573. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14574. if (taicpu(p).opcode = A_TEST) then
  14575. while GetNextInstruction(p, hp1) and
  14576. TrySwapMovCmp(p, hp1) do
  14577. begin
  14578. if MatchInstruction(hp1, A_MOV, []) then
  14579. begin
  14580. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14581. begin
  14582. { A little hacky, but since TEST doesn't read the flags, only
  14583. modify them, it's safe if they get scrambled by MOV -> XOR }
  14584. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14585. Result := PostPeepholeOptMov(hp1);
  14586. {$ifdef x86_64}
  14587. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14588. { Used to shrink instruction size }
  14589. PostPeepholeOptXor(hp1);
  14590. {$endif x86_64}
  14591. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14592. end
  14593. else
  14594. begin
  14595. Result := PostPeepholeOptMov(hp1);
  14596. {$ifdef x86_64}
  14597. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14598. { Used to shrink instruction size }
  14599. PostPeepholeOptXor(hp1);
  14600. {$endif x86_64}
  14601. end;
  14602. end;
  14603. { Enabling this flag is actually a null operation, but it marks
  14604. the code as 'modified' during this pass }
  14605. Include(OptsToCheck, aoc_ForceNewIteration);
  14606. end;
  14607. { If x is a power of 2 (popcnt = 1), change:
  14608. or $x, %reg/ref
  14609. To:
  14610. bts lb(x), %reg/ref
  14611. }
  14612. if (taicpu(p).opcode = A_OR) and
  14613. IsBTXAcceptable(p) and
  14614. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14615. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14616. (
  14617. { Don't optimise if a test instruction follows }
  14618. not GetNextInstruction(p, hp1) or
  14619. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14620. ) then
  14621. begin
  14622. 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);
  14623. taicpu(p).opcode := A_BTS;
  14624. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14625. Result := True;
  14626. Exit;
  14627. end;
  14628. { If x is a power of 2 (popcnt = 1), change:
  14629. test $x, %reg/ref
  14630. je / sete / cmove (or jne / setne)
  14631. To:
  14632. bt lb(x), %reg/ref
  14633. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14634. }
  14635. if (taicpu(p).opcode = A_TEST) and
  14636. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14637. (taicpu(p).oper[0]^.typ = top_const) and
  14638. (
  14639. (cs_opt_size in current_settings.optimizerswitches) or
  14640. (
  14641. (taicpu(p).oper[1]^.typ = top_reg) and
  14642. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14643. ) or
  14644. (
  14645. (taicpu(p).oper[1]^.typ <> top_reg) and
  14646. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14647. )
  14648. ) and
  14649. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14650. { For sizes less than S_L, the byte size is equal or larger with BT,
  14651. so don't bother optimising }
  14652. (taicpu(p).opsize >= S_L) then
  14653. begin
  14654. IsValid := True;
  14655. { Check the next set of instructions, watching the FLAGS register
  14656. and the conditions used }
  14657. TransferUsedRegs(TmpUsedRegs);
  14658. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14659. hp1 := p;
  14660. hp2 := nil;
  14661. while GetNextInstruction(hp1, hp1) do
  14662. begin
  14663. if not Assigned(hp2) then
  14664. { The first instruction after TEST }
  14665. hp2 := hp1;
  14666. if (hp1.typ <> ait_instruction) then
  14667. begin
  14668. { If the flags are no longer in use, everything is fine }
  14669. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14670. IsValid := False;
  14671. Break;
  14672. end;
  14673. case taicpu(hp1).condition of
  14674. C_None:
  14675. begin
  14676. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14677. { Something is not quite normal, so play safe and don't change }
  14678. IsValid := False;
  14679. Break;
  14680. end;
  14681. C_E, C_Z, C_NE, C_NZ:
  14682. { This is fine };
  14683. else
  14684. begin
  14685. { Unsupported condition }
  14686. IsValid := False;
  14687. Break;
  14688. end;
  14689. end;
  14690. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14691. end;
  14692. if IsValid then
  14693. begin
  14694. while hp2 <> hp1 do
  14695. begin
  14696. case taicpu(hp2).condition of
  14697. C_Z, C_E:
  14698. taicpu(hp2).condition := C_NC;
  14699. C_NZ, C_NE:
  14700. taicpu(hp2).condition := C_C;
  14701. else
  14702. { Should not get this by this point }
  14703. InternalError(2022110701);
  14704. end;
  14705. GetNextInstruction(hp2, hp2);
  14706. end;
  14707. 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);
  14708. taicpu(p).opcode := A_BT;
  14709. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14710. Result := True;
  14711. Exit;
  14712. end;
  14713. end;
  14714. { removes the line marked with (x) from the sequence
  14715. and/or/xor/add/sub/... $x, %y
  14716. test/or %y, %y | test $-1, %y (x)
  14717. j(n)z _Label
  14718. as the first instruction already adjusts the ZF
  14719. %y operand may also be a reference }
  14720. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14721. MatchOperand(taicpu(p).oper[0]^,-1);
  14722. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14723. GetLastInstruction(p, hp1) and
  14724. (tai(hp1).typ = ait_instruction) and
  14725. GetNextInstruction(p,hp2) and
  14726. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14727. case taicpu(hp1).opcode Of
  14728. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14729. { These two instructions set the zero flag if the result is zero }
  14730. A_POPCNT, A_LZCNT:
  14731. begin
  14732. if (
  14733. { With POPCNT, an input of zero will set the zero flag
  14734. because the population count of zero is zero }
  14735. (taicpu(hp1).opcode = A_POPCNT) and
  14736. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14737. (
  14738. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14739. { Faster than going through the second half of the 'or'
  14740. condition below }
  14741. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14742. )
  14743. ) or (
  14744. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14745. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14746. { and in case of carry for A(E)/B(E)/C/NC }
  14747. (
  14748. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14749. (
  14750. (taicpu(hp1).opcode <> A_ADD) and
  14751. (taicpu(hp1).opcode <> A_SUB) and
  14752. (taicpu(hp1).opcode <> A_LZCNT)
  14753. )
  14754. )
  14755. ) then
  14756. begin
  14757. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14758. RemoveCurrentP(p, hp2);
  14759. Result:=true;
  14760. Exit;
  14761. end;
  14762. end;
  14763. A_SHL, A_SAL, A_SHR, A_SAR:
  14764. begin
  14765. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14766. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14767. { therefore, it's only safe to do this optimization for }
  14768. { shifts by a (nonzero) constant }
  14769. (taicpu(hp1).oper[0]^.typ = top_const) and
  14770. (taicpu(hp1).oper[0]^.val <> 0) and
  14771. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14772. { and in case of carry for A(E)/B(E)/C/NC }
  14773. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14774. begin
  14775. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14776. RemoveCurrentP(p, hp2);
  14777. Result:=true;
  14778. Exit;
  14779. end;
  14780. end;
  14781. A_DEC, A_INC, A_NEG:
  14782. begin
  14783. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14784. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14785. { and in case of carry for A(E)/B(E)/C/NC }
  14786. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14787. begin
  14788. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14789. RemoveCurrentP(p, hp2);
  14790. Result:=true;
  14791. Exit;
  14792. end;
  14793. end;
  14794. A_ANDN, A_BZHI:
  14795. begin
  14796. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14797. { Only the zero and sign flags are consistent with what the result is }
  14798. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14799. begin
  14800. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14801. RemoveCurrentP(p, hp2);
  14802. Result:=true;
  14803. Exit;
  14804. end;
  14805. end;
  14806. A_BEXTR:
  14807. begin
  14808. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14809. { Only the zero flag is set }
  14810. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14811. begin
  14812. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14813. RemoveCurrentP(p, hp2);
  14814. Result:=true;
  14815. Exit;
  14816. end;
  14817. end;
  14818. else
  14819. ;
  14820. end; { case }
  14821. { change "test $-1,%reg" into "test %reg,%reg" }
  14822. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14823. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14824. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14825. if MatchInstruction(p, A_OR, []) and
  14826. { Can only match if they're both registers }
  14827. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14828. begin
  14829. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14830. taicpu(p).opcode := A_TEST;
  14831. { No need to set Result to True, as we've done all the optimisations we can }
  14832. end;
  14833. end;
  14834. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14835. var
  14836. hp1,hp3 : tai;
  14837. {$ifndef x86_64}
  14838. hp2 : taicpu;
  14839. {$endif x86_64}
  14840. begin
  14841. Result:=false;
  14842. hp3:=nil;
  14843. {$ifndef x86_64}
  14844. { don't do this on modern CPUs, this really hurts them due to
  14845. broken call/ret pairing }
  14846. if (current_settings.optimizecputype < cpu_Pentium2) and
  14847. not(cs_create_pic in current_settings.moduleswitches) and
  14848. GetNextInstruction(p, hp1) and
  14849. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14850. MatchOpType(taicpu(hp1),top_ref) and
  14851. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14852. begin
  14853. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14854. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14855. InsertLLItem(p.previous, p, hp2);
  14856. taicpu(p).opcode := A_JMP;
  14857. taicpu(p).is_jmp := true;
  14858. RemoveInstruction(hp1);
  14859. Result:=true;
  14860. end
  14861. else
  14862. {$endif x86_64}
  14863. { replace
  14864. call procname
  14865. ret
  14866. by
  14867. jmp procname
  14868. but do it only on level 4 because it destroys stack back traces
  14869. else if the subroutine is marked as no return, remove the ret
  14870. }
  14871. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14872. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14873. GetNextInstruction(p, hp1) and
  14874. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14875. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14876. SetAndTest(hp1,hp3) and
  14877. GetNextInstruction(hp1,hp1) and
  14878. MatchInstruction(hp1,A_RET,[S_NO])
  14879. )
  14880. ) and
  14881. (taicpu(hp1).ops=0) then
  14882. begin
  14883. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14884. { we might destroy stack alignment here if we do not do a call }
  14885. (target_info.stackalign<=sizeof(SizeUInt)) then
  14886. begin
  14887. taicpu(p).opcode := A_JMP;
  14888. taicpu(p).is_jmp := true;
  14889. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14890. end
  14891. else
  14892. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14893. RemoveInstruction(hp1);
  14894. if Assigned(hp3) then
  14895. begin
  14896. AsmL.Remove(hp3);
  14897. AsmL.InsertBefore(hp3,p)
  14898. end;
  14899. Result:=true;
  14900. end;
  14901. end;
  14902. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14903. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14904. begin
  14905. case OpSize of
  14906. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14907. Result := (Val <= $FF) and (Val >= -128);
  14908. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14909. Result := (Val <= $FFFF) and (Val >= -32768);
  14910. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14911. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14912. else
  14913. Result := True;
  14914. end;
  14915. end;
  14916. var
  14917. hp1, hp2 : tai;
  14918. SizeChange: Boolean;
  14919. PreMessage: string;
  14920. begin
  14921. Result := False;
  14922. if (taicpu(p).oper[0]^.typ = top_reg) and
  14923. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14924. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14925. begin
  14926. { Change (using movzbl %al,%eax as an example):
  14927. movzbl %al, %eax movzbl %al, %eax
  14928. cmpl x, %eax testl %eax,%eax
  14929. To:
  14930. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14931. movzbl %al, %eax movzbl %al, %eax
  14932. Smaller instruction and minimises pipeline stall as the CPU
  14933. doesn't have to wait for the register to get zero-extended. [Kit]
  14934. Also allow if the smaller of the two registers is being checked,
  14935. as this still removes the false dependency.
  14936. }
  14937. if
  14938. (
  14939. (
  14940. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14941. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14942. ) or (
  14943. { If MatchOperand returns True, they must both be registers }
  14944. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14945. )
  14946. ) and
  14947. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14948. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14949. begin
  14950. 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);
  14951. asml.Remove(hp1);
  14952. asml.InsertBefore(hp1, p);
  14953. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14954. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14955. begin
  14956. taicpu(hp1).opcode := A_TEST;
  14957. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14958. end;
  14959. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14960. case taicpu(p).opsize of
  14961. S_BW, S_BL:
  14962. begin
  14963. SizeChange := taicpu(hp1).opsize <> S_B;
  14964. taicpu(hp1).changeopsize(S_B);
  14965. end;
  14966. S_WL:
  14967. begin
  14968. SizeChange := taicpu(hp1).opsize <> S_W;
  14969. taicpu(hp1).changeopsize(S_W);
  14970. end
  14971. else
  14972. InternalError(2020112701);
  14973. end;
  14974. UpdateUsedRegs(tai(p.Next));
  14975. { Check if the register is used aferwards - if not, we can
  14976. remove the movzx instruction completely }
  14977. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14978. begin
  14979. { Hp1 is a better position than p for debugging purposes }
  14980. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14981. RemoveCurrentp(p, hp1);
  14982. Result := True;
  14983. end;
  14984. if SizeChange then
  14985. DebugMsg(SPeepholeOptimization + PreMessage +
  14986. 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)
  14987. else
  14988. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14989. Exit;
  14990. end;
  14991. { Change (using movzwl %ax,%eax as an example):
  14992. movzwl %ax, %eax
  14993. movb %al, (dest) (Register is smaller than read register in movz)
  14994. To:
  14995. movb %al, (dest) (Move one back to avoid a false dependency)
  14996. movzwl %ax, %eax
  14997. }
  14998. if (taicpu(hp1).opcode = A_MOV) and
  14999. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15000. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15001. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15002. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15003. begin
  15004. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15005. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15006. asml.Remove(hp1);
  15007. asml.InsertBefore(hp1, p);
  15008. if taicpu(hp1).oper[1]^.typ = top_reg then
  15009. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15010. { Check if the register is used aferwards - if not, we can
  15011. remove the movzx instruction completely }
  15012. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15013. begin
  15014. { Hp1 is a better position than p for debugging purposes }
  15015. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15016. RemoveCurrentp(p, hp1);
  15017. Result := True;
  15018. end;
  15019. Exit;
  15020. end;
  15021. end;
  15022. end;
  15023. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15024. var
  15025. hp1: tai;
  15026. {$ifdef x86_64}
  15027. PreMessage, RegName: string;
  15028. {$endif x86_64}
  15029. begin
  15030. Result := False;
  15031. { If x is a power of 2 (popcnt = 1), change:
  15032. xor $x, %reg/ref
  15033. To:
  15034. btc lb(x), %reg/ref
  15035. }
  15036. if IsBTXAcceptable(p) and
  15037. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15038. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15039. (
  15040. { Don't optimise if a test instruction follows }
  15041. not GetNextInstruction(p, hp1) or
  15042. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15043. ) then
  15044. begin
  15045. 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);
  15046. taicpu(p).opcode := A_BTC;
  15047. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15048. Result := True;
  15049. Exit;
  15050. end;
  15051. {$ifdef x86_64}
  15052. { Code size reduction by J. Gareth "Kit" Moreton }
  15053. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15054. as this removes the REX prefix }
  15055. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15056. Exit;
  15057. if taicpu(p).oper[0]^.typ <> top_reg then
  15058. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15059. InternalError(2018011500);
  15060. case taicpu(p).opsize of
  15061. S_Q:
  15062. begin
  15063. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15064. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15065. { The actual optimization }
  15066. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15067. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15068. taicpu(p).changeopsize(S_L);
  15069. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15070. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15071. end;
  15072. else
  15073. ;
  15074. end;
  15075. {$endif x86_64}
  15076. end;
  15077. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15078. var
  15079. XReg: TRegister;
  15080. begin
  15081. Result := False;
  15082. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15083. Smaller encoding and slightly faster on some platforms (also works for
  15084. ZMM-sized registers) }
  15085. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15086. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15087. begin
  15088. XReg := taicpu(p).oper[0]^.reg;
  15089. if (taicpu(p).oper[1]^.reg = XReg) then
  15090. begin
  15091. taicpu(p).changeopsize(S_XMM);
  15092. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15093. if (cs_opt_size in current_settings.optimizerswitches) then
  15094. begin
  15095. { Change input registers to %xmm0 to reduce size. Note that
  15096. there's a risk of a false dependency doing this, so only
  15097. optimise for size here }
  15098. XReg := NR_XMM0;
  15099. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15100. end
  15101. else
  15102. begin
  15103. setsubreg(XReg, R_SUBMMX);
  15104. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15105. end;
  15106. taicpu(p).oper[0]^.reg := XReg;
  15107. taicpu(p).oper[1]^.reg := XReg;
  15108. Result := True;
  15109. end;
  15110. end;
  15111. end;
  15112. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15113. var
  15114. OperIdx: Integer;
  15115. begin
  15116. for OperIdx := 0 to p.ops - 1 do
  15117. if p.oper[OperIdx]^.typ = top_ref then
  15118. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15119. end;
  15120. end.