aoptx86.pas 763 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  126. function PrePeepholeOptSxx(var p : tai) : boolean;
  127. function PrePeepholeOptIMUL(var p : tai) : boolean;
  128. function PrePeepholeOptAND(var p : tai) : boolean;
  129. function OptPass1Test(var p: tai): boolean;
  130. function OptPass1Add(var p: tai): boolean;
  131. function OptPass1AND(var p : tai) : boolean;
  132. function OptPass1CMOVcc(var p: tai): Boolean;
  133. function OptPass1_V_MOVAP(var p : tai) : boolean;
  134. function OptPass1VOP(var p : tai) : boolean;
  135. function OptPass1MOV(var p : tai) : boolean;
  136. function OptPass1MOVD(var p : tai) : boolean;
  137. function OptPass1Movx(var p : tai) : boolean;
  138. function OptPass1MOVXX(var p : tai) : boolean;
  139. function OptPass1OP(var p : tai) : boolean;
  140. function OptPass1LEA(var p : tai) : boolean;
  141. function OptPass1Sub(var p : tai) : boolean;
  142. function OptPass1SHLSAL(var p : tai) : boolean;
  143. function OptPass1SHR(var p : tai) : boolean;
  144. function OptPass1FSTP(var p : tai) : boolean;
  145. function OptPass1FLD(var p : tai) : boolean;
  146. function OptPass1Cmp(var p : tai) : boolean;
  147. function OptPass1PXor(var p : tai) : boolean;
  148. function OptPass1VPXor(var p: tai): boolean;
  149. function OptPass1Imul(var p : tai) : boolean;
  150. function OptPass1Jcc(var p : tai) : boolean;
  151. function OptPass1SHXX(var p: tai): boolean;
  152. function OptPass1VMOVDQ(var p: tai): Boolean;
  153. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  154. function OptPass1STCCLC(var p: tai): Boolean;
  155. function OptPass2STCCLC(var p: tai): Boolean;
  156. function OptPass2CMOVcc(var p: tai): Boolean;
  157. function OptPass2Movx(var p : tai): Boolean;
  158. function OptPass2MOV(var p : tai) : boolean;
  159. function OptPass2Imul(var p : tai) : boolean;
  160. function OptPass2Jmp(var p : tai) : boolean;
  161. function OptPass2Jcc(var p : tai) : boolean;
  162. function OptPass2Lea(var p: tai): Boolean;
  163. function OptPass2SUB(var p: tai): Boolean;
  164. function OptPass2ADD(var p : tai): Boolean;
  165. function OptPass2SETcc(var p : tai) : boolean;
  166. function OptPass2Cmp(var p: tai): Boolean;
  167. function OptPass2Test(var p: tai): Boolean;
  168. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  169. function PostPeepholeOptMov(var p : tai) : Boolean;
  170. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  171. function PostPeepholeOptXor(var p : tai) : Boolean;
  172. function PostPeepholeOptAnd(var p : tai) : boolean;
  173. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  174. function PostPeepholeOptCmp(var p : tai) : Boolean;
  175. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  176. function PostPeepholeOptCall(var p : tai) : Boolean;
  177. function PostPeepholeOptLea(var p : tai) : Boolean;
  178. function PostPeepholeOptPush(var p: tai): Boolean;
  179. function PostPeepholeOptShr(var p : tai) : boolean;
  180. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  181. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  182. function PostPeepholeOptRET(var p: tai): Boolean;
  183. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  184. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  185. function TrySwapMovOp(var p, hp1: tai): Boolean;
  186. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  187. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  188. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  189. { Processor-dependent reference optimisation }
  190. class procedure OptimizeRefs(var p: taicpu); static;
  191. end;
  192. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  194. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  195. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  196. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  197. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  198. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  199. {$if max_operands>2}
  200. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  201. {$endif max_operands>2}
  202. function RefsEqual(const r1, r2: treference): boolean;
  203. { Like RefsEqual, but doesn't compare the offsets }
  204. function RefsAlmostEqual(const r1, r2: treference): boolean;
  205. { Note that Result is set to True if the references COULD overlap but the
  206. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  207. might still overlap because %reg2 could be equal to %reg1-4 }
  208. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  209. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  210. { returns true, if ref is a reference using only the registers passed as base and index
  211. and having an offset }
  212. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  213. implementation
  214. uses
  215. cutils,verbose,
  216. systems,
  217. globals,
  218. cpuinfo,
  219. procinfo,
  220. paramgr,
  221. aasmbase,
  222. aoptbase,aoptutils,
  223. symconst,symsym,
  224. cgx86,
  225. itcpugas;
  226. {$ifndef 8086}
  227. const
  228. MAX_CMOV_INSTRUCTIONS = 4;
  229. MAX_CMOV_REGISTERS = 8;
  230. type
  231. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  232. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  233. tsProcessed);
  234. { For OptPass2Jcc }
  235. TCMOVTracking = object
  236. private
  237. CMOVScore, ConstCount: LongInt;
  238. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  239. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  240. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  241. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  242. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  243. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  244. fOptimizer: TX86AsmOptimizer;
  245. fLabel: TAsmSymbol;
  246. fInsertionPoint,
  247. fCondition,
  248. fInitialJump,
  249. fFirstMovBlock,
  250. fFirstMovBlockStop,
  251. fSecondJump,
  252. fThirdJump,
  253. fSecondMovBlock,
  254. fSecondMovBlockStop,
  255. fMidLabel,
  256. fEndLabel,
  257. fAllocationRange: tai;
  258. fState: TCMovTrackingState;
  259. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  260. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  261. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  262. public
  263. RegisterTracking: TAllUsedRegs;
  264. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  265. destructor Done;
  266. procedure Process(out new_p: tai);
  267. property State: TCMovTrackingState read fState;
  268. end;
  269. PCMOVTracking = ^TCMOVTracking;
  270. {$endif 8086}
  271. {$ifdef DEBUG_AOPTCPU}
  272. const
  273. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  274. {$else DEBUG_AOPTCPU}
  275. { Empty strings help the optimizer to remove string concatenations that won't
  276. ever appear to the user on release builds. [Kit] }
  277. const
  278. SPeepholeOptimization = '';
  279. {$endif DEBUG_AOPTCPU}
  280. LIST_STEP_SIZE = 4;
  281. type
  282. TJumpTrackingItem = class(TLinkedListItem)
  283. private
  284. FSymbol: TAsmSymbol;
  285. FRefs: LongInt;
  286. public
  287. constructor Create(ASymbol: TAsmSymbol);
  288. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  289. property Symbol: TAsmSymbol read FSymbol;
  290. property Refs: LongInt read FRefs;
  291. end;
  292. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  293. begin
  294. inherited Create;
  295. FSymbol := ASymbol;
  296. FRefs := 0;
  297. end;
  298. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  299. begin
  300. Inc(FRefs);
  301. end;
  302. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  303. begin
  304. result :=
  305. (instr.typ = ait_instruction) and
  306. (taicpu(instr).opcode = op) and
  307. ((opsize = []) or (taicpu(instr).opsize in opsize));
  308. end;
  309. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  310. begin
  311. result :=
  312. (instr.typ = ait_instruction) and
  313. ((taicpu(instr).opcode = op1) or
  314. (taicpu(instr).opcode = op2)
  315. ) and
  316. ((opsize = []) or (taicpu(instr).opsize in opsize));
  317. end;
  318. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  319. begin
  320. result :=
  321. (instr.typ = ait_instruction) and
  322. ((taicpu(instr).opcode = op1) or
  323. (taicpu(instr).opcode = op2) or
  324. (taicpu(instr).opcode = op3)
  325. ) and
  326. ((opsize = []) or (taicpu(instr).opsize in opsize));
  327. end;
  328. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  329. const opsize : topsizes) : boolean;
  330. var
  331. op : TAsmOp;
  332. begin
  333. result:=false;
  334. if (instr.typ <> ait_instruction) or
  335. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  336. exit;
  337. for op in ops do
  338. begin
  339. if taicpu(instr).opcode = op then
  340. begin
  341. result:=true;
  342. exit;
  343. end;
  344. end;
  345. end;
  346. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  347. begin
  348. result := (oper.typ = top_reg) and (oper.reg = reg);
  349. end;
  350. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  351. begin
  352. result := (oper.typ = top_const) and (oper.val = a);
  353. end;
  354. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  355. begin
  356. result := oper1.typ = oper2.typ;
  357. if result then
  358. case oper1.typ of
  359. top_const:
  360. Result:=oper1.val = oper2.val;
  361. top_reg:
  362. Result:=oper1.reg = oper2.reg;
  363. top_ref:
  364. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  365. else
  366. internalerror(2013102801);
  367. end
  368. end;
  369. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  370. begin
  371. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  372. if result then
  373. case oper1.typ of
  374. top_const:
  375. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  376. top_reg:
  377. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  378. top_ref:
  379. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  380. else
  381. internalerror(2020052401);
  382. end
  383. end;
  384. function RefsEqual(const r1, r2: treference): boolean;
  385. begin
  386. RefsEqual :=
  387. (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.offset = r2.offset) and
  392. (r1.volatility + r2.volatility = []);
  393. end;
  394. function RefsAlmostEqual(const r1, r2: treference): boolean;
  395. begin
  396. RefsAlmostEqual :=
  397. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  398. (r1.relsymbol = r2.relsymbol) and
  399. (r1.segment = r2.segment) and (r1.base = r2.base) and
  400. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  401. { Don't compare the offsets }
  402. (r1.volatility + r2.volatility = []);
  403. end;
  404. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  405. begin
  406. if (r1.symbol<>r2.symbol) then
  407. { If the index registers are different, there's a chance one could
  408. be set so it equals the other symbol }
  409. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  410. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  411. (r1.relsymbol = r2.relsymbol) and
  412. (r1.segment = r2.segment) and (r1.base = r2.base) and
  413. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  414. (r1.volatility + r2.volatility = []) then
  415. { In this case, it all depends on the offsets }
  416. Exit(abs(r1.offset - r2.offset) < Range);
  417. { There's a chance things MIGHT overlap, so take no chances }
  418. Result := True;
  419. end;
  420. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  421. begin
  422. Result:=(ref.offset=0) and
  423. (ref.scalefactor in [0,1]) and
  424. (ref.segment=NR_NO) and
  425. (ref.symbol=nil) and
  426. (ref.relsymbol=nil) and
  427. ((base=NR_INVALID) or
  428. (ref.base=base)) and
  429. ((index=NR_INVALID) or
  430. (ref.index=index)) and
  431. (ref.volatility=[]);
  432. end;
  433. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  434. begin
  435. Result:=(ref.scalefactor in [0,1]) and
  436. (ref.segment=NR_NO) and
  437. (ref.symbol=nil) and
  438. (ref.relsymbol=nil) and
  439. ((base=NR_INVALID) or
  440. (ref.base=base)) and
  441. ((index=NR_INVALID) or
  442. (ref.index=index)) and
  443. (ref.volatility=[]);
  444. end;
  445. function InstrReadsFlags(p: tai): boolean;
  446. begin
  447. InstrReadsFlags := true;
  448. case p.typ of
  449. ait_instruction:
  450. if InsProp[taicpu(p).opcode].Ch*
  451. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  452. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  453. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  454. exit;
  455. ait_label:
  456. exit;
  457. else
  458. ;
  459. end;
  460. InstrReadsFlags := false;
  461. end;
  462. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  463. begin
  464. Next:=Current;
  465. repeat
  466. Result:=GetNextInstruction(Next,Next);
  467. until not (Result) or
  468. not(cs_opt_level3 in current_settings.optimizerswitches) or
  469. (Next.typ<>ait_instruction) or
  470. RegInInstruction(reg,Next) or
  471. is_calljmp(taicpu(Next).opcode);
  472. end;
  473. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  474. var
  475. GetNextResult: Boolean;
  476. begin
  477. Result:=0;
  478. Next:=Current;
  479. repeat
  480. GetNextResult := GetNextInstruction(Next,Next);
  481. if GetNextResult then
  482. Inc(Result)
  483. else
  484. { Must return zero upon hitting the end of the linked list without a match }
  485. Result := 0;
  486. until not (GetNextResult) or
  487. not(cs_opt_level3 in current_settings.optimizerswitches) or
  488. (Next.typ<>ait_instruction) or
  489. RegInInstruction(reg,Next) or
  490. is_calljmp(taicpu(Next).opcode);
  491. end;
  492. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  493. procedure TrackJump(Symbol: TAsmSymbol);
  494. var
  495. Search: TJumpTrackingItem;
  496. begin
  497. { See if an entry already exists in our jump tracking list
  498. (faster to search backwards due to the higher chance of
  499. matching destinations) }
  500. Search := TJumpTrackingItem(JumpTracking.Last);
  501. while Assigned(Search) do
  502. begin
  503. if Search.Symbol = Symbol then
  504. begin
  505. { Found it - remove it so it can be pushed to the front }
  506. JumpTracking.Remove(Search);
  507. Break;
  508. end;
  509. Search := TJumpTrackingItem(Search.Previous);
  510. end;
  511. if not Assigned(Search) then
  512. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  513. JumpTracking.Concat(Search);
  514. Search.IncRefs;
  515. end;
  516. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  517. var
  518. Search: TJumpTrackingItem;
  519. begin
  520. Result := False;
  521. { See if this label appears in the tracking list }
  522. Search := TJumpTrackingItem(JumpTracking.Last);
  523. while Assigned(Search) do
  524. begin
  525. if Search.Symbol = Symbol then
  526. begin
  527. { Found it - let's see what we can discover }
  528. if Search.Symbol.getrefs = Search.Refs then
  529. begin
  530. { Success - all the references are accounted for }
  531. JumpTracking.Remove(Search);
  532. Search.Free;
  533. { It is logically impossible for CrossJump to be false here
  534. because we must have run into a conditional jump for
  535. this label at some point }
  536. if not CrossJump then
  537. InternalError(2022041710);
  538. if JumpTracking.First = nil then
  539. { Tracking list is now empty - no more cross jumps }
  540. CrossJump := False;
  541. Result := True;
  542. Exit;
  543. end;
  544. { If the references don't match, it's possible to enter
  545. this label through other means, so drop out }
  546. Exit;
  547. end;
  548. Search := TJumpTrackingItem(Search.Previous);
  549. end;
  550. end;
  551. var
  552. Next_Label: tai;
  553. begin
  554. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  555. Next := Current;
  556. repeat
  557. Result := GetNextInstruction(Next,Next);
  558. if not Result then
  559. Break;
  560. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  561. if is_calljmpuncondret(taicpu(Next).opcode) then
  562. begin
  563. if (taicpu(Next).opcode = A_JMP) and
  564. { Remove dead code now to save time }
  565. RemoveDeadCodeAfterJump(taicpu(Next)) then
  566. { A jump was removed, but not the current instruction, and
  567. Result doesn't necessarily translate into an optimisation
  568. routine's Result, so use the "Force New Iteration" flag so
  569. mark a new pass }
  570. Include(OptsToCheck, aoc_ForceNewIteration);
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if IsJumpToLabel(taicpu(Next)) and
  582. GetNextInstruction(Next, Next_Label) then
  583. begin
  584. { If we have JMP .lbl, and the label after it has all of its
  585. references tracked, then this is probably an if-else style of
  586. block and we can keep tracking. If the label for this jump
  587. then appears later and is fully tracked, then it's the end
  588. of the if-else blocks and the code paths converge (thus
  589. marking the end of the cross-jump) }
  590. if (Next_Label.typ = ait_label) then
  591. begin
  592. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  593. begin
  594. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  595. Next := Next_Label;
  596. { CrossJump gets set to false by LabelAccountedFor if the
  597. list is completely emptied (as it indicates that all
  598. code paths have converged). We could avoid this nuance
  599. by moving the TrackJump call to before the
  600. LabelAccountedFor call, but this is slower in situations
  601. where LabelAccountedFor would return False due to the
  602. creation of a new object that is not used and destroyed
  603. soon after. }
  604. CrossJump := True;
  605. Continue;
  606. end;
  607. end
  608. else if (Next_Label.typ <> ait_marker) then
  609. { We just did a RemoveDeadCodeAfterJump, so either we find
  610. a label, the end of the procedure or some kind of marker}
  611. InternalError(2022041720);
  612. end;
  613. Result := False;
  614. Exit;
  615. end
  616. else
  617. begin
  618. if not Assigned(JumpTracking) then
  619. begin
  620. { Cross-label optimisations often causes other optimisations
  621. to perform worse because they're not given the chance to
  622. optimise locally. In this case, don't do the cross-label
  623. optimisations yet, but flag them as a potential possibility
  624. for the next iteration of Pass 1 }
  625. if not NotFirstIteration then
  626. Include(OptsToCheck, aoc_ForceNewIteration);
  627. end
  628. else if IsJumpToLabel(taicpu(Next)) then
  629. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  630. else
  631. { Conditional jumps should always be a jump to label }
  632. InternalError(2022041701);
  633. CrossJump := True;
  634. Continue;
  635. end;
  636. if Next.typ = ait_label then
  637. begin
  638. if not Assigned(JumpTracking) then
  639. begin
  640. { Cross-label optimisations often causes other optimisations
  641. to perform worse because they're not given the chance to
  642. optimise locally. In this case, don't do the cross-label
  643. optimisations yet, but flag them as a potential possibility
  644. for the next iteration of Pass 1 }
  645. if not NotFirstIteration then
  646. Include(OptsToCheck, aoc_ForceNewIteration);
  647. end
  648. else if LabelAccountedFor(tai_label(Next).labsym) then
  649. Continue;
  650. { If we reach here, we're at a label that hasn't been seen before
  651. (or JumpTracking was nil) }
  652. Break;
  653. end;
  654. until not Result or
  655. not (cs_opt_level3 in current_settings.optimizerswitches) or
  656. not (Next.typ in [ait_label, ait_instruction]) or
  657. RegInInstruction(reg,Next);
  658. end;
  659. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  660. begin
  661. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  662. begin
  663. Result:=GetNextInstruction(Current,Next);
  664. exit;
  665. end;
  666. Next:=tai(Current.Next);
  667. Result:=false;
  668. while assigned(Next) do
  669. begin
  670. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  671. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  672. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  673. exit
  674. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  675. begin
  676. Result:=true;
  677. exit;
  678. end;
  679. Next:=tai(Next.Next);
  680. end;
  681. end;
  682. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  683. begin
  684. Result:=RegReadByInstruction(reg,hp);
  685. end;
  686. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  687. var
  688. p: taicpu;
  689. opcount: longint;
  690. begin
  691. RegReadByInstruction := false;
  692. if hp.typ <> ait_instruction then
  693. exit;
  694. p := taicpu(hp);
  695. case p.opcode of
  696. A_CALL:
  697. regreadbyinstruction := true;
  698. A_IMUL:
  699. case p.ops of
  700. 1:
  701. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  702. (
  703. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  704. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  705. );
  706. 2,3:
  707. regReadByInstruction :=
  708. reginop(reg,p.oper[0]^) or
  709. reginop(reg,p.oper[1]^);
  710. else
  711. InternalError(2019112801);
  712. end;
  713. A_MUL:
  714. begin
  715. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  716. (
  717. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  718. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  719. );
  720. end;
  721. A_IDIV,A_DIV:
  722. begin
  723. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  724. (
  725. (getregtype(reg)=R_INTREGISTER) and
  726. (
  727. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  728. )
  729. );
  730. end;
  731. else
  732. begin
  733. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  734. begin
  735. RegReadByInstruction := false;
  736. exit;
  737. end;
  738. for opcount := 0 to p.ops-1 do
  739. if (p.oper[opCount]^.typ = top_ref) and
  740. RegInRef(reg,p.oper[opcount]^.ref^) then
  741. begin
  742. RegReadByInstruction := true;
  743. exit
  744. end;
  745. { special handling for SSE MOVSD }
  746. if (p.opcode=A_MOVSD) and (p.ops>0) then
  747. begin
  748. if p.ops<>2 then
  749. internalerror(2017042702);
  750. regReadByInstruction := reginop(reg,p.oper[0]^) or
  751. (
  752. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  753. );
  754. exit;
  755. end;
  756. with insprop[p.opcode] do
  757. begin
  758. case getregtype(reg) of
  759. R_INTREGISTER:
  760. begin
  761. case getsupreg(reg) of
  762. RS_EAX:
  763. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  764. begin
  765. RegReadByInstruction := true;
  766. exit
  767. end;
  768. RS_ECX:
  769. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  770. begin
  771. RegReadByInstruction := true;
  772. exit
  773. end;
  774. RS_EDX:
  775. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  776. begin
  777. RegReadByInstruction := true;
  778. exit
  779. end;
  780. RS_EBX:
  781. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  782. begin
  783. RegReadByInstruction := true;
  784. exit
  785. end;
  786. RS_ESP:
  787. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  788. begin
  789. RegReadByInstruction := true;
  790. exit
  791. end;
  792. RS_EBP:
  793. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  794. begin
  795. RegReadByInstruction := true;
  796. exit
  797. end;
  798. RS_ESI:
  799. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  800. begin
  801. RegReadByInstruction := true;
  802. exit
  803. end;
  804. RS_EDI:
  805. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  806. begin
  807. RegReadByInstruction := true;
  808. exit
  809. end;
  810. end;
  811. end;
  812. R_MMREGISTER:
  813. begin
  814. case getsupreg(reg) of
  815. RS_XMM0:
  816. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  817. begin
  818. RegReadByInstruction := true;
  819. exit
  820. end;
  821. end;
  822. end;
  823. else
  824. ;
  825. end;
  826. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  827. begin
  828. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  829. begin
  830. case p.condition of
  831. C_A,C_NBE, { CF=0 and ZF=0 }
  832. C_BE,C_NA: { CF=1 or ZF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  834. C_AE,C_NB,C_NC, { CF=0 }
  835. C_B,C_NAE,C_C: { CF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  837. C_NE,C_NZ, { ZF=0 }
  838. C_E,C_Z: { ZF=1 }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  840. C_G,C_NLE, { ZF=0 and SF=OF }
  841. C_LE,C_NG: { ZF=1 or SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_GE,C_NL, { SF=OF }
  844. C_L,C_NGE: { SF<>OF }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  846. C_NO, { OF=0 }
  847. C_O: { OF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  849. C_NP,C_PO, { PF=0 }
  850. C_P,C_PE: { PF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  852. C_NS, { SF=0 }
  853. C_S: { SF=1 }
  854. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  855. else
  856. internalerror(2017042701);
  857. end;
  858. if RegReadByInstruction then
  859. exit;
  860. end;
  861. case getsubreg(reg) of
  862. R_SUBW,R_SUBD,R_SUBQ:
  863. RegReadByInstruction :=
  864. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  865. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  866. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  867. R_SUBFLAGCARRY:
  868. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  869. R_SUBFLAGPARITY:
  870. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  871. R_SUBFLAGAUXILIARY:
  872. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  873. R_SUBFLAGZERO:
  874. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  875. R_SUBFLAGSIGN:
  876. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  877. R_SUBFLAGOVERFLOW:
  878. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGINTERRUPT:
  880. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. R_SUBFLAGDIRECTION:
  882. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  883. else
  884. internalerror(2017042601);
  885. end;
  886. exit;
  887. end;
  888. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  889. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  890. (p.oper[0]^.reg=p.oper[1]^.reg) then
  891. exit;
  892. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  893. begin
  894. RegReadByInstruction := true;
  895. exit
  896. end;
  897. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  898. begin
  899. RegReadByInstruction := true;
  900. exit
  901. end;
  902. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  903. begin
  904. RegReadByInstruction := true;
  905. exit
  906. end;
  907. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  908. begin
  909. RegReadByInstruction := true;
  910. exit
  911. end;
  912. end;
  913. end;
  914. end;
  915. end;
  916. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  917. begin
  918. result:=false;
  919. if p1.typ<>ait_instruction then
  920. exit;
  921. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  922. exit(true);
  923. if (getregtype(reg)=R_INTREGISTER) and
  924. { change information for xmm movsd are not correct }
  925. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  926. begin
  927. { Handle instructions that behave differently depending on the size and operand count }
  928. case taicpu(p1).opcode of
  929. A_MUL, A_DIV, A_IDIV:
  930. if taicpu(p1).opsize = S_B then
  931. Result := (getsupreg(Reg) = RS_EAX)
  932. else
  933. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  934. A_IMUL:
  935. if taicpu(p1).ops = 1 then
  936. begin
  937. if taicpu(p1).opsize = S_B then
  938. Result := (getsupreg(Reg) = RS_EAX)
  939. else
  940. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  941. end;
  942. { If ops are greater than 1, call inherited method }
  943. else
  944. case getsupreg(reg) of
  945. { RS_EAX = RS_RAX on x86-64 }
  946. RS_EAX:
  947. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  948. RS_ECX:
  949. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  950. RS_EDX:
  951. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  952. RS_EBX:
  953. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  954. RS_ESP:
  955. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  956. RS_EBP:
  957. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_ESI:
  959. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. RS_EDI:
  961. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  962. else
  963. ;
  964. end;
  965. end;
  966. if result then
  967. exit;
  968. end
  969. else if getregtype(reg)=R_MMREGISTER then
  970. begin
  971. case getsupreg(reg) of
  972. RS_XMM0:
  973. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. else
  975. ;
  976. end;
  977. if result then
  978. exit;
  979. end
  980. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  981. begin
  982. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  983. exit(true);
  984. case getsubreg(reg) of
  985. R_SUBFLAGCARRY:
  986. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  987. R_SUBFLAGPARITY:
  988. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  989. R_SUBFLAGAUXILIARY:
  990. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  991. R_SUBFLAGZERO:
  992. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  993. R_SUBFLAGSIGN:
  994. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  995. R_SUBFLAGOVERFLOW:
  996. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGINTERRUPT:
  998. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBFLAGDIRECTION:
  1000. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1001. R_SUBW,R_SUBD,R_SUBQ:
  1002. { Everything except the direction bits }
  1003. Result:=
  1004. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1005. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1006. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1007. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1008. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1009. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1010. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1011. else
  1012. ;
  1013. end;
  1014. if result then
  1015. exit;
  1016. end
  1017. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1018. exit(true);
  1019. Result:=inherited RegInInstruction(Reg, p1);
  1020. end;
  1021. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1022. const
  1023. WriteOps: array[0..3] of set of TInsChange =
  1024. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1025. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1026. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1027. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1028. var
  1029. OperIdx: Integer;
  1030. begin
  1031. Result := False;
  1032. if p1.typ <> ait_instruction then
  1033. exit;
  1034. with insprop[taicpu(p1).opcode] do
  1035. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1036. begin
  1037. case getsubreg(reg) of
  1038. R_SUBW,R_SUBD,R_SUBQ:
  1039. Result :=
  1040. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1041. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1042. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1043. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1044. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1045. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1046. R_SUBFLAGCARRY:
  1047. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1048. R_SUBFLAGPARITY:
  1049. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1050. R_SUBFLAGAUXILIARY:
  1051. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1052. R_SUBFLAGZERO:
  1053. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1054. R_SUBFLAGSIGN:
  1055. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGOVERFLOW:
  1057. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGINTERRUPT:
  1059. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. R_SUBFLAGDIRECTION:
  1061. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1062. else
  1063. internalerror(2017042602);
  1064. end;
  1065. exit;
  1066. end;
  1067. case taicpu(p1).opcode of
  1068. A_CALL:
  1069. { We could potentially set Result to False if the register in
  1070. question is non-volatile for the subroutine's calling convention,
  1071. but this would require detecting the calling convention in use and
  1072. also assuming that the routine doesn't contain malformed assembly
  1073. language, for example... so it could only be done under -O4 as it
  1074. would be considered a side-effect. [Kit] }
  1075. Result := True;
  1076. A_MOVSD:
  1077. { special handling for SSE MOVSD }
  1078. if (taicpu(p1).ops>0) then
  1079. begin
  1080. if taicpu(p1).ops<>2 then
  1081. internalerror(2017042703);
  1082. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1083. end;
  1084. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1085. so fix it here (FK)
  1086. }
  1087. A_VMOVSS,
  1088. A_VMOVSD:
  1089. begin
  1090. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1091. exit;
  1092. end;
  1093. A_MUL, A_DIV, A_IDIV:
  1094. begin
  1095. if taicpu(p1).opsize = S_B then
  1096. Result := (getsupreg(Reg) = RS_EAX)
  1097. else
  1098. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1099. end;
  1100. A_IMUL:
  1101. begin
  1102. if taicpu(p1).ops = 1 then
  1103. begin
  1104. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1105. end
  1106. else
  1107. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1108. Exit;
  1109. end;
  1110. else
  1111. ;
  1112. end;
  1113. if Result then
  1114. exit;
  1115. with insprop[taicpu(p1).opcode] do
  1116. begin
  1117. if getregtype(reg)=R_INTREGISTER then
  1118. begin
  1119. case getsupreg(reg) of
  1120. RS_EAX:
  1121. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1122. begin
  1123. Result := True;
  1124. exit
  1125. end;
  1126. RS_ECX:
  1127. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1128. begin
  1129. Result := True;
  1130. exit
  1131. end;
  1132. RS_EDX:
  1133. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1134. begin
  1135. Result := True;
  1136. exit
  1137. end;
  1138. RS_EBX:
  1139. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1140. begin
  1141. Result := True;
  1142. exit
  1143. end;
  1144. RS_ESP:
  1145. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1146. begin
  1147. Result := True;
  1148. exit
  1149. end;
  1150. RS_EBP:
  1151. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1152. begin
  1153. Result := True;
  1154. exit
  1155. end;
  1156. RS_ESI:
  1157. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1158. begin
  1159. Result := True;
  1160. exit
  1161. end;
  1162. RS_EDI:
  1163. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1164. begin
  1165. Result := True;
  1166. exit
  1167. end;
  1168. end;
  1169. end;
  1170. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1171. if (WriteOps[OperIdx]*Ch<>[]) and
  1172. { The register doesn't get modified inside a reference }
  1173. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1174. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1175. begin
  1176. Result := true;
  1177. exit
  1178. end;
  1179. end;
  1180. end;
  1181. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1182. const
  1183. WriteOps: array[0..3] of set of TInsChange =
  1184. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1185. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1186. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1187. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1188. var
  1189. X: Integer;
  1190. CurrentP1Size: asizeint;
  1191. begin
  1192. Result := (
  1193. (Ref.base <> NR_NO) and
  1194. {$ifdef x86_64}
  1195. (Ref.base <> NR_RIP) and
  1196. {$endif x86_64}
  1197. RegModifiedBetween(Ref.base, p1, p2)
  1198. ) or
  1199. (
  1200. (Ref.index <> NR_NO) and
  1201. (Ref.index <> Ref.base) and
  1202. RegModifiedBetween(Ref.index, p1, p2)
  1203. );
  1204. { Now check to see if the memory itself is written to }
  1205. if not Result then
  1206. begin
  1207. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1208. if p1.typ = ait_instruction then
  1209. begin
  1210. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1211. with insprop[taicpu(p1).opcode] do
  1212. for X := 0 to taicpu(p1).ops - 1 do
  1213. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1214. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1215. { Catch any potential overlaps }
  1216. (
  1217. (RefSize = 0) or
  1218. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1219. ) and
  1220. (
  1221. (CurrentP1Size = 0) or
  1222. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1223. ) and
  1224. { Reference is used, but does the instruction write to it? }
  1225. (
  1226. (Ch_All in Ch) or
  1227. ((WriteOps[X] * Ch) <> [])
  1228. ) then
  1229. begin
  1230. Result := True;
  1231. Break;
  1232. end;
  1233. end;
  1234. end;
  1235. end;
  1236. {$ifdef DEBUG_AOPTCPU}
  1237. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1238. begin
  1239. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1240. end;
  1241. function debug_tostr(i: tcgint): string; inline;
  1242. begin
  1243. Result := tostr(i);
  1244. end;
  1245. function debug_hexstr(i: tcgint): string;
  1246. begin
  1247. Result := '0x';
  1248. case i of
  1249. 0..$FF:
  1250. Result := Result + hexstr(i, 2);
  1251. $100..$FFFF:
  1252. Result := Result + hexstr(i, 4);
  1253. $10000..$FFFFFF:
  1254. Result := Result + hexstr(i, 6);
  1255. $1000000..$FFFFFFFF:
  1256. Result := Result + hexstr(i, 8);
  1257. else
  1258. Result := Result + hexstr(i, 16);
  1259. end;
  1260. end;
  1261. function debug_regname(r: TRegister): string; inline;
  1262. begin
  1263. Result := '%' + std_regname(r);
  1264. end;
  1265. { Debug output function - creates a string representation of an operator }
  1266. function debug_operstr(oper: TOper): string;
  1267. begin
  1268. case oper.typ of
  1269. top_const:
  1270. Result := '$' + debug_tostr(oper.val);
  1271. top_reg:
  1272. Result := debug_regname(oper.reg);
  1273. top_ref:
  1274. begin
  1275. if oper.ref^.offset <> 0 then
  1276. Result := debug_tostr(oper.ref^.offset) + '('
  1277. else
  1278. Result := '(';
  1279. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1280. begin
  1281. Result := Result + debug_regname(oper.ref^.base);
  1282. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1283. Result := Result + ',' + debug_regname(oper.ref^.index);
  1284. end
  1285. else
  1286. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1287. Result := Result + debug_regname(oper.ref^.index);
  1288. if (oper.ref^.scalefactor > 1) then
  1289. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1290. else
  1291. Result := Result + ')';
  1292. end;
  1293. else
  1294. Result := '[UNKNOWN]';
  1295. end;
  1296. end;
  1297. function debug_op2str(opcode: tasmop): string; inline;
  1298. begin
  1299. Result := std_op2str[opcode];
  1300. end;
  1301. function debug_opsize2str(opsize: topsize): string; inline;
  1302. begin
  1303. Result := gas_opsize2str[opsize];
  1304. end;
  1305. {$else DEBUG_AOPTCPU}
  1306. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1307. begin
  1308. end;
  1309. function debug_tostr(i: tcgint): string; inline;
  1310. begin
  1311. Result := '';
  1312. end;
  1313. function debug_hexstr(i: tcgint): string; inline;
  1314. begin
  1315. Result := '';
  1316. end;
  1317. function debug_regname(r: TRegister): string; inline;
  1318. begin
  1319. Result := '';
  1320. end;
  1321. function debug_operstr(oper: TOper): string; inline;
  1322. begin
  1323. Result := '';
  1324. end;
  1325. function debug_op2str(opcode: tasmop): string; inline;
  1326. begin
  1327. Result := '';
  1328. end;
  1329. function debug_opsize2str(opsize: topsize): string; inline;
  1330. begin
  1331. Result := '';
  1332. end;
  1333. {$endif DEBUG_AOPTCPU}
  1334. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1335. begin
  1336. {$ifdef x86_64}
  1337. { Always fine on x86-64 }
  1338. Result := True;
  1339. {$else x86_64}
  1340. Result :=
  1341. {$ifdef i8086}
  1342. (current_settings.cputype >= cpu_386) and
  1343. {$endif i8086}
  1344. (
  1345. { Always accept if optimising for size }
  1346. (cs_opt_size in current_settings.optimizerswitches) or
  1347. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1348. (current_settings.optimizecputype >= cpu_Pentium2)
  1349. );
  1350. {$endif x86_64}
  1351. end;
  1352. { Attempts to allocate a volatile integer register for use between p and hp,
  1353. using AUsedRegs for the current register usage information. Returns NR_NO
  1354. if no free register could be found }
  1355. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1356. var
  1357. RegSet: TCPURegisterSet;
  1358. CurrentSuperReg: Integer;
  1359. CurrentReg: TRegister;
  1360. Currentp: tai;
  1361. Breakout: Boolean;
  1362. begin
  1363. Result := NR_NO;
  1364. RegSet :=
  1365. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1366. current_procinfo.saved_regs_int;
  1367. (*
  1368. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1369. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1370. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1371. *)
  1372. for CurrentSuperReg in RegSet do
  1373. begin
  1374. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1375. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1376. {$if defined(i386) or defined(i8086)}
  1377. { If the target size is 8-bit, make sure we can actually encode it }
  1378. and (
  1379. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1380. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1381. )
  1382. {$endif i386 or i8086}
  1383. then
  1384. begin
  1385. Currentp := p;
  1386. Breakout := False;
  1387. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1388. begin
  1389. case Currentp.typ of
  1390. ait_instruction:
  1391. begin
  1392. if RegInInstruction(CurrentReg, Currentp) then
  1393. begin
  1394. Breakout := True;
  1395. Break;
  1396. end;
  1397. { Cannot allocate across an unconditional jump }
  1398. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1399. Exit;
  1400. end;
  1401. ait_marker:
  1402. { Don't try anything more if a marker is hit }
  1403. Exit;
  1404. ait_regalloc:
  1405. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1406. begin
  1407. Breakout := True;
  1408. Break;
  1409. end;
  1410. else
  1411. ;
  1412. end;
  1413. end;
  1414. if Breakout then
  1415. { Try the next register }
  1416. Continue;
  1417. { We have a free register available }
  1418. Result := CurrentReg;
  1419. if not DontAlloc then
  1420. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1421. Exit;
  1422. end;
  1423. end;
  1424. end;
  1425. { Attempts to allocate a volatile MM register for use between p and hp,
  1426. using AUsedRegs for the current register usage information. Returns NR_NO
  1427. if no free register could be found }
  1428. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1429. var
  1430. RegSet: TCPURegisterSet;
  1431. CurrentSuperReg: Integer;
  1432. CurrentReg: TRegister;
  1433. Currentp: tai;
  1434. Breakout: Boolean;
  1435. begin
  1436. Result := NR_NO;
  1437. RegSet :=
  1438. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1439. current_procinfo.saved_regs_mm;
  1440. for CurrentSuperReg in RegSet do
  1441. begin
  1442. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1443. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1444. begin
  1445. Currentp := p;
  1446. Breakout := False;
  1447. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1448. begin
  1449. case Currentp.typ of
  1450. ait_instruction:
  1451. begin
  1452. if RegInInstruction(CurrentReg, Currentp) then
  1453. begin
  1454. Breakout := True;
  1455. Break;
  1456. end;
  1457. { Cannot allocate across an unconditional jump }
  1458. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1459. Exit;
  1460. end;
  1461. ait_marker:
  1462. { Don't try anything more if a marker is hit }
  1463. Exit;
  1464. ait_regalloc:
  1465. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1466. begin
  1467. Breakout := True;
  1468. Break;
  1469. end;
  1470. else
  1471. ;
  1472. end;
  1473. end;
  1474. if Breakout then
  1475. { Try the next register }
  1476. Continue;
  1477. { We have a free register available }
  1478. Result := CurrentReg;
  1479. if not DontAlloc then
  1480. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1481. Exit;
  1482. end;
  1483. end;
  1484. end;
  1485. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1486. begin
  1487. if not SuperRegistersEqual(reg1,reg2) then
  1488. exit(false);
  1489. if getregtype(reg1)<>R_INTREGISTER then
  1490. exit(true); {because SuperRegisterEqual is true}
  1491. case getsubreg(reg1) of
  1492. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1493. higher, it preserves the high bits, so the new value depends on
  1494. reg2's previous value. In other words, it is equivalent to doing:
  1495. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1496. R_SUBL:
  1497. exit(getsubreg(reg2)=R_SUBL);
  1498. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1499. higher, it actually does a:
  1500. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1501. R_SUBH:
  1502. exit(getsubreg(reg2)=R_SUBH);
  1503. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1504. bits of reg2:
  1505. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1506. R_SUBW:
  1507. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1508. { a write to R_SUBD always overwrites every other subregister,
  1509. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1510. R_SUBD,
  1511. R_SUBQ:
  1512. exit(true);
  1513. else
  1514. internalerror(2017042801);
  1515. end;
  1516. end;
  1517. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1518. begin
  1519. if not SuperRegistersEqual(reg1,reg2) then
  1520. exit(false);
  1521. if getregtype(reg1)<>R_INTREGISTER then
  1522. exit(true); {because SuperRegisterEqual is true}
  1523. case getsubreg(reg1) of
  1524. R_SUBL:
  1525. exit(getsubreg(reg2)<>R_SUBH);
  1526. R_SUBH:
  1527. exit(getsubreg(reg2)<>R_SUBL);
  1528. R_SUBW,
  1529. R_SUBD,
  1530. R_SUBQ:
  1531. exit(true);
  1532. else
  1533. internalerror(2017042802);
  1534. end;
  1535. end;
  1536. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1537. var
  1538. hp1 : tai;
  1539. l : TCGInt;
  1540. begin
  1541. result:=false;
  1542. if not(GetNextInstruction(p, hp1)) then
  1543. exit;
  1544. { changes the code sequence
  1545. shr/sar const1, x
  1546. shl const2, x
  1547. to
  1548. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1549. if (taicpu(p).oper[0]^.typ = top_const) and
  1550. MatchInstruction(hp1,A_SHL,[]) and
  1551. (taicpu(hp1).oper[0]^.typ = top_const) and
  1552. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1553. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1554. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1555. begin
  1556. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1557. not(cs_opt_size in current_settings.optimizerswitches)
  1558. {$ifdef x86_64}
  1559. and (
  1560. (taicpu(p).opsize <> S_Q) or
  1561. { 64-bit AND can only store signed 32-bit immediates }
  1562. (taicpu(p).oper[0]^.val < 32)
  1563. )
  1564. {$endif x86_64}
  1565. then
  1566. begin
  1567. { shr/sar const1, %reg
  1568. shl const2, %reg
  1569. with const1 > const2 }
  1570. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1571. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1572. taicpu(hp1).opcode := A_AND;
  1573. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1574. case taicpu(p).opsize Of
  1575. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1576. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1577. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1578. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1579. else
  1580. Internalerror(2017050703)
  1581. end;
  1582. end
  1583. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1584. not(cs_opt_size in current_settings.optimizerswitches)
  1585. {$ifdef x86_64}
  1586. and (
  1587. (taicpu(p).opsize <> S_Q) or
  1588. { 64-bit AND can only store signed 32-bit immediates }
  1589. (taicpu(p).oper[0]^.val < 32)
  1590. )
  1591. {$endif x86_64}
  1592. then
  1593. begin
  1594. { shr/sar const1, %reg
  1595. shl const2, %reg
  1596. with const1 < const2 }
  1597. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1598. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1599. taicpu(p).opcode := A_AND;
  1600. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1601. case taicpu(p).opsize Of
  1602. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1603. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1604. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1605. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1606. else
  1607. Internalerror(2017050702)
  1608. end;
  1609. end
  1610. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1611. {$ifdef x86_64}
  1612. and (
  1613. (taicpu(p).opsize <> S_Q) or
  1614. { 64-bit AND can only store signed 32-bit immediates }
  1615. (taicpu(p).oper[0]^.val < 32)
  1616. )
  1617. {$endif x86_64}
  1618. then
  1619. begin
  1620. { shr/sar const1, %reg
  1621. shl const2, %reg
  1622. with const1 = const2 }
  1623. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1624. taicpu(p).opcode := A_AND;
  1625. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1626. case taicpu(p).opsize Of
  1627. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1628. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1629. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1630. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1631. else
  1632. Internalerror(2017050701)
  1633. end;
  1634. RemoveInstruction(hp1);
  1635. end;
  1636. end;
  1637. end;
  1638. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1639. var
  1640. opsize : topsize;
  1641. hp1, hp2 : tai;
  1642. tmpref : treference;
  1643. ShiftValue : Cardinal;
  1644. BaseValue : TCGInt;
  1645. begin
  1646. result:=false;
  1647. opsize:=taicpu(p).opsize;
  1648. { changes certain "imul const, %reg"'s to lea sequences }
  1649. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1650. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1651. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1652. if (taicpu(p).oper[0]^.val = 1) then
  1653. if (taicpu(p).ops = 2) then
  1654. { remove "imul $1, reg" }
  1655. begin
  1656. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1657. Result := RemoveCurrentP(p);
  1658. end
  1659. else
  1660. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1661. begin
  1662. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1663. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1664. asml.InsertAfter(hp1, p);
  1665. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1666. RemoveCurrentP(p, hp1);
  1667. Result := True;
  1668. end
  1669. else if ((taicpu(p).ops <= 2) or
  1670. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1671. not(cs_opt_size in current_settings.optimizerswitches) and
  1672. (not(GetNextInstruction(p, hp1)) or
  1673. not((tai(hp1).typ = ait_instruction) and
  1674. ((taicpu(hp1).opcode=A_Jcc) and
  1675. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1676. begin
  1677. {
  1678. imul X, reg1, reg2 to
  1679. lea (reg1,reg1,Y), reg2
  1680. shl ZZ,reg2
  1681. imul XX, reg1 to
  1682. lea (reg1,reg1,YY), reg1
  1683. shl ZZ,reg2
  1684. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1685. it does not exist as a separate optimization target in FPC though.
  1686. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1687. at most two zeros
  1688. }
  1689. reference_reset(tmpref,1,[]);
  1690. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1691. begin
  1692. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1693. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1694. TmpRef.base := taicpu(p).oper[1]^.reg;
  1695. TmpRef.index := taicpu(p).oper[1]^.reg;
  1696. if not(BaseValue in [3,5,9]) then
  1697. Internalerror(2018110101);
  1698. TmpRef.ScaleFactor := BaseValue-1;
  1699. if (taicpu(p).ops = 2) then
  1700. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1701. else
  1702. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1703. AsmL.InsertAfter(hp1,p);
  1704. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1705. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1706. RemoveCurrentP(p, hp1);
  1707. if ShiftValue>0 then
  1708. begin
  1709. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1710. AsmL.InsertAfter(hp2,hp1);
  1711. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1712. end;
  1713. Result := True;
  1714. end;
  1715. end;
  1716. end;
  1717. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1718. begin
  1719. Result := False;
  1720. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1721. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1722. begin
  1723. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1724. taicpu(p).opcode := A_MOV;
  1725. Result := True;
  1726. end;
  1727. end;
  1728. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1729. var
  1730. p: taicpu absolute hp; { Implicit typecast }
  1731. i: Integer;
  1732. begin
  1733. Result := False;
  1734. if not assigned(hp) or
  1735. (hp.typ <> ait_instruction) then
  1736. Exit;
  1737. Prefetch(insprop[p.opcode]);
  1738. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1739. with insprop[p.opcode] do
  1740. begin
  1741. case getsubreg(reg) of
  1742. R_SUBW,R_SUBD,R_SUBQ:
  1743. Result:=
  1744. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1745. uncommon flags are checked first }
  1746. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1747. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1748. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1749. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1750. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1751. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1752. R_SUBFLAGCARRY:
  1753. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1754. R_SUBFLAGPARITY:
  1755. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1756. R_SUBFLAGAUXILIARY:
  1757. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1758. R_SUBFLAGZERO:
  1759. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1760. R_SUBFLAGSIGN:
  1761. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1762. R_SUBFLAGOVERFLOW:
  1763. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1764. R_SUBFLAGINTERRUPT:
  1765. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1766. R_SUBFLAGDIRECTION:
  1767. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1768. else
  1769. internalerror(2017050501);
  1770. end;
  1771. exit;
  1772. end;
  1773. { Handle special cases first }
  1774. case p.opcode of
  1775. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1776. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1777. begin
  1778. Result :=
  1779. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1780. (p.oper[1]^.typ = top_reg) and
  1781. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1782. (
  1783. (p.oper[0]^.typ = top_const) or
  1784. (
  1785. (p.oper[0]^.typ = top_reg) and
  1786. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1787. ) or (
  1788. (p.oper[0]^.typ = top_ref) and
  1789. not RegInRef(reg,p.oper[0]^.ref^)
  1790. )
  1791. );
  1792. end;
  1793. A_MUL, A_IMUL:
  1794. Result :=
  1795. (
  1796. (p.ops=3) and { IMUL only }
  1797. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1798. (
  1799. (
  1800. (p.oper[1]^.typ=top_reg) and
  1801. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1802. ) or (
  1803. (p.oper[1]^.typ=top_ref) and
  1804. not RegInRef(reg,p.oper[1]^.ref^)
  1805. )
  1806. )
  1807. ) or (
  1808. (
  1809. (p.ops=1) and
  1810. (
  1811. (
  1812. (
  1813. (p.oper[0]^.typ=top_reg) and
  1814. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1815. )
  1816. ) or (
  1817. (p.oper[0]^.typ=top_ref) and
  1818. not RegInRef(reg,p.oper[0]^.ref^)
  1819. )
  1820. ) and (
  1821. (
  1822. (p.opsize=S_B) and
  1823. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1824. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1825. ) or (
  1826. (p.opsize=S_W) and
  1827. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1828. ) or (
  1829. (p.opsize=S_L) and
  1830. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1831. {$ifdef x86_64}
  1832. ) or (
  1833. (p.opsize=S_Q) and
  1834. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1835. {$endif x86_64}
  1836. )
  1837. )
  1838. )
  1839. );
  1840. A_CBW:
  1841. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1842. {$ifndef x86_64}
  1843. A_LDS:
  1844. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1845. A_LES:
  1846. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1847. {$endif not x86_64}
  1848. A_LFS:
  1849. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1850. A_LGS:
  1851. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1852. A_LSS:
  1853. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1854. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1855. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1856. A_LODSB:
  1857. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1858. A_LODSW:
  1859. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1860. {$ifdef x86_64}
  1861. A_LODSQ:
  1862. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1863. {$endif x86_64}
  1864. A_LODSD:
  1865. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1866. A_FSTSW, A_FNSTSW:
  1867. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1868. else
  1869. begin
  1870. with insprop[p.opcode] do
  1871. begin
  1872. if (
  1873. { xor %reg,%reg etc. is classed as a new value }
  1874. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1875. MatchOpType(p, top_reg, top_reg) and
  1876. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1877. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1878. ) then
  1879. begin
  1880. Result := True;
  1881. Exit;
  1882. end;
  1883. { Make sure the entire register is overwritten }
  1884. if (getregtype(reg) = R_INTREGISTER) then
  1885. begin
  1886. if (p.ops > 0) then
  1887. begin
  1888. if RegInOp(reg, p.oper[0]^) then
  1889. begin
  1890. if (p.oper[0]^.typ = top_ref) then
  1891. begin
  1892. if RegInRef(reg, p.oper[0]^.ref^) then
  1893. begin
  1894. Result := False;
  1895. Exit;
  1896. end;
  1897. end
  1898. else if (p.oper[0]^.typ = top_reg) then
  1899. begin
  1900. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1901. begin
  1902. Result := False;
  1903. Exit;
  1904. end
  1905. else if ([Ch_WOp1]*Ch<>[]) then
  1906. begin
  1907. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1908. Result := True
  1909. else
  1910. begin
  1911. Result := False;
  1912. Exit;
  1913. end;
  1914. end;
  1915. end;
  1916. end;
  1917. if (p.ops > 1) then
  1918. begin
  1919. if RegInOp(reg, p.oper[1]^) then
  1920. begin
  1921. if (p.oper[1]^.typ = top_ref) then
  1922. begin
  1923. if RegInRef(reg, p.oper[1]^.ref^) then
  1924. begin
  1925. Result := False;
  1926. Exit;
  1927. end;
  1928. end
  1929. else if (p.oper[1]^.typ = top_reg) then
  1930. begin
  1931. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1932. begin
  1933. Result := False;
  1934. Exit;
  1935. end
  1936. else if ([Ch_WOp2]*Ch<>[]) then
  1937. begin
  1938. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1939. Result := True
  1940. else
  1941. begin
  1942. Result := False;
  1943. Exit;
  1944. end;
  1945. end;
  1946. end;
  1947. end;
  1948. if (p.ops > 2) then
  1949. begin
  1950. if RegInOp(reg, p.oper[2]^) then
  1951. begin
  1952. if (p.oper[2]^.typ = top_ref) then
  1953. begin
  1954. if RegInRef(reg, p.oper[2]^.ref^) then
  1955. begin
  1956. Result := False;
  1957. Exit;
  1958. end;
  1959. end
  1960. else if (p.oper[2]^.typ = top_reg) then
  1961. begin
  1962. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1963. begin
  1964. Result := False;
  1965. Exit;
  1966. end
  1967. else if ([Ch_WOp3]*Ch<>[]) then
  1968. begin
  1969. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1970. Result := True
  1971. else
  1972. begin
  1973. Result := False;
  1974. Exit;
  1975. end;
  1976. end;
  1977. end;
  1978. end;
  1979. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1980. begin
  1981. if (p.oper[3]^.typ = top_ref) then
  1982. begin
  1983. if RegInRef(reg, p.oper[3]^.ref^) then
  1984. begin
  1985. Result := False;
  1986. Exit;
  1987. end;
  1988. end
  1989. else if (p.oper[3]^.typ = top_reg) then
  1990. begin
  1991. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1992. begin
  1993. Result := False;
  1994. Exit;
  1995. end
  1996. else if ([Ch_WOp4]*Ch<>[]) then
  1997. begin
  1998. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1999. Result := True
  2000. else
  2001. begin
  2002. Result := False;
  2003. Exit;
  2004. end;
  2005. end;
  2006. end;
  2007. end;
  2008. end;
  2009. end;
  2010. end;
  2011. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2012. case getsupreg(reg) of
  2013. RS_EAX:
  2014. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2015. begin
  2016. Result := True;
  2017. Exit;
  2018. end;
  2019. RS_ECX:
  2020. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2021. begin
  2022. Result := True;
  2023. Exit;
  2024. end;
  2025. RS_EDX:
  2026. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2027. begin
  2028. Result := True;
  2029. Exit;
  2030. end;
  2031. RS_EBX:
  2032. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2033. begin
  2034. Result := True;
  2035. Exit;
  2036. end;
  2037. RS_ESP:
  2038. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2039. begin
  2040. Result := True;
  2041. Exit;
  2042. end;
  2043. RS_EBP:
  2044. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2045. begin
  2046. Result := True;
  2047. Exit;
  2048. end;
  2049. RS_ESI:
  2050. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2051. begin
  2052. Result := True;
  2053. Exit;
  2054. end;
  2055. RS_EDI:
  2056. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2057. begin
  2058. Result := True;
  2059. Exit;
  2060. end;
  2061. else
  2062. ;
  2063. end;
  2064. end;
  2065. end;
  2066. end;
  2067. end;
  2068. end;
  2069. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2070. var
  2071. hp2,hp3 : tai;
  2072. begin
  2073. { some x86-64 issue a NOP before the real exit code }
  2074. if MatchInstruction(p,A_NOP,[]) then
  2075. GetNextInstruction(p,p);
  2076. result:=assigned(p) and (p.typ=ait_instruction) and
  2077. ((taicpu(p).opcode = A_RET) or
  2078. ((taicpu(p).opcode=A_LEAVE) and
  2079. GetNextInstruction(p,hp2) and
  2080. MatchInstruction(hp2,A_RET,[S_NO])
  2081. ) or
  2082. (((taicpu(p).opcode=A_LEA) and
  2083. MatchOpType(taicpu(p),top_ref,top_reg) and
  2084. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2085. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2086. ) and
  2087. GetNextInstruction(p,hp2) and
  2088. MatchInstruction(hp2,A_RET,[S_NO])
  2089. ) or
  2090. ((((taicpu(p).opcode=A_MOV) and
  2091. MatchOpType(taicpu(p),top_reg,top_reg) and
  2092. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2093. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2094. ((taicpu(p).opcode=A_LEA) and
  2095. MatchOpType(taicpu(p),top_ref,top_reg) and
  2096. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2097. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2098. )
  2099. ) and
  2100. GetNextInstruction(p,hp2) and
  2101. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2102. MatchOpType(taicpu(hp2),top_reg) and
  2103. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2104. GetNextInstruction(hp2,hp3) and
  2105. MatchInstruction(hp3,A_RET,[S_NO])
  2106. )
  2107. );
  2108. end;
  2109. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2110. begin
  2111. isFoldableArithOp := False;
  2112. case hp1.opcode of
  2113. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2114. isFoldableArithOp :=
  2115. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2116. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2117. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2118. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2119. (taicpu(hp1).oper[1]^.reg = reg);
  2120. A_INC,A_DEC,A_NEG,A_NOT:
  2121. isFoldableArithOp :=
  2122. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2123. (taicpu(hp1).oper[0]^.reg = reg);
  2124. else
  2125. ;
  2126. end;
  2127. end;
  2128. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2129. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2130. var
  2131. hp2: tai;
  2132. begin
  2133. hp2 := p;
  2134. repeat
  2135. hp2 := tai(hp2.previous);
  2136. if assigned(hp2) and
  2137. (hp2.typ = ait_regalloc) and
  2138. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2139. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2140. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2141. begin
  2142. RemoveInstruction(hp2);
  2143. break;
  2144. end;
  2145. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2146. end;
  2147. begin
  2148. case current_procinfo.procdef.returndef.typ of
  2149. arraydef,recorddef,pointerdef,
  2150. stringdef,enumdef,procdef,objectdef,errordef,
  2151. filedef,setdef,procvardef,
  2152. classrefdef,forwarddef:
  2153. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2154. orddef:
  2155. if current_procinfo.procdef.returndef.size <> 0 then
  2156. begin
  2157. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2158. { for int64/qword }
  2159. if current_procinfo.procdef.returndef.size = 8 then
  2160. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2161. end;
  2162. else
  2163. ;
  2164. end;
  2165. end;
  2166. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2167. var
  2168. hp1: tai;
  2169. operswap: poper;
  2170. begin
  2171. Result := False;
  2172. { Optimise:
  2173. cmov(c) %reg1,%reg2
  2174. mov %reg2,%reg1
  2175. (%reg2 dealloc.)
  2176. To:
  2177. cmov(~c) %reg2,%reg1
  2178. }
  2179. if (taicpu(p).oper[0]^.typ = top_reg) then
  2180. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2181. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2182. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2183. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2184. begin
  2185. TransferUsedRegs(TmpUsedRegs);
  2186. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2187. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2188. begin
  2189. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2190. { Save time by swapping the pointers (they're both registers, so
  2191. we don't need to worry about reference counts) }
  2192. operswap := taicpu(p).oper[0];
  2193. taicpu(p).oper[0] := taicpu(p).oper[1];
  2194. taicpu(p).oper[1] := operswap;
  2195. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2196. RemoveInstruction(hp1);
  2197. { It's still a CMOV, so we can look further ahead }
  2198. Include(OptsToCheck, aoc_ForceNewIteration);
  2199. { But first, let's see if this will get optimised again
  2200. (probably won't happen, but best to be sure) }
  2201. Continue;
  2202. end;
  2203. Break;
  2204. end;
  2205. end;
  2206. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2207. var
  2208. hp1,hp2 : tai;
  2209. begin
  2210. result:=false;
  2211. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2212. begin
  2213. { vmova* reg1,reg1
  2214. =>
  2215. <nop> }
  2216. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2217. begin
  2218. RemoveCurrentP(p);
  2219. result:=true;
  2220. exit;
  2221. end;
  2222. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2223. (hp1.typ = ait_instruction) and
  2224. (
  2225. { Under -O2 and below, the instructions are always adjacent }
  2226. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2227. (taicpu(hp1).ops <= 1) or
  2228. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2229. { If reg1 = reg3, reg1 must not be modified in between }
  2230. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2231. ) then
  2232. begin
  2233. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2234. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2235. begin
  2236. { vmova* reg1,reg2
  2237. ...
  2238. vmova* reg2,reg3
  2239. dealloc reg2
  2240. =>
  2241. vmova* reg1,reg3 }
  2242. TransferUsedRegs(TmpUsedRegs);
  2243. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2244. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2245. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2246. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2247. begin
  2248. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2249. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2250. TransferUsedRegs(TmpUsedRegs);
  2251. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2252. RemoveInstruction(hp1);
  2253. result:=true;
  2254. exit;
  2255. end;
  2256. { special case:
  2257. vmova* reg1,<op>
  2258. ...
  2259. vmova* <op>,reg1
  2260. =>
  2261. vmova* reg1,<op> }
  2262. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2263. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2264. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2265. ) then
  2266. begin
  2267. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end
  2273. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2274. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2275. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2276. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2277. ) and
  2278. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2279. begin
  2280. { vmova* reg1,reg2
  2281. ...
  2282. vmovs* reg2,<op>
  2283. dealloc reg2
  2284. =>
  2285. vmovs* reg1,<op> }
  2286. TransferUsedRegs(TmpUsedRegs);
  2287. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2288. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2289. begin
  2290. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2291. taicpu(p).opcode:=taicpu(hp1).opcode;
  2292. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2293. TransferUsedRegs(TmpUsedRegs);
  2294. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2295. RemoveInstruction(hp1);
  2296. result:=true;
  2297. exit;
  2298. end
  2299. end;
  2300. if MatchInstruction(hp1,[A_VFMADDPD,
  2301. A_VFMADD132PD,
  2302. A_VFMADD132PS,
  2303. A_VFMADD132SD,
  2304. A_VFMADD132SS,
  2305. A_VFMADD213PD,
  2306. A_VFMADD213PS,
  2307. A_VFMADD213SD,
  2308. A_VFMADD213SS,
  2309. A_VFMADD231PD,
  2310. A_VFMADD231PS,
  2311. A_VFMADD231SD,
  2312. A_VFMADD231SS,
  2313. A_VFMADDSUB132PD,
  2314. A_VFMADDSUB132PS,
  2315. A_VFMADDSUB213PD,
  2316. A_VFMADDSUB213PS,
  2317. A_VFMADDSUB231PD,
  2318. A_VFMADDSUB231PS,
  2319. A_VFMSUB132PD,
  2320. A_VFMSUB132PS,
  2321. A_VFMSUB132SD,
  2322. A_VFMSUB132SS,
  2323. A_VFMSUB213PD,
  2324. A_VFMSUB213PS,
  2325. A_VFMSUB213SD,
  2326. A_VFMSUB213SS,
  2327. A_VFMSUB231PD,
  2328. A_VFMSUB231PS,
  2329. A_VFMSUB231SD,
  2330. A_VFMSUB231SS,
  2331. A_VFMSUBADD132PD,
  2332. A_VFMSUBADD132PS,
  2333. A_VFMSUBADD213PD,
  2334. A_VFMSUBADD213PS,
  2335. A_VFMSUBADD231PD,
  2336. A_VFMSUBADD231PS,
  2337. A_VFNMADD132PD,
  2338. A_VFNMADD132PS,
  2339. A_VFNMADD132SD,
  2340. A_VFNMADD132SS,
  2341. A_VFNMADD213PD,
  2342. A_VFNMADD213PS,
  2343. A_VFNMADD213SD,
  2344. A_VFNMADD213SS,
  2345. A_VFNMADD231PD,
  2346. A_VFNMADD231PS,
  2347. A_VFNMADD231SD,
  2348. A_VFNMADD231SS,
  2349. A_VFNMSUB132PD,
  2350. A_VFNMSUB132PS,
  2351. A_VFNMSUB132SD,
  2352. A_VFNMSUB132SS,
  2353. A_VFNMSUB213PD,
  2354. A_VFNMSUB213PS,
  2355. A_VFNMSUB213SD,
  2356. A_VFNMSUB213SS,
  2357. A_VFNMSUB231PD,
  2358. A_VFNMSUB231PS,
  2359. A_VFNMSUB231SD,
  2360. A_VFNMSUB231SS],[S_NO]) and
  2361. { we mix single and double opperations here because we assume that the compiler
  2362. generates vmovapd only after double operations and vmovaps only after single operations }
  2363. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2364. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2365. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2366. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2367. begin
  2368. TransferUsedRegs(TmpUsedRegs);
  2369. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2370. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2371. begin
  2372. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2373. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2374. RemoveCurrentP(p)
  2375. else
  2376. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2377. RemoveInstruction(hp2);
  2378. end;
  2379. end
  2380. else if (hp1.typ = ait_instruction) and
  2381. (((taicpu(p).opcode=A_MOVAPS) and
  2382. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2383. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2384. ((taicpu(p).opcode=A_MOVAPD) and
  2385. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2386. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2387. ) and
  2388. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2389. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2390. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2391. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2392. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2393. { change
  2394. movapX reg,reg2
  2395. addsX/subsX/... reg3, reg2
  2396. movapX reg2,reg
  2397. to
  2398. addsX/subsX/... reg3,reg
  2399. }
  2400. begin
  2401. TransferUsedRegs(TmpUsedRegs);
  2402. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2403. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2404. begin
  2405. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2406. debug_op2str(taicpu(p).opcode)+' '+
  2407. debug_op2str(taicpu(hp1).opcode)+' '+
  2408. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2409. { we cannot eliminate the first move if
  2410. the operations uses the same register for source and dest }
  2411. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2412. { Remember that hp1 is not necessarily the immediate
  2413. next instruction }
  2414. RemoveCurrentP(p);
  2415. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2416. RemoveInstruction(hp2);
  2417. result:=true;
  2418. end;
  2419. end
  2420. else if (hp1.typ = ait_instruction) and
  2421. (((taicpu(p).opcode=A_VMOVAPD) and
  2422. (taicpu(hp1).opcode=A_VCOMISD)) or
  2423. ((taicpu(p).opcode=A_VMOVAPS) and
  2424. ((taicpu(hp1).opcode=A_VCOMISS))
  2425. )
  2426. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2427. { change
  2428. movapX reg,reg1
  2429. vcomisX reg1,reg1
  2430. to
  2431. vcomisX reg,reg
  2432. }
  2433. begin
  2434. TransferUsedRegs(TmpUsedRegs);
  2435. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2436. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2437. begin
  2438. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2439. debug_op2str(taicpu(p).opcode)+' '+
  2440. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2441. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2442. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2443. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2444. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2445. RemoveCurrentP(p);
  2446. result:=true;
  2447. exit;
  2448. end;
  2449. end
  2450. end;
  2451. end;
  2452. end;
  2453. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2454. var
  2455. hp1 : tai;
  2456. begin
  2457. result:=false;
  2458. { replace
  2459. V<Op>X %mreg1,%mreg2,%mreg3
  2460. VMovX %mreg3,%mreg4
  2461. dealloc %mreg3
  2462. by
  2463. V<Op>X %mreg1,%mreg2,%mreg4
  2464. ?
  2465. }
  2466. if GetNextInstruction(p,hp1) and
  2467. { we mix single and double operations here because we assume that the compiler
  2468. generates vmovapd only after double operations and vmovaps only after single operations }
  2469. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2470. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2471. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2472. begin
  2473. TransferUsedRegs(TmpUsedRegs);
  2474. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2475. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2476. begin
  2477. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2478. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2479. RemoveInstruction(hp1);
  2480. result:=true;
  2481. end;
  2482. end;
  2483. end;
  2484. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2485. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2486. begin
  2487. Result := False;
  2488. { For safety reasons, only check for exact register matches }
  2489. { Check base register }
  2490. if (ref.base = AOldReg) then
  2491. begin
  2492. ref.base := ANewReg;
  2493. Result := True;
  2494. end;
  2495. { Check index register }
  2496. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2497. begin
  2498. ref.index := ANewReg;
  2499. Result := True;
  2500. end;
  2501. end;
  2502. { Replaces all references to AOldReg in an operand to ANewReg }
  2503. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2504. var
  2505. OldSupReg, NewSupReg: TSuperRegister;
  2506. OldSubReg, NewSubReg: TSubRegister;
  2507. OldRegType: TRegisterType;
  2508. ThisOper: POper;
  2509. begin
  2510. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2511. Result := False;
  2512. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2513. InternalError(2020011801);
  2514. OldSupReg := getsupreg(AOldReg);
  2515. OldSubReg := getsubreg(AOldReg);
  2516. OldRegType := getregtype(AOldReg);
  2517. NewSupReg := getsupreg(ANewReg);
  2518. NewSubReg := getsubreg(ANewReg);
  2519. if OldRegType <> getregtype(ANewReg) then
  2520. InternalError(2020011802);
  2521. if OldSubReg <> NewSubReg then
  2522. InternalError(2020011803);
  2523. case ThisOper^.typ of
  2524. top_reg:
  2525. if (
  2526. (ThisOper^.reg = AOldReg) or
  2527. (
  2528. (OldRegType = R_INTREGISTER) and
  2529. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2530. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2531. (
  2532. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2533. {$ifndef x86_64}
  2534. and (
  2535. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2536. don't have an 8-bit representation }
  2537. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2538. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2539. )
  2540. {$endif x86_64}
  2541. )
  2542. )
  2543. ) then
  2544. begin
  2545. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2546. Result := True;
  2547. end;
  2548. top_ref:
  2549. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2550. Result := True;
  2551. else
  2552. ;
  2553. end;
  2554. end;
  2555. { Replaces all references to AOldReg in an instruction to ANewReg }
  2556. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2557. const
  2558. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2559. var
  2560. OperIdx: Integer;
  2561. begin
  2562. Result := False;
  2563. for OperIdx := 0 to p.ops - 1 do
  2564. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2565. begin
  2566. { The shift and rotate instructions can only use CL }
  2567. if not (
  2568. (OperIdx = 0) and
  2569. { This second condition just helps to avoid unnecessarily
  2570. calling MatchInstruction for 10 different opcodes }
  2571. (p.oper[0]^.reg = NR_CL) and
  2572. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2573. ) then
  2574. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2575. end
  2576. else if p.oper[OperIdx]^.typ = top_ref then
  2577. { It's okay to replace registers in references that get written to }
  2578. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2579. end;
  2580. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2581. begin
  2582. Result :=
  2583. (ref^.index = NR_NO) and
  2584. (
  2585. {$ifdef x86_64}
  2586. (
  2587. (ref^.base = NR_RIP) and
  2588. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2589. ) or
  2590. {$endif x86_64}
  2591. (ref^.refaddr = addr_full) or
  2592. (ref^.base = NR_STACK_POINTER_REG) or
  2593. (ref^.base = current_procinfo.framepointer)
  2594. );
  2595. end;
  2596. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2597. var
  2598. l: asizeint;
  2599. begin
  2600. Result := False;
  2601. { Should have been checked previously }
  2602. if p.opcode <> A_LEA then
  2603. InternalError(2020072501);
  2604. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2605. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2606. not(cs_opt_size in current_settings.optimizerswitches) then
  2607. exit;
  2608. with p.oper[0]^.ref^ do
  2609. begin
  2610. if (base <> p.oper[1]^.reg) or
  2611. (index <> NR_NO) or
  2612. assigned(symbol) then
  2613. exit;
  2614. l:=offset;
  2615. if (l=1) and UseIncDec then
  2616. begin
  2617. p.opcode:=A_INC;
  2618. p.loadreg(0,p.oper[1]^.reg);
  2619. p.ops:=1;
  2620. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2621. end
  2622. else if (l=-1) and UseIncDec then
  2623. begin
  2624. p.opcode:=A_DEC;
  2625. p.loadreg(0,p.oper[1]^.reg);
  2626. p.ops:=1;
  2627. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2628. end
  2629. else
  2630. begin
  2631. if (l<0) and (l<>-2147483648) then
  2632. begin
  2633. p.opcode:=A_SUB;
  2634. p.loadConst(0,-l);
  2635. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2636. end
  2637. else
  2638. begin
  2639. p.opcode:=A_ADD;
  2640. p.loadConst(0,l);
  2641. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2642. end;
  2643. end;
  2644. end;
  2645. Result := True;
  2646. end;
  2647. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2648. var
  2649. CurrentReg, ReplaceReg: TRegister;
  2650. begin
  2651. Result := False;
  2652. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2653. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2654. case hp.opcode of
  2655. A_FSTSW, A_FNSTSW,
  2656. A_IN, A_INS, A_OUT, A_OUTS,
  2657. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2658. { These routines have explicit operands, but they are restricted in
  2659. what they can be (e.g. IN and OUT can only read from AL, AX or
  2660. EAX. }
  2661. Exit;
  2662. A_IMUL:
  2663. begin
  2664. { The 1-operand version writes to implicit registers
  2665. The 2-operand version reads from the first operator, and reads
  2666. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2667. the 3-operand version reads from a register that it doesn't write to
  2668. }
  2669. case hp.ops of
  2670. 1:
  2671. if (
  2672. (
  2673. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2674. ) or
  2675. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2676. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2677. begin
  2678. Result := True;
  2679. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2680. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2681. end;
  2682. 2:
  2683. { Only modify the first parameter }
  2684. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2685. begin
  2686. Result := True;
  2687. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2688. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2689. end;
  2690. 3:
  2691. { Only modify the second parameter }
  2692. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2693. begin
  2694. Result := True;
  2695. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2696. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2697. end;
  2698. else
  2699. InternalError(2020012901);
  2700. end;
  2701. end;
  2702. else
  2703. if (hp.ops > 0) and
  2704. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2705. begin
  2706. Result := True;
  2707. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2708. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2709. end;
  2710. end;
  2711. end;
  2712. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2713. var
  2714. hp2, hp_regalloc: tai;
  2715. p_SourceReg, p_TargetReg: TRegister;
  2716. begin
  2717. Result := False;
  2718. { Backward optimisation. If we have:
  2719. func. %reg1,%reg2
  2720. mov %reg2,%reg3
  2721. (dealloc %reg2)
  2722. Change to:
  2723. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2724. Perform similar optimisations with 1, 3 and 4-operand instructions
  2725. that only have one output.
  2726. }
  2727. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2728. begin
  2729. p_SourceReg := taicpu(p).oper[0]^.reg;
  2730. p_TargetReg := taicpu(p).oper[1]^.reg;
  2731. TransferUsedRegs(TmpUsedRegs);
  2732. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2733. GetLastInstruction(p, hp2) and
  2734. (hp2.typ = ait_instruction) and
  2735. { Have to make sure it's an instruction that only reads from
  2736. the first operands and only writes (not reads or modifies) to
  2737. the last one; in essence, a pure function such as BSR, POPCNT
  2738. or ANDN }
  2739. (
  2740. (
  2741. (taicpu(hp2).ops = 1) and
  2742. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2743. ) or
  2744. (
  2745. (taicpu(hp2).ops = 2) and
  2746. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2747. ) or
  2748. (
  2749. (taicpu(hp2).ops = 3) and
  2750. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2751. ) or
  2752. (
  2753. (taicpu(hp2).ops = 4) and
  2754. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2755. )
  2756. ) and
  2757. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2758. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2759. begin
  2760. case taicpu(hp2).opcode of
  2761. A_FSTSW, A_FNSTSW,
  2762. A_IN, A_INS, A_OUT, A_OUTS,
  2763. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2764. { These routines have explicit operands, but they are restricted in
  2765. what they can be (e.g. IN and OUT can only read from AL, AX or
  2766. EAX. }
  2767. ;
  2768. else
  2769. begin
  2770. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2771. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2772. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2773. if Assigned(hp_regalloc) then
  2774. begin
  2775. Asml.Remove(hp_regalloc);
  2776. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2777. begin
  2778. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2779. hp_regalloc.Free;
  2780. end
  2781. else
  2782. { If the register is not explicitly deallocated, it's
  2783. being reused, so move the allocation to after func. }
  2784. AsmL.InsertAfter(hp_regalloc, hp2);
  2785. end;
  2786. if not RegInInstruction(p_TargetReg, hp2) then
  2787. begin
  2788. TransferUsedRegs(TmpUsedRegs);
  2789. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2790. end;
  2791. { Actually make the changes }
  2792. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2793. RemoveCurrentp(p, hp1);
  2794. { If the Func was another MOV instruction, we might get
  2795. "mov %reg,%reg" that doesn't get removed in Pass 2
  2796. otherwise, so deal with it here (also do something
  2797. similar with lea (%reg),%reg}
  2798. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2799. begin
  2800. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2801. if p = hp2 then
  2802. RemoveCurrentp(p)
  2803. else
  2804. RemoveInstruction(hp2);
  2805. end;
  2806. Result := True;
  2807. Exit;
  2808. end;
  2809. end;
  2810. end;
  2811. end;
  2812. end;
  2813. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2814. begin
  2815. Result := False;
  2816. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2817. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2818. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2819. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2820. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2821. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2822. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2823. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2824. begin
  2825. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2826. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2827. Result := True;
  2828. Include(OptsToCheck, aoc_ForceNewIteration);
  2829. end;
  2830. end;
  2831. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2832. var
  2833. hp1, hp2, hp3, hp4: tai;
  2834. DoOptimisation, TempBool: Boolean;
  2835. {$ifdef x86_64}
  2836. NewConst: TCGInt;
  2837. {$endif x86_64}
  2838. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2839. begin
  2840. if taicpu(hp1).opcode = signed_movop then
  2841. begin
  2842. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2843. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2844. end
  2845. else
  2846. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2847. end;
  2848. function TryConstMerge(var p1, p2: tai): Boolean;
  2849. var
  2850. ThisRef: TReference;
  2851. begin
  2852. Result := False;
  2853. ThisRef := taicpu(p2).oper[1]^.ref^;
  2854. { Only permit writes to the stack, since we can guarantee alignment with that }
  2855. if (ThisRef.index = NR_NO) and
  2856. (
  2857. (ThisRef.base = NR_STACK_POINTER_REG) or
  2858. (ThisRef.base = current_procinfo.framepointer)
  2859. ) then
  2860. begin
  2861. case taicpu(p).opsize of
  2862. S_B:
  2863. begin
  2864. { Word writes must be on a 2-byte boundary }
  2865. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2866. begin
  2867. { Reduce offset of second reference to see if it is sequential with the first }
  2868. Dec(ThisRef.offset, 1);
  2869. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2870. begin
  2871. { Make sure the constants aren't represented as a
  2872. negative number, as these won't merge properly }
  2873. taicpu(p1).opsize := S_W;
  2874. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2875. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2876. RemoveInstruction(p2);
  2877. Result := True;
  2878. end;
  2879. end;
  2880. end;
  2881. S_W:
  2882. begin
  2883. { Longword writes must be on a 4-byte boundary }
  2884. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2885. begin
  2886. { Reduce offset of second reference to see if it is sequential with the first }
  2887. Dec(ThisRef.offset, 2);
  2888. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2889. begin
  2890. { Make sure the constants aren't represented as a
  2891. negative number, as these won't merge properly }
  2892. taicpu(p1).opsize := S_L;
  2893. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2894. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2895. RemoveInstruction(p2);
  2896. Result := True;
  2897. end;
  2898. end;
  2899. end;
  2900. {$ifdef x86_64}
  2901. S_L:
  2902. begin
  2903. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2904. see if the constants can be encoded this way. }
  2905. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2906. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2907. { Quadword writes must be on an 8-byte boundary }
  2908. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2909. begin
  2910. { Reduce offset of second reference to see if it is sequential with the first }
  2911. Dec(ThisRef.offset, 4);
  2912. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2913. begin
  2914. { Make sure the constants aren't represented as a
  2915. negative number, as these won't merge properly }
  2916. taicpu(p1).opsize := S_Q;
  2917. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2918. taicpu(p1).oper[0]^.val := NewConst;
  2919. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2920. RemoveInstruction(p2);
  2921. Result := True;
  2922. end;
  2923. end;
  2924. end;
  2925. {$endif x86_64}
  2926. else
  2927. ;
  2928. end;
  2929. end;
  2930. end;
  2931. var
  2932. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2933. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2934. NewSize: topsize; NewOffset: asizeint;
  2935. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2936. SourceRef, TargetRef: TReference;
  2937. MovAligned, MovUnaligned: TAsmOp;
  2938. ThisRef: TReference;
  2939. JumpTracking: TLinkedList;
  2940. begin
  2941. Result:=false;
  2942. { remove mov reg1,reg1? }
  2943. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2944. then
  2945. begin
  2946. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2947. { take care of the register (de)allocs following p }
  2948. RemoveCurrentP(p);
  2949. Result := True;
  2950. exit;
  2951. end;
  2952. { Prevent compiler warnings }
  2953. p_SourceReg := NR_NO;
  2954. p_TargetReg := NR_NO;
  2955. if taicpu(p).oper[1]^.typ = top_reg then
  2956. begin
  2957. { Saves on a large number of dereferences }
  2958. p_TargetReg := taicpu(p).oper[1]^.reg;
  2959. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2960. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2961. else
  2962. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2963. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2964. while True do
  2965. begin
  2966. if (taicpu(hp1).opcode = A_AND) and
  2967. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2968. begin
  2969. { A change has occurred, just not in p }
  2970. Include(OptsToCheck, aoc_ForceNewIteration);
  2971. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2972. begin
  2973. case taicpu(p).opsize of
  2974. S_L:
  2975. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2976. begin
  2977. { Optimize out:
  2978. mov x, %reg
  2979. and ffffffffh, %reg
  2980. }
  2981. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2982. RemoveInstruction(hp1);
  2983. Result:=true;
  2984. exit;
  2985. end;
  2986. S_Q: { TODO: Confirm if this is even possible }
  2987. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2988. begin
  2989. { Optimize out:
  2990. mov x, %reg
  2991. and ffffffffffffffffh, %reg
  2992. }
  2993. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2994. RemoveInstruction(hp1);
  2995. Result:=true;
  2996. exit;
  2997. end;
  2998. else
  2999. ;
  3000. end;
  3001. if (
  3002. { Make sure that if a reference is used, its registers
  3003. are not modified in between }
  3004. (
  3005. (taicpu(p).oper[0]^.typ = top_reg) and
  3006. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3007. ) or
  3008. (
  3009. (taicpu(p).oper[0]^.typ = top_ref) and
  3010. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3011. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3012. )
  3013. ) and
  3014. GetNextInstruction(hp1,hp2) and
  3015. MatchInstruction(hp2,A_TEST,[]) and
  3016. (
  3017. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3018. (
  3019. { If the register being tested is smaller than the one
  3020. that received a bitwise AND, permit it if the constant
  3021. fits into the smaller size }
  3022. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3023. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3024. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3025. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3026. (
  3027. (
  3028. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3029. (taicpu(hp1).oper[0]^.val <= $FF)
  3030. ) or
  3031. (
  3032. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3033. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3034. {$ifdef x86_64}
  3035. ) or
  3036. (
  3037. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3038. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3039. {$endif x86_64}
  3040. )
  3041. )
  3042. )
  3043. ) and
  3044. (
  3045. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3046. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3047. ) and
  3048. GetNextInstruction(hp2,hp3) and
  3049. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3050. (taicpu(hp3).condition in [C_E,C_NE]) then
  3051. begin
  3052. TransferUsedRegs(TmpUsedRegs);
  3053. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3054. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3055. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3056. begin
  3057. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3058. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3059. taicpu(hp1).opcode:=A_TEST;
  3060. { Shrink the TEST instruction down to the smallest possible size }
  3061. case taicpu(hp1).oper[0]^.val of
  3062. 0..255:
  3063. if (taicpu(hp1).opsize <> S_B)
  3064. {$ifndef x86_64}
  3065. and (
  3066. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3067. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3068. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3069. )
  3070. {$endif x86_64}
  3071. then
  3072. begin
  3073. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3074. { Only print debug message if the TEST instruction
  3075. is a different size before and after }
  3076. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3077. taicpu(hp1).opsize := S_B;
  3078. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3079. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3080. end;
  3081. 256..65535:
  3082. if (taicpu(hp1).opsize <> S_W) then
  3083. begin
  3084. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3085. { Only print debug message if the TEST instruction
  3086. is a different size before and after }
  3087. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3088. taicpu(hp1).opsize := S_W;
  3089. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3090. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3091. end;
  3092. {$ifdef x86_64}
  3093. 65536..$7FFFFFFF:
  3094. if (taicpu(hp1).opsize <> S_L) then
  3095. begin
  3096. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3097. { Only print debug message if the TEST instruction
  3098. is a different size before and after }
  3099. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3100. taicpu(hp1).opsize := S_L;
  3101. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3102. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3103. end;
  3104. {$endif x86_64}
  3105. else
  3106. ;
  3107. end;
  3108. RemoveInstruction(hp2);
  3109. RemoveCurrentP(p);
  3110. Result:=true;
  3111. exit;
  3112. end;
  3113. end;
  3114. end;
  3115. if IsMOVZXAcceptable and
  3116. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3117. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3118. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3119. then
  3120. begin
  3121. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3122. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3123. case taicpu(p).opsize of
  3124. S_B:
  3125. if (taicpu(hp1).oper[0]^.val = $ff) then
  3126. begin
  3127. { Convert:
  3128. movb x, %regl movb x, %regl
  3129. andw ffh, %regw andl ffh, %regd
  3130. To:
  3131. movzbw x, %regd movzbl x, %regd
  3132. (Identical registers, just different sizes)
  3133. }
  3134. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3135. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3136. case taicpu(hp1).opsize of
  3137. S_W: NewSize := S_BW;
  3138. S_L: NewSize := S_BL;
  3139. {$ifdef x86_64}
  3140. S_Q: NewSize := S_BQ;
  3141. {$endif x86_64}
  3142. else
  3143. InternalError(2018011510);
  3144. end;
  3145. end
  3146. else
  3147. NewSize := S_NO;
  3148. S_W:
  3149. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3150. begin
  3151. { Convert:
  3152. movw x, %regw
  3153. andl ffffh, %regd
  3154. To:
  3155. movzwl x, %regd
  3156. (Identical registers, just different sizes)
  3157. }
  3158. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3159. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3160. case taicpu(hp1).opsize of
  3161. S_L: NewSize := S_WL;
  3162. {$ifdef x86_64}
  3163. S_Q: NewSize := S_WQ;
  3164. {$endif x86_64}
  3165. else
  3166. InternalError(2018011511);
  3167. end;
  3168. end
  3169. else
  3170. NewSize := S_NO;
  3171. else
  3172. NewSize := S_NO;
  3173. end;
  3174. if NewSize <> S_NO then
  3175. begin
  3176. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3177. { The actual optimization }
  3178. taicpu(p).opcode := A_MOVZX;
  3179. taicpu(p).changeopsize(NewSize);
  3180. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3181. { Make sure we deal with any reference counts that were increased }
  3182. if taicpu(hp1).oper[1]^.typ = top_ref then
  3183. begin
  3184. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3185. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3186. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3187. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3188. end;
  3189. { Safeguard if "and" is followed by a conditional command }
  3190. TransferUsedRegs(TmpUsedRegs);
  3191. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3192. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3193. begin
  3194. { At this point, the "and" command is effectively equivalent to
  3195. "test %reg,%reg". This will be handled separately by the
  3196. Peephole Optimizer. [Kit] }
  3197. DebugMsg(SPeepholeOptimization + PreMessage +
  3198. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3199. end
  3200. else
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3203. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3204. RemoveInstruction(hp1);
  3205. end;
  3206. Result := True;
  3207. Exit;
  3208. { Go through DeepMOVOpt again (jump to "while True do") }
  3209. Continue;
  3210. end;
  3211. end;
  3212. end;
  3213. if taicpu(p).oper[0]^.typ = top_reg then
  3214. begin
  3215. p_SourceReg := taicpu(p).oper[0]^.reg;
  3216. { Look for:
  3217. mov %reg1,%reg2
  3218. ??? %reg2,r/m
  3219. Change to:
  3220. mov %reg1,%reg2
  3221. ??? %reg1,r/m
  3222. }
  3223. if RegReadByInstruction(p_TargetReg, hp1) and
  3224. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3225. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3226. begin
  3227. { A change has occurred, just not in p }
  3228. Include(OptsToCheck, aoc_ForceNewIteration);
  3229. TransferUsedRegs(TmpUsedRegs);
  3230. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3231. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3232. { Just in case something didn't get modified (e.g. an
  3233. implicit register) }
  3234. not RegReadByInstruction(p_TargetReg, hp1) then
  3235. begin
  3236. { We can remove the original MOV }
  3237. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3238. RemoveCurrentP(p);
  3239. { UsedRegs got updated by RemoveCurrentp }
  3240. Result := True;
  3241. Exit;
  3242. end;
  3243. { If we know a MOV instruction has become a null operation, we might as well
  3244. get rid of it now to save time. }
  3245. if (taicpu(hp1).opcode = A_MOV) and
  3246. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3247. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3248. { Just being a register is enough to confirm it's a null operation }
  3249. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3250. begin
  3251. Result := True;
  3252. { Speed-up to reduce a pipeline stall... if we had something like...
  3253. movl %eax,%edx
  3254. movw %dx,%ax
  3255. ... the second instruction would change to movw %ax,%ax, but
  3256. given that it is now %ax that's active rather than %eax,
  3257. penalties might occur due to a partial register write, so instead,
  3258. change it to a MOVZX instruction when optimising for speed.
  3259. }
  3260. if not (cs_opt_size in current_settings.optimizerswitches) and
  3261. IsMOVZXAcceptable and
  3262. (taicpu(hp1).opsize < taicpu(p).opsize)
  3263. {$ifdef x86_64}
  3264. { operations already implicitly set the upper 64 bits to zero }
  3265. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3266. {$endif x86_64}
  3267. then
  3268. begin
  3269. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3270. case taicpu(p).opsize of
  3271. S_W:
  3272. if taicpu(hp1).opsize = S_B then
  3273. taicpu(hp1).opsize := S_BL
  3274. else
  3275. InternalError(2020012911);
  3276. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3277. case taicpu(hp1).opsize of
  3278. S_B:
  3279. taicpu(hp1).opsize := S_BL;
  3280. S_W:
  3281. taicpu(hp1).opsize := S_WL;
  3282. else
  3283. InternalError(2020012912);
  3284. end;
  3285. else
  3286. InternalError(2020012910);
  3287. end;
  3288. taicpu(hp1).opcode := A_MOVZX;
  3289. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3290. end
  3291. else
  3292. begin
  3293. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3294. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3295. RemoveInstruction(hp1);
  3296. { The instruction after what was hp1 is now the immediate next instruction,
  3297. so we can continue to make optimisations if it's present }
  3298. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3299. Exit;
  3300. hp1 := hp2;
  3301. end;
  3302. end;
  3303. end;
  3304. {$ifdef x86_64}
  3305. { Change:
  3306. movl %reg1l,%reg2l
  3307. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3308. To:
  3309. movl %reg1l,%reg2l
  3310. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3311. If %reg1 = %reg3, convert to:
  3312. movl %reg1l,%reg2l
  3313. andl %reg1l,%reg1l
  3314. }
  3315. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3316. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3317. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3318. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3319. begin
  3320. TransferUsedRegs(TmpUsedRegs);
  3321. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3322. taicpu(hp1).opsize := S_L;
  3323. taicpu(hp1).loadreg(0, p_SourceReg);
  3324. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3325. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3326. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3327. begin
  3328. { %reg1 = %reg3 }
  3329. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3330. taicpu(hp1).opcode := A_AND;
  3331. end
  3332. else
  3333. begin
  3334. { %reg1 <> %reg3 }
  3335. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3336. end;
  3337. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3338. begin
  3339. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3340. RemoveCurrentP(p);
  3341. Result := True;
  3342. Exit;
  3343. end
  3344. else
  3345. begin
  3346. { Initial instruction wasn't actually changed }
  3347. Include(OptsToCheck, aoc_ForceNewIteration);
  3348. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3349. appears below since %reg1 has technically changed }
  3350. if taicpu(hp1).opcode = A_AND then
  3351. Exit;
  3352. end;
  3353. end;
  3354. {$endif x86_64}
  3355. end
  3356. else if taicpu(p).oper[0]^.typ = top_const then
  3357. begin
  3358. if (taicpu(hp1).opcode = A_OR) and
  3359. (taicpu(p).oper[1]^.typ = top_reg) and
  3360. MatchOperand(taicpu(p).oper[0]^, 0) and
  3361. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3362. begin
  3363. { mov 0, %reg
  3364. or ###,%reg
  3365. Change to (only if the flags are not used):
  3366. mov ###,%reg
  3367. }
  3368. TransferUsedRegs(TmpUsedRegs);
  3369. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3370. DoOptimisation := True;
  3371. { Even if the flags are used, we might be able to do the optimisation
  3372. if the conditions are predictable }
  3373. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3374. begin
  3375. { Only perform if ### = %reg (the same register) or equal to 0,
  3376. so %reg is guaranteed to still have a value of zero }
  3377. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3378. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3379. begin
  3380. hp2 := hp1;
  3381. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3382. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3383. GetNextInstruction(hp2, hp3) do
  3384. begin
  3385. { Don't continue modifying if the flags state is getting changed }
  3386. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3387. Break;
  3388. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3389. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3390. begin
  3391. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3392. begin
  3393. { Condition is always true }
  3394. case taicpu(hp3).opcode of
  3395. A_Jcc:
  3396. begin
  3397. { Check for jump shortcuts before we destroy the condition }
  3398. hp4 := hp3;
  3399. DoJumpOptimizations(hp3, TempBool);
  3400. { Make sure hp3 hasn't changed }
  3401. if (hp4 = hp3) then
  3402. begin
  3403. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3404. MakeUnconditional(taicpu(hp3));
  3405. end;
  3406. Result := True;
  3407. end;
  3408. A_CMOVcc:
  3409. begin
  3410. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3411. taicpu(hp3).opcode := A_MOV;
  3412. taicpu(hp3).condition := C_None;
  3413. Result := True;
  3414. end;
  3415. A_SETcc:
  3416. begin
  3417. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3418. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3419. taicpu(hp3).opcode := A_MOV;
  3420. taicpu(hp3).ops := 2;
  3421. taicpu(hp3).condition := C_None;
  3422. taicpu(hp3).opsize := S_B;
  3423. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3424. taicpu(hp3).loadconst(0, 1);
  3425. Result := True;
  3426. end;
  3427. else
  3428. InternalError(2021090701);
  3429. end;
  3430. end
  3431. 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
  3432. begin
  3433. { Condition is always false }
  3434. case taicpu(hp3).opcode of
  3435. A_Jcc:
  3436. begin
  3437. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3438. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3439. RemoveInstruction(hp3);
  3440. Result := True;
  3441. { Since hp3 was deleted, hp2 must not be updated }
  3442. Continue;
  3443. end;
  3444. A_CMOVcc:
  3445. begin
  3446. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3447. RemoveInstruction(hp3);
  3448. Result := True;
  3449. { Since hp3 was deleted, hp2 must not be updated }
  3450. Continue;
  3451. end;
  3452. A_SETcc:
  3453. begin
  3454. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3455. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3456. taicpu(hp3).opcode := A_MOV;
  3457. taicpu(hp3).ops := 2;
  3458. taicpu(hp3).condition := C_None;
  3459. taicpu(hp3).opsize := S_B;
  3460. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3461. taicpu(hp3).loadconst(0, 0);
  3462. Result := True;
  3463. end;
  3464. else
  3465. InternalError(2021090702);
  3466. end;
  3467. end
  3468. else
  3469. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3470. DoOptimisation := False;
  3471. end;
  3472. hp2 := hp3;
  3473. end;
  3474. if DoOptimisation then
  3475. begin
  3476. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3477. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3478. { Flags are still in use - don't optimise }
  3479. DoOptimisation := False;
  3480. end;
  3481. end
  3482. else
  3483. DoOptimisation := False;
  3484. end;
  3485. if DoOptimisation then
  3486. begin
  3487. {$ifdef x86_64}
  3488. { OR only supports 32-bit sign-extended constants for 64-bit
  3489. instructions, so compensate for this if the constant is
  3490. encoded as a value greater than or equal to 2^31 }
  3491. if (taicpu(hp1).opsize = S_Q) and
  3492. (taicpu(hp1).oper[0]^.typ = top_const) and
  3493. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3494. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3495. {$endif x86_64}
  3496. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3497. taicpu(hp1).opcode := A_MOV;
  3498. RemoveCurrentP(p);
  3499. Result := True;
  3500. Exit;
  3501. end;
  3502. end;
  3503. end
  3504. else if
  3505. { oper[0] is a reference }
  3506. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3507. begin
  3508. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3509. begin
  3510. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3511. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3512. ) or
  3513. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3514. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3515. )
  3516. ) and
  3517. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3518. { mov ref,reg1
  3519. lea (reg1,reg2),reg2
  3520. to
  3521. add ref,reg2 }
  3522. begin
  3523. TransferUsedRegs(TmpUsedRegs);
  3524. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3525. { If the flags register is in use, don't change the instruction to an
  3526. ADD otherwise this will scramble the flags. [Kit] }
  3527. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3528. { reg1 may not be used afterwards }
  3529. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3530. begin
  3531. Taicpu(hp1).opcode:=A_ADD;
  3532. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3533. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3534. RemoveCurrentp(p);
  3535. result:=true;
  3536. exit;
  3537. end;
  3538. end;
  3539. { If the LEA instruction can be converted into an arithmetic instruction,
  3540. it may be possible to then fold it in the next optimisation. }
  3541. if ConvertLEA(taicpu(hp1)) then
  3542. Include(OptsToCheck, aoc_ForceNewIteration);
  3543. end;
  3544. {
  3545. mov ref,reg0
  3546. <op> reg0,reg1
  3547. dealloc reg0
  3548. to
  3549. <op> ref,reg1
  3550. }
  3551. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3552. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3553. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3554. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3555. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3556. begin
  3557. TransferUsedRegs(TmpUsedRegs);
  3558. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3559. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3560. begin
  3561. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3562. { loadref increases the reference count, so decrement it again }
  3563. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3564. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3565. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3566. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3567. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3568. { See if we can remove the allocation of reg0 }
  3569. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3570. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3571. RemoveCurrentp(p);
  3572. Result:=true;
  3573. exit;
  3574. end;
  3575. end;
  3576. end;
  3577. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3578. overwrites the original destination register. e.g.
  3579. movl ###,%reg2d
  3580. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3581. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3582. }
  3583. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3584. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3585. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3586. begin
  3587. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3588. begin
  3589. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3590. case taicpu(p).oper[0]^.typ of
  3591. top_const:
  3592. { We have something like:
  3593. movb $x, %regb
  3594. movzbl %regb,%regd
  3595. Change to:
  3596. movl $x, %regd
  3597. }
  3598. begin
  3599. case taicpu(hp1).opsize of
  3600. S_BW:
  3601. begin
  3602. convert_mov_value(A_MOVSX, $FF);
  3603. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3604. taicpu(p).opsize := S_W;
  3605. end;
  3606. S_BL:
  3607. begin
  3608. convert_mov_value(A_MOVSX, $FF);
  3609. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3610. taicpu(p).opsize := S_L;
  3611. end;
  3612. S_WL:
  3613. begin
  3614. convert_mov_value(A_MOVSX, $FFFF);
  3615. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3616. taicpu(p).opsize := S_L;
  3617. end;
  3618. {$ifdef x86_64}
  3619. S_BQ:
  3620. begin
  3621. convert_mov_value(A_MOVSX, $FF);
  3622. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3623. taicpu(p).opsize := S_Q;
  3624. end;
  3625. S_WQ:
  3626. begin
  3627. convert_mov_value(A_MOVSX, $FFFF);
  3628. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3629. taicpu(p).opsize := S_Q;
  3630. end;
  3631. S_LQ:
  3632. begin
  3633. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3634. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3635. taicpu(p).opsize := S_Q;
  3636. end;
  3637. {$endif x86_64}
  3638. else
  3639. { If hp1 was a MOV instruction, it should have been
  3640. optimised already }
  3641. InternalError(2020021001);
  3642. end;
  3643. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3644. RemoveInstruction(hp1);
  3645. Result := True;
  3646. Exit;
  3647. end;
  3648. top_ref:
  3649. begin
  3650. { We have something like:
  3651. movb mem, %regb
  3652. movzbl %regb,%regd
  3653. Change to:
  3654. movzbl mem, %regd
  3655. }
  3656. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3657. begin
  3658. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3659. taicpu(p).opcode := taicpu(hp1).opcode;
  3660. taicpu(p).opsize := taicpu(hp1).opsize;
  3661. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3662. RemoveInstruction(hp1);
  3663. Result := True;
  3664. Exit;
  3665. end;
  3666. end;
  3667. else
  3668. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3669. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3670. Exit;
  3671. end;
  3672. end
  3673. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3674. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3675. optimised }
  3676. else
  3677. begin
  3678. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3679. RemoveCurrentP(p);
  3680. Result := True;
  3681. Exit;
  3682. end;
  3683. end;
  3684. if (taicpu(hp1).opcode = A_MOV) and
  3685. (
  3686. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3687. {$ifdef x86_64}
  3688. or (
  3689. { Permit zero extension from 32- to 64-bit when writing
  3690. a constant (it will be checked to see if it fits into
  3691. a signed 32-bit integer) }
  3692. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3693. (
  3694. { Valid situations... writing an unsigned 32-bit
  3695. immediate, or the destination is a 64-bit register }
  3696. (taicpu(p).oper[0]^.typ = top_const) or
  3697. (taicpu(hp1).oper[1]^.typ = top_reg)
  3698. ) and
  3699. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3700. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3701. )
  3702. {$endif x86_64}
  3703. ) then
  3704. begin
  3705. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3706. TransferUsedRegs(TmpUsedRegs);
  3707. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3708. { we have
  3709. mov x, %treg
  3710. mov %treg, y
  3711. }
  3712. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3713. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3714. begin
  3715. { we've got
  3716. mov x, %treg
  3717. mov %treg, y
  3718. with %treg is not used after }
  3719. case taicpu(p).oper[0]^.typ Of
  3720. { top_reg is covered by DeepMOVOpt }
  3721. top_const:
  3722. begin
  3723. { change
  3724. mov const, %treg
  3725. mov %treg, y
  3726. to
  3727. mov const, y
  3728. }
  3729. {$ifdef x86_64}
  3730. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3731. (
  3732. { For 32-to-64-bit zero-extension, the immediate
  3733. must be between 0 and 2^31 - 1}
  3734. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3735. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3736. ) or
  3737. (
  3738. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3739. (
  3740. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3741. )
  3742. ) then
  3743. {$endif x86_64}
  3744. begin
  3745. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3746. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3747. RemoveCurrentP(p);
  3748. Result := True;
  3749. Exit;
  3750. end;
  3751. end;
  3752. top_ref:
  3753. case taicpu(hp1).oper[1]^.typ of
  3754. top_reg:
  3755. { change
  3756. mov mem, %treg
  3757. mov %treg, %reg
  3758. to
  3759. mov mem, %reg"
  3760. }
  3761. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3762. begin
  3763. {$ifdef x86_64}
  3764. { If zero extending from 32-bit to 64-bit,
  3765. we have to make sure the replaced
  3766. register is the right size }
  3767. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3768. {$else}
  3769. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3770. {$endif x86_64}
  3771. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3772. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3773. RemoveInstruction(hp1);
  3774. Result := True;
  3775. Exit;
  3776. end
  3777. else if
  3778. { Make sure that if a reference is used, its
  3779. registers are not modified in between }
  3780. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3781. begin
  3782. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3783. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3784. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3785. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3786. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3787. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3788. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3789. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3790. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3791. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3792. RemoveCurrentP(p);
  3793. Result := True;
  3794. Exit;
  3795. end;
  3796. top_ref:
  3797. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3798. begin
  3799. {$ifdef x86_64}
  3800. { Look for the following to simplify:
  3801. mov x(mem1), %reg
  3802. mov %reg, y(mem2)
  3803. mov x+8(mem1), %reg
  3804. mov %reg, y+8(mem2)
  3805. Change to:
  3806. movdqu x(mem1), %xmmreg
  3807. movdqu %xmmreg, y(mem2)
  3808. ...but only as long as the memory blocks don't overlap
  3809. }
  3810. SourceRef := taicpu(p).oper[0]^.ref^;
  3811. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3812. if (taicpu(p).opsize = S_Q) and
  3813. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3814. GetNextInstruction(hp1, hp2) and
  3815. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3816. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3817. begin
  3818. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3819. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3820. Inc(SourceRef.offset, 8);
  3821. if UseAVX then
  3822. begin
  3823. MovAligned := A_VMOVDQA;
  3824. MovUnaligned := A_VMOVDQU;
  3825. end
  3826. else
  3827. begin
  3828. MovAligned := A_MOVDQA;
  3829. MovUnaligned := A_MOVDQU;
  3830. end;
  3831. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3832. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3833. begin
  3834. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3835. Inc(TargetRef.offset, 8);
  3836. if GetNextInstruction(hp2, hp3) and
  3837. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3838. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3839. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3840. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3841. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3842. begin
  3843. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3844. if NewMMReg <> NR_NO then
  3845. begin
  3846. { Remember that the offsets are 8 ahead }
  3847. if ((SourceRef.offset mod 16) = 8) and
  3848. (
  3849. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3850. (SourceRef.base = current_procinfo.framepointer) or
  3851. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3852. ) then
  3853. taicpu(p).opcode := MovAligned
  3854. else
  3855. taicpu(p).opcode := MovUnaligned;
  3856. taicpu(p).opsize := S_XMM;
  3857. taicpu(p).oper[1]^.reg := NewMMReg;
  3858. if ((TargetRef.offset mod 16) = 8) and
  3859. (
  3860. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3861. (TargetRef.base = current_procinfo.framepointer) or
  3862. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3863. ) then
  3864. taicpu(hp1).opcode := MovAligned
  3865. else
  3866. taicpu(hp1).opcode := MovUnaligned;
  3867. taicpu(hp1).opsize := S_XMM;
  3868. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3869. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3870. RemoveInstruction(hp2);
  3871. RemoveInstruction(hp3);
  3872. Result := True;
  3873. Exit;
  3874. end;
  3875. end;
  3876. end
  3877. else
  3878. begin
  3879. { See if the next references are 8 less rather than 8 greater }
  3880. Dec(SourceRef.offset, 16); { -8 the other way }
  3881. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3882. begin
  3883. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3884. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3885. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3886. GetNextInstruction(hp2, hp3) and
  3887. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3888. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3889. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3890. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3891. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3892. begin
  3893. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3894. if NewMMReg <> NR_NO then
  3895. begin
  3896. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3897. if ((SourceRef.offset mod 16) = 0) and
  3898. (
  3899. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3900. (SourceRef.base = current_procinfo.framepointer) or
  3901. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3902. ) then
  3903. taicpu(hp2).opcode := MovAligned
  3904. else
  3905. taicpu(hp2).opcode := MovUnaligned;
  3906. taicpu(hp2).opsize := S_XMM;
  3907. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3908. if ((TargetRef.offset mod 16) = 0) and
  3909. (
  3910. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3911. (TargetRef.base = current_procinfo.framepointer) or
  3912. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3913. ) then
  3914. taicpu(hp3).opcode := MovAligned
  3915. else
  3916. taicpu(hp3).opcode := MovUnaligned;
  3917. taicpu(hp3).opsize := S_XMM;
  3918. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3919. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3920. RemoveInstruction(hp1);
  3921. RemoveCurrentP(p);
  3922. Result := True;
  3923. Exit;
  3924. end;
  3925. end;
  3926. end;
  3927. end;
  3928. end;
  3929. {$endif x86_64}
  3930. end;
  3931. else
  3932. { The write target should be a reg or a ref }
  3933. InternalError(2021091601);
  3934. end;
  3935. else
  3936. ;
  3937. end;
  3938. end
  3939. else if (taicpu(p).oper[0]^.typ = top_const) and
  3940. { %treg is used afterwards, but all eventualities other
  3941. than the first MOV instruction being a constant are
  3942. covered by DeepMOVOpt, so only check for that }
  3943. (
  3944. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3945. not (cs_opt_size in current_settings.optimizerswitches) or
  3946. (taicpu(hp1).opsize = S_B)
  3947. ) and
  3948. (
  3949. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3950. (
  3951. { For 32-to-64-bit zero-extension, the immediate
  3952. must be between 0 and 2^31 - 1}
  3953. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3954. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3955. ) or
  3956. (
  3957. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3958. (
  3959. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3960. )
  3961. )
  3962. ) then
  3963. begin
  3964. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3965. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3966. Include(OptsToCheck, aoc_ForceNewIteration);
  3967. end;
  3968. end;
  3969. Break;
  3970. end;
  3971. end;
  3972. if taicpu(p).oper[0]^.typ = top_reg then
  3973. begin
  3974. { oper[1] is a reference }
  3975. { Saves on a large number of dereferences }
  3976. p_SourceReg := taicpu(p).oper[0]^.reg;
  3977. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3978. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3979. else
  3980. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3981. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3982. begin
  3983. if taicpu(p).oper[1]^.typ = top_reg then
  3984. begin
  3985. p_TargetReg := taicpu(p).oper[1]^.reg;
  3986. { Change:
  3987. movl %reg1,%reg2
  3988. ...
  3989. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3990. ...
  3991. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3992. To:
  3993. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3994. ...
  3995. movl x(%reg1),%reg1
  3996. ...
  3997. movl %reg1,%regX
  3998. }
  3999. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4000. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4001. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4002. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4003. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4004. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4005. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4006. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4007. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4008. begin
  4009. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4010. if RegInRef(p_TargetReg, SourceRef) and
  4011. { If %reg1 also appears in the second reference, then it will
  4012. not refer to the same memory block as the first reference }
  4013. not RegInRef(p_SourceReg, SourceRef) then
  4014. begin
  4015. { Check to see if the references match if %reg2 is changed to %reg1 }
  4016. if SourceRef.base = p_TargetReg then
  4017. SourceRef.base := p_SourceReg;
  4018. if SourceRef.index = p_TargetReg then
  4019. SourceRef.index := p_SourceReg;
  4020. { RefsEqual also checks to ensure both references are non-volatile }
  4021. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4022. begin
  4023. taicpu(hp2).loadreg(0, p_SourceReg);
  4024. TransferUsedRegs(TmpUsedRegs);
  4025. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4026. { Make sure the register is allocated between these instructions
  4027. even though it doesn't change value, since it may cause
  4028. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4029. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4030. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4031. Result := True;
  4032. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4035. RemoveCurrentP(p);
  4036. Exit;
  4037. end
  4038. else
  4039. begin
  4040. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4041. begin
  4042. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4043. RemoveCurrentP(p);
  4044. Exit;
  4045. end;
  4046. end;
  4047. { If we reach this point, p and hp1 weren't actually modified,
  4048. so we can do a bit more work on this pass }
  4049. end;
  4050. end;
  4051. end;
  4052. end;
  4053. end;
  4054. end;
  4055. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4056. { All the next optimisations require a next instruction }
  4057. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4058. Exit;
  4059. { Change:
  4060. movl/q (ref), %reg
  4061. movd/q %reg, %xmm0
  4062. (dealloc %reg)
  4063. To:
  4064. movd/q (ref), %xmm0
  4065. }
  4066. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4067. MatchInstruction(hp1,[A_MOVD,A_VMOVD{$ifdef x86_64},A_MOVQ,A_VMOVQ{$endif x86_64}],[]) and
  4068. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  4069. (taicpu(hp1).oper[1]^.typ=top_reg) and
  4070. (GetRegType(taicpu(hp1).oper[1]^.reg)=R_MMREGISTER) then
  4071. begin
  4072. TransferUsedRegs(TmpUsedRegs);
  4073. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4074. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  4075. begin
  4076. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  4077. { loadref increases the reference count, so decrement it again }
  4078. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  4079. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  4080. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  4081. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  4082. DebugMsg(SPeepholeOptimization+'Merged MOV and (V)MOVD/(V)MOVQ to eliminate intermediate register (MovMovD/Q2MovD/Q)',p);
  4083. RemoveCurrentP(p,hp1);
  4084. Result:=True;
  4085. Exit;
  4086. end;
  4087. end;
  4088. { Next instruction is also a MOV ? }
  4089. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4090. begin
  4091. if MatchOpType(taicpu(p), top_const, top_ref) and
  4092. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4093. TryConstMerge(p, hp1) then
  4094. begin
  4095. Result := True;
  4096. { In case we have four byte writes in a row, check for 2 more
  4097. right now so we don't have to wait for another iteration of
  4098. pass 1
  4099. }
  4100. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4101. case taicpu(p).opsize of
  4102. S_W:
  4103. begin
  4104. if GetNextInstruction(p, hp1) and
  4105. MatchInstruction(hp1, A_MOV, [S_B]) and
  4106. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4107. GetNextInstruction(hp1, hp2) and
  4108. MatchInstruction(hp2, A_MOV, [S_B]) and
  4109. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4110. { Try to merge the two bytes }
  4111. TryConstMerge(hp1, hp2) then
  4112. { Now try to merge the two words (hp2 will get deleted) }
  4113. TryConstMerge(p, hp1);
  4114. end;
  4115. S_L:
  4116. begin
  4117. { Though this only really benefits x86_64 and not i386, it
  4118. gets a potential optimisation done faster and hence
  4119. reduces the number of times OptPass1MOV is entered }
  4120. if GetNextInstruction(p, hp1) and
  4121. MatchInstruction(hp1, A_MOV, [S_W]) and
  4122. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4123. GetNextInstruction(hp1, hp2) and
  4124. MatchInstruction(hp2, A_MOV, [S_W]) and
  4125. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4126. { Try to merge the two words }
  4127. TryConstMerge(hp1, hp2) then
  4128. { This will always fail on i386, so don't bother
  4129. calling it unless we're doing x86_64 }
  4130. {$ifdef x86_64}
  4131. { Now try to merge the two longwords (hp2 will get deleted) }
  4132. TryConstMerge(p, hp1)
  4133. {$endif x86_64}
  4134. ;
  4135. end;
  4136. else
  4137. ;
  4138. end;
  4139. Exit;
  4140. end;
  4141. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4142. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4143. { mov reg1, mem1 or mov mem1, reg1
  4144. mov mem2, reg2 mov reg2, mem2}
  4145. begin
  4146. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4147. { mov reg1, mem1 or mov mem1, reg1
  4148. mov mem2, reg1 mov reg2, mem1}
  4149. begin
  4150. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4151. { Removes the second statement from
  4152. mov reg1, mem1/reg2
  4153. mov mem1/reg2, reg1 }
  4154. begin
  4155. if taicpu(p).oper[0]^.typ=top_reg then
  4156. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4157. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4158. RemoveInstruction(hp1);
  4159. Result:=true;
  4160. exit;
  4161. end
  4162. else
  4163. begin
  4164. TransferUsedRegs(TmpUsedRegs);
  4165. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4166. if (taicpu(p).oper[1]^.typ = top_ref) and
  4167. { mov reg1, mem1
  4168. mov mem2, reg1 }
  4169. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4170. GetNextInstruction(hp1, hp2) and
  4171. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4172. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4173. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4174. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4175. { change to
  4176. mov reg1, mem1 mov reg1, mem1
  4177. mov mem2, reg1 cmp reg1, mem2
  4178. cmp mem1, reg1
  4179. }
  4180. begin
  4181. RemoveInstruction(hp2);
  4182. taicpu(hp1).opcode := A_CMP;
  4183. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4184. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4185. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4186. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4187. end;
  4188. end;
  4189. end
  4190. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4191. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4192. begin
  4193. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4194. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4195. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4196. end
  4197. else
  4198. begin
  4199. TransferUsedRegs(TmpUsedRegs);
  4200. if GetNextInstruction(hp1, hp2) and
  4201. MatchOpType(taicpu(p),top_ref,top_reg) and
  4202. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4203. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4204. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4205. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4206. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4207. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4208. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4209. { mov mem1, %reg1
  4210. mov %reg1, mem2
  4211. mov mem2, reg2
  4212. to:
  4213. mov mem1, reg2
  4214. mov reg2, mem2}
  4215. begin
  4216. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4217. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4218. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4219. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4220. RemoveInstruction(hp2);
  4221. Result := True;
  4222. end
  4223. {$ifdef i386}
  4224. { this is enabled for i386 only, as the rules to create the reg sets below
  4225. are too complicated for x86-64, so this makes this code too error prone
  4226. on x86-64
  4227. }
  4228. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4229. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4230. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4231. { mov mem1, reg1 mov mem1, reg1
  4232. mov reg1, mem2 mov reg1, mem2
  4233. mov mem2, reg2 mov mem2, reg1
  4234. to: to:
  4235. mov mem1, reg1 mov mem1, reg1
  4236. mov mem1, reg2 mov reg1, mem2
  4237. mov reg1, mem2
  4238. or (if mem1 depends on reg1
  4239. and/or if mem2 depends on reg2)
  4240. to:
  4241. mov mem1, reg1
  4242. mov reg1, mem2
  4243. mov reg1, reg2
  4244. }
  4245. begin
  4246. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4247. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4248. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4249. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4250. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4251. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4252. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4253. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4254. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4255. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4256. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4257. end
  4258. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4259. begin
  4260. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4261. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4262. end
  4263. else
  4264. begin
  4265. RemoveInstruction(hp2);
  4266. end
  4267. {$endif i386}
  4268. ;
  4269. end;
  4270. end
  4271. { movl [mem1],reg1
  4272. movl [mem1],reg2
  4273. to
  4274. movl [mem1],reg1
  4275. movl reg1,reg2
  4276. }
  4277. else if not CheckMovMov2MovMov2(p, hp1) and
  4278. { movl const1,[mem1]
  4279. movl [mem1],reg1
  4280. to
  4281. movl const1,reg1
  4282. movl reg1,[mem1]
  4283. }
  4284. MatchOpType(Taicpu(p),top_const,top_ref) and
  4285. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4286. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4287. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4288. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4289. begin
  4290. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4291. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4292. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4293. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4294. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4295. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4296. Result:=true;
  4297. exit;
  4298. end;
  4299. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4300. end;
  4301. { search further than the next instruction for a mov (as long as it's not a jump) }
  4302. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4303. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4304. (taicpu(p).oper[1]^.typ = top_reg) and
  4305. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4306. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4307. begin
  4308. { we work with hp2 here, so hp1 can be still used later on when
  4309. checking for GetNextInstruction_p }
  4310. hp3 := hp1;
  4311. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4312. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4313. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4314. TransferUsedRegs(TmpUsedRegs);
  4315. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4316. if NotFirstIteration then
  4317. JumpTracking := TLinkedList.Create
  4318. else
  4319. JumpTracking := nil;
  4320. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4321. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4322. (hp2.typ=ait_instruction) do
  4323. begin
  4324. case taicpu(hp2).opcode of
  4325. A_POP:
  4326. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4327. begin
  4328. if not CrossJump and
  4329. not RegUsedBetween(p_TargetReg, p, hp2) then
  4330. begin
  4331. { We can remove the original MOV since the register
  4332. wasn't used between it and its popping from the stack }
  4333. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4334. RemoveCurrentp(p, hp1);
  4335. Result := True;
  4336. JumpTracking.Free;
  4337. Exit;
  4338. end;
  4339. { Can't go any further }
  4340. Break;
  4341. end;
  4342. A_MOV:
  4343. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4344. ((taicpu(p).oper[0]^.typ=top_const) or
  4345. ((taicpu(p).oper[0]^.typ=top_reg) and
  4346. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4347. )
  4348. ) then
  4349. begin
  4350. { we have
  4351. mov x, %treg
  4352. mov %treg, y
  4353. }
  4354. { We don't need to call UpdateUsedRegs for every instruction between
  4355. p and hp2 because the register we're concerned about will not
  4356. become deallocated (otherwise GetNextInstructionUsingReg would
  4357. have stopped at an earlier instruction). [Kit] }
  4358. TempRegUsed :=
  4359. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4360. RegReadByInstruction(p_TargetReg, hp3) or
  4361. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4362. case taicpu(p).oper[0]^.typ Of
  4363. top_reg:
  4364. begin
  4365. { change
  4366. mov %reg, %treg
  4367. mov %treg, y
  4368. to
  4369. mov %reg, y
  4370. }
  4371. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4372. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4373. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4374. begin
  4375. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4376. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4377. if TempRegUsed then
  4378. begin
  4379. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4380. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4381. { Set the start of the next GetNextInstructionUsingRegCond search
  4382. to start at the entry right before hp2 (which is about to be removed) }
  4383. hp3 := tai(hp2.Previous);
  4384. RemoveInstruction(hp2);
  4385. Include(OptsToCheck, aoc_ForceNewIteration);
  4386. { See if there's more we can optimise }
  4387. Continue;
  4388. end
  4389. else
  4390. begin
  4391. RemoveInstruction(hp2);
  4392. { We can remove the original MOV too }
  4393. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4394. RemoveCurrentP(p, hp1);
  4395. Result:=true;
  4396. JumpTracking.Free;
  4397. Exit;
  4398. end;
  4399. end
  4400. else
  4401. begin
  4402. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4403. taicpu(hp2).loadReg(0, p_SourceReg);
  4404. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4405. { Check to see if the register also appears in the reference }
  4406. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4407. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4408. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4409. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4410. begin
  4411. { Don't remove the first instruction if the temporary register is in use }
  4412. if not TempRegUsed then
  4413. begin
  4414. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4415. RemoveCurrentP(p, hp1);
  4416. Result:=true;
  4417. JumpTracking.Free;
  4418. Exit;
  4419. end;
  4420. { No need to set Result to True here. If there's another instruction later
  4421. on that can be optimised, it will be detected when the main Pass 1 loop
  4422. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4423. hp3 := hp2;
  4424. Continue;
  4425. end;
  4426. end;
  4427. end;
  4428. top_const:
  4429. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4430. begin
  4431. { change
  4432. mov const, %treg
  4433. mov %treg, y
  4434. to
  4435. mov const, y
  4436. }
  4437. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4438. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4439. begin
  4440. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4441. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4442. if TempRegUsed then
  4443. begin
  4444. { Don't remove the first instruction if the temporary register is in use }
  4445. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4446. { No need to set Result to True. If there's another instruction later on
  4447. that can be optimised, it will be detected when the main Pass 1 loop
  4448. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4449. end
  4450. else
  4451. begin
  4452. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4453. RemoveCurrentP(p, hp1);
  4454. Result:=true;
  4455. Exit;
  4456. end;
  4457. end;
  4458. end;
  4459. else
  4460. Internalerror(2019103001);
  4461. end;
  4462. end
  4463. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4464. begin
  4465. if not CrossJump and
  4466. not RegUsedBetween(p_TargetReg, p, hp2) and
  4467. not RegReadByInstruction(p_TargetReg, hp2) then
  4468. begin
  4469. { Register is not used before it is overwritten }
  4470. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4471. RemoveCurrentp(p, hp1);
  4472. Result := True;
  4473. Exit;
  4474. end;
  4475. if (taicpu(p).oper[0]^.typ = top_const) and
  4476. (taicpu(hp2).oper[0]^.typ = top_const) then
  4477. begin
  4478. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4479. begin
  4480. { Same value - register hasn't changed }
  4481. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4482. RemoveInstruction(hp2);
  4483. Include(OptsToCheck, aoc_ForceNewIteration);
  4484. { See if there's more we can optimise }
  4485. Continue;
  4486. end;
  4487. end;
  4488. {$ifdef x86_64}
  4489. end
  4490. { Change:
  4491. movl %reg1l,%reg2l
  4492. ...
  4493. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4494. To:
  4495. movl %reg1l,%reg2l
  4496. ...
  4497. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4498. If %reg1 = %reg3, convert to:
  4499. movl %reg1l,%reg2l
  4500. ...
  4501. andl %reg1l,%reg1l
  4502. }
  4503. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4504. (taicpu(p).oper[0]^.typ = top_reg) and
  4505. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4506. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4507. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4508. begin
  4509. TempRegUsed :=
  4510. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4511. RegReadByInstruction(p_TargetReg, hp3) or
  4512. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4513. taicpu(hp2).opsize := S_L;
  4514. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4515. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4516. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4517. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4518. begin
  4519. { %reg1 = %reg3 }
  4520. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4521. taicpu(hp2).opcode := A_AND;
  4522. end
  4523. else
  4524. begin
  4525. { %reg1 <> %reg3 }
  4526. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4527. end;
  4528. if not TempRegUsed then
  4529. begin
  4530. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4531. RemoveCurrentP(p, hp1);
  4532. Result := True;
  4533. Exit;
  4534. end
  4535. else
  4536. begin
  4537. { Initial instruction wasn't actually changed }
  4538. Include(OptsToCheck, aoc_ForceNewIteration);
  4539. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4540. appears below since %reg1 has technically changed }
  4541. if taicpu(hp2).opcode = A_AND then
  4542. Break;
  4543. end;
  4544. {$endif x86_64}
  4545. end
  4546. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4547. GetNextInstruction(hp2, hp4) and
  4548. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4549. { Optimise the following first:
  4550. movl [mem1],reg1
  4551. movl [mem1],reg2
  4552. to
  4553. movl [mem1],reg1
  4554. movl reg1,reg2
  4555. If [mem1] contains the target register and reg1 is the
  4556. the source register, this optimisation will get missed
  4557. and produce less efficient code later on.
  4558. }
  4559. if CheckMovMov2MovMov2(hp2, hp4) then
  4560. { Initial instruction wasn't actually changed }
  4561. Include(OptsToCheck, aoc_ForceNewIteration);
  4562. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4563. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4564. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4565. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4566. begin
  4567. {
  4568. Change from:
  4569. mov ###, %reg
  4570. ...
  4571. movs/z %reg,%reg (Same register, just different sizes)
  4572. To:
  4573. movs/z ###, %reg (Longer version)
  4574. ...
  4575. (remove)
  4576. }
  4577. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4578. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4579. { Keep the first instruction as mov if ### is a constant }
  4580. if taicpu(p).oper[0]^.typ = top_const then
  4581. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4582. else
  4583. begin
  4584. taicpu(p).opcode := taicpu(hp2).opcode;
  4585. taicpu(p).opsize := taicpu(hp2).opsize;
  4586. end;
  4587. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4588. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4589. RemoveInstruction(hp2);
  4590. Result := True;
  4591. JumpTracking.Free;
  4592. Exit;
  4593. end;
  4594. else
  4595. { Move down to the if-block below };
  4596. end;
  4597. { Also catches MOV/S/Z instructions that aren't modified }
  4598. if taicpu(p).oper[0]^.typ = top_reg then
  4599. begin
  4600. p_SourceReg := taicpu(p).oper[0]^.reg;
  4601. if
  4602. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4603. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4604. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4605. begin
  4606. Result := True;
  4607. { Just in case something didn't get modified (e.g. an
  4608. implicit register). Also, if it does read from this
  4609. register, then there's no longer an advantage to
  4610. changing the register on subsequent instructions.}
  4611. if not RegReadByInstruction(p_TargetReg, hp2) then
  4612. begin
  4613. { If a conditional jump was crossed, do not delete
  4614. the original MOV no matter what }
  4615. if not CrossJump and
  4616. { RegEndOfLife returns True if the register is
  4617. deallocated before the next instruction or has
  4618. been loaded with a new value }
  4619. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4620. begin
  4621. { We can remove the original MOV }
  4622. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4623. RemoveCurrentp(p, hp1);
  4624. JumpTracking.Free;
  4625. Result := True;
  4626. Exit;
  4627. end;
  4628. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4629. begin
  4630. { See if there's more we can optimise }
  4631. hp3 := hp2;
  4632. Continue;
  4633. end;
  4634. end;
  4635. end;
  4636. end;
  4637. { Break out of the while loop under normal circumstances }
  4638. Break;
  4639. end;
  4640. JumpTracking.Free;
  4641. end;
  4642. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4643. (taicpu(p).oper[1]^.typ = top_reg) and
  4644. (taicpu(p).opsize = S_L) and
  4645. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4646. (hp2.typ = ait_instruction) and
  4647. (taicpu(hp2).opcode = A_AND) and
  4648. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4649. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4650. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4651. ) then
  4652. begin
  4653. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4654. begin
  4655. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4656. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4657. begin
  4658. { Optimize out:
  4659. mov x, %reg
  4660. and ffffffffh, %reg
  4661. }
  4662. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4663. RemoveInstruction(hp2);
  4664. Result:=true;
  4665. exit;
  4666. end;
  4667. end;
  4668. end;
  4669. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4670. x >= RetOffset) as it doesn't do anything (it writes either to a
  4671. parameter or to the temporary storage room for the function
  4672. result)
  4673. }
  4674. if IsExitCode(hp1) and
  4675. (taicpu(p).oper[1]^.typ = top_ref) and
  4676. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4677. (
  4678. (
  4679. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4680. not (
  4681. assigned(current_procinfo.procdef.funcretsym) and
  4682. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4683. )
  4684. ) or
  4685. { Also discard writes to the stack that are below the base pointer,
  4686. as this is temporary storage rather than a function result on the
  4687. stack, say. }
  4688. (
  4689. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4690. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4691. )
  4692. ) then
  4693. begin
  4694. RemoveCurrentp(p, hp1);
  4695. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4696. RemoveLastDeallocForFuncRes(p);
  4697. Result:=true;
  4698. exit;
  4699. end;
  4700. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4701. begin
  4702. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4703. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4704. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4705. begin
  4706. { change
  4707. mov reg1, mem1
  4708. test/cmp x, mem1
  4709. to
  4710. mov reg1, mem1
  4711. test/cmp x, reg1
  4712. }
  4713. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4714. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4715. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4716. Result := True;
  4717. Exit;
  4718. end;
  4719. if DoMovCmpMemOpt(p, hp1) then
  4720. begin
  4721. Result := True;
  4722. Exit;
  4723. end;
  4724. end;
  4725. if (taicpu(p).oper[1]^.typ = top_reg) and
  4726. (hp1.typ = ait_instruction) and
  4727. GetNextInstruction(hp1, hp2) and
  4728. MatchInstruction(hp2,A_MOV,[]) and
  4729. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4730. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4731. (
  4732. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4733. {$ifdef x86_64}
  4734. or
  4735. (
  4736. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4737. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4738. )
  4739. {$endif x86_64}
  4740. ) then
  4741. begin
  4742. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4743. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4744. { change movsX/movzX reg/ref, reg2
  4745. add/sub/or/... reg3/$const, reg2
  4746. mov reg2 reg/ref
  4747. dealloc reg2
  4748. to
  4749. add/sub/or/... reg3/$const, reg/ref }
  4750. begin
  4751. TransferUsedRegs(TmpUsedRegs);
  4752. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4753. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4754. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4755. begin
  4756. { by example:
  4757. movswl %si,%eax movswl %si,%eax p
  4758. decl %eax addl %edx,%eax hp1
  4759. movw %ax,%si movw %ax,%si hp2
  4760. ->
  4761. movswl %si,%eax movswl %si,%eax p
  4762. decw %eax addw %edx,%eax hp1
  4763. movw %ax,%si movw %ax,%si hp2
  4764. }
  4765. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4766. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4767. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4768. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4769. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4770. {
  4771. ->
  4772. movswl %si,%eax movswl %si,%eax p
  4773. decw %si addw %dx,%si hp1
  4774. movw %ax,%si movw %ax,%si hp2
  4775. }
  4776. case taicpu(hp1).ops of
  4777. 1:
  4778. begin
  4779. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4780. if taicpu(hp1).oper[0]^.typ=top_reg then
  4781. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4782. end;
  4783. 2:
  4784. begin
  4785. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4786. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4787. (taicpu(hp1).opcode<>A_SHL) and
  4788. (taicpu(hp1).opcode<>A_SHR) and
  4789. (taicpu(hp1).opcode<>A_SAR) then
  4790. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4791. end;
  4792. else
  4793. internalerror(2008042701);
  4794. end;
  4795. {
  4796. ->
  4797. decw %si addw %dx,%si p
  4798. }
  4799. RemoveInstruction(hp2);
  4800. RemoveCurrentP(p, hp1);
  4801. Result:=True;
  4802. Exit;
  4803. end;
  4804. end;
  4805. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4806. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4807. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4808. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4809. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4810. ) and
  4811. { if ref contains a symbol, we cannot change its size to a smaller size }
  4812. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4813. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4814. )
  4815. {$ifdef i386}
  4816. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4817. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4818. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4819. {$endif i386}
  4820. then
  4821. { change movsX/movzX reg/ref, reg2
  4822. add/sub/or/... regX/$const, reg2
  4823. mov reg2, reg3
  4824. dealloc reg2
  4825. to
  4826. movsX/movzX reg/ref, reg3
  4827. add/sub/or/... reg3/$const, reg3
  4828. }
  4829. begin
  4830. TransferUsedRegs(TmpUsedRegs);
  4831. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4832. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4833. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4834. begin
  4835. { by example:
  4836. movswl %si,%eax movswl %si,%eax p
  4837. decl %eax addl %edx,%eax hp1
  4838. movw %ax,%si movw %ax,%si hp2
  4839. ->
  4840. movswl %si,%eax movswl %si,%eax p
  4841. decw %eax addw %edx,%eax hp1
  4842. movw %ax,%si movw %ax,%si hp2
  4843. }
  4844. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4845. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4846. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4847. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4848. { limit size of constants as well to avoid assembler errors, but
  4849. check opsize to avoid overflow when left shifting the 1 }
  4850. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4851. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4852. {$ifdef x86_64}
  4853. { Be careful of, for example:
  4854. movl %reg1,%reg2
  4855. addl %reg3,%reg2
  4856. movq %reg2,%reg4
  4857. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4858. }
  4859. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4860. begin
  4861. taicpu(hp2).changeopsize(S_L);
  4862. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4863. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4864. end;
  4865. {$endif x86_64}
  4866. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4867. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4868. if taicpu(p).oper[0]^.typ=top_reg then
  4869. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4870. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4871. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4872. {
  4873. ->
  4874. movswl %si,%eax movswl %si,%eax p
  4875. decw %si addw %dx,%si hp1
  4876. movw %ax,%si movw %ax,%si hp2
  4877. }
  4878. case taicpu(hp1).ops of
  4879. 1:
  4880. begin
  4881. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4882. if taicpu(hp1).oper[0]^.typ=top_reg then
  4883. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4884. end;
  4885. 2:
  4886. begin
  4887. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4888. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4889. (taicpu(hp1).opcode<>A_SHL) and
  4890. (taicpu(hp1).opcode<>A_SHR) and
  4891. (taicpu(hp1).opcode<>A_SAR) then
  4892. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4893. end;
  4894. else
  4895. internalerror(2018111801);
  4896. end;
  4897. {
  4898. ->
  4899. decw %si addw %dx,%si p
  4900. }
  4901. RemoveInstruction(hp2);
  4902. end;
  4903. end;
  4904. end;
  4905. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4906. GetNextInstruction(hp1, hp2) and
  4907. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4908. MatchOperand(Taicpu(p).oper[0]^,0) and
  4909. (Taicpu(p).oper[1]^.typ = top_reg) and
  4910. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4911. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4912. { mov reg1,0
  4913. bts reg1,operand1 --> mov reg1,operand2
  4914. or reg1,operand2 bts reg1,operand1}
  4915. begin
  4916. Taicpu(hp2).opcode:=A_MOV;
  4917. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4918. asml.remove(hp1);
  4919. insertllitem(hp2,hp2.next,hp1);
  4920. RemoveCurrentp(p, hp1);
  4921. Result:=true;
  4922. exit;
  4923. end;
  4924. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4925. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4926. GetNextInstruction(hp1, hp2) and
  4927. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4928. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4929. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4930. { change
  4931. mov reg1,reg2
  4932. sub reg3,reg2
  4933. cmp reg3,reg1
  4934. into
  4935. mov reg1,reg2
  4936. sub reg3,reg2
  4937. }
  4938. begin
  4939. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4940. RemoveInstruction(hp2);
  4941. Result:=true;
  4942. exit;
  4943. end;
  4944. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4945. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4946. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4947. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4948. begin
  4949. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4950. {$ifdef x86_64}
  4951. { Convert:
  4952. movq x(ref),%reg64
  4953. shrq y,%reg64
  4954. To:
  4955. movl x+4(ref),%reg32
  4956. shrl y-32,%reg32 (Remove if y = 32)
  4957. }
  4958. if (taicpu(p).opsize = S_Q) and
  4959. (taicpu(hp1).opcode = A_SHR) and
  4960. (taicpu(hp1).oper[0]^.val >= 32) then
  4961. begin
  4962. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4963. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4964. { Convert to 32-bit }
  4965. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4966. taicpu(p).opsize := S_L;
  4967. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4968. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4969. if (taicpu(hp1).oper[0]^.val = 32) then
  4970. begin
  4971. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4972. RemoveInstruction(hp1);
  4973. end
  4974. else
  4975. begin
  4976. { This will potentially open up more arithmetic operations since
  4977. the peephole optimizer now has a big hint that only the lower
  4978. 32 bits are currently in use (and opcodes are smaller in size) }
  4979. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4980. taicpu(hp1).opsize := S_L;
  4981. Dec(taicpu(hp1).oper[0]^.val, 32);
  4982. DebugMsg(SPeepholeOptimization + PreMessage +
  4983. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4984. end;
  4985. Result := True;
  4986. Exit;
  4987. end;
  4988. {$endif x86_64}
  4989. { Convert:
  4990. movl x(ref),%reg
  4991. shrl $24,%reg
  4992. To:
  4993. movzbl x+3(ref),%reg
  4994. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4995. Also accept sar instead of shr, but convert to movsx instead of movzx
  4996. }
  4997. if taicpu(hp1).opcode = A_SHR then
  4998. MovUnaligned := A_MOVZX
  4999. else
  5000. MovUnaligned := A_MOVSX;
  5001. NewSize := S_NO;
  5002. NewOffset := 0;
  5003. case taicpu(p).opsize of
  5004. S_B:
  5005. { No valid combinations };
  5006. S_W:
  5007. if (taicpu(hp1).oper[0]^.val = 8) then
  5008. begin
  5009. NewSize := S_BW;
  5010. NewOffset := 1;
  5011. end;
  5012. S_L:
  5013. case taicpu(hp1).oper[0]^.val of
  5014. 16:
  5015. begin
  5016. NewSize := S_WL;
  5017. NewOffset := 2;
  5018. end;
  5019. 24:
  5020. begin
  5021. NewSize := S_BL;
  5022. NewOffset := 3;
  5023. end;
  5024. else
  5025. ;
  5026. end;
  5027. {$ifdef x86_64}
  5028. S_Q:
  5029. case taicpu(hp1).oper[0]^.val of
  5030. 32:
  5031. begin
  5032. if taicpu(hp1).opcode = A_SAR then
  5033. begin
  5034. { 32-bit to 64-bit is a distinct instruction }
  5035. MovUnaligned := A_MOVSXD;
  5036. NewSize := S_LQ;
  5037. NewOffset := 4;
  5038. end
  5039. else
  5040. { Should have been handled by MovShr2Mov above }
  5041. InternalError(2022081811);
  5042. end;
  5043. 48:
  5044. begin
  5045. NewSize := S_WQ;
  5046. NewOffset := 6;
  5047. end;
  5048. 56:
  5049. begin
  5050. NewSize := S_BQ;
  5051. NewOffset := 7;
  5052. end;
  5053. else
  5054. ;
  5055. end;
  5056. {$endif x86_64}
  5057. else
  5058. InternalError(2022081810);
  5059. end;
  5060. if (NewSize <> S_NO) and
  5061. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5062. begin
  5063. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5064. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5065. debug_op2str(MovUnaligned);
  5066. {$ifdef x86_64}
  5067. if MovUnaligned <> A_MOVSXD then
  5068. { Don't add size suffix for MOVSXD }
  5069. {$endif x86_64}
  5070. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5071. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5072. taicpu(p).opcode := MovUnaligned;
  5073. taicpu(p).opsize := NewSize;
  5074. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5075. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5076. RemoveInstruction(hp1);
  5077. Result := True;
  5078. Exit;
  5079. end;
  5080. end;
  5081. { Backward optimisation shared with OptPass2MOV }
  5082. if FuncMov2Func(p, hp1) then
  5083. begin
  5084. Result := True;
  5085. Exit;
  5086. end;
  5087. end;
  5088. function TX86AsmOptimizer.OptPass1MOVD(var p : tai) : boolean;
  5089. { This function also handles the 64-bit version, MOVQ }
  5090. var
  5091. hp1: tai;
  5092. begin
  5093. Result:=false;
  5094. { Change:
  5095. movd/q %xmm0, %reg
  5096. ...
  5097. movl/q %reg, (ref)
  5098. (dealloc %reg)
  5099. To:
  5100. movd/q %xmm0, (ref)
  5101. }
  5102. if MatchOpType(taicpu(p),top_reg,top_reg) and
  5103. (GetRegType(taicpu(p).oper[0]^.reg)=R_MMREGISTER) and
  5104. (GetRegType(taicpu(p).oper[1]^.reg)=R_INTREGISTER) and
  5105. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  5106. MatchInstruction(hp1, A_MOV, []) and
  5107. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  5108. (taicpu(hp1).oper[1]^.typ=top_ref) and
  5109. not RegInRef(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.ref^) then
  5110. begin
  5111. TransferUsedRegs(TmpUsedRegs);
  5112. UpdateUsedRegsBetween(TmpUsedRegs,p,hp1);
  5113. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  5114. begin
  5115. if (
  5116. { Instructions are always adjacent under -O2 and under }
  5117. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5118. (
  5119. (
  5120. (taicpu(hp1).oper[1]^.ref^.base=NR_NO) or
  5121. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.base,p,hp1)
  5122. ) and
  5123. (
  5124. (taicpu(hp1).oper[1]^.ref^.index=NR_NO) or
  5125. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.index,p,hp1)
  5126. )
  5127. )
  5128. ) then
  5129. begin
  5130. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1a)',p);
  5131. taicpu(p).loadref(1,taicpu(hp1).oper[1]^.ref^);
  5132. { loadref increases the reference count, so decrement it again }
  5133. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5134. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5135. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5136. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5137. RemoveInstruction(hp1);
  5138. Include(OptsToCheck, aoc_ForceNewIteration);
  5139. end
  5140. else if not RegModifiedBetween(taicpu(p).oper[0]^.reg,p,hp1) then
  5141. begin
  5142. { Still possible to optimise if hp1 is converted instead }
  5143. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1b)',hp1);
  5144. { Decrement the reference prior to replacing it }
  5145. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5146. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5147. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5148. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5149. taicpu(hp1).opcode:=taicpu(p).opcode;
  5150. taicpu(hp1).opsize:=taicpu(p).opsize;
  5151. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  5152. TransferUsedRegs(TmpUsedRegs);
  5153. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,TmpUsedRegs);
  5154. RemoveCurrentP(p);
  5155. Result:=True;
  5156. Exit;
  5157. end;
  5158. end;
  5159. end;
  5160. end;
  5161. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5162. var
  5163. hp1 : tai;
  5164. begin
  5165. Result:=false;
  5166. if taicpu(p).ops <> 2 then
  5167. exit;
  5168. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5169. GetNextInstruction(p,hp1) then
  5170. begin
  5171. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5172. (taicpu(hp1).ops = 2) then
  5173. begin
  5174. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5175. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5176. { movXX reg1, mem1 or movXX mem1, reg1
  5177. movXX mem2, reg2 movXX reg2, mem2}
  5178. begin
  5179. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5180. { movXX reg1, mem1 or movXX mem1, reg1
  5181. movXX mem2, reg1 movXX reg2, mem1}
  5182. begin
  5183. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5184. begin
  5185. { Removes the second statement from
  5186. movXX reg1, mem1/reg2
  5187. movXX mem1/reg2, reg1
  5188. }
  5189. if taicpu(p).oper[0]^.typ=top_reg then
  5190. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5191. { Removes the second statement from
  5192. movXX mem1/reg1, reg2
  5193. movXX reg2, mem1/reg1
  5194. }
  5195. if (taicpu(p).oper[1]^.typ=top_reg) and
  5196. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5197. begin
  5198. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5199. RemoveInstruction(hp1);
  5200. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5201. Result:=true;
  5202. exit;
  5203. end
  5204. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5205. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5206. begin
  5207. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5208. RemoveInstruction(hp1);
  5209. Result:=true;
  5210. exit;
  5211. end;
  5212. end
  5213. end;
  5214. end;
  5215. end;
  5216. end;
  5217. end;
  5218. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5219. var
  5220. hp1 : tai;
  5221. begin
  5222. result:=false;
  5223. { replace
  5224. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5225. MovX %mreg2,%mreg1
  5226. dealloc %mreg2
  5227. by
  5228. <Op>X %mreg2,%mreg1
  5229. ?
  5230. }
  5231. if GetNextInstruction(p,hp1) and
  5232. { we mix single and double opperations here because we assume that the compiler
  5233. generates vmovapd only after double operations and vmovaps only after single operations }
  5234. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5235. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5236. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5237. (taicpu(p).oper[0]^.typ=top_reg) then
  5238. begin
  5239. TransferUsedRegs(TmpUsedRegs);
  5240. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5241. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5242. begin
  5243. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5244. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5245. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5246. RemoveInstruction(hp1);
  5247. result:=true;
  5248. end;
  5249. end;
  5250. end;
  5251. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5252. var
  5253. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5254. JumpLabel, JumpLabel_dist: TAsmLabel;
  5255. FirstValue, SecondValue: TCGInt;
  5256. function OptimizeJump(var InputP: tai): Boolean;
  5257. var
  5258. TempBool: Boolean;
  5259. begin
  5260. Result := False;
  5261. TempBool := True;
  5262. if DoJumpOptimizations(InputP, TempBool) or
  5263. not TempBool then
  5264. begin
  5265. Result := True;
  5266. if Assigned(InputP) then
  5267. begin
  5268. { CollapseZeroDistJump will be set to the label or an align
  5269. before it after the jump if it optimises, whether or not
  5270. the label is live or dead }
  5271. if (InputP.typ = ait_align) or
  5272. (
  5273. (InputP.typ = ait_label) and
  5274. not (tai_label(InputP).labsym.is_used)
  5275. ) then
  5276. GetNextInstruction(InputP, InputP);
  5277. end;
  5278. Exit;
  5279. end;
  5280. end;
  5281. begin
  5282. Result := False;
  5283. if (taicpu(p).oper[0]^.typ = top_const) and
  5284. (taicpu(p).oper[0]^.val <> -1) then
  5285. begin
  5286. { Convert unsigned maximum constants to -1 to aid optimisation }
  5287. case taicpu(p).opsize of
  5288. S_B:
  5289. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5290. begin
  5291. taicpu(p).oper[0]^.val := -1;
  5292. Result := True;
  5293. Exit;
  5294. end;
  5295. S_W:
  5296. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5297. begin
  5298. taicpu(p).oper[0]^.val := -1;
  5299. Result := True;
  5300. Exit;
  5301. end;
  5302. S_L:
  5303. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5304. begin
  5305. taicpu(p).oper[0]^.val := -1;
  5306. Result := True;
  5307. Exit;
  5308. end;
  5309. {$ifdef x86_64}
  5310. S_Q:
  5311. { Storing anything greater than $7FFFFFFF is not possible so do
  5312. nothing };
  5313. {$endif x86_64}
  5314. else
  5315. InternalError(2021121001);
  5316. end;
  5317. end;
  5318. if GetNextInstruction(p, hp1) and
  5319. TrySwapMovCmp(p, hp1) then
  5320. begin
  5321. Result := True;
  5322. Exit;
  5323. end;
  5324. p_label := nil;
  5325. JumpLabel := nil;
  5326. if MatchInstruction(hp1, A_Jcc, []) then
  5327. begin
  5328. if OptimizeJump(hp1) then
  5329. begin
  5330. Result := True;
  5331. if Assigned(hp1) then
  5332. begin
  5333. { CollapseZeroDistJump will be set to the label or an align
  5334. before it after the jump if it optimises, whether or not
  5335. the label is live or dead }
  5336. if (hp1.typ = ait_align) or
  5337. (
  5338. (hp1.typ = ait_label) and
  5339. not (tai_label(hp1).labsym.is_used)
  5340. ) then
  5341. GetNextInstruction(hp1, hp1);
  5342. end;
  5343. TransferUsedRegs(TmpUsedRegs);
  5344. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5345. if not Assigned(hp1) or
  5346. (
  5347. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5348. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5349. ) then
  5350. begin
  5351. { No more conditional jumps; conditional statement is no longer required }
  5352. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5353. RemoveCurrentP(p);
  5354. end;
  5355. Exit;
  5356. end;
  5357. if IsJumpToLabel(taicpu(hp1)) then
  5358. begin
  5359. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5360. if Assigned(JumpLabel) then
  5361. p_label := getlabelwithsym(JumpLabel);
  5362. end;
  5363. end;
  5364. { Search for:
  5365. test $x,(reg/ref)
  5366. jne @lbl1
  5367. test $y,(reg/ref) (same register or reference)
  5368. jne @lbl1
  5369. Change to:
  5370. test $(x or y),(reg/ref)
  5371. jne @lbl1
  5372. (Note, this doesn't work with je instead of jne)
  5373. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5374. Also search for:
  5375. test $x,(reg/ref)
  5376. je @lbl1
  5377. ...
  5378. test $y,(reg/ref)
  5379. je/jne @lbl2
  5380. If (x or y) = x, then the second jump is deterministic
  5381. }
  5382. if (
  5383. (
  5384. (taicpu(p).oper[0]^.typ = top_const) or
  5385. (
  5386. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5387. (taicpu(p).oper[0]^.typ = top_reg) and
  5388. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5389. )
  5390. ) and
  5391. MatchInstruction(hp1, A_JCC, [])
  5392. ) then
  5393. begin
  5394. if (taicpu(p).oper[0]^.typ = top_reg) and
  5395. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5396. FirstValue := -1
  5397. else
  5398. FirstValue := taicpu(p).oper[0]^.val;
  5399. { If we have several test/jne's in a row, it might be the case that
  5400. the second label doesn't go to the same location, but the one
  5401. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5402. so accommodate for this with a while loop.
  5403. }
  5404. hp1_last := hp1;
  5405. while (
  5406. (
  5407. (taicpu(p).oper[1]^.typ = top_reg) and
  5408. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5409. ) or GetNextInstruction(hp1_last, p_dist)
  5410. ) and (p_dist.typ = ait_instruction) do
  5411. begin
  5412. if (
  5413. (
  5414. (taicpu(p_dist).opcode = A_TEST) and
  5415. (
  5416. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5417. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5418. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5419. )
  5420. ) or
  5421. (
  5422. { cmp 0,%reg = test %reg,%reg }
  5423. (taicpu(p_dist).opcode = A_CMP) and
  5424. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5425. )
  5426. ) and
  5427. { Make sure the destination operands are actually the same }
  5428. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5429. GetNextInstruction(p_dist, hp1_dist) and
  5430. MatchInstruction(hp1_dist, A_JCC, []) then
  5431. begin
  5432. if OptimizeJump(hp1_dist) then
  5433. begin
  5434. Result := True;
  5435. Exit;
  5436. end;
  5437. if
  5438. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5439. (
  5440. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5441. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5442. ) then
  5443. SecondValue := -1
  5444. else
  5445. SecondValue := taicpu(p_dist).oper[0]^.val;
  5446. { If both of the TEST constants are identical, delete the
  5447. second TEST that is unnecessary (be careful though, just
  5448. in case the flags are modified in between) }
  5449. if (FirstValue = SecondValue) then
  5450. begin
  5451. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5452. begin
  5453. { Since the second jump's condition is a subset of the first, we
  5454. know it will never branch because the first jump dominates it.
  5455. Get it out of the way now rather than wait for the jump
  5456. optimisations for a speed boost. }
  5457. if IsJumpToLabel(taicpu(hp1_dist)) then
  5458. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5459. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5460. RemoveInstruction(hp1_dist);
  5461. Result := True;
  5462. end
  5463. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5464. begin
  5465. { If the inverse of the first condition is a subset of the second,
  5466. the second one will definitely branch if the first one doesn't }
  5467. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5468. { We can remove the TEST instruction too }
  5469. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5470. RemoveInstruction(p_dist);
  5471. MakeUnconditional(taicpu(hp1_dist));
  5472. RemoveDeadCodeAfterJump(hp1_dist);
  5473. { Since the jump is now unconditional, we can't
  5474. continue any further with this particular
  5475. optimisation. The original TEST is still intact
  5476. though, so there might be something else we can
  5477. do }
  5478. Include(OptsToCheck, aoc_ForceNewIteration);
  5479. Break;
  5480. end;
  5481. if Result or
  5482. { If a jump wasn't removed or made unconditional, only
  5483. remove the identical TEST instruction if the flags
  5484. weren't modified }
  5485. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5486. begin
  5487. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5488. RemoveInstruction(p_dist);
  5489. { If the jump was removed or made unconditional, we
  5490. don't need to allocate NR_DEFAULTFLAGS over the
  5491. entire range }
  5492. if not Result then
  5493. begin
  5494. { Mark the flags as 'in use' over the entire range }
  5495. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5496. { Speed gain - continue search from the Jcc instruction }
  5497. hp1_last := hp1_dist;
  5498. { Only the TEST instruction was removed, and the
  5499. original was unchanged, so we can safely do
  5500. another iteration of the while loop }
  5501. Include(OptsToCheck, aoc_ForceNewIteration);
  5502. Continue;
  5503. end;
  5504. Exit;
  5505. end;
  5506. end;
  5507. hp1_last := nil;
  5508. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5509. (
  5510. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5511. { Always adjacent under -O2 and under }
  5512. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5513. (
  5514. GetNextInstruction(hp1, hp1_last) and
  5515. (hp1_last = p_dist)
  5516. )
  5517. ) and
  5518. (
  5519. (
  5520. { Test the following variant:
  5521. test $x,(reg/ref)
  5522. jne @lbl1
  5523. test $y,(reg/ref)
  5524. je @lbl2
  5525. @lbl1:
  5526. Becomes:
  5527. test $(x or y),(reg/ref)
  5528. je @lbl2
  5529. @lbl1: (may become a dead label)
  5530. }
  5531. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5532. GetNextInstruction(hp1_dist, hp1_last) and
  5533. (hp1_last = p_label)
  5534. ) or
  5535. (
  5536. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5537. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5538. then the second jump will never branch, so it can also be
  5539. removed regardless of where it goes }
  5540. (
  5541. (FirstValue = -1) or
  5542. (SecondValue = -1) or
  5543. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5544. )
  5545. )
  5546. ) then
  5547. begin
  5548. { Same jump location... can be a register since nothing's changed }
  5549. { If any of the entries are equivalent to test %reg,%reg, then the
  5550. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5551. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5552. if (hp1_last = p_label) then
  5553. begin
  5554. { Variant }
  5555. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5556. RemoveInstruction(p_dist);
  5557. if Assigned(JumpLabel) then
  5558. JumpLabel.decrefs;
  5559. RemoveInstruction(hp1);
  5560. end
  5561. else
  5562. begin
  5563. { Only remove the second test if no jumps or other conditional instructions follow }
  5564. TransferUsedRegs(TmpUsedRegs);
  5565. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5567. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5568. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5569. begin
  5570. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5571. RemoveInstruction(p_dist);
  5572. { Remove the first jump, not the second, to keep
  5573. any register deallocations between the second
  5574. TEST/JNE pair in the same place. Aids future
  5575. optimisation. }
  5576. if Assigned(JumpLabel) then
  5577. JumpLabel.decrefs;
  5578. RemoveInstruction(hp1);
  5579. end
  5580. else
  5581. begin
  5582. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5583. if IsJumpToLabel(taicpu(hp1_dist)) then
  5584. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5585. { Remove second jump in this instance }
  5586. RemoveInstruction(hp1_dist);
  5587. end;
  5588. end;
  5589. Result := True;
  5590. Exit;
  5591. end;
  5592. end;
  5593. if { If -O2 and under, it may stop on any old instruction }
  5594. (cs_opt_level3 in current_settings.optimizerswitches) and
  5595. (taicpu(p).oper[1]^.typ = top_reg) and
  5596. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5597. begin
  5598. hp1_last := p_dist;
  5599. Continue;
  5600. end;
  5601. Break;
  5602. end;
  5603. end;
  5604. { Search for:
  5605. test %reg,%reg
  5606. j(c1) @lbl1
  5607. ...
  5608. @lbl:
  5609. test %reg,%reg (same register)
  5610. j(c2) @lbl2
  5611. If c2 is a subset of c1, change to:
  5612. test %reg,%reg
  5613. j(c1) @lbl2
  5614. (@lbl1 may become a dead label as a result)
  5615. }
  5616. if (taicpu(p).oper[1]^.typ = top_reg) and
  5617. (taicpu(p).oper[0]^.typ = top_reg) and
  5618. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5619. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5620. Assigned(p_label) and
  5621. GetNextInstruction(p_label, p_dist) and
  5622. MatchInstruction(p_dist, A_TEST, []) and
  5623. { It's fine if the second test uses smaller sub-registers }
  5624. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5625. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5626. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5627. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5628. GetNextInstruction(p_dist, hp1_dist) and
  5629. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5630. begin
  5631. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5632. if JumpLabel = JumpLabel_dist then
  5633. { This is an infinite loop }
  5634. Exit;
  5635. { Best optimisation when the first condition is a subset (or equal) of the second }
  5636. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5637. begin
  5638. { Any registers used here will already be allocated }
  5639. if Assigned(JumpLabel) then
  5640. JumpLabel.DecRefs;
  5641. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5642. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5643. Result := True;
  5644. Exit;
  5645. end;
  5646. end;
  5647. end;
  5648. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5649. var
  5650. hp1, hp2: tai;
  5651. ActiveReg: TRegister;
  5652. OldOffset: asizeint;
  5653. ThisConst: TCGInt;
  5654. function RegDeallocated: Boolean;
  5655. begin
  5656. TransferUsedRegs(TmpUsedRegs);
  5657. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5658. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5659. end;
  5660. begin
  5661. result:=false;
  5662. hp1 := nil;
  5663. { replace
  5664. addX const,%reg1
  5665. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5666. dealloc %reg1
  5667. by
  5668. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5669. }
  5670. if MatchOpType(taicpu(p),top_const,top_reg) then
  5671. begin
  5672. ActiveReg := taicpu(p).oper[1]^.reg;
  5673. { Ensures the entire register was updated }
  5674. if (taicpu(p).opsize >= S_L) and
  5675. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5676. MatchInstruction(hp1,A_LEA,[]) and
  5677. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5678. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5679. (
  5680. { Cover the case where the register in the reference is also the destination register }
  5681. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5682. (
  5683. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5684. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5685. RegDeallocated
  5686. )
  5687. ) then
  5688. begin
  5689. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5690. {$push}
  5691. {$R-}{$Q-}
  5692. { Explicitly disable overflow checking for these offset calculation
  5693. as those do not matter for the final result }
  5694. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5695. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5696. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5697. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5698. {$pop}
  5699. {$ifdef x86_64}
  5700. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5701. begin
  5702. { Overflow; abort }
  5703. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5704. end
  5705. else
  5706. {$endif x86_64}
  5707. begin
  5708. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5709. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5710. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5711. RemoveCurrentP(p, hp1)
  5712. else
  5713. RemoveCurrentP(p);
  5714. result:=true;
  5715. Exit;
  5716. end;
  5717. end;
  5718. if (
  5719. { Save calling GetNextInstructionUsingReg again }
  5720. Assigned(hp1) or
  5721. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5722. ) and
  5723. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5724. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5725. begin
  5726. { Make sure the flags aren't in use by the second operation }
  5727. TransferUsedRegs(TmpUsedRegs);
  5728. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5729. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5730. begin
  5731. if taicpu(hp1).oper[0]^.typ = top_const then
  5732. begin
  5733. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5734. if taicpu(hp1).opcode = A_ADD then
  5735. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5736. else
  5737. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5738. Result := True;
  5739. { Handle any overflows }
  5740. case taicpu(p).opsize of
  5741. S_B:
  5742. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5743. S_W:
  5744. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5745. S_L:
  5746. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5747. {$ifdef x86_64}
  5748. S_Q:
  5749. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5750. { Overflow; abort }
  5751. Result := False
  5752. else
  5753. taicpu(p).oper[0]^.val := ThisConst;
  5754. {$endif x86_64}
  5755. else
  5756. InternalError(2021102610);
  5757. end;
  5758. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5759. if Result then
  5760. begin
  5761. if (taicpu(p).oper[0]^.val < 0) and
  5762. (
  5763. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5764. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5765. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5766. ) then
  5767. begin
  5768. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5769. taicpu(p).opcode := A_SUB;
  5770. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5771. end
  5772. else
  5773. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5774. RemoveInstruction(hp1);
  5775. end;
  5776. end
  5777. else
  5778. begin
  5779. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5780. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5781. Asml.Remove(p);
  5782. Asml.InsertAfter(p, hp1);
  5783. p := hp1;
  5784. Result := True;
  5785. Exit;
  5786. end;
  5787. end;
  5788. end;
  5789. if DoArithCombineOpt(p) then
  5790. Result:=true;
  5791. end;
  5792. end;
  5793. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5794. var
  5795. hp1, hp2: tai;
  5796. ref: Integer;
  5797. saveref: treference;
  5798. offsetcalc: Int64;
  5799. TempReg: TRegister;
  5800. Multiple: TCGInt;
  5801. Adjacent, IntermediateRegDiscarded: Boolean;
  5802. begin
  5803. Result:=false;
  5804. { play save and throw an error if LEA uses a seg register prefix,
  5805. this is most likely an error somewhere else }
  5806. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5807. internalerror(2022022001);
  5808. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5809. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5810. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5811. (
  5812. { do not mess with leas accessing the stack pointer
  5813. unless it's a null operation }
  5814. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5815. (
  5816. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5817. (taicpu(p).oper[0]^.ref^.offset = 0)
  5818. )
  5819. ) and
  5820. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5821. begin
  5822. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5823. begin
  5824. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5825. begin
  5826. taicpu(p).opcode := A_MOV;
  5827. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5828. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5829. end
  5830. else
  5831. begin
  5832. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5833. RemoveCurrentP(p);
  5834. end;
  5835. Result:=true;
  5836. exit;
  5837. end
  5838. else if (
  5839. { continue to use lea to adjust the stack pointer,
  5840. it is the recommended way, but only if not optimizing for size }
  5841. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5842. (cs_opt_size in current_settings.optimizerswitches)
  5843. ) and
  5844. { If the flags register is in use, don't change the instruction
  5845. to an ADD otherwise this will scramble the flags. [Kit] }
  5846. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5847. ConvertLEA(taicpu(p)) then
  5848. begin
  5849. Result:=true;
  5850. exit;
  5851. end;
  5852. end;
  5853. { Don't optimise if the stack or frame pointer is the destination register }
  5854. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5855. Exit;
  5856. if GetNextInstruction(p,hp1) and
  5857. (hp1.typ=ait_instruction) then
  5858. begin
  5859. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5860. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5861. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5862. begin
  5863. TransferUsedRegs(TmpUsedRegs);
  5864. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5865. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5866. begin
  5867. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5868. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5869. RemoveInstruction(hp1);
  5870. result:=true;
  5871. exit;
  5872. end;
  5873. end;
  5874. { changes
  5875. lea <ref1>, reg1
  5876. <op> ...,<ref. with reg1>,...
  5877. to
  5878. <op> ...,<ref1>,... }
  5879. { find a reference which uses reg1 }
  5880. 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
  5881. ref:=0
  5882. 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
  5883. ref:=1
  5884. else
  5885. ref:=-1;
  5886. if (ref<>-1) and
  5887. { reg1 must be either the base or the index }
  5888. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5889. begin
  5890. { reg1 can be removed from the reference }
  5891. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5892. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5893. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5894. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5895. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5896. else
  5897. Internalerror(2019111201);
  5898. { check if the can insert all data of the lea into the second instruction }
  5899. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5900. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5901. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5902. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5903. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5904. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5905. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5906. {$ifdef x86_64}
  5907. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5908. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5909. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5910. )
  5911. {$endif x86_64}
  5912. then
  5913. begin
  5914. { reg1 might not used by the second instruction after it is remove from the reference }
  5915. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5916. begin
  5917. TransferUsedRegs(TmpUsedRegs);
  5918. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5919. { reg1 is not updated so it might not be used afterwards }
  5920. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5921. begin
  5922. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5923. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5924. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5925. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5926. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5927. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5928. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5929. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5930. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5931. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5932. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5933. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5934. RemoveCurrentP(p, hp1);
  5935. result:=true;
  5936. exit;
  5937. end
  5938. end;
  5939. end;
  5940. { recover }
  5941. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5942. end;
  5943. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5944. if Adjacent or
  5945. { Check further ahead (up to 2 instructions ahead for -O2) }
  5946. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5947. begin
  5948. { Check common LEA/LEA conditions }
  5949. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5950. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5951. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5952. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5953. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5954. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5955. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5956. (
  5957. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5958. calling it (since it calls GetNextInstruction) }
  5959. Adjacent or
  5960. (
  5961. (
  5962. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5963. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5964. ) and (
  5965. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5966. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5967. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5968. )
  5969. )
  5970. ) then
  5971. begin
  5972. TransferUsedRegs(TmpUsedRegs);
  5973. hp2 := p;
  5974. repeat
  5975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5976. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5977. IntermediateRegDiscarded :=
  5978. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5979. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5980. { changes
  5981. lea offset1(regX,scale), reg1
  5982. lea offset2(reg1,reg1), reg2
  5983. to
  5984. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5985. and
  5986. lea offset1(regX,scale1), reg1
  5987. lea offset2(reg1,scale2), reg2
  5988. to
  5989. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5990. and
  5991. lea offset1(regX,scale1), reg1
  5992. lea offset2(reg3,reg1,scale2), reg2
  5993. to
  5994. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5995. ... so long as the final scale does not exceed 8
  5996. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5997. }
  5998. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5999. (
  6000. { Don't optimise if size is a concern and the intermediate register remains in use }
  6001. IntermediateRegDiscarded or
  6002. (
  6003. not (cs_opt_size in current_settings.optimizerswitches) and
  6004. { If the intermediate register is not discarded, it must not
  6005. appear in the first LEA's reference. (Fixes #41166) }
  6006. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6007. )
  6008. ) and
  6009. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6010. (
  6011. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  6012. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6013. ) and (
  6014. (
  6015. { lea (reg1,scale2), reg2 variant }
  6016. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  6017. (
  6018. Adjacent or
  6019. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  6020. ) and
  6021. (
  6022. (
  6023. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  6024. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  6025. ) or (
  6026. { lea (regX,regX), reg1 variant }
  6027. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  6028. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  6029. )
  6030. )
  6031. ) or (
  6032. { lea (reg1,reg1), reg1 variant }
  6033. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6034. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  6035. )
  6036. ) then
  6037. begin
  6038. { Make everything homogeneous to make calculations easier }
  6039. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  6040. begin
  6041. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  6042. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  6043. taicpu(p).oper[0]^.ref^.scalefactor := 2
  6044. else
  6045. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  6046. taicpu(p).oper[0]^.ref^.base := NR_NO;
  6047. end;
  6048. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6049. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6050. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6051. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6052. begin
  6053. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6054. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  6055. begin
  6056. { Put the register to change in the index register }
  6057. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  6058. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  6059. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  6060. end;
  6061. { Change lea (reg,reg) to lea(,reg,2) }
  6062. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  6063. begin
  6064. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  6065. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  6066. end;
  6067. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  6068. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6069. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  6070. { Just to prevent miscalculations }
  6071. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  6072. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  6073. else
  6074. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  6075. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6076. if IntermediateRegDiscarded then
  6077. begin
  6078. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  6079. RemoveCurrentP(p);
  6080. end
  6081. else
  6082. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  6083. result:=true;
  6084. exit;
  6085. end;
  6086. end;
  6087. { changes
  6088. lea offset1(regX), reg1
  6089. lea offset2(reg1), reg2
  6090. to
  6091. lea offset1+offset2(regX), reg2 }
  6092. if (
  6093. { Don't optimise if size is a concern and the intermediate register remains in use }
  6094. IntermediateRegDiscarded or
  6095. (
  6096. not (cs_opt_size in current_settings.optimizerswitches) and
  6097. { If the intermediate register is not discarded, it must not
  6098. appear in the first LEA's reference. (Fixes #41166) }
  6099. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6100. )
  6101. ) and
  6102. (
  6103. (
  6104. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6105. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6106. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6107. ) or (
  6108. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6109. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6110. (
  6111. (
  6112. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6113. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6114. ) or (
  6115. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6116. (
  6117. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6118. (
  6119. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6120. (
  6121. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6122. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6123. )
  6124. )
  6125. )
  6126. )
  6127. )
  6128. )
  6129. ) then
  6130. begin
  6131. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6132. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6133. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6134. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6135. begin
  6136. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6137. begin
  6138. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6139. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6140. { if the register is used as index and base, we have to increase for base as well
  6141. and adapt base }
  6142. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6143. begin
  6144. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6145. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6146. end;
  6147. end
  6148. else
  6149. begin
  6150. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6151. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6152. end;
  6153. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6154. begin
  6155. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6156. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6157. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6158. { Catch the situation where the base = index
  6159. and treat this as *2. The scalefactor of
  6160. p will be 0 or 1 due to the conditional
  6161. checks above. Fixes i40647 }
  6162. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6163. else
  6164. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6165. end;
  6166. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6167. if IntermediateRegDiscarded then
  6168. begin
  6169. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6170. RemoveCurrentP(p);
  6171. end
  6172. else
  6173. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6174. result:=true;
  6175. exit;
  6176. end;
  6177. end;
  6178. end;
  6179. { Change:
  6180. leal/q $x(%reg1),%reg2
  6181. ...
  6182. shll/q $y,%reg2
  6183. To:
  6184. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6185. }
  6186. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6187. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6188. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6189. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6190. (taicpu(hp1).oper[0]^.val <= 3) then
  6191. begin
  6192. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6193. TransferUsedRegs(TmpUsedRegs);
  6194. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6195. if
  6196. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6197. (this works even if scalefactor is zero) }
  6198. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6199. { Ensure offset doesn't go out of bounds }
  6200. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6201. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6202. (
  6203. (
  6204. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6205. (
  6206. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6207. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6208. (
  6209. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6210. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6211. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6212. )
  6213. )
  6214. ) or (
  6215. (
  6216. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6217. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6218. ) and
  6219. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6220. )
  6221. ) then
  6222. begin
  6223. repeat
  6224. with taicpu(p).oper[0]^.ref^ do
  6225. begin
  6226. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6227. if index = base then
  6228. begin
  6229. if Multiple > 4 then
  6230. { Optimisation will no longer work because resultant
  6231. scale factor will exceed 8 }
  6232. Break;
  6233. base := NR_NO;
  6234. scalefactor := 2;
  6235. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6236. end
  6237. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6238. begin
  6239. { Scale factor only works on the index register }
  6240. index := base;
  6241. base := NR_NO;
  6242. end;
  6243. { For safety }
  6244. if scalefactor <= 1 then
  6245. begin
  6246. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6247. scalefactor := Multiple;
  6248. end
  6249. else
  6250. begin
  6251. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6252. scalefactor := scalefactor * Multiple;
  6253. end;
  6254. offset := offset * Multiple;
  6255. end;
  6256. RemoveInstruction(hp1);
  6257. Result := True;
  6258. Exit;
  6259. { This repeat..until loop exists for the benefit of Break }
  6260. until True;
  6261. end;
  6262. end;
  6263. end;
  6264. end;
  6265. end;
  6266. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6267. var
  6268. hp1 : tai;
  6269. SubInstr: Boolean;
  6270. ThisConst: TCGInt;
  6271. const
  6272. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6273. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6274. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6275. begin
  6276. Result := False;
  6277. if taicpu(p).oper[0]^.typ <> top_const then
  6278. { Should have been confirmed before calling }
  6279. InternalError(2021102601);
  6280. SubInstr := (taicpu(p).opcode = A_SUB);
  6281. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6282. GetLastInstruction(p, hp1) and
  6283. (hp1.typ = ait_instruction) and
  6284. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6285. begin
  6286. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6287. { Bad size }
  6288. InternalError(2022042001);
  6289. case taicpu(hp1).opcode Of
  6290. A_INC:
  6291. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6292. begin
  6293. if SubInstr then
  6294. ThisConst := taicpu(p).oper[0]^.val - 1
  6295. else
  6296. ThisConst := taicpu(p).oper[0]^.val + 1;
  6297. end
  6298. else
  6299. Exit;
  6300. A_DEC:
  6301. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6302. begin
  6303. if SubInstr then
  6304. ThisConst := taicpu(p).oper[0]^.val + 1
  6305. else
  6306. ThisConst := taicpu(p).oper[0]^.val - 1;
  6307. end
  6308. else
  6309. Exit;
  6310. A_SUB:
  6311. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6312. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6313. begin
  6314. if SubInstr then
  6315. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6316. else
  6317. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6318. end
  6319. else
  6320. Exit;
  6321. A_ADD:
  6322. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6323. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6324. begin
  6325. if SubInstr then
  6326. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6327. else
  6328. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6329. end
  6330. else
  6331. Exit;
  6332. else
  6333. Exit;
  6334. end;
  6335. { Check that the values are in range }
  6336. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6337. { Overflow; abort }
  6338. Exit;
  6339. if (ThisConst = 0) then
  6340. begin
  6341. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6342. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6343. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6344. RemoveInstruction(hp1);
  6345. hp1 := tai(p.next);
  6346. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6347. if not GetLastInstruction(hp1, p) then
  6348. p := hp1;
  6349. end
  6350. else
  6351. begin
  6352. if taicpu(hp1).opercnt=1 then
  6353. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6354. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6355. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6356. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6357. else
  6358. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6359. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6360. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6361. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6362. RemoveInstruction(hp1);
  6363. taicpu(p).loadconst(0, ThisConst);
  6364. end;
  6365. Result := True;
  6366. end;
  6367. end;
  6368. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6369. begin
  6370. Result := False;
  6371. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6372. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6373. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6374. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6375. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6376. (
  6377. (
  6378. (taicpu(hp1).opcode = A_TEST)
  6379. ) or (
  6380. (taicpu(hp1).opcode = A_CMP) and
  6381. { A sanity check more than anything }
  6382. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6383. )
  6384. ) then
  6385. begin
  6386. { change
  6387. mov mem, %reg
  6388. ...
  6389. cmp/test x, %reg / test %reg,%reg
  6390. (reg deallocated)
  6391. to
  6392. cmp/test x, mem / cmp 0, mem
  6393. }
  6394. TransferUsedRegs(TmpUsedRegs);
  6395. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6396. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6397. begin
  6398. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6399. if (taicpu(hp1).opcode = A_TEST) and
  6400. (
  6401. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6402. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6403. ) then
  6404. begin
  6405. taicpu(hp1).opcode := A_CMP;
  6406. taicpu(hp1).loadconst(0, 0);
  6407. end;
  6408. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6409. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6410. RemoveCurrentP(p);
  6411. if (p <> hp1) then
  6412. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6413. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6414. { Make sure the flags are allocated across the CMP instruction }
  6415. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6416. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6417. Result := True;
  6418. Exit;
  6419. end;
  6420. end;
  6421. end;
  6422. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6423. var
  6424. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6425. ThisReg, SecondReg: TRegister;
  6426. JumpLoc: TAsmLabel;
  6427. NewSize: TOpSize;
  6428. begin
  6429. Result := False;
  6430. {
  6431. Convert:
  6432. j<c> .L1
  6433. .L2:
  6434. mov 1,reg
  6435. jmp .L3 (or ret, although it might not be a RET yet)
  6436. .L1:
  6437. mov 0,reg
  6438. jmp .L3 (or ret)
  6439. ( As long as .L3 <> .L1 or .L2)
  6440. To:
  6441. mov 0,reg
  6442. set<not(c)> reg
  6443. jmp .L3 (or ret)
  6444. .L2:
  6445. mov 1,reg
  6446. jmp .L3 (or ret)
  6447. .L1:
  6448. mov 0,reg
  6449. jmp .L3 (or ret)
  6450. }
  6451. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6452. Exit;
  6453. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6454. if GetNextInstruction(hp_label, hp2) and
  6455. MatchInstruction(hp2,A_MOV,[]) and
  6456. (taicpu(hp2).oper[0]^.typ = top_const) and
  6457. (
  6458. (
  6459. (taicpu(hp2).oper[1]^.typ = top_reg)
  6460. {$ifdef i386}
  6461. { Under i386, ESI, EDI, EBP and ESP
  6462. don't have an 8-bit representation }
  6463. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6464. {$endif i386}
  6465. ) or (
  6466. {$ifdef i386}
  6467. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6468. {$endif i386}
  6469. (taicpu(hp2).opsize = S_B)
  6470. )
  6471. ) and
  6472. GetNextInstruction(hp2, hp3) and
  6473. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6474. (
  6475. (taicpu(hp3).opcode=A_RET) or
  6476. (
  6477. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6478. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6479. )
  6480. ) and
  6481. GetNextInstruction(hp3, hp4) and
  6482. FindLabel(JumpLoc, hp4) and
  6483. (
  6484. not (cs_opt_size in current_settings.optimizerswitches) or
  6485. { If the initial jump is the label's only reference, then it will
  6486. become a dead label if the other conditions are met and hence
  6487. remove at least 2 instructions, including a jump }
  6488. (JumpLoc.getrefs = 1)
  6489. ) and
  6490. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6491. that will be optimised out }
  6492. GetNextInstruction(hp4, hp5) and
  6493. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6494. (taicpu(hp5).oper[0]^.typ = top_const) and
  6495. (
  6496. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6497. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6498. ) and
  6499. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6500. GetNextInstruction(hp5,hp6) and
  6501. (
  6502. not (hp6.typ in [ait_align, ait_label]) or
  6503. SkipLabels(hp6, hp6)
  6504. ) and
  6505. (hp6.typ=ait_instruction) then
  6506. begin
  6507. { First, let's look at the two jumps that are hp3 and hp6 }
  6508. if not
  6509. (
  6510. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6511. (
  6512. (taicpu(hp6).opcode=A_RET) or
  6513. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6514. )
  6515. ) then
  6516. { If condition is False, then the JMP/RET instructions matched conventionally }
  6517. begin
  6518. { See if one of the jumps can be instantly converted into a RET }
  6519. if (taicpu(hp3).opcode=A_JMP) then
  6520. begin
  6521. { Reuse hp5 }
  6522. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6523. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6524. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6525. Exit;
  6526. if MatchInstruction(hp5, A_RET, []) then
  6527. begin
  6528. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6529. ConvertJumpToRET(hp3, hp5);
  6530. Result := True;
  6531. end
  6532. else
  6533. Exit;
  6534. end;
  6535. if (taicpu(hp6).opcode=A_JMP) then
  6536. begin
  6537. { Reuse hp5 }
  6538. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6539. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6540. Exit;
  6541. if MatchInstruction(hp5, A_RET, []) then
  6542. begin
  6543. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6544. ConvertJumpToRET(hp6, hp5);
  6545. Result := True;
  6546. end
  6547. else
  6548. Exit;
  6549. end;
  6550. if not
  6551. (
  6552. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6553. (
  6554. (taicpu(hp6).opcode=A_RET) or
  6555. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6556. )
  6557. ) then
  6558. { Still doesn't match }
  6559. Exit;
  6560. end;
  6561. if (taicpu(hp2).oper[0]^.val = 1) then
  6562. begin
  6563. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6564. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6565. end
  6566. else
  6567. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6568. if taicpu(hp2).opsize=S_B then
  6569. begin
  6570. if taicpu(hp2).oper[1]^.typ = top_reg then
  6571. begin
  6572. SecondReg := taicpu(hp2).oper[1]^.reg;
  6573. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6574. end
  6575. else
  6576. begin
  6577. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6578. SecondReg := NR_NO;
  6579. end;
  6580. hp_pos := p;
  6581. hp_allocstart := hp4;
  6582. end
  6583. else
  6584. begin
  6585. { Will be a register because the size can't be S_B otherwise }
  6586. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6587. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6588. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6589. if (cs_opt_size in current_settings.optimizerswitches) then
  6590. begin
  6591. { Favour using MOVZX when optimising for size }
  6592. case taicpu(hp2).opsize of
  6593. S_W:
  6594. NewSize := S_BW;
  6595. S_L:
  6596. NewSize := S_BL;
  6597. {$ifdef x86_64}
  6598. S_Q:
  6599. begin
  6600. NewSize := S_BL;
  6601. { Will implicitly zero-extend to 64-bit }
  6602. setsubreg(SecondReg, R_SUBD);
  6603. end;
  6604. {$endif x86_64}
  6605. else
  6606. InternalError(2022101301);
  6607. end;
  6608. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6609. { Inserting it right before p will guarantee that the flags are also tracked }
  6610. Asml.InsertBefore(hp5, p);
  6611. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6612. hp_pos := hp5;
  6613. hp_allocstart := hp4;
  6614. end
  6615. else
  6616. begin
  6617. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6618. { Inserting it right before p will guarantee that the flags are also tracked }
  6619. Asml.InsertBefore(hp5, p);
  6620. hp_pos := p;
  6621. hp_allocstart := hp5;
  6622. end;
  6623. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6624. end;
  6625. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6626. taicpu(hp4).condition := taicpu(p).condition;
  6627. asml.InsertBefore(hp4, hp_pos);
  6628. if taicpu(hp3).is_jmp then
  6629. begin
  6630. JumpLoc.decrefs;
  6631. MakeUnconditional(taicpu(p));
  6632. { This also increases the reference count }
  6633. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6634. end
  6635. else
  6636. ConvertJumpToRET(p, hp3);
  6637. if SecondReg <> NR_NO then
  6638. { Ensure the destination register is allocated over this region }
  6639. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6640. if (JumpLoc.getrefs = 0) then
  6641. RemoveDeadCodeAfterJump(hp3);
  6642. Result:=true;
  6643. exit;
  6644. end;
  6645. end;
  6646. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6647. var
  6648. hp1, hp2: tai;
  6649. ActiveReg: TRegister;
  6650. OldOffset: asizeint;
  6651. ThisConst: TCGInt;
  6652. function RegDeallocated: Boolean;
  6653. begin
  6654. TransferUsedRegs(TmpUsedRegs);
  6655. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6656. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6657. end;
  6658. begin
  6659. Result:=false;
  6660. hp1 := nil;
  6661. { replace
  6662. subX const,%reg1
  6663. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6664. dealloc %reg1
  6665. by
  6666. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6667. }
  6668. if MatchOpType(taicpu(p),top_const,top_reg) then
  6669. begin
  6670. ActiveReg := taicpu(p).oper[1]^.reg;
  6671. { Ensures the entire register was updated }
  6672. if (taicpu(p).opsize >= S_L) and
  6673. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6674. MatchInstruction(hp1,A_LEA,[]) and
  6675. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6676. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6677. (
  6678. { Cover the case where the register in the reference is also the destination register }
  6679. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6680. (
  6681. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6682. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6683. RegDeallocated
  6684. )
  6685. ) then
  6686. begin
  6687. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6688. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6689. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6690. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6691. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6692. {$ifdef x86_64}
  6693. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6694. begin
  6695. { Overflow; abort }
  6696. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6697. end
  6698. else
  6699. {$endif x86_64}
  6700. begin
  6701. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6702. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6703. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6704. RemoveCurrentP(p, hp1)
  6705. else
  6706. RemoveCurrentP(p);
  6707. result:=true;
  6708. Exit;
  6709. end;
  6710. end;
  6711. if (
  6712. { Save calling GetNextInstructionUsingReg again }
  6713. Assigned(hp1) or
  6714. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6715. ) and
  6716. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6717. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6718. begin
  6719. { Make sure the flags aren't in use by the second operation }
  6720. TransferUsedRegs(TmpUsedRegs);
  6721. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6722. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6723. begin
  6724. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6725. begin
  6726. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6727. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6728. Result := True;
  6729. { Handle any overflows }
  6730. case taicpu(p).opsize of
  6731. S_B:
  6732. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6733. S_W:
  6734. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6735. S_L:
  6736. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6737. {$ifdef x86_64}
  6738. S_Q:
  6739. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6740. { Overflow; abort }
  6741. Result := False
  6742. else
  6743. taicpu(p).oper[0]^.val := ThisConst;
  6744. {$endif x86_64}
  6745. else
  6746. InternalError(2021102611);
  6747. end;
  6748. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6749. if Result then
  6750. begin
  6751. if (taicpu(p).oper[0]^.val < 0) and
  6752. (
  6753. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6754. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6755. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6756. ) then
  6757. begin
  6758. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6759. taicpu(p).opcode := A_SUB;
  6760. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6761. end
  6762. else
  6763. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6764. RemoveInstruction(hp1);
  6765. end;
  6766. end
  6767. else
  6768. begin
  6769. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6770. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6771. Asml.Remove(p);
  6772. Asml.InsertAfter(p, hp1);
  6773. p := hp1;
  6774. Result := True;
  6775. Exit;
  6776. end;
  6777. end;
  6778. end;
  6779. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6780. { * change "sub/add const1, reg" or "dec reg" followed by
  6781. "sub const2, reg" to one "sub ..., reg" }
  6782. {$ifdef i386}
  6783. if (taicpu(p).oper[0]^.val = 2) and
  6784. (ActiveReg = NR_ESP) and
  6785. { Don't do the sub/push optimization if the sub }
  6786. { comes from setting up the stack frame (JM) }
  6787. (not(GetLastInstruction(p,hp1)) or
  6788. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6789. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6790. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6791. begin
  6792. hp1 := tai(p.next);
  6793. while Assigned(hp1) and
  6794. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6795. not RegReadByInstruction(NR_ESP,hp1) and
  6796. not RegModifiedByInstruction(NR_ESP,hp1) do
  6797. hp1 := tai(hp1.next);
  6798. if Assigned(hp1) and
  6799. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6800. begin
  6801. taicpu(hp1).changeopsize(S_L);
  6802. if taicpu(hp1).oper[0]^.typ=top_reg then
  6803. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6804. hp1 := tai(p.next);
  6805. RemoveCurrentp(p, hp1);
  6806. Result:=true;
  6807. exit;
  6808. end;
  6809. end;
  6810. {$endif i386}
  6811. if DoArithCombineOpt(p) then
  6812. Result:=true;
  6813. end;
  6814. end;
  6815. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6816. var
  6817. TmpBool1,TmpBool2 : Boolean;
  6818. tmpref : treference;
  6819. hp1,hp2: tai;
  6820. mask, shiftval: tcgint;
  6821. begin
  6822. Result:=false;
  6823. { All these optimisations work on "shl/sal const,%reg" }
  6824. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6825. Exit;
  6826. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6827. (taicpu(p).oper[0]^.val <= 3) then
  6828. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6829. begin
  6830. { should we check the next instruction? }
  6831. TmpBool1 := True;
  6832. { have we found an add/sub which could be
  6833. integrated in the lea? }
  6834. TmpBool2 := False;
  6835. reference_reset(tmpref,2,[]);
  6836. TmpRef.index := taicpu(p).oper[1]^.reg;
  6837. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6838. while TmpBool1 and
  6839. GetNextInstruction(p, hp1) and
  6840. (tai(hp1).typ = ait_instruction) and
  6841. ((((taicpu(hp1).opcode = A_ADD) or
  6842. (taicpu(hp1).opcode = A_SUB)) and
  6843. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6844. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6845. (((taicpu(hp1).opcode = A_INC) or
  6846. (taicpu(hp1).opcode = A_DEC)) and
  6847. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6848. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6849. ((taicpu(hp1).opcode = A_LEA) and
  6850. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6851. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6852. (not GetNextInstruction(hp1,hp2) or
  6853. not instrReadsFlags(hp2)) Do
  6854. begin
  6855. TmpBool1 := False;
  6856. if taicpu(hp1).opcode=A_LEA then
  6857. begin
  6858. if (TmpRef.base = NR_NO) and
  6859. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6860. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6861. { Segment register isn't a concern here }
  6862. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6863. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6864. begin
  6865. TmpBool1 := True;
  6866. TmpBool2 := True;
  6867. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6868. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6869. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6870. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6871. RemoveInstruction(hp1);
  6872. end
  6873. end
  6874. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6875. begin
  6876. TmpBool1 := True;
  6877. TmpBool2 := True;
  6878. case taicpu(hp1).opcode of
  6879. A_ADD:
  6880. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6881. A_SUB:
  6882. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6883. else
  6884. internalerror(2019050536);
  6885. end;
  6886. RemoveInstruction(hp1);
  6887. end
  6888. else
  6889. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6890. (((taicpu(hp1).opcode = A_ADD) and
  6891. (TmpRef.base = NR_NO)) or
  6892. (taicpu(hp1).opcode = A_INC) or
  6893. (taicpu(hp1).opcode = A_DEC)) then
  6894. begin
  6895. TmpBool1 := True;
  6896. TmpBool2 := True;
  6897. case taicpu(hp1).opcode of
  6898. A_ADD:
  6899. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6900. A_INC:
  6901. inc(TmpRef.offset);
  6902. A_DEC:
  6903. dec(TmpRef.offset);
  6904. else
  6905. internalerror(2019050535);
  6906. end;
  6907. RemoveInstruction(hp1);
  6908. end;
  6909. end;
  6910. if TmpBool2
  6911. {$ifndef x86_64}
  6912. or
  6913. ((current_settings.optimizecputype < cpu_Pentium2) and
  6914. (taicpu(p).oper[0]^.val <= 3) and
  6915. not(cs_opt_size in current_settings.optimizerswitches))
  6916. {$endif x86_64}
  6917. then
  6918. begin
  6919. if not(TmpBool2) and
  6920. (taicpu(p).oper[0]^.val=1) then
  6921. begin
  6922. taicpu(p).opcode := A_ADD;
  6923. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6924. end
  6925. else
  6926. begin
  6927. taicpu(p).opcode := A_LEA;
  6928. taicpu(p).loadref(0, TmpRef);
  6929. end;
  6930. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6931. Result := True;
  6932. end;
  6933. end
  6934. {$ifndef x86_64}
  6935. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6936. begin
  6937. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6938. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6939. (unlike shl, which is only Tairable in the U pipe) }
  6940. if taicpu(p).oper[0]^.val=1 then
  6941. begin
  6942. taicpu(p).opcode := A_ADD;
  6943. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6944. Result := True;
  6945. end
  6946. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6947. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6948. else if (taicpu(p).opsize = S_L) and
  6949. (taicpu(p).oper[0]^.val<= 3) then
  6950. begin
  6951. reference_reset(tmpref,2,[]);
  6952. TmpRef.index := taicpu(p).oper[1]^.reg;
  6953. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6954. taicpu(p).opcode := A_LEA;
  6955. taicpu(p).loadref(0, TmpRef);
  6956. Result := True;
  6957. end;
  6958. end
  6959. {$endif x86_64}
  6960. else if
  6961. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6962. (
  6963. (
  6964. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6965. SetAndTest(hp1, hp2)
  6966. {$ifdef x86_64}
  6967. ) or
  6968. (
  6969. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6970. GetNextInstruction(hp1, hp2) and
  6971. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6972. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6973. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6974. {$endif x86_64}
  6975. )
  6976. ) and
  6977. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6978. begin
  6979. { Change:
  6980. shl x, %reg1
  6981. mov -(1<<x), %reg2
  6982. and %reg2, %reg1
  6983. Or:
  6984. shl x, %reg1
  6985. and -(1<<x), %reg1
  6986. To just:
  6987. shl x, %reg1
  6988. Since the and operation only zeroes bits that are already zero from the shl operation
  6989. }
  6990. case taicpu(p).oper[0]^.val of
  6991. 8:
  6992. mask:=$FFFFFFFFFFFFFF00;
  6993. 16:
  6994. mask:=$FFFFFFFFFFFF0000;
  6995. 32:
  6996. mask:=$FFFFFFFF00000000;
  6997. 63:
  6998. { Constant pre-calculated to prevent overflow errors with Int64 }
  6999. mask:=$8000000000000000;
  7000. else
  7001. begin
  7002. if taicpu(p).oper[0]^.val >= 64 then
  7003. { Shouldn't happen realistically, since the register
  7004. is guaranteed to be set to zero at this point }
  7005. mask := 0
  7006. else
  7007. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  7008. end;
  7009. end;
  7010. if taicpu(hp1).oper[0]^.val = mask then
  7011. begin
  7012. { Everything checks out, perform the optimisation, as long as
  7013. the FLAGS register isn't being used}
  7014. TransferUsedRegs(TmpUsedRegs);
  7015. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7016. {$ifdef x86_64}
  7017. if (hp1 <> hp2) then
  7018. begin
  7019. { "shl/mov/and" version }
  7020. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7021. { Don't do the optimisation if the FLAGS register is in use }
  7022. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  7023. begin
  7024. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  7025. { Don't remove the 'mov' instruction if its register is used elsewhere }
  7026. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  7027. begin
  7028. RemoveInstruction(hp1);
  7029. Result := True;
  7030. end;
  7031. { Only set Result to True if the 'mov' instruction was removed }
  7032. RemoveInstruction(hp2);
  7033. end;
  7034. end
  7035. else
  7036. {$endif x86_64}
  7037. begin
  7038. { "shl/and" version }
  7039. { Don't do the optimisation if the FLAGS register is in use }
  7040. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  7041. begin
  7042. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  7043. RemoveInstruction(hp1);
  7044. Result := True;
  7045. end;
  7046. end;
  7047. Exit;
  7048. end
  7049. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  7050. begin
  7051. { Even if the mask doesn't allow for its removal, we might be
  7052. able to optimise the mask for the "shl/and" version, which
  7053. may permit other peephole optimisations }
  7054. {$ifdef DEBUG_AOPTCPU}
  7055. mask := taicpu(hp1).oper[0]^.val and mask;
  7056. if taicpu(hp1).oper[0]^.val <> mask then
  7057. begin
  7058. DebugMsg(
  7059. SPeepholeOptimization +
  7060. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  7061. ' to $' + debug_tostr(mask) +
  7062. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  7063. taicpu(hp1).oper[0]^.val := mask;
  7064. end;
  7065. {$else DEBUG_AOPTCPU}
  7066. { If debugging is off, just set the operand even if it's the same }
  7067. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  7068. {$endif DEBUG_AOPTCPU}
  7069. end;
  7070. end;
  7071. {
  7072. change
  7073. shl/sal const,reg
  7074. <op> ...(...,reg,1),...
  7075. into
  7076. <op> ...(...,reg,1 shl const),...
  7077. if const in 1..3
  7078. }
  7079. if MatchOpType(taicpu(p), top_const, top_reg) and
  7080. (taicpu(p).oper[0]^.val in [1..3]) and
  7081. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7082. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  7083. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  7084. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  7085. MatchOpType(taicpu(hp1),top_ref))
  7086. ) and
  7087. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  7088. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  7089. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  7090. begin
  7091. TransferUsedRegs(TmpUsedRegs);
  7092. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7093. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  7094. begin
  7095. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7096. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7097. RemoveCurrentP(p);
  7098. Result:=true;
  7099. exit;
  7100. end;
  7101. end;
  7102. if MatchOpType(taicpu(p), top_const, top_reg) and
  7103. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7104. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7105. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7106. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7107. begin
  7108. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7109. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7110. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7111. {$ifdef x86_64}
  7112. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7113. {$endif x86_64}
  7114. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7115. begin
  7116. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7117. taicpu(hp1).opcode:=A_MOV;
  7118. taicpu(hp1).oper[0]^.val:=0;
  7119. end
  7120. else
  7121. begin
  7122. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7123. taicpu(hp1).oper[0]^.val:=shiftval;
  7124. end;
  7125. RemoveCurrentP(p);
  7126. Result:=true;
  7127. exit;
  7128. end;
  7129. end;
  7130. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7131. begin
  7132. case shr_size of
  7133. S_B:
  7134. { No valid combinations }
  7135. Result := False;
  7136. S_W:
  7137. Result := (Shift >= 8) and (movz_size = S_BW);
  7138. S_L:
  7139. Result :=
  7140. (Shift >= 24) { Any opsize is valid for this shift } or
  7141. ((Shift >= 16) and (movz_size = S_WL));
  7142. {$ifdef x86_64}
  7143. S_Q:
  7144. Result :=
  7145. (Shift >= 56) { Any opsize is valid for this shift } or
  7146. ((Shift >= 48) and (movz_size = S_WL));
  7147. {$endif x86_64}
  7148. else
  7149. InternalError(2022081510);
  7150. end;
  7151. end;
  7152. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7153. var
  7154. hp1, hp2: tai;
  7155. IdentityMask, Shift: TCGInt;
  7156. LimitSize: Topsize;
  7157. DoNotMerge: Boolean;
  7158. begin
  7159. if not MatchInstruction(p, A_SHR, []) then
  7160. InternalError(2025040301);
  7161. Result := False;
  7162. DoNotMerge := False;
  7163. Shift := taicpu(p).oper[0]^.val;
  7164. LimitSize := taicpu(p).opsize;
  7165. hp1 := p;
  7166. repeat
  7167. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7168. Exit;
  7169. case taicpu(hp1).opcode of
  7170. A_AND:
  7171. { Detect:
  7172. shr x, %reg
  7173. and y, %reg
  7174. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7175. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7176. (Post-peephole only)
  7177. }
  7178. if PostPeephole and
  7179. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7180. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7181. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7182. begin
  7183. { Make sure the FLAGS register isn't in use }
  7184. TransferUsedRegs(TmpUsedRegs);
  7185. hp2 := p;
  7186. repeat
  7187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7188. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7189. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7190. begin
  7191. { Generate the identity mask }
  7192. case taicpu(p).opsize of
  7193. S_B:
  7194. IdentityMask := $FF shr Shift;
  7195. S_W:
  7196. IdentityMask := $FFFF shr Shift;
  7197. S_L:
  7198. IdentityMask := $FFFFFFFF shr Shift;
  7199. {$ifdef x86_64}
  7200. S_Q:
  7201. { We need to force the operands to be unsigned 64-bit
  7202. integers otherwise the wrong value is generated }
  7203. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7204. {$endif x86_64}
  7205. else
  7206. InternalError(2022081501);
  7207. end;
  7208. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7209. begin
  7210. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7211. { All the possible 1 bits are covered, so we can remove the AND }
  7212. hp2 := tai(hp1.Previous);
  7213. RemoveInstruction(hp1);
  7214. { p wasn't actually changed, so don't set Result to True,
  7215. but a change was nonetheless made elsewhere }
  7216. Include(OptsToCheck, aoc_ForceNewIteration);
  7217. { Do another pass in case other AND or MOVZX instructions
  7218. follow }
  7219. hp1 := hp2;
  7220. Continue;
  7221. end;
  7222. end;
  7223. end;
  7224. A_TEST, A_CMP:
  7225. { Skip over relevant comparisons, but shift instructions must
  7226. now not be merged since the original value is being read }
  7227. begin
  7228. DoNotMerge := True;
  7229. Continue;
  7230. end;
  7231. A_Jcc:
  7232. { Skip over conditional jumps and relevant comparisons }
  7233. Continue;
  7234. A_MOVZX:
  7235. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7236. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7237. begin
  7238. { Since the original register is being read as is, subsequent
  7239. SHRs must not be merged at this point }
  7240. DoNotMerge := True;
  7241. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7242. begin
  7243. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7244. begin
  7245. { If the MOVZX instruction reads and writes the same register,
  7246. defer this to the post-peephole optimisation stage }
  7247. if PostPeephole then
  7248. begin
  7249. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7250. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7251. hp2 := tai(hp1.Previous);
  7252. RemoveInstruction(hp1);
  7253. hp1 := hp2;
  7254. end;
  7255. end
  7256. else { Different register target }
  7257. begin
  7258. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7259. taicpu(hp1).opcode := A_MOV;
  7260. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7261. case taicpu(hp1).opsize of
  7262. S_BW:
  7263. taicpu(hp1).opsize := S_W;
  7264. S_BL, S_WL:
  7265. taicpu(hp1).opsize := S_L;
  7266. else
  7267. InternalError(2022081503);
  7268. end;
  7269. { p itself hasn't changed, so no need to set Result to True }
  7270. Include(OptsToCheck, aoc_ForceNewIteration);
  7271. { See if there's anything afterwards that can be
  7272. optimised, since the input register hasn't changed }
  7273. Continue;
  7274. end;
  7275. Exit;
  7276. end
  7277. else if PostPeephole and
  7278. (Shift > 0) and
  7279. (taicpu(p).opsize = S_W) and
  7280. (taicpu(hp1).opsize = S_WL) and
  7281. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7282. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7283. begin
  7284. { Detect:
  7285. shr x, %ax (x > 0)
  7286. ...
  7287. movzwl %ax,%eax
  7288. -
  7289. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7290. But first, check to see if movzwl %ax,%eax can be removed...
  7291. }
  7292. hp2 := tai(hp1.Previous);
  7293. TransferUsedRegs(TmpUsedRegs);
  7294. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7295. if PostPeepholeOptMovZX(hp1) then
  7296. hp1 := hp2
  7297. else
  7298. begin
  7299. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7300. taicpu(hp1).opcode := A_CWDE;
  7301. taicpu(hp1).clearop(0);
  7302. taicpu(hp1).clearop(1);
  7303. taicpu(hp1).ops := 0;
  7304. end;
  7305. RestoreUsedRegs(TmpUsedRegs);
  7306. { Don't need to set aoc_ForceNewIteration if
  7307. PostPeepholeOptMovZX returned True because it's the
  7308. post-peephole stage }
  7309. end;
  7310. { Move onto the next instruction }
  7311. Continue;
  7312. end;
  7313. A_SHL, A_SAL, A_SHR:
  7314. if (taicpu(hp1).opsize <= LimitSize) and
  7315. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7316. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7317. begin
  7318. { Make sure the sizes don't exceed the register size limit
  7319. (measured by the shift value falling below the limit) }
  7320. if taicpu(hp1).opsize < LimitSize then
  7321. LimitSize := taicpu(hp1).opsize;
  7322. if taicpu(hp1).opcode = A_SHR then
  7323. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7324. else
  7325. begin
  7326. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7327. DoNotMerge := True;
  7328. end;
  7329. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7330. Exit;
  7331. { Since we've established that the combined shift is within
  7332. limits, we can actually combine the adjacent SHR
  7333. instructions even if they're different sizes }
  7334. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7335. begin
  7336. hp2 := tai(hp1.Previous);
  7337. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7338. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7339. RemoveInstruction(hp1);
  7340. hp1 := hp2;
  7341. { Though p has changed, only the constant has, and its
  7342. effects can still be detected on the next iteration of
  7343. the repeat..until loop }
  7344. Include(OptsToCheck, aoc_ForceNewIteration);
  7345. end;
  7346. { Move onto the next instruction }
  7347. Continue;
  7348. end;
  7349. else
  7350. ;
  7351. end;
  7352. { If the register isn't actually modified, move onto the next instruction,
  7353. but set DoNotMerge to True since the register is being read }
  7354. if (
  7355. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7356. the next instruction, whether or not it contains the register }
  7357. (cs_opt_level3 in current_settings.optimizerswitches) or
  7358. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7359. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7360. begin
  7361. DoNotMerge := True;
  7362. Continue;
  7363. end;
  7364. Break;
  7365. until False;
  7366. end;
  7367. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7368. begin
  7369. Result := False;
  7370. { All these optimisations work on "shr const,%reg" }
  7371. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7372. Exit;
  7373. Result := HandleSHRMerge(p, False);
  7374. end;
  7375. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7376. var
  7377. CurrentRef: TReference;
  7378. FullReg: TRegister;
  7379. hp1, hp2: tai;
  7380. begin
  7381. Result := False;
  7382. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7383. Exit;
  7384. { We assume you've checked if the operand is actually a reference by
  7385. this point. If it isn't, you'll most likely get an access violation }
  7386. CurrentRef := first_mov.oper[1]^.ref^;
  7387. { Memory must be aligned }
  7388. if (CurrentRef.offset mod 4) <> 0 then
  7389. Exit;
  7390. Inc(CurrentRef.offset);
  7391. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7392. if MatchOperand(second_mov.oper[0]^, 0) and
  7393. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7394. GetNextInstruction(second_mov, hp1) and
  7395. (hp1.typ = ait_instruction) and
  7396. (taicpu(hp1).opcode = A_MOV) and
  7397. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7398. (taicpu(hp1).oper[0]^.val = 0) then
  7399. begin
  7400. Inc(CurrentRef.offset);
  7401. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7402. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7403. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7404. begin
  7405. case taicpu(hp1).opsize of
  7406. S_B:
  7407. if GetNextInstruction(hp1, hp2) and
  7408. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7409. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7410. (taicpu(hp2).oper[0]^.val = 0) then
  7411. begin
  7412. Inc(CurrentRef.offset);
  7413. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7414. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7415. (taicpu(hp2).opsize = S_B) then
  7416. begin
  7417. RemoveInstruction(hp1);
  7418. RemoveInstruction(hp2);
  7419. first_mov.opsize := S_L;
  7420. if first_mov.oper[0]^.typ = top_reg then
  7421. begin
  7422. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7423. { Reuse second_mov as a MOVZX instruction }
  7424. second_mov.opcode := A_MOVZX;
  7425. second_mov.opsize := S_BL;
  7426. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7427. second_mov.loadreg(1, FullReg);
  7428. first_mov.oper[0]^.reg := FullReg;
  7429. asml.Remove(second_mov);
  7430. asml.InsertBefore(second_mov, first_mov);
  7431. end
  7432. else
  7433. { It's a value }
  7434. begin
  7435. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7436. RemoveInstruction(second_mov);
  7437. end;
  7438. Result := True;
  7439. Exit;
  7440. end;
  7441. end;
  7442. S_W:
  7443. begin
  7444. RemoveInstruction(hp1);
  7445. first_mov.opsize := S_L;
  7446. if first_mov.oper[0]^.typ = top_reg then
  7447. begin
  7448. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7449. { Reuse second_mov as a MOVZX instruction }
  7450. second_mov.opcode := A_MOVZX;
  7451. second_mov.opsize := S_BL;
  7452. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7453. second_mov.loadreg(1, FullReg);
  7454. first_mov.oper[0]^.reg := FullReg;
  7455. asml.Remove(second_mov);
  7456. asml.InsertBefore(second_mov, first_mov);
  7457. end
  7458. else
  7459. { It's a value }
  7460. begin
  7461. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7462. RemoveInstruction(second_mov);
  7463. end;
  7464. Result := True;
  7465. Exit;
  7466. end;
  7467. else
  7468. ;
  7469. end;
  7470. end;
  7471. end;
  7472. end;
  7473. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7474. { returns true if a "continue" should be done after this optimization }
  7475. var
  7476. hp1, hp2, hp3: tai;
  7477. begin
  7478. Result := false;
  7479. hp3 := nil;
  7480. if MatchOpType(taicpu(p),top_ref) and
  7481. GetNextInstruction(p, hp1) and
  7482. (hp1.typ = ait_instruction) and
  7483. (((taicpu(hp1).opcode = A_FLD) and
  7484. (taicpu(p).opcode = A_FSTP)) or
  7485. ((taicpu(p).opcode = A_FISTP) and
  7486. (taicpu(hp1).opcode = A_FILD))) and
  7487. MatchOpType(taicpu(hp1),top_ref) and
  7488. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7489. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7490. begin
  7491. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7492. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7493. GetNextInstruction(hp1, hp2) and
  7494. (((hp2.typ = ait_instruction) and
  7495. IsExitCode(hp2) and
  7496. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7497. not(assigned(current_procinfo.procdef.funcretsym) and
  7498. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7499. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7500. { fstp <temp>
  7501. fld <temp>
  7502. <dealloc> <temp>
  7503. }
  7504. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7505. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7506. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7507. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7508. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7509. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7510. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7511. )
  7512. )
  7513. ) then
  7514. begin
  7515. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7516. RemoveInstruction(hp1);
  7517. RemoveCurrentP(p, hp2);
  7518. { first case: exit code }
  7519. if hp2.typ = ait_instruction then
  7520. RemoveLastDeallocForFuncRes(p);
  7521. Result := true;
  7522. end
  7523. else
  7524. { we can do this only in fast math mode as fstp is rounding ...
  7525. ... still disabled as it breaks the compiler and/or rtl }
  7526. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7527. { ... or if another fstp equal to the first one follows }
  7528. GetNextInstruction(hp1,hp2) and
  7529. (hp2.typ = ait_instruction) and
  7530. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7531. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7532. begin
  7533. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7534. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7535. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7536. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7537. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7538. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7539. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7540. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7541. ) then
  7542. begin
  7543. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7544. RemoveCurrentP(p,hp2);
  7545. RemoveInstruction(hp1);
  7546. Result := true;
  7547. end
  7548. else if { fst can't store an extended/comp value }
  7549. (taicpu(p).opsize <> S_FX) and
  7550. (taicpu(p).opsize <> S_IQ) then
  7551. begin
  7552. if (taicpu(p).opcode = A_FSTP) then
  7553. taicpu(p).opcode := A_FST
  7554. else
  7555. taicpu(p).opcode := A_FIST;
  7556. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7557. RemoveInstruction(hp1);
  7558. Result := true;
  7559. end;
  7560. end;
  7561. end;
  7562. end;
  7563. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7564. var
  7565. hp1, hp2, hp3: tai;
  7566. begin
  7567. result:=false;
  7568. if MatchOpType(taicpu(p),top_reg) and
  7569. GetNextInstruction(p, hp1) and
  7570. (hp1.typ = Ait_Instruction) and
  7571. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7572. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7573. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7574. { change to
  7575. fld reg fxxx reg,st
  7576. fxxxp st, st1 (hp1)
  7577. Remark: non commutative operations must be reversed!
  7578. }
  7579. begin
  7580. case taicpu(hp1).opcode Of
  7581. A_FMULP,A_FADDP,
  7582. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7583. begin
  7584. case taicpu(hp1).opcode Of
  7585. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7586. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7587. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7588. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7589. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7590. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7591. else
  7592. internalerror(2019050534);
  7593. end;
  7594. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7595. taicpu(hp1).oper[1]^.reg := NR_ST;
  7596. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7597. RemoveCurrentP(p, hp1);
  7598. Result:=true;
  7599. exit;
  7600. end;
  7601. else
  7602. ;
  7603. end;
  7604. end
  7605. else
  7606. if MatchOpType(taicpu(p),top_ref) and
  7607. GetNextInstruction(p, hp2) and
  7608. (hp2.typ = Ait_Instruction) and
  7609. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7610. (taicpu(p).opsize in [S_FS, S_FL]) and
  7611. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7612. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7613. if GetLastInstruction(p, hp1) and
  7614. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7615. MatchOpType(taicpu(hp1),top_ref) and
  7616. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7617. if ((taicpu(hp2).opcode = A_FMULP) or
  7618. (taicpu(hp2).opcode = A_FADDP)) then
  7619. { change to
  7620. fld/fst mem1 (hp1) fld/fst mem1
  7621. fld mem1 (p) fadd/
  7622. faddp/ fmul st, st
  7623. fmulp st, st1 (hp2) }
  7624. begin
  7625. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7626. RemoveCurrentP(p, hp1);
  7627. if (taicpu(hp2).opcode = A_FADDP) then
  7628. taicpu(hp2).opcode := A_FADD
  7629. else
  7630. taicpu(hp2).opcode := A_FMUL;
  7631. taicpu(hp2).oper[1]^.reg := NR_ST;
  7632. end
  7633. else
  7634. { change to
  7635. fld/fst mem1 (hp1) fld/fst mem1
  7636. fld mem1 (p) fld st
  7637. }
  7638. begin
  7639. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7640. taicpu(p).changeopsize(S_FL);
  7641. taicpu(p).loadreg(0,NR_ST);
  7642. end
  7643. else
  7644. begin
  7645. case taicpu(hp2).opcode Of
  7646. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7647. { change to
  7648. fld/fst mem1 (hp1) fld/fst mem1
  7649. fld mem2 (p) fxxx mem2
  7650. fxxxp st, st1 (hp2) }
  7651. begin
  7652. case taicpu(hp2).opcode Of
  7653. A_FADDP: taicpu(p).opcode := A_FADD;
  7654. A_FMULP: taicpu(p).opcode := A_FMUL;
  7655. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7656. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7657. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7658. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7659. else
  7660. internalerror(2019050533);
  7661. end;
  7662. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7663. RemoveInstruction(hp2);
  7664. end
  7665. else
  7666. ;
  7667. end
  7668. end
  7669. end;
  7670. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7671. begin
  7672. Result := condition_in(cond1, cond2) or
  7673. { Not strictly subsets due to the actual flags checked, but because we're
  7674. comparing integers, E is a subset of AE and GE and their aliases }
  7675. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7676. end;
  7677. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7678. var
  7679. v: TCGInt;
  7680. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7681. FirstMatch, TempBool: Boolean;
  7682. NewReg: TRegister;
  7683. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7684. begin
  7685. Result:=false;
  7686. { All these optimisations need a next instruction }
  7687. if not GetNextInstruction(p, hp1) then
  7688. Exit;
  7689. true_hp1 := hp1;
  7690. { Search for:
  7691. cmp ###,###
  7692. j(c1) @lbl1
  7693. ...
  7694. @lbl:
  7695. cmp ###,### (same comparison as above)
  7696. j(c2) @lbl2
  7697. If c1 is a subset of c2, change to:
  7698. cmp ###,###
  7699. j(c1) @lbl2
  7700. (@lbl1 may become a dead label as a result)
  7701. }
  7702. { Also handle cases where there are multiple jumps in a row }
  7703. p_jump := hp1;
  7704. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7705. begin
  7706. Prefetch(p_jump.Next);
  7707. if IsJumpToLabel(taicpu(p_jump)) then
  7708. begin
  7709. { Do jump optimisations first in case the condition becomes
  7710. unnecessary }
  7711. TempBool := True;
  7712. if DoJumpOptimizations(p_jump, TempBool) or
  7713. not TempBool then
  7714. begin
  7715. if Assigned(p_jump) then
  7716. begin
  7717. { CollapseZeroDistJump will be set to the label or an align
  7718. before it after the jump if it optimises, whether or not
  7719. the label is live or dead }
  7720. if (p_jump.typ = ait_align) or
  7721. (
  7722. (p_jump.typ = ait_label) and
  7723. not (tai_label(p_jump).labsym.is_used)
  7724. ) then
  7725. GetNextInstruction(p_jump, p_jump);
  7726. end;
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7729. if not Assigned(p_jump) or
  7730. (
  7731. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7732. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7733. ) then
  7734. begin
  7735. { No more conditional jumps; conditional statement is no longer required }
  7736. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7737. RemoveCurrentP(p);
  7738. Result := True;
  7739. Exit;
  7740. end;
  7741. hp1 := p_jump;
  7742. Include(OptsToCheck, aoc_ForceNewIteration);
  7743. Continue;
  7744. end;
  7745. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7746. if GetNextInstruction(p_jump, hp2) and
  7747. (
  7748. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7749. not TempBool
  7750. ) then
  7751. begin
  7752. hp1 := p_jump;
  7753. Include(OptsToCheck, aoc_ForceNewIteration);
  7754. Continue;
  7755. end;
  7756. p_label := nil;
  7757. if Assigned(JumpLabel) then
  7758. p_label := getlabelwithsym(JumpLabel);
  7759. if Assigned(p_label) and
  7760. GetNextInstruction(p_label, p_dist) and
  7761. MatchInstruction(p_dist, A_CMP, []) and
  7762. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7763. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7764. GetNextInstruction(p_dist, hp1_dist) and
  7765. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7766. begin
  7767. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7768. if JumpLabel = JumpLabel_dist then
  7769. { This is an infinite loop }
  7770. Exit;
  7771. { Best optimisation when the first condition is a subset (or equal) of the second }
  7772. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7773. begin
  7774. { Any registers used here will already be allocated }
  7775. if Assigned(JumpLabel) then
  7776. JumpLabel.DecRefs;
  7777. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7778. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7779. Include(OptsToCheck, aoc_ForceNewIteration);
  7780. { Don't exit yet. Since p and p_jump haven't actually been
  7781. removed, we can check for more on this iteration }
  7782. end
  7783. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7784. GetNextInstruction(hp1_dist, hp1_label) and
  7785. (hp1_label.typ = ait_label) then
  7786. begin
  7787. JumpLabel_far := tai_label(hp1_label).labsym;
  7788. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7789. { This is an infinite loop }
  7790. Exit;
  7791. if Assigned(JumpLabel_far) then
  7792. begin
  7793. { In this situation, if the first jump branches, the second one will never,
  7794. branch so change the destination label to after the second jump }
  7795. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7796. if Assigned(JumpLabel) then
  7797. JumpLabel.DecRefs;
  7798. JumpLabel_far.IncRefs;
  7799. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7800. Result := True;
  7801. { Don't exit yet. Since p and p_jump haven't actually been
  7802. removed, we can check for more on this iteration }
  7803. Continue;
  7804. end;
  7805. end;
  7806. end;
  7807. end;
  7808. { Search for:
  7809. cmp ###,###
  7810. j(c1) @lbl1
  7811. cmp ###,### (same as first)
  7812. Remove second cmp
  7813. }
  7814. if GetNextInstruction(p_jump, hp2) and
  7815. (
  7816. (
  7817. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7818. (
  7819. (
  7820. MatchOpType(taicpu(p), top_const, top_reg) and
  7821. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7822. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7823. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7824. ) or (
  7825. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7826. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7827. )
  7828. )
  7829. ) or (
  7830. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7831. MatchOperand(taicpu(p).oper[0]^, 0) and
  7832. (taicpu(p).oper[1]^.typ = top_reg) and
  7833. MatchInstruction(hp2, A_TEST, []) and
  7834. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7835. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7836. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7837. )
  7838. ) then
  7839. begin
  7840. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7841. TransferUsedRegs(TmpUsedRegs);
  7842. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7843. RemoveInstruction(hp2);
  7844. Result := True;
  7845. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7846. end
  7847. else
  7848. begin
  7849. { hp2 is the next instruction, so save time and just set p_jump
  7850. to it instead of calling GetNextInstruction below }
  7851. p_jump := hp2;
  7852. Continue;
  7853. end;
  7854. GetNextInstruction(p_jump, p_jump);
  7855. end;
  7856. if (
  7857. { Don't call GetNextInstruction again if we already have it }
  7858. (true_hp1 = p_jump) or
  7859. GetNextInstruction(p, hp1)
  7860. ) and
  7861. MatchInstruction(hp1, A_Jcc, []) and
  7862. IsJumpToLabel(taicpu(hp1)) and
  7863. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7864. GetNextInstruction(hp1, hp2) then
  7865. begin
  7866. {
  7867. cmp x, y (or "cmp y, x")
  7868. je @lbl
  7869. mov x, y
  7870. @lbl:
  7871. (x and y can be constants, registers or references)
  7872. Change to:
  7873. mov x, y (x and y will always be equal in the end)
  7874. @lbl: (may beceome a dead label)
  7875. Also:
  7876. cmp x, y (or "cmp y, x")
  7877. jne @lbl
  7878. mov x, y
  7879. @lbl:
  7880. (x and y can be constants, registers or references)
  7881. Change to:
  7882. Absolutely nothing! (Except @lbl if it's still live)
  7883. }
  7884. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7885. (
  7886. (
  7887. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7888. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7889. ) or (
  7890. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7891. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7892. )
  7893. ) and
  7894. GetNextInstruction(hp2, hp1_label) and
  7895. (hp1_label.typ = ait_label) and
  7896. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7897. begin
  7898. tai_label(hp1_label).labsym.DecRefs;
  7899. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7900. begin
  7901. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7902. RemoveInstruction(hp2);
  7903. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7904. end
  7905. else
  7906. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7907. RemoveInstruction(hp1);
  7908. RemoveCurrentp(p, hp2);
  7909. Result := True;
  7910. Exit;
  7911. end;
  7912. {
  7913. Try to optimise the following:
  7914. cmp $x,### ($x and $y can be registers or constants)
  7915. je @lbl1 (only reference)
  7916. cmp $y,### (### are identical)
  7917. @Lbl:
  7918. sete %reg1
  7919. Change to:
  7920. cmp $x,###
  7921. sete %reg2 (allocate new %reg2)
  7922. cmp $y,###
  7923. sete %reg1
  7924. orb %reg2,%reg1
  7925. (dealloc %reg2)
  7926. This adds an instruction (so don't perform under -Os), but it removes
  7927. a conditional branch.
  7928. }
  7929. if not (cs_opt_size in current_settings.optimizerswitches) and
  7930. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7931. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7932. { The first operand of CMP instructions can only be a register or
  7933. immediate anyway, so no need to check }
  7934. GetNextInstruction(hp2, p_label) and
  7935. (p_label.typ = ait_label) and
  7936. (tai_label(p_label).labsym.getrefs = 1) and
  7937. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7938. GetNextInstruction(p_label, p_dist) and
  7939. MatchInstruction(p_dist, A_SETcc, []) and
  7940. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7941. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7942. begin
  7943. TransferUsedRegs(TmpUsedRegs);
  7944. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7945. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7946. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7947. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7948. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7949. { Get the instruction after the SETcc instruction so we can
  7950. allocate a new register over the entire range }
  7951. GetNextInstruction(p_dist, hp1_dist) then
  7952. begin
  7953. { Register can appear in p if it's not used afterwards, so only
  7954. allocate between hp1 and hp1_dist }
  7955. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7956. if NewReg <> NR_NO then
  7957. begin
  7958. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7959. { Change the jump instruction into a SETcc instruction }
  7960. taicpu(hp1).opcode := A_SETcc;
  7961. taicpu(hp1).opsize := S_B;
  7962. taicpu(hp1).loadreg(0, NewReg);
  7963. { This is now a dead label }
  7964. tai_label(p_label).labsym.decrefs;
  7965. { Prefer adding before the next instruction so the FLAGS
  7966. register is deallicated first }
  7967. AsmL.InsertBefore(
  7968. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7969. hp1_dist
  7970. );
  7971. Result := True;
  7972. { Don't exit yet, as p wasn't changed and hp1, while
  7973. modified, is still intact and might be optimised by the
  7974. SETcc optimisation below }
  7975. end;
  7976. end;
  7977. end;
  7978. end;
  7979. if (taicpu(p).oper[0]^.typ = top_const) and
  7980. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7981. begin
  7982. if (taicpu(p).oper[0]^.val = 0) and
  7983. (taicpu(p).oper[1]^.typ = top_reg) then
  7984. begin
  7985. hp2 := p;
  7986. FirstMatch := True;
  7987. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7988. anything meaningful once it's converted to "test %reg,%reg";
  7989. additionally, some jumps will always (or never) branch, so
  7990. evaluate every jump immediately following the
  7991. comparison, optimising the conditions if possible.
  7992. Similarly with SETcc... those that are always set to 0 or 1
  7993. are changed to MOV instructions }
  7994. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7995. (
  7996. GetNextInstruction(hp2, hp1) and
  7997. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7998. ) do
  7999. begin
  8000. Prefetch(hp1.Next);
  8001. FirstMatch := False;
  8002. case taicpu(hp1).condition of
  8003. C_B, C_C, C_NAE, C_O:
  8004. { For B/NAE:
  8005. Will never branch since an unsigned integer can never be below zero
  8006. For C/O:
  8007. Result cannot overflow because 0 is being subtracted
  8008. }
  8009. begin
  8010. if taicpu(hp1).opcode = A_Jcc then
  8011. begin
  8012. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  8013. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  8014. RemoveInstruction(hp1);
  8015. { Since hp1 was deleted, hp2 must not be updated }
  8016. Continue;
  8017. end
  8018. else
  8019. begin
  8020. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  8021. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  8022. taicpu(hp1).opcode := A_MOV;
  8023. taicpu(hp1).ops := 2;
  8024. taicpu(hp1).condition := C_None;
  8025. taicpu(hp1).opsize := S_B;
  8026. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8027. taicpu(hp1).loadconst(0, 0);
  8028. end;
  8029. end;
  8030. C_BE, C_NA:
  8031. begin
  8032. { Will only branch if equal to zero }
  8033. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  8034. taicpu(hp1).condition := C_E;
  8035. end;
  8036. C_A, C_NBE:
  8037. begin
  8038. { Will only branch if not equal to zero }
  8039. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  8040. taicpu(hp1).condition := C_NE;
  8041. end;
  8042. C_AE, C_NB, C_NC, C_NO:
  8043. begin
  8044. { Will always branch }
  8045. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  8046. if taicpu(hp1).opcode = A_Jcc then
  8047. begin
  8048. MakeUnconditional(taicpu(hp1));
  8049. { Any jumps/set that follow will now be dead code }
  8050. RemoveDeadCodeAfterJump(taicpu(hp1));
  8051. Break;
  8052. end
  8053. else
  8054. begin
  8055. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  8056. taicpu(hp1).opcode := A_MOV;
  8057. taicpu(hp1).ops := 2;
  8058. taicpu(hp1).condition := C_None;
  8059. taicpu(hp1).opsize := S_B;
  8060. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8061. taicpu(hp1).loadconst(0, 1);
  8062. end;
  8063. end;
  8064. C_None:
  8065. InternalError(2020012201);
  8066. C_P, C_PE, C_NP, C_PO:
  8067. { We can't handle parity checks and they should never be generated
  8068. after a general-purpose CMP (it's used in some floating-point
  8069. comparisons that don't use CMP) }
  8070. InternalError(2020012202);
  8071. else
  8072. { Zero/Equality, Sign, their complements and all of the
  8073. signed comparisons do not need to be converted };
  8074. end;
  8075. hp2 := hp1;
  8076. end;
  8077. { Convert the instruction to a TEST }
  8078. taicpu(p).opcode := A_TEST;
  8079. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8080. Result := True;
  8081. Exit;
  8082. end
  8083. else
  8084. begin
  8085. TransferUsedRegs(TmpUsedRegs);
  8086. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8087. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8088. begin
  8089. if (taicpu(p).oper[0]^.val = 1) and
  8090. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  8091. begin
  8092. { Convert; To:
  8093. cmp $1,r/m cmp $0,r/m
  8094. jl @lbl jle @lbl
  8095. (Also do inverted conditions)
  8096. }
  8097. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8098. taicpu(p).oper[0]^.val := 0;
  8099. if taicpu(hp1).condition in [C_L, C_NGE] then
  8100. taicpu(hp1).condition := C_LE
  8101. else
  8102. taicpu(hp1).condition := C_NLE;
  8103. { If the instruction is now "cmp $0,%reg", convert it to a
  8104. TEST (and effectively do the work of the "cmp $0,%reg" in
  8105. the block above)
  8106. }
  8107. if (taicpu(p).oper[1]^.typ = top_reg) then
  8108. begin
  8109. taicpu(p).opcode := A_TEST;
  8110. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8111. end;
  8112. Result := True;
  8113. Exit;
  8114. end
  8115. else if (taicpu(p).oper[1]^.typ = top_reg)
  8116. {$ifdef x86_64}
  8117. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8118. {$endif x86_64}
  8119. then
  8120. begin
  8121. { cmp register,$8000 neg register
  8122. je target --> jo target
  8123. .... only if register is deallocated before jump.}
  8124. case Taicpu(p).opsize of
  8125. S_B: v:=$80;
  8126. S_W: v:=$8000;
  8127. S_L: v:=qword($80000000);
  8128. else
  8129. internalerror(2013112905);
  8130. end;
  8131. if (taicpu(p).oper[0]^.val=v) and
  8132. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8133. begin
  8134. TransferUsedRegs(TmpUsedRegs);
  8135. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8136. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8137. begin
  8138. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8139. Taicpu(p).opcode:=A_NEG;
  8140. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8141. Taicpu(p).clearop(1);
  8142. Taicpu(p).ops:=1;
  8143. if Taicpu(hp1).condition=C_E then
  8144. Taicpu(hp1).condition:=C_O
  8145. else
  8146. Taicpu(hp1).condition:=C_NO;
  8147. Result:=true;
  8148. exit;
  8149. end;
  8150. end;
  8151. end;
  8152. end;
  8153. end;
  8154. end;
  8155. if TrySwapMovCmp(p, hp1) then
  8156. begin
  8157. Result := True;
  8158. Exit;
  8159. end;
  8160. end;
  8161. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8162. var
  8163. hp1: tai;
  8164. begin
  8165. {
  8166. remove the second (v)pxor from
  8167. pxor reg,reg
  8168. ...
  8169. pxor reg,reg
  8170. }
  8171. Result:=false;
  8172. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8173. MatchOpType(taicpu(p),top_reg,top_reg) and
  8174. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8175. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8176. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8177. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8178. begin
  8179. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8180. RemoveInstruction(hp1);
  8181. Result:=true;
  8182. Exit;
  8183. end
  8184. {
  8185. replace
  8186. pxor reg1,reg1
  8187. movapd/s reg1,reg2
  8188. dealloc reg1
  8189. by
  8190. pxor reg2,reg2
  8191. }
  8192. else if GetNextInstruction(p,hp1) and
  8193. { we mix single and double opperations here because we assume that the compiler
  8194. generates vmovapd only after double operations and vmovaps only after single operations }
  8195. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8196. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8197. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8198. (taicpu(p).oper[0]^.typ=top_reg) then
  8199. begin
  8200. TransferUsedRegs(TmpUsedRegs);
  8201. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8202. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8203. begin
  8204. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8205. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8206. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8207. RemoveInstruction(hp1);
  8208. result:=true;
  8209. end;
  8210. end;
  8211. end;
  8212. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8213. var
  8214. hp1: tai;
  8215. begin
  8216. {
  8217. remove the second (v)pxor from
  8218. (v)pxor reg,reg
  8219. ...
  8220. (v)pxor reg,reg
  8221. }
  8222. Result:=false;
  8223. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8224. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8225. begin
  8226. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8227. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8228. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8229. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8230. begin
  8231. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8232. RemoveInstruction(hp1);
  8233. Result:=true;
  8234. Exit;
  8235. end;
  8236. {$ifdef x86_64}
  8237. {
  8238. replace
  8239. vpxor reg1,reg1,reg1
  8240. vmov reg,mem
  8241. by
  8242. movq $0,mem
  8243. }
  8244. if GetNextInstruction(p,hp1) and
  8245. MatchInstruction(hp1,A_VMOVSD,[]) and
  8246. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8247. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8248. begin
  8249. TransferUsedRegs(TmpUsedRegs);
  8250. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8251. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8252. begin
  8253. taicpu(hp1).loadconst(0,0);
  8254. taicpu(hp1).opcode:=A_MOV;
  8255. taicpu(hp1).opsize:=S_Q;
  8256. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8257. RemoveCurrentP(p);
  8258. result:=true;
  8259. Exit;
  8260. end;
  8261. end;
  8262. {$endif x86_64}
  8263. end
  8264. {
  8265. replace
  8266. vpxor reg1,reg1,reg2
  8267. by
  8268. vpxor reg2,reg2,reg2
  8269. to avoid unncessary data dependencies
  8270. }
  8271. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8272. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8273. begin
  8274. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8275. { avoid unncessary data dependency }
  8276. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8277. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8278. result:=true;
  8279. exit;
  8280. end;
  8281. Result:=OptPass1VOP(p);
  8282. end;
  8283. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8284. var
  8285. hp1 : tai;
  8286. begin
  8287. result:=false;
  8288. { replace
  8289. IMul const,%mreg1,%mreg2
  8290. Mov %reg2,%mreg3
  8291. dealloc %mreg3
  8292. by
  8293. Imul const,%mreg1,%mreg23
  8294. }
  8295. if (taicpu(p).ops=3) and
  8296. GetNextInstruction(p,hp1) and
  8297. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8298. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8299. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8300. begin
  8301. TransferUsedRegs(TmpUsedRegs);
  8302. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8303. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8304. begin
  8305. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8306. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8307. RemoveInstruction(hp1);
  8308. result:=true;
  8309. end;
  8310. end;
  8311. end;
  8312. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8313. var
  8314. hp1 : tai;
  8315. begin
  8316. result:=false;
  8317. { replace
  8318. IMul %reg0,%reg1,%reg2
  8319. Mov %reg2,%reg3
  8320. dealloc %reg2
  8321. by
  8322. Imul %reg0,%reg1,%reg3
  8323. }
  8324. if GetNextInstruction(p,hp1) and
  8325. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8326. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8327. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8328. begin
  8329. TransferUsedRegs(TmpUsedRegs);
  8330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8331. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8332. begin
  8333. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8334. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8335. RemoveInstruction(hp1);
  8336. result:=true;
  8337. end;
  8338. end;
  8339. end;
  8340. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8341. var
  8342. hp1: tai;
  8343. begin
  8344. Result:=false;
  8345. { get rid of
  8346. (v)cvtss2sd reg0,<reg1,>reg2
  8347. (v)cvtss2sd reg2,<reg2,>reg0
  8348. }
  8349. if GetNextInstruction(p,hp1) and
  8350. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8351. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8352. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8353. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8354. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8355. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8356. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8357. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8358. )
  8359. ) then
  8360. begin
  8361. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8362. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8363. begin
  8364. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8365. RemoveCurrentP(p);
  8366. RemoveInstruction(hp1);
  8367. end
  8368. else
  8369. begin
  8370. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8371. if taicpu(hp1).opcode=A_CVTSD2SS then
  8372. begin
  8373. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8374. taicpu(p).opcode:=A_MOVAPS;
  8375. end
  8376. else
  8377. begin
  8378. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8379. taicpu(p).opcode:=A_VMOVAPS;
  8380. end;
  8381. taicpu(p).ops:=2;
  8382. RemoveInstruction(hp1);
  8383. end;
  8384. Result:=true;
  8385. Exit;
  8386. end;
  8387. end;
  8388. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8389. var
  8390. hp1, hp2, hp3, hp4, hp5: tai;
  8391. ThisReg: TRegister;
  8392. begin
  8393. Result := False;
  8394. if not GetNextInstruction(p,hp1) then
  8395. Exit;
  8396. {
  8397. convert
  8398. j<c> .L1
  8399. mov 1,reg
  8400. jmp .L2
  8401. .L1
  8402. mov 0,reg
  8403. .L2
  8404. into
  8405. mov 0,reg
  8406. set<not(c)> reg
  8407. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8408. would destroy the flag contents
  8409. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8410. executed at the same time as a previous comparison.
  8411. set<not(c)> reg
  8412. movzx reg, reg
  8413. }
  8414. if MatchInstruction(hp1,A_MOV,[]) and
  8415. (taicpu(hp1).oper[0]^.typ = top_const) and
  8416. (
  8417. (
  8418. (taicpu(hp1).oper[1]^.typ = top_reg)
  8419. {$ifdef i386}
  8420. { Under i386, ESI, EDI, EBP and ESP
  8421. don't have an 8-bit representation }
  8422. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8423. {$endif i386}
  8424. ) or (
  8425. {$ifdef i386}
  8426. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8427. {$endif i386}
  8428. (taicpu(hp1).opsize = S_B)
  8429. )
  8430. ) and
  8431. GetNextInstruction(hp1,hp2) and
  8432. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8433. GetNextInstruction(hp2,hp3) and
  8434. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8435. GetNextInstruction(hp3,hp4) and
  8436. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8437. (taicpu(hp4).oper[0]^.typ = top_const) and
  8438. (
  8439. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8440. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8441. ) and
  8442. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8443. GetNextInstruction(hp4,hp5) and
  8444. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8445. begin
  8446. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8447. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8448. tai_label(hp3).labsym.DecRefs;
  8449. { If this isn't the only reference to the middle label, we can
  8450. still make a saving - only that the first jump and everything
  8451. that follows will remain. }
  8452. if (tai_label(hp3).labsym.getrefs = 0) then
  8453. begin
  8454. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8455. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8456. else
  8457. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8458. { remove jump, first label and second MOV (also catching any aligns) }
  8459. repeat
  8460. if not GetNextInstruction(hp2, hp3) then
  8461. InternalError(2021040810);
  8462. RemoveInstruction(hp2);
  8463. hp2 := hp3;
  8464. until hp2 = hp5;
  8465. { Don't decrement reference count before the removal loop
  8466. above, otherwise GetNextInstruction won't stop on the
  8467. the label }
  8468. tai_label(hp5).labsym.DecRefs;
  8469. end
  8470. else
  8471. begin
  8472. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8473. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8474. else
  8475. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8476. end;
  8477. taicpu(p).opcode:=A_SETcc;
  8478. taicpu(p).opsize:=S_B;
  8479. taicpu(p).is_jmp:=False;
  8480. if taicpu(hp1).opsize=S_B then
  8481. begin
  8482. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8483. if taicpu(hp1).oper[1]^.typ = top_reg then
  8484. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8485. RemoveInstruction(hp1);
  8486. end
  8487. else
  8488. begin
  8489. { Will be a register because the size can't be S_B otherwise }
  8490. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8491. taicpu(p).loadreg(0, ThisReg);
  8492. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8493. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8494. begin
  8495. case taicpu(hp1).opsize of
  8496. S_W:
  8497. taicpu(hp1).opsize := S_BW;
  8498. S_L:
  8499. taicpu(hp1).opsize := S_BL;
  8500. {$ifdef x86_64}
  8501. S_Q:
  8502. begin
  8503. taicpu(hp1).opsize := S_BL;
  8504. { Change the destination register to 32-bit }
  8505. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8506. end;
  8507. {$endif x86_64}
  8508. else
  8509. InternalError(2021040820);
  8510. end;
  8511. taicpu(hp1).opcode := A_MOVZX;
  8512. taicpu(hp1).loadreg(0, ThisReg);
  8513. end
  8514. else
  8515. begin
  8516. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8517. { hp1 is already a MOV instruction with the correct register }
  8518. taicpu(hp1).loadconst(0, 0);
  8519. { Inserting it right before p will guarantee that the flags are also tracked }
  8520. asml.Remove(hp1);
  8521. asml.InsertBefore(hp1, p);
  8522. end;
  8523. end;
  8524. Result:=true;
  8525. exit;
  8526. end
  8527. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8528. Result := TryJccStcClcOpt(p, hp1)
  8529. else if (hp1.typ = ait_label) then
  8530. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8531. end;
  8532. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8533. var
  8534. hp1, hp2, hp3: tai;
  8535. SourceRef, TargetRef: TReference;
  8536. CurrentReg: TRegister;
  8537. begin
  8538. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8539. if not UseAVX then
  8540. InternalError(2021100501);
  8541. Result := False;
  8542. { Look for the following to simplify:
  8543. vmovdqa/u x(mem1), %xmmreg
  8544. vmovdqa/u %xmmreg, y(mem2)
  8545. vmovdqa/u x+16(mem1), %xmmreg
  8546. vmovdqa/u %xmmreg, y+16(mem2)
  8547. Change to:
  8548. vmovdqa/u x(mem1), %ymmreg
  8549. vmovdqa/u %ymmreg, y(mem2)
  8550. vpxor %ymmreg, %ymmreg, %ymmreg
  8551. ( The VPXOR instruction is to zero the upper half, thus removing the
  8552. need to call the potentially expensive VZEROUPPER instruction. Other
  8553. peephole optimisations can remove VPXOR if it's unnecessary )
  8554. }
  8555. TransferUsedRegs(TmpUsedRegs);
  8556. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8557. { NOTE: In the optimisations below, if the references dictate that an
  8558. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8559. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8560. if (taicpu(p).opsize = S_XMM) and
  8561. MatchOpType(taicpu(p), top_ref, top_reg) and
  8562. GetNextInstruction(p, hp1) and
  8563. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8564. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8565. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8566. begin
  8567. SourceRef := taicpu(p).oper[0]^.ref^;
  8568. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8569. if GetNextInstruction(hp1, hp2) and
  8570. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8571. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8572. begin
  8573. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8574. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8575. Inc(SourceRef.offset, 16);
  8576. { Reuse the register in the first block move }
  8577. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8578. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8579. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8580. begin
  8581. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8582. Inc(TargetRef.offset, 16);
  8583. if GetNextInstruction(hp2, hp3) and
  8584. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8585. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8586. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8587. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8588. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8589. begin
  8590. { Update the register tracking to the new size }
  8591. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8592. { Remember that the offsets are 16 ahead }
  8593. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8594. if not (
  8595. ((SourceRef.offset mod 32) = 16) and
  8596. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8597. ) then
  8598. taicpu(p).opcode := A_VMOVDQU;
  8599. taicpu(p).opsize := S_YMM;
  8600. taicpu(p).oper[1]^.reg := CurrentReg;
  8601. if not (
  8602. ((TargetRef.offset mod 32) = 16) and
  8603. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8604. ) then
  8605. taicpu(hp1).opcode := A_VMOVDQU;
  8606. taicpu(hp1).opsize := S_YMM;
  8607. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8608. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8609. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8610. if (pi_uses_ymm in current_procinfo.flags) then
  8611. RemoveInstruction(hp2)
  8612. else
  8613. begin
  8614. taicpu(hp2).opcode := A_VPXOR;
  8615. taicpu(hp2).opsize := S_YMM;
  8616. taicpu(hp2).loadreg(0, CurrentReg);
  8617. taicpu(hp2).loadreg(1, CurrentReg);
  8618. taicpu(hp2).loadreg(2, CurrentReg);
  8619. taicpu(hp2).ops := 3;
  8620. end;
  8621. RemoveInstruction(hp3);
  8622. Result := True;
  8623. Exit;
  8624. end;
  8625. end
  8626. else
  8627. begin
  8628. { See if the next references are 16 less rather than 16 greater }
  8629. Dec(SourceRef.offset, 32); { -16 the other way }
  8630. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8631. begin
  8632. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8633. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8634. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8635. GetNextInstruction(hp2, hp3) and
  8636. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8637. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8638. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8639. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8640. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8641. begin
  8642. { Update the register tracking to the new size }
  8643. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8644. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8645. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8646. if not(
  8647. ((SourceRef.offset mod 32) = 0) and
  8648. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8649. ) then
  8650. taicpu(hp2).opcode := A_VMOVDQU;
  8651. taicpu(hp2).opsize := S_YMM;
  8652. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8653. if not (
  8654. ((TargetRef.offset mod 32) = 0) and
  8655. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8656. ) then
  8657. taicpu(hp3).opcode := A_VMOVDQU;
  8658. taicpu(hp3).opsize := S_YMM;
  8659. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8660. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8661. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8662. if (pi_uses_ymm in current_procinfo.flags) then
  8663. RemoveInstruction(hp1)
  8664. else
  8665. begin
  8666. taicpu(hp1).opcode := A_VPXOR;
  8667. taicpu(hp1).opsize := S_YMM;
  8668. taicpu(hp1).loadreg(0, CurrentReg);
  8669. taicpu(hp1).loadreg(1, CurrentReg);
  8670. taicpu(hp1).loadreg(2, CurrentReg);
  8671. taicpu(hp1).ops := 3;
  8672. Asml.Remove(hp1);
  8673. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8674. end;
  8675. RemoveCurrentP(p, hp2);
  8676. Result := True;
  8677. Exit;
  8678. end;
  8679. end;
  8680. end;
  8681. end;
  8682. end;
  8683. end;
  8684. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8685. var
  8686. hp2, hp3, first_assignment: tai;
  8687. IncCount, OperIdx: Integer;
  8688. OrigLabel: TAsmLabel;
  8689. begin
  8690. Count := 0;
  8691. Result := False;
  8692. first_assignment := nil;
  8693. if (LoopCount >= 20) then
  8694. begin
  8695. { Guard against infinite loops }
  8696. Exit;
  8697. end;
  8698. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8699. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8700. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8701. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8702. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8703. Exit;
  8704. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8705. {
  8706. change
  8707. jmp .L1
  8708. ...
  8709. .L1:
  8710. mov ##, ## ( multiple movs possible )
  8711. jmp/ret
  8712. into
  8713. mov ##, ##
  8714. jmp/ret
  8715. }
  8716. if not Assigned(hp1) then
  8717. begin
  8718. hp1 := GetLabelWithSym(OrigLabel);
  8719. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8720. Exit;
  8721. end;
  8722. hp2 := hp1;
  8723. while Assigned(hp2) do
  8724. begin
  8725. if Assigned(hp2) and (hp2.typ = ait_label) then
  8726. SkipLabels(hp2,hp2);
  8727. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8728. Break;
  8729. case taicpu(hp2).opcode of
  8730. A_MOVSD:
  8731. begin
  8732. if taicpu(hp2).ops = 0 then
  8733. { Wrong MOVSD }
  8734. Break;
  8735. Inc(Count);
  8736. if Count >= 5 then
  8737. { Too many to be worthwhile }
  8738. Break;
  8739. GetNextInstruction(hp2, hp2);
  8740. Continue;
  8741. end;
  8742. A_MOV,
  8743. A_MOVD,
  8744. A_MOVQ,
  8745. A_MOVSX,
  8746. {$ifdef x86_64}
  8747. A_MOVSXD,
  8748. {$endif x86_64}
  8749. A_MOVZX,
  8750. A_MOVAPS,
  8751. A_MOVUPS,
  8752. A_MOVSS,
  8753. A_MOVAPD,
  8754. A_MOVUPD,
  8755. A_MOVDQA,
  8756. A_MOVDQU,
  8757. A_VMOVSS,
  8758. A_VMOVAPS,
  8759. A_VMOVUPS,
  8760. A_VMOVSD,
  8761. A_VMOVAPD,
  8762. A_VMOVUPD,
  8763. A_VMOVDQA,
  8764. A_VMOVDQU:
  8765. begin
  8766. Inc(Count);
  8767. if Count >= 5 then
  8768. { Too many to be worthwhile }
  8769. Break;
  8770. GetNextInstruction(hp2, hp2);
  8771. Continue;
  8772. end;
  8773. A_JMP:
  8774. begin
  8775. { Guard against infinite loops }
  8776. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8777. Exit;
  8778. { Analyse this jump first in case it also duplicates assignments }
  8779. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8780. begin
  8781. { Something did change! }
  8782. Result := True;
  8783. Inc(Count, IncCount);
  8784. if Count >= 5 then
  8785. begin
  8786. { Too many to be worthwhile }
  8787. Exit;
  8788. end;
  8789. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8790. Break;
  8791. end;
  8792. Result := True;
  8793. Break;
  8794. end;
  8795. A_RET:
  8796. begin
  8797. Result := True;
  8798. Break;
  8799. end;
  8800. else
  8801. Break;
  8802. end;
  8803. end;
  8804. if Result then
  8805. begin
  8806. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8807. if Count = 0 then
  8808. begin
  8809. Result := False;
  8810. Exit;
  8811. end;
  8812. TransferUsedRegs(TmpUsedRegs);
  8813. hp3 := p;
  8814. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8815. while True do
  8816. begin
  8817. if Assigned(hp1) and (hp1.typ = ait_label) then
  8818. SkipLabels(hp1,hp1);
  8819. case hp1.typ of
  8820. ait_regalloc:
  8821. if tai_regalloc(hp1).ratype = ra_dealloc then
  8822. begin
  8823. { Duplicate the register deallocation... }
  8824. hp3:=tai(hp1.getcopy);
  8825. if first_assignment = nil then
  8826. first_assignment := hp3;
  8827. asml.InsertBefore(hp3, p);
  8828. { ... but also reallocate it after the jump }
  8829. hp3:=tai(hp1.getcopy);
  8830. tai_regalloc(hp3).ratype := ra_alloc;
  8831. asml.InsertAfter(hp3, p);
  8832. end;
  8833. ait_instruction:
  8834. case taicpu(hp1).opcode of
  8835. A_JMP:
  8836. begin
  8837. { Change the original jump to the new destination }
  8838. OrigLabel.decrefs;
  8839. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8840. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8841. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8842. if not Assigned(first_assignment) then
  8843. InternalError(2021040810)
  8844. else
  8845. p := first_assignment;
  8846. Exit;
  8847. end;
  8848. A_RET:
  8849. begin
  8850. { Now change the jump into a RET instruction }
  8851. ConvertJumpToRET(p, hp1);
  8852. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8853. if not Assigned(first_assignment) then
  8854. InternalError(2021040811)
  8855. else
  8856. p := first_assignment;
  8857. Exit;
  8858. end;
  8859. else
  8860. begin
  8861. { Duplicate the MOV instruction }
  8862. hp3:=tai(hp1.getcopy);
  8863. if first_assignment = nil then
  8864. first_assignment := hp3;
  8865. asml.InsertBefore(hp3, p);
  8866. { Make sure the compiler knows about any final registers written here }
  8867. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8868. with taicpu(hp3).oper[OperIdx]^ do
  8869. begin
  8870. case typ of
  8871. top_ref:
  8872. begin
  8873. if (ref^.base <> NR_NO) and
  8874. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8875. (
  8876. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8877. (
  8878. { Allow the frame pointer if it's not being used by the procedure as such }
  8879. Assigned(current_procinfo) and
  8880. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8881. )
  8882. )
  8883. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8884. then
  8885. begin
  8886. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8887. if not Assigned(first_assignment) then
  8888. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8889. end;
  8890. if (ref^.index <> NR_NO) and
  8891. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8892. (
  8893. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8894. (
  8895. { Allow the frame pointer if it's not being used by the procedure as such }
  8896. Assigned(current_procinfo) and
  8897. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8898. )
  8899. )
  8900. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8901. (ref^.index <> ref^.base) then
  8902. begin
  8903. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8904. if not Assigned(first_assignment) then
  8905. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8906. end;
  8907. end;
  8908. top_reg:
  8909. begin
  8910. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8911. if not Assigned(first_assignment) then
  8912. IncludeRegInUsedRegs(reg, UsedRegs);
  8913. end;
  8914. else
  8915. ;
  8916. end;
  8917. end;
  8918. end;
  8919. end;
  8920. else
  8921. InternalError(2021040720);
  8922. end;
  8923. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8924. { Should have dropped out earlier }
  8925. InternalError(2021040710);
  8926. end;
  8927. end;
  8928. end;
  8929. const
  8930. WriteOp: array[0..3] of set of TInsChange = (
  8931. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8932. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8933. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8934. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8935. RegWriteFlags: array[0..7] of set of TInsChange = (
  8936. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8937. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8938. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8939. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8940. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8941. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8942. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8943. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8944. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8945. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8946. var
  8947. hp2: tai;
  8948. X: Integer;
  8949. begin
  8950. { If we have something like:
  8951. op ###,###
  8952. mov ###,###
  8953. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8954. interfere in regards to what they write to.
  8955. NOTE: p must be a 2-operand instruction
  8956. }
  8957. Result := False;
  8958. if (hp1.typ <> ait_instruction) or
  8959. taicpu(hp1).is_jmp or
  8960. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8961. Exit;
  8962. { NOP is a pipeline fence, likely marking the beginning of the function
  8963. epilogue, so drop out. Similarly, drop out if POP or RET are
  8964. encountered }
  8965. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8966. Exit;
  8967. if (taicpu(hp1).opcode = A_MOVSD) and
  8968. (taicpu(hp1).ops = 0) then
  8969. { Wrong MOVSD }
  8970. Exit;
  8971. { Check for writes to specific registers first }
  8972. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8973. for X := 0 to 7 do
  8974. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8975. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8976. Exit;
  8977. for X := 0 to taicpu(hp1).ops - 1 do
  8978. begin
  8979. { Check to see if this operand writes to something }
  8980. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8981. { And matches something in the CMP/TEST instruction }
  8982. (
  8983. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8984. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8985. (
  8986. { If it's a register, make sure the register written to doesn't
  8987. appear in the cmp instruction as part of a reference }
  8988. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8989. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8990. )
  8991. ) then
  8992. Exit;
  8993. end;
  8994. { Check p to make sure it doesn't write to something that affects hp1 }
  8995. { Check for writes to specific registers first }
  8996. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8997. for X := 0 to 7 do
  8998. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8999. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  9000. Exit;
  9001. for X := 0 to taicpu(p).ops - 1 do
  9002. begin
  9003. { Check to see if this operand writes to something }
  9004. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  9005. { And matches something in hp1 }
  9006. (taicpu(p).oper[X]^.typ = top_reg) and
  9007. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  9008. Exit;
  9009. end;
  9010. { The instruction can be safely moved }
  9011. asml.Remove(hp1);
  9012. { Try to insert after the last instructions where the FLAGS register is not
  9013. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  9014. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  9015. asml.InsertBefore(hp1, hp2)
  9016. { Failing that, try to insert after the last instructions where the
  9017. FLAGS register is not yet in use }
  9018. else if GetLastInstruction(p, hp2) and
  9019. (
  9020. (hp2.typ <> ait_instruction) or
  9021. { Don't insert after an instruction that uses the flags when p doesn't use them }
  9022. RegInInstruction(NR_DEFAULTFLAGS, p) or
  9023. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  9024. ) then
  9025. asml.InsertAfter(hp1, hp2)
  9026. else
  9027. { Note, if p.Previous is nil (even if it should logically never be the
  9028. case), FindRegAllocBackward immediately exits with False and so we
  9029. safely land here (we can't just pass p because FindRegAllocBackward
  9030. immediately exits on an instruction). [Kit] }
  9031. asml.InsertBefore(hp1, p);
  9032. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  9033. { We can't trust UsedRegs because we're looking backwards, although we
  9034. know the registers are allocated after p at the very least, so manually
  9035. create tai_regalloc objects if needed }
  9036. for X := 0 to taicpu(hp1).ops - 1 do
  9037. case taicpu(hp1).oper[X]^.typ of
  9038. top_reg:
  9039. begin
  9040. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  9041. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  9042. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  9043. end;
  9044. top_ref:
  9045. begin
  9046. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  9047. begin
  9048. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  9049. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  9050. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  9051. end;
  9052. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  9053. begin
  9054. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  9055. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  9056. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  9057. end;
  9058. end;
  9059. else
  9060. ;
  9061. end;
  9062. Result := True;
  9063. end;
  9064. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  9065. var
  9066. hp2: tai;
  9067. X: Integer;
  9068. begin
  9069. { If we have something like:
  9070. cmp ###,%reg1
  9071. mov 0,%reg2
  9072. And no modified registers are shared, move the instruction to before
  9073. the comparison as this means it can be optimised without worrying
  9074. about the FLAGS register. (CMP/MOV is generated by
  9075. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  9076. As long as the second instruction doesn't use the flags or one of the
  9077. registers used by CMP or TEST (also check any references that use the
  9078. registers), then it can be moved prior to the comparison.
  9079. }
  9080. Result := False;
  9081. if not TrySwapMovOp(p, hp1) then
  9082. Exit;
  9083. if taicpu(hp1).opcode = A_LEA then
  9084. { The flags will be overwritten by the CMP/TEST instruction }
  9085. ConvertLEA(taicpu(hp1));
  9086. Result := True;
  9087. { Can we move it one further back? }
  9088. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  9089. { Check to see if CMP/TEST is a comparison against zero }
  9090. (
  9091. (
  9092. (taicpu(p).opcode = A_CMP) and
  9093. MatchOperand(taicpu(p).oper[0]^, 0)
  9094. ) or
  9095. (
  9096. (taicpu(p).opcode = A_TEST) and
  9097. (
  9098. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9099. MatchOperand(taicpu(p).oper[0]^, -1)
  9100. )
  9101. )
  9102. ) and
  9103. { These instructions set the zero flag if the result is zero }
  9104. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9105. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9106. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9107. TrySwapMovOp(hp2, hp1);
  9108. end;
  9109. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9110. var
  9111. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9112. JumpLabel: TAsmLabel;
  9113. TmpBool: Boolean;
  9114. begin
  9115. Result := False;
  9116. { Look for:
  9117. stc/clc
  9118. j(c) .L1
  9119. ...
  9120. .L1:
  9121. set(n)cb %reg
  9122. (flags deallocated)
  9123. j(c) .L2
  9124. Change to:
  9125. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9126. j(c) .L2
  9127. }
  9128. p_last := p;
  9129. while GetNextInstruction(p_last, hp1) and
  9130. (hp1.typ = ait_instruction) and
  9131. IsJumpToLabel(taicpu(hp1)) do
  9132. begin
  9133. if DoJumpOptimizations(hp1, TmpBool) then
  9134. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9135. Continue;
  9136. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9137. if not Assigned(JumpLabel) then
  9138. InternalError(2024012801);
  9139. { Optimise the J(c); stc/clc optimisation first since this will
  9140. get missed if the main optimisation takes place }
  9141. if (taicpu(hp1).opcode = A_JCC) then
  9142. begin
  9143. if GetNextInstruction(hp1, hp2) and
  9144. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9145. TryJccStcClcOpt(hp1, hp2) then
  9146. begin
  9147. Result := True;
  9148. Exit;
  9149. end;
  9150. hp2 := nil; { Suppress compiler warning }
  9151. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9152. { Make sure the flags aren't used again }
  9153. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9154. begin
  9155. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9156. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9157. begin
  9158. if (taicpu(p).opcode = A_STC) then
  9159. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9160. else
  9161. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9162. MakeUnconditional(taicpu(hp1));
  9163. { Move the jump to after the flag deallocations }
  9164. Asml.Remove(hp1);
  9165. Asml.InsertAfter(hp1, hp2);
  9166. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9167. Result := True;
  9168. Exit;
  9169. end
  9170. else
  9171. begin
  9172. if (taicpu(p).opcode = A_STC) then
  9173. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9174. else
  9175. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9176. { In this case, the jump is deterministic in that it will never be taken }
  9177. JumpLabel.DecRefs;
  9178. RemoveInstruction(hp1);
  9179. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9180. Result := True;
  9181. Exit;
  9182. end;
  9183. end;
  9184. end;
  9185. hp2 := nil; { Suppress compiler warning }
  9186. if
  9187. { Make sure the carry flag doesn't appear in the jump conditions }
  9188. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9189. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9190. GetNextInstruction(hp2, p_dist) and
  9191. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9192. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9193. begin
  9194. case taicpu(p_dist).opcode of
  9195. A_Jcc:
  9196. begin
  9197. if DoJumpOptimizations(p_dist, TmpBool) then
  9198. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9199. Continue;
  9200. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9201. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9202. begin
  9203. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9204. JumpLabel.decrefs;
  9205. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9206. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9207. Result := True;
  9208. Exit;
  9209. end
  9210. else if GetNextInstruction(p_dist, hp1_dist) and
  9211. (hp1_dist.typ = ait_label) then
  9212. begin
  9213. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9214. JumpLabel.decrefs;
  9215. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9216. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9217. Result := True;
  9218. Exit;
  9219. end;
  9220. end;
  9221. A_SETcc:
  9222. if { Make sure the flags aren't used again }
  9223. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9224. GetNextInstruction(hp2, hp1_dist) and
  9225. (hp1_dist.typ = ait_instruction) and
  9226. IsJumpToLabel(taicpu(hp1_dist)) and
  9227. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9228. { This works if hp1_dist or both are regular JMP instructions }
  9229. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9230. (
  9231. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9232. { Make sure the register isn't still in use, otherwise it
  9233. may get corrupted (fixes #40659) }
  9234. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9235. ) then
  9236. begin
  9237. taicpu(p).allocate_oper(2);
  9238. taicpu(p).ops := 2;
  9239. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9240. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9241. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9242. taicpu(p).opcode := A_MOV;
  9243. taicpu(p).opsize := S_B;
  9244. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9245. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9246. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9247. JumpLabel.decrefs;
  9248. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9249. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9250. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9251. (tai_regalloc(hp2).ratype = ra_alloc) then
  9252. begin
  9253. Asml.Remove(hp2);
  9254. Asml.InsertAfter(hp2, p);
  9255. end;
  9256. Result := True;
  9257. Exit;
  9258. end;
  9259. else
  9260. ;
  9261. end;
  9262. end;
  9263. p_last := hp1;
  9264. end;
  9265. end;
  9266. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9267. var
  9268. hp2, hp3: tai;
  9269. TempBool: Boolean;
  9270. begin
  9271. Result := False;
  9272. {
  9273. j(c) .L1
  9274. stc/clc
  9275. .L1:
  9276. jc/jnc .L2
  9277. (Flags deallocated)
  9278. Change to:
  9279. j)c) .L1
  9280. jmp .L2
  9281. .L1:
  9282. jc/jnc .L2
  9283. Then call DoJumpOptimizations to convert to:
  9284. j(nc) .L2
  9285. .L1: (may become a dead label)
  9286. jc/jnc .L2
  9287. }
  9288. if GetNextInstruction(hp1, hp2) and
  9289. (hp2.typ = ait_label) and
  9290. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9291. GetNextInstruction(hp2, hp3) and
  9292. MatchInstruction(hp3, A_Jcc, []) and
  9293. (
  9294. (
  9295. (taicpu(hp3).condition = C_C) and
  9296. (taicpu(hp1).opcode = A_STC)
  9297. ) or (
  9298. (taicpu(hp3).condition = C_NC) and
  9299. (taicpu(hp1).opcode = A_CLC)
  9300. )
  9301. ) and
  9302. { Make sure the flags aren't used again }
  9303. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9304. begin
  9305. taicpu(hp1).allocate_oper(1);
  9306. taicpu(hp1).ops := 1;
  9307. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9308. taicpu(hp1).opcode := A_JMP;
  9309. taicpu(hp1).is_jmp := True;
  9310. TempBool := True; { Prevent compiler warnings }
  9311. if DoJumpOptimizations(p, TempBool) then
  9312. Result := True
  9313. else
  9314. Include(OptsToCheck, aoc_ForceNewIteration);
  9315. end;
  9316. end;
  9317. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9318. begin
  9319. { This generally only executes under -O3 and above }
  9320. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9321. end;
  9322. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9323. var
  9324. hp1, hp2: tai;
  9325. FoundComparison: Boolean;
  9326. begin
  9327. { Run the pass 1 optimisations as well, since they may have some effect
  9328. after the CMOV blocks are created in OptPass2Jcc }
  9329. Result := False;
  9330. { Result := OptPass1CMOVcc(p);
  9331. if Result then
  9332. Exit;}
  9333. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9334. and make a slightly inefficent result on branching-type blocks, notably
  9335. when setting a function result then jumping to the function epilogue.
  9336. In this case, change:
  9337. cmov(c) %reg1,%reg2
  9338. j(c) @lbl
  9339. (%reg2 deallocated)
  9340. To:
  9341. mov %reg11,%reg2
  9342. j(c) @lbl
  9343. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9344. jump because if it's not present, we may end up with a jump that's
  9345. completely unrelated.
  9346. }
  9347. hp1 := p;
  9348. while GetNextInstruction(hp1, hp1) and
  9349. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9350. if (hp1.typ = ait_instruction) and
  9351. (taicpu(hp1).opcode = A_Jcc) and
  9352. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9353. begin
  9354. TransferUsedRegs(TmpUsedRegs);
  9355. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9356. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9357. (
  9358. { See if we can find a more distant instruction that overwrites
  9359. the destination register }
  9360. (cs_opt_level3 in current_settings.optimizerswitches) and
  9361. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9362. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9363. ) then
  9364. begin
  9365. if (taicpu(p).oper[0]^.typ = top_reg) then
  9366. begin
  9367. { Search backwards to see if the source register is set to a
  9368. constant }
  9369. FoundComparison := False;
  9370. hp1 := p;
  9371. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9372. begin
  9373. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9374. begin
  9375. FoundComparison := True;
  9376. Continue;
  9377. end;
  9378. { Once we find the CMP, TEST or similar instruction, we
  9379. have to stop if we find anything other than a MOV }
  9380. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9381. Break;
  9382. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9383. { Destination register was modified }
  9384. Break;
  9385. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9386. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9387. begin
  9388. { Found a constant! }
  9389. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9390. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9391. { The source register is no longer in use }
  9392. RemoveInstruction(hp1);
  9393. Break;
  9394. end;
  9395. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9396. { Some other instruction has modified the source register }
  9397. Break;
  9398. end;
  9399. end;
  9400. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9401. taicpu(p).opcode := A_MOV;
  9402. taicpu(p).condition := C_None;
  9403. { Rely on the post peephole stage to put the MOV before the
  9404. CMP/TEST instruction that appears prior }
  9405. Result := True;
  9406. Exit;
  9407. end;
  9408. end;
  9409. end;
  9410. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9411. function IsXCHGAcceptable: Boolean; inline;
  9412. begin
  9413. { Always accept if optimising for size }
  9414. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9415. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9416. than 3, so it becomes a saving compared to three MOVs with two of
  9417. them able to execute simultaneously. [Kit] }
  9418. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9419. end;
  9420. var
  9421. NewRef: TReference;
  9422. hp1, hp2, hp3, hp4: Tai;
  9423. {$ifndef x86_64}
  9424. OperIdx: Integer;
  9425. {$endif x86_64}
  9426. NewInstr : Taicpu;
  9427. NewAligh : Tai_align;
  9428. DestLabel: TAsmLabel;
  9429. TempTracking: TAllUsedRegs;
  9430. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9431. var
  9432. NextInstr: tai;
  9433. begin
  9434. Result := False;
  9435. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9436. if not GetNextInstruction(InputInstr, NextInstr) or
  9437. (
  9438. { The FLAGS register isn't always tracked properly, so do not
  9439. perform this optimisation if a conditional statement follows }
  9440. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9441. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9442. ) then
  9443. begin
  9444. reference_reset(NewRef, 1, []);
  9445. NewRef.base := taicpu(p).oper[0]^.reg;
  9446. NewRef.scalefactor := 1;
  9447. if taicpu(InputInstr).opcode = A_ADD then
  9448. begin
  9449. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9450. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9451. end
  9452. else
  9453. begin
  9454. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9455. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9456. end;
  9457. taicpu(p).opcode := A_LEA;
  9458. taicpu(p).loadref(0, NewRef);
  9459. { For the sake of debugging, have the line info match the
  9460. arithmetic instruction rather than the MOV instruction }
  9461. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9462. RemoveInstruction(InputInstr);
  9463. Result := True;
  9464. end;
  9465. end;
  9466. begin
  9467. Result:=false;
  9468. { This optimisation adds an instruction, so only do it for speed }
  9469. if not (cs_opt_size in current_settings.optimizerswitches) and
  9470. MatchOpType(taicpu(p), top_const, top_reg) and
  9471. (taicpu(p).oper[0]^.val = 0) then
  9472. begin
  9473. { To avoid compiler warning }
  9474. DestLabel := nil;
  9475. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9476. InternalError(2021040750);
  9477. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9478. Exit;
  9479. case hp1.typ of
  9480. ait_label:
  9481. begin
  9482. { Change:
  9483. mov $0,%reg mov $0,%reg
  9484. @Lbl1: @Lbl1:
  9485. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9486. je @Lbl2 jne @Lbl2
  9487. To: To:
  9488. mov $0,%reg mov $0,%reg
  9489. jmp @Lbl2 jmp @Lbl3
  9490. (align) (align)
  9491. @Lbl1: @Lbl1:
  9492. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9493. je @Lbl2 je @Lbl2
  9494. @Lbl3: <-- Only if label exists
  9495. (Not if it's optimised for size)
  9496. }
  9497. if not GetNextInstruction(hp1, hp2) then
  9498. Exit;
  9499. if (hp2.typ = ait_instruction) and
  9500. (
  9501. { Register sizes must exactly match }
  9502. (
  9503. (taicpu(hp2).opcode = A_CMP) and
  9504. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9505. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9506. ) or (
  9507. (taicpu(hp2).opcode = A_TEST) and
  9508. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9509. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9510. )
  9511. ) and GetNextInstruction(hp2, hp3) and
  9512. (hp3.typ = ait_instruction) and
  9513. (taicpu(hp3).opcode = A_JCC) and
  9514. (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
  9515. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9516. begin
  9517. { Check condition of jump }
  9518. { Always true? }
  9519. if condition_in(C_E, taicpu(hp3).condition) then
  9520. begin
  9521. { Copy label symbol and obtain matching label entry for the
  9522. conditional jump, as this will be our destination}
  9523. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9524. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9525. Result := True;
  9526. end
  9527. { Always false? }
  9528. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9529. begin
  9530. { This is only worth it if there's a jump to take }
  9531. case hp2.typ of
  9532. ait_instruction:
  9533. begin
  9534. if taicpu(hp2).opcode = A_JMP then
  9535. begin
  9536. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9537. { An unconditional jump follows the conditional jump which will always be false,
  9538. so use this jump's destination for the new jump }
  9539. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9540. Result := True;
  9541. end
  9542. else if taicpu(hp2).opcode = A_JCC then
  9543. begin
  9544. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9545. if condition_in(C_E, taicpu(hp2).condition) then
  9546. begin
  9547. { A second conditional jump follows the conditional jump which will always be false,
  9548. while the second jump is always True, so use this jump's destination for the new jump }
  9549. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9550. Result := True;
  9551. end;
  9552. { Don't risk it if the jump isn't always true (Result remains False) }
  9553. end;
  9554. end;
  9555. else
  9556. { If anything else don't optimise };
  9557. end;
  9558. end;
  9559. if Result then
  9560. begin
  9561. { Just so we have something to insert as a paremeter}
  9562. reference_reset(NewRef, 1, []);
  9563. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9564. { Now actually load the correct parameter (this also
  9565. increases the reference count) }
  9566. NewInstr.loadsymbol(0, DestLabel, 0);
  9567. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9568. begin
  9569. { Get instruction before original label (may not be p under -O3) }
  9570. if not GetLastInstruction(hp1, hp2) then
  9571. { Shouldn't fail here }
  9572. InternalError(2021040701);
  9573. end
  9574. else
  9575. hp2 := p;
  9576. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9577. AsmL.InsertAfter(NewInstr, hp2);
  9578. { Add new alignment field }
  9579. (* AsmL.InsertAfter(
  9580. cai_align.create_max(
  9581. current_settings.alignment.jumpalign,
  9582. current_settings.alignment.jumpalignskipmax
  9583. ),
  9584. NewInstr
  9585. ); *)
  9586. end;
  9587. Exit;
  9588. end;
  9589. end;
  9590. else
  9591. ;
  9592. end;
  9593. end;
  9594. if not GetNextInstruction(p, hp1) then
  9595. Exit;
  9596. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9597. begin
  9598. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9599. begin
  9600. Result := True;
  9601. Exit;
  9602. end;
  9603. { This optimisation is only effective on a second run of Pass 2,
  9604. hence -O3 or above.
  9605. Change:
  9606. mov %reg1,%reg2
  9607. cmp/test (contains %reg1)
  9608. mov x, %reg1
  9609. (another mov or a j(c))
  9610. To:
  9611. mov %reg1,%reg2
  9612. mov x, %reg1
  9613. cmp (%reg1 replaced with %reg2)
  9614. (another mov or a j(c))
  9615. The requirement of an additional MOV or a jump ensures there
  9616. isn't performance loss, since a j(c) will permit macro-fusion
  9617. with the cmp instruction, while another MOV likely means it's
  9618. not all being executed in a single cycle due to parallelisation.
  9619. }
  9620. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9621. MatchOpType(taicpu(p), top_reg, top_reg) and
  9622. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9623. GetNextInstruction(hp1, hp2) and
  9624. MatchInstruction(hp2, A_MOV, []) and
  9625. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9626. { Registers don't have to be the same size in this case }
  9627. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9628. GetNextInstruction(hp2, hp3) and
  9629. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9630. { Make sure the operands in the camparison can be safely replaced }
  9631. (
  9632. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9633. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9634. ) and
  9635. (
  9636. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9637. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9638. ) then
  9639. begin
  9640. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9641. AsmL.Remove(hp2);
  9642. AsmL.InsertAfter(hp2, p);
  9643. Result := True;
  9644. Exit;
  9645. end;
  9646. end;
  9647. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9648. begin
  9649. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9650. further, but we can't just put this jump optimisation in pass 1
  9651. because it tends to perform worse when conditional jumps are
  9652. nearby (e.g. when converting CMOV instructions). [Kit] }
  9653. CopyUsedRegs(TempTracking);
  9654. UpdateUsedRegs(tai(p.Next));
  9655. if OptPass2JMP(hp1) then
  9656. begin
  9657. { Restore register state }
  9658. RestoreUsedRegs(TempTracking);
  9659. ReleaseUsedRegs(TempTracking);
  9660. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9661. OptPass1MOV(p);
  9662. Result := True;
  9663. Exit;
  9664. end;
  9665. { If OptPass2JMP returned False, no optimisations were done to
  9666. the jump and there are no further optimisations that can be done
  9667. to the MOV instruction on this pass other than FuncMov2Func }
  9668. { Restore register state }
  9669. RestoreUsedRegs(TempTracking);
  9670. ReleaseUsedRegs(TempTracking);
  9671. Result := FuncMov2Func(p, hp1);
  9672. Exit;
  9673. end;
  9674. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9675. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9676. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9677. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9678. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9679. begin
  9680. { Change:
  9681. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9682. addl/q $x,%reg2 subl/q $x,%reg2
  9683. To:
  9684. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9685. }
  9686. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9687. { be lazy, checking separately for sub would be slightly better }
  9688. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9689. begin
  9690. TransferUsedRegs(TmpUsedRegs);
  9691. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9692. if TryMovArith2Lea(hp1) then
  9693. begin
  9694. Result := True;
  9695. Exit;
  9696. end
  9697. end
  9698. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9699. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9700. { Same as above, but also adds or subtracts to %reg2 in between.
  9701. It's still valid as long as the flags aren't in use }
  9702. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9703. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9704. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9705. { be lazy, checking separately for sub would be slightly better }
  9706. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9707. begin
  9708. TransferUsedRegs(TmpUsedRegs);
  9709. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9710. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9711. if TryMovArith2Lea(hp2) then
  9712. begin
  9713. Result := True;
  9714. Exit;
  9715. end;
  9716. end;
  9717. end;
  9718. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9719. {$ifdef x86_64}
  9720. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9721. {$else x86_64}
  9722. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9723. {$endif x86_64}
  9724. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9725. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9726. { mov reg1, reg2 mov reg1, reg2
  9727. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9728. begin
  9729. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9730. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9731. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9732. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9733. TransferUsedRegs(TmpUsedRegs);
  9734. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9735. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9736. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9737. then
  9738. begin
  9739. RemoveCurrentP(p, hp1);
  9740. Result:=true;
  9741. end;
  9742. Exit;
  9743. end;
  9744. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9745. IsXCHGAcceptable and
  9746. { XCHG doesn't support 8-bit registers }
  9747. (taicpu(p).opsize <> S_B) and
  9748. MatchInstruction(hp1, A_MOV, []) and
  9749. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9750. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9751. GetNextInstruction(hp1, hp2) and
  9752. MatchInstruction(hp2, A_MOV, []) and
  9753. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9754. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9755. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9756. begin
  9757. { mov %reg1,%reg2
  9758. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9759. mov %reg2,%reg3
  9760. (%reg2 not used afterwards)
  9761. Note that xchg takes 3 cycles to execute, and generally mov's take
  9762. only one cycle apiece, but the first two mov's can be executed in
  9763. parallel, only taking 2 cycles overall. Older processors should
  9764. therefore only optimise for size. [Kit]
  9765. }
  9766. TransferUsedRegs(TmpUsedRegs);
  9767. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9768. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9769. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9770. begin
  9771. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9772. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9773. taicpu(hp1).opcode := A_XCHG;
  9774. RemoveCurrentP(p, hp1);
  9775. RemoveInstruction(hp2);
  9776. Result := True;
  9777. Exit;
  9778. end;
  9779. end;
  9780. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9781. MatchInstruction(hp1, A_SAR, []) then
  9782. begin
  9783. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9784. begin
  9785. { the use of %edx also covers the opsize being S_L }
  9786. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9787. begin
  9788. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9789. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9790. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9791. begin
  9792. { Change:
  9793. movl %eax,%edx
  9794. sarl $31,%edx
  9795. To:
  9796. cltd
  9797. }
  9798. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9799. RemoveInstruction(hp1);
  9800. taicpu(p).opcode := A_CDQ;
  9801. taicpu(p).opsize := S_NO;
  9802. taicpu(p).clearop(1);
  9803. taicpu(p).clearop(0);
  9804. taicpu(p).ops:=0;
  9805. Result := True;
  9806. Exit;
  9807. end
  9808. else if (cs_opt_size in current_settings.optimizerswitches) and
  9809. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9810. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9811. begin
  9812. { Change:
  9813. movl %edx,%eax
  9814. sarl $31,%edx
  9815. To:
  9816. movl %edx,%eax
  9817. cltd
  9818. Note that this creates a dependency between the two instructions,
  9819. so only perform if optimising for size.
  9820. }
  9821. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9822. taicpu(hp1).opcode := A_CDQ;
  9823. taicpu(hp1).opsize := S_NO;
  9824. taicpu(hp1).clearop(1);
  9825. taicpu(hp1).clearop(0);
  9826. taicpu(hp1).ops:=0;
  9827. Include(OptsToCheck, aoc_ForceNewIteration);
  9828. Exit;
  9829. end;
  9830. {$ifndef x86_64}
  9831. end
  9832. { Don't bother if CMOV is supported, because a more optimal
  9833. sequence would have been generated for the Abs() intrinsic }
  9834. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9835. { the use of %eax also covers the opsize being S_L }
  9836. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9837. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9838. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9839. GetNextInstruction(hp1, hp2) and
  9840. MatchInstruction(hp2, A_XOR, [S_L]) and
  9841. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9842. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9843. GetNextInstruction(hp2, hp3) and
  9844. MatchInstruction(hp3, A_SUB, [S_L]) and
  9845. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9846. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9847. begin
  9848. { Change:
  9849. movl %eax,%edx
  9850. sarl $31,%eax
  9851. xorl %eax,%edx
  9852. subl %eax,%edx
  9853. (Instruction that uses %edx)
  9854. (%eax deallocated)
  9855. (%edx deallocated)
  9856. To:
  9857. cltd
  9858. xorl %edx,%eax <-- Note the registers have swapped
  9859. subl %edx,%eax
  9860. (Instruction that uses %eax) <-- %eax rather than %edx
  9861. }
  9862. TransferUsedRegs(TmpUsedRegs);
  9863. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9864. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9865. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9866. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9867. begin
  9868. if GetNextInstruction(hp3, hp4) and
  9869. not RegModifiedByInstruction(NR_EDX, hp4) and
  9870. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9871. begin
  9872. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9873. taicpu(p).opcode := A_CDQ;
  9874. taicpu(p).clearop(1);
  9875. taicpu(p).clearop(0);
  9876. taicpu(p).ops:=0;
  9877. RemoveInstruction(hp1);
  9878. taicpu(hp2).loadreg(0, NR_EDX);
  9879. taicpu(hp2).loadreg(1, NR_EAX);
  9880. taicpu(hp3).loadreg(0, NR_EDX);
  9881. taicpu(hp3).loadreg(1, NR_EAX);
  9882. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9883. { Convert references in the following instruction (hp4) from %edx to %eax }
  9884. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9885. with taicpu(hp4).oper[OperIdx]^ do
  9886. case typ of
  9887. top_reg:
  9888. if getsupreg(reg) = RS_EDX then
  9889. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9890. top_ref:
  9891. begin
  9892. if getsupreg(reg) = RS_EDX then
  9893. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9894. if getsupreg(reg) = RS_EDX then
  9895. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9896. end;
  9897. else
  9898. ;
  9899. end;
  9900. Result := True;
  9901. Exit;
  9902. end;
  9903. end;
  9904. {$else x86_64}
  9905. end;
  9906. end
  9907. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9908. { the use of %rdx also covers the opsize being S_Q }
  9909. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9910. begin
  9911. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9912. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9913. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9914. begin
  9915. { Change:
  9916. movq %rax,%rdx
  9917. sarq $63,%rdx
  9918. To:
  9919. cqto
  9920. }
  9921. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9922. RemoveInstruction(hp1);
  9923. taicpu(p).opcode := A_CQO;
  9924. taicpu(p).opsize := S_NO;
  9925. taicpu(p).clearop(1);
  9926. taicpu(p).clearop(0);
  9927. taicpu(p).ops:=0;
  9928. Result := True;
  9929. Exit;
  9930. end
  9931. else if (cs_opt_size in current_settings.optimizerswitches) and
  9932. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9933. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9934. begin
  9935. { Change:
  9936. movq %rdx,%rax
  9937. sarq $63,%rdx
  9938. To:
  9939. movq %rdx,%rax
  9940. cqto
  9941. Note that this creates a dependency between the two instructions,
  9942. so only perform if optimising for size.
  9943. }
  9944. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9945. taicpu(hp1).opcode := A_CQO;
  9946. taicpu(hp1).opsize := S_NO;
  9947. taicpu(hp1).clearop(1);
  9948. taicpu(hp1).clearop(0);
  9949. taicpu(hp1).ops:=0;
  9950. Include(OptsToCheck, aoc_ForceNewIteration);
  9951. Exit;
  9952. {$endif x86_64}
  9953. end;
  9954. end;
  9955. end;
  9956. if MatchInstruction(hp1, A_MOV, []) and
  9957. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9958. { Though "GetNextInstruction" could be factored out, along with
  9959. the instructions that depend on hp2, it is an expensive call that
  9960. should be delayed for as long as possible, hence we do cheaper
  9961. checks first that are likely to be False. [Kit] }
  9962. begin
  9963. if (
  9964. (
  9965. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9966. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9967. (
  9968. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9969. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9970. )
  9971. ) or
  9972. (
  9973. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9974. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9975. (
  9976. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9977. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9978. )
  9979. )
  9980. ) and
  9981. GetNextInstruction(hp1, hp2) and
  9982. MatchInstruction(hp2, A_SAR, []) and
  9983. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9984. begin
  9985. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9986. begin
  9987. { Change:
  9988. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9989. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9990. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9991. To:
  9992. movl r/m,%eax <- Note the change in register
  9993. cltd
  9994. }
  9995. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9996. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9997. taicpu(p).loadreg(1, NR_EAX);
  9998. taicpu(hp1).opcode := A_CDQ;
  9999. taicpu(hp1).clearop(1);
  10000. taicpu(hp1).clearop(0);
  10001. taicpu(hp1).ops:=0;
  10002. RemoveInstruction(hp2);
  10003. Include(OptsToCheck, aoc_ForceNewIteration);
  10004. (*
  10005. {$ifdef x86_64}
  10006. end
  10007. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  10008. { This code sequence does not get generated - however it might become useful
  10009. if and when 128-bit signed integer types make an appearance, so the code
  10010. is kept here for when it is eventually needed. [Kit] }
  10011. (
  10012. (
  10013. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  10014. (
  10015. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10016. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  10017. )
  10018. ) or
  10019. (
  10020. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  10021. (
  10022. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10023. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  10024. )
  10025. )
  10026. ) and
  10027. GetNextInstruction(hp1, hp2) and
  10028. MatchInstruction(hp2, A_SAR, [S_Q]) and
  10029. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  10030. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  10031. begin
  10032. { Change:
  10033. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  10034. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  10035. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  10036. To:
  10037. movq r/m,%rax <- Note the change in register
  10038. cqto
  10039. }
  10040. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  10041. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  10042. taicpu(p).loadreg(1, NR_RAX);
  10043. taicpu(hp1).opcode := A_CQO;
  10044. taicpu(hp1).clearop(1);
  10045. taicpu(hp1).clearop(0);
  10046. taicpu(hp1).ops:=0;
  10047. RemoveInstruction(hp2);
  10048. Include(OptsToCheck, aoc_ForceNewIteration);
  10049. {$endif x86_64}
  10050. *)
  10051. end;
  10052. end;
  10053. {$ifdef x86_64}
  10054. end;
  10055. if (taicpu(p).opsize = S_L) and
  10056. (taicpu(p).oper[1]^.typ = top_reg) and
  10057. (
  10058. MatchInstruction(hp1, A_MOV,[]) and
  10059. (taicpu(hp1).opsize = S_L) and
  10060. (taicpu(hp1).oper[1]^.typ = top_reg)
  10061. ) and (
  10062. GetNextInstruction(hp1, hp2) and
  10063. (tai(hp2).typ=ait_instruction) and
  10064. (taicpu(hp2).opsize = S_Q) and
  10065. (
  10066. (
  10067. MatchInstruction(hp2, A_ADD,[]) and
  10068. (taicpu(hp2).opsize = S_Q) and
  10069. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10070. (
  10071. (
  10072. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10073. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10074. ) or (
  10075. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10076. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10077. )
  10078. )
  10079. ) or (
  10080. MatchInstruction(hp2, A_LEA,[]) and
  10081. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  10082. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  10083. (
  10084. (
  10085. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10086. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10087. ) or (
  10088. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10089. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  10090. )
  10091. ) and (
  10092. (
  10093. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10094. ) or (
  10095. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10096. )
  10097. )
  10098. )
  10099. )
  10100. ) and (
  10101. GetNextInstruction(hp2, hp3) and
  10102. MatchInstruction(hp3, A_SHR,[]) and
  10103. (taicpu(hp3).opsize = S_Q) and
  10104. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10105. (taicpu(hp3).oper[0]^.val = 1) and
  10106. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10107. ) then
  10108. begin
  10109. { Change movl x, reg1d movl x, reg1d
  10110. movl y, reg2d movl y, reg2d
  10111. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10112. shrq $1, reg1q shrq $1, reg1q
  10113. ( reg1d and reg2d can be switched around in the first two instructions )
  10114. To movl x, reg1d
  10115. addl y, reg1d
  10116. rcrl $1, reg1d
  10117. This corresponds to the common expression (x + y) shr 1, where
  10118. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10119. smaller code, but won't account for x + y causing an overflow). [Kit]
  10120. }
  10121. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10122. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10123. begin
  10124. { Change first MOV command to have the same register as the final output }
  10125. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10126. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10127. Result := True;
  10128. end
  10129. else
  10130. begin
  10131. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10132. Include(OptsToCheck, aoc_ForceNewIteration);
  10133. end;
  10134. { Change second MOV command to an ADD command. This is easier than
  10135. converting the existing command because it means we don't have to
  10136. touch 'y', which might be a complicated reference, and also the
  10137. fact that the third command might either be ADD or LEA. [Kit] }
  10138. taicpu(hp1).opcode := A_ADD;
  10139. { Delete old ADD/LEA instruction }
  10140. RemoveInstruction(hp2);
  10141. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10142. taicpu(hp3).opcode := A_RCR;
  10143. taicpu(hp3).changeopsize(S_L);
  10144. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10145. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10146. called, so FuncMov2Func below is safe to call }
  10147. {$endif x86_64}
  10148. end;
  10149. if FuncMov2Func(p, hp1) then
  10150. begin
  10151. Result := True;
  10152. Exit;
  10153. end;
  10154. end;
  10155. {$push}
  10156. {$q-}{$r-}
  10157. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10158. var
  10159. ThisReg: TRegister;
  10160. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10161. TargetSubReg: TSubRegister;
  10162. hp1, hp2: tai;
  10163. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10164. { Store list of found instructions so we don't have to call
  10165. GetNextInstructionUsingReg multiple times }
  10166. InstrList: array of taicpu;
  10167. InstrMax, Index: Integer;
  10168. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10169. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10170. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10171. WorkingValue: TCgInt;
  10172. PreMessage: string;
  10173. { Data flow analysis }
  10174. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10175. BitwiseOnly, OrXorUsed,
  10176. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10177. function CheckOverflowConditions: Boolean;
  10178. begin
  10179. Result := True;
  10180. if (TestValSignedMax > SignedUpperLimit) then
  10181. UpperSignedOverflow := True;
  10182. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10183. LowerSignedOverflow := True;
  10184. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10185. LowerUnsignedOverflow := True;
  10186. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10187. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10188. begin
  10189. { Absolute overflow }
  10190. Result := False;
  10191. Exit;
  10192. end;
  10193. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10194. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10195. ShiftDownOverflow := True;
  10196. if (TestValMin < 0) or (TestValMax < 0) then
  10197. begin
  10198. LowerUnsignedOverflow := True;
  10199. UpperUnsignedOverflow := True;
  10200. end;
  10201. end;
  10202. function AdjustInitialLoadAndSize: Boolean;
  10203. begin
  10204. Result := False;
  10205. if not p_removed then
  10206. begin
  10207. if TargetSize = MinSize then
  10208. begin
  10209. { Convert the input MOVZX to a MOV }
  10210. if (taicpu(p).oper[0]^.typ = top_reg) and
  10211. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10212. begin
  10213. { Or remove it completely! }
  10214. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10215. RemoveCurrentP(p);
  10216. p_removed := True;
  10217. end
  10218. else
  10219. begin
  10220. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10221. taicpu(p).opcode := A_MOV;
  10222. taicpu(p).oper[1]^.reg := ThisReg;
  10223. taicpu(p).opsize := TargetSize;
  10224. end;
  10225. Result := True;
  10226. end
  10227. else if TargetSize <> MaxSize then
  10228. begin
  10229. case MaxSize of
  10230. S_L:
  10231. if TargetSize = S_W then
  10232. begin
  10233. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10234. taicpu(p).opsize := S_BW;
  10235. taicpu(p).oper[1]^.reg := ThisReg;
  10236. Result := True;
  10237. end
  10238. else
  10239. InternalError(2020112341);
  10240. S_W:
  10241. if TargetSize = S_L then
  10242. begin
  10243. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10244. taicpu(p).opsize := S_BL;
  10245. taicpu(p).oper[1]^.reg := ThisReg;
  10246. Result := True;
  10247. end
  10248. else
  10249. InternalError(2020112342);
  10250. else
  10251. ;
  10252. end;
  10253. end
  10254. else if not hp1_removed and not RegInUse then
  10255. begin
  10256. { If we have something like:
  10257. movzbl (oper),%regd
  10258. add x, %regd
  10259. movzbl %regb, %regd
  10260. We can reduce the register size to the input of the final
  10261. movzbl instruction. Overflows won't have any effect.
  10262. }
  10263. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10264. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10265. begin
  10266. TargetSize := S_B;
  10267. setsubreg(ThisReg, R_SUBL);
  10268. Result := True;
  10269. end
  10270. else if (taicpu(p).opsize = S_WL) and
  10271. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10272. begin
  10273. TargetSize := S_W;
  10274. setsubreg(ThisReg, R_SUBW);
  10275. Result := True;
  10276. end;
  10277. if Result then
  10278. begin
  10279. { Convert the input MOVZX to a MOV }
  10280. if (taicpu(p).oper[0]^.typ = top_reg) and
  10281. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10282. begin
  10283. { Or remove it completely! }
  10284. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10285. RemoveCurrentP(p);
  10286. p_removed := True;
  10287. end
  10288. else
  10289. begin
  10290. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10291. taicpu(p).opcode := A_MOV;
  10292. taicpu(p).oper[1]^.reg := ThisReg;
  10293. taicpu(p).opsize := TargetSize;
  10294. end;
  10295. end;
  10296. end;
  10297. end;
  10298. end;
  10299. procedure AdjustFinalLoad;
  10300. begin
  10301. if not LowerUnsignedOverflow then
  10302. begin
  10303. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10304. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10305. begin
  10306. { Convert the output MOVZX to a MOV }
  10307. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10308. begin
  10309. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10310. if (MinSize = S_B) or
  10311. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10312. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10313. begin
  10314. { Remove it completely! }
  10315. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10316. { Be careful; if p = hp1 and p was also removed, p
  10317. will become a dangling pointer }
  10318. if p = hp1 then
  10319. begin
  10320. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10321. p_removed := True;
  10322. end
  10323. else
  10324. RemoveInstruction(hp1);
  10325. hp1_removed := True;
  10326. end;
  10327. end
  10328. else
  10329. begin
  10330. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10331. taicpu(hp1).opcode := A_MOV;
  10332. taicpu(hp1).oper[0]^.reg := ThisReg;
  10333. taicpu(hp1).opsize := TargetSize;
  10334. end;
  10335. end
  10336. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10337. begin
  10338. { Need to change the size of the output }
  10339. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10340. taicpu(hp1).oper[0]^.reg := ThisReg;
  10341. taicpu(hp1).opsize := S_BL;
  10342. end;
  10343. end;
  10344. end;
  10345. function CompressInstructions: Boolean;
  10346. var
  10347. LocalIndex: Integer;
  10348. begin
  10349. Result := False;
  10350. { The objective here is to try to find a combination that
  10351. removes one of the MOV/Z instructions. }
  10352. if (
  10353. (taicpu(p).oper[0]^.typ <> top_reg) or
  10354. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10355. ) and
  10356. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10357. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10358. begin
  10359. { Make a preference to remove the second MOVZX instruction }
  10360. case taicpu(hp1).opsize of
  10361. S_BL, S_WL:
  10362. begin
  10363. TargetSize := S_L;
  10364. TargetSubReg := R_SUBD;
  10365. end;
  10366. S_BW:
  10367. begin
  10368. TargetSize := S_W;
  10369. TargetSubReg := R_SUBW;
  10370. end;
  10371. else
  10372. InternalError(2020112302);
  10373. end;
  10374. end
  10375. else
  10376. begin
  10377. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10378. begin
  10379. { Exceeded lower bound but not upper bound }
  10380. TargetSize := MaxSize;
  10381. end
  10382. else if not LowerUnsignedOverflow then
  10383. begin
  10384. { Size didn't exceed lower bound }
  10385. TargetSize := MinSize;
  10386. end
  10387. else
  10388. Exit;
  10389. end;
  10390. case TargetSize of
  10391. S_B:
  10392. TargetSubReg := R_SUBL;
  10393. S_W:
  10394. TargetSubReg := R_SUBW;
  10395. S_L:
  10396. TargetSubReg := R_SUBD;
  10397. else
  10398. InternalError(2020112350);
  10399. end;
  10400. { Update the register to its new size }
  10401. setsubreg(ThisReg, TargetSubReg);
  10402. RegInUse := False;
  10403. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10404. begin
  10405. { Check to see if the active register is used afterwards;
  10406. if not, we can change it and make a saving. }
  10407. TransferUsedRegs(TmpUsedRegs);
  10408. { The target register may be marked as in use to cross
  10409. a jump to a distant label, so exclude it }
  10410. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10411. hp2 := p;
  10412. repeat
  10413. { Explicitly check for the excluded register (don't include the first
  10414. instruction as it may be reading from here }
  10415. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10416. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10417. begin
  10418. RegInUse := True;
  10419. Break;
  10420. end;
  10421. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10422. if not GetNextInstruction(hp2, hp2) then
  10423. InternalError(2020112340);
  10424. until (hp2 = hp1);
  10425. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10426. { We might still be able to get away with this }
  10427. RegInUse := not
  10428. (
  10429. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10430. (hp2.typ = ait_instruction) and
  10431. (
  10432. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10433. instruction that doesn't actually contain ThisReg }
  10434. (cs_opt_level3 in current_settings.optimizerswitches) or
  10435. RegInInstruction(ThisReg, hp2)
  10436. ) and
  10437. RegLoadedWithNewValue(ThisReg, hp2)
  10438. );
  10439. if not RegInUse then
  10440. begin
  10441. { Force the register size to the same as this instruction so it can be removed}
  10442. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10443. begin
  10444. TargetSize := S_L;
  10445. TargetSubReg := R_SUBD;
  10446. end
  10447. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10448. begin
  10449. TargetSize := S_W;
  10450. TargetSubReg := R_SUBW;
  10451. end;
  10452. ThisReg := taicpu(hp1).oper[1]^.reg;
  10453. setsubreg(ThisReg, TargetSubReg);
  10454. RegChanged := True;
  10455. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10456. TransferUsedRegs(TmpUsedRegs);
  10457. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10458. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10459. if p = hp1 then
  10460. begin
  10461. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10462. p_removed := True;
  10463. end
  10464. else
  10465. RemoveInstruction(hp1);
  10466. hp1_removed := True;
  10467. { Instruction will become "mov %reg,%reg" }
  10468. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10469. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10470. begin
  10471. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10472. RemoveCurrentP(p);
  10473. p_removed := True;
  10474. end
  10475. else
  10476. taicpu(p).oper[1]^.reg := ThisReg;
  10477. Result := True;
  10478. end
  10479. else
  10480. begin
  10481. if TargetSize <> MaxSize then
  10482. begin
  10483. { Since the register is in use, we have to force it to
  10484. MaxSize otherwise part of it may become undefined later on }
  10485. TargetSize := MaxSize;
  10486. case TargetSize of
  10487. S_B:
  10488. TargetSubReg := R_SUBL;
  10489. S_W:
  10490. TargetSubReg := R_SUBW;
  10491. S_L:
  10492. TargetSubReg := R_SUBD;
  10493. else
  10494. InternalError(2020112351);
  10495. end;
  10496. setsubreg(ThisReg, TargetSubReg);
  10497. end;
  10498. AdjustFinalLoad;
  10499. end;
  10500. end
  10501. else
  10502. AdjustFinalLoad;
  10503. Result := AdjustInitialLoadAndSize or Result;
  10504. { Now go through every instruction we found and change the
  10505. size. If TargetSize = MaxSize, then almost no changes are
  10506. needed and Result can remain False if it hasn't been set
  10507. yet.
  10508. If RegChanged is True, then the register requires changing
  10509. and so the point about TargetSize = MaxSize doesn't apply. }
  10510. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10511. begin
  10512. for LocalIndex := 0 to InstrMax do
  10513. begin
  10514. { If p_removed is true, then the original MOV/Z was removed
  10515. and removing the AND instruction may not be safe if it
  10516. appears first }
  10517. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10518. InternalError(2020112310);
  10519. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10520. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10521. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10522. InstrList[LocalIndex].opsize := TargetSize;
  10523. end;
  10524. Result := True;
  10525. end;
  10526. end;
  10527. begin
  10528. Result := False;
  10529. p_removed := False;
  10530. hp1_removed := False;
  10531. ThisReg := taicpu(p).oper[1]^.reg;
  10532. { Check for:
  10533. movs/z ###,%ecx (or %cx or %rcx)
  10534. ...
  10535. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10536. (dealloc %ecx)
  10537. Change to:
  10538. mov ###,%cl (if ### = %cl, then remove completely)
  10539. ...
  10540. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10541. }
  10542. if (getsupreg(ThisReg) = RS_ECX) and
  10543. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10544. (hp1.typ = ait_instruction) and
  10545. (
  10546. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10547. instruction that doesn't actually contain ECX }
  10548. (cs_opt_level3 in current_settings.optimizerswitches) or
  10549. RegInInstruction(NR_ECX, hp1) or
  10550. (
  10551. { It's common for the shift/rotate's read/write register to be
  10552. initialised in between, so under -O2 and under, search ahead
  10553. one more instruction
  10554. }
  10555. GetNextInstruction(hp1, hp1) and
  10556. (hp1.typ = ait_instruction) and
  10557. RegInInstruction(NR_ECX, hp1)
  10558. )
  10559. ) and
  10560. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10561. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10562. begin
  10563. TransferUsedRegs(TmpUsedRegs);
  10564. hp2 := p;
  10565. repeat
  10566. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10567. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10568. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10569. begin
  10570. case taicpu(p).opsize of
  10571. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10572. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10573. begin
  10574. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10575. RemoveCurrentP(p);
  10576. end
  10577. else
  10578. begin
  10579. taicpu(p).opcode := A_MOV;
  10580. taicpu(p).opsize := S_B;
  10581. taicpu(p).oper[1]^.reg := NR_CL;
  10582. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10583. end;
  10584. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10585. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10586. begin
  10587. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10588. RemoveCurrentP(p);
  10589. end
  10590. else
  10591. begin
  10592. taicpu(p).opcode := A_MOV;
  10593. taicpu(p).opsize := S_W;
  10594. taicpu(p).oper[1]^.reg := NR_CX;
  10595. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10596. end;
  10597. {$ifdef x86_64}
  10598. S_LQ:
  10599. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10600. begin
  10601. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10602. RemoveCurrentP(p);
  10603. end
  10604. else
  10605. begin
  10606. taicpu(p).opcode := A_MOV;
  10607. taicpu(p).opsize := S_L;
  10608. taicpu(p).oper[1]^.reg := NR_ECX;
  10609. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10610. end;
  10611. {$endif x86_64}
  10612. else
  10613. InternalError(2021120401);
  10614. end;
  10615. Result := True;
  10616. Exit;
  10617. end;
  10618. end;
  10619. { This is anything but quick! }
  10620. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10621. Exit;
  10622. SetLength(InstrList, 0);
  10623. InstrMax := -1;
  10624. case taicpu(p).opsize of
  10625. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10626. begin
  10627. {$if defined(i386) or defined(i8086)}
  10628. { If the target size is 8-bit, make sure we can actually encode it }
  10629. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10630. Exit;
  10631. {$endif i386 or i8086}
  10632. LowerLimit := $FF;
  10633. SignedLowerLimit := $7F;
  10634. SignedLowerLimitBottom := -128;
  10635. MinSize := S_B;
  10636. if taicpu(p).opsize = S_BW then
  10637. begin
  10638. MaxSize := S_W;
  10639. UpperLimit := $FFFF;
  10640. SignedUpperLimit := $7FFF;
  10641. SignedUpperLimitBottom := -32768;
  10642. end
  10643. else
  10644. begin
  10645. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10646. MaxSize := S_L;
  10647. UpperLimit := $FFFFFFFF;
  10648. SignedUpperLimit := $7FFFFFFF;
  10649. SignedUpperLimitBottom := -2147483648;
  10650. end;
  10651. end;
  10652. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10653. begin
  10654. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10655. LowerLimit := $FFFF;
  10656. SignedLowerLimit := $7FFF;
  10657. SignedLowerLimitBottom := -32768;
  10658. UpperLimit := $FFFFFFFF;
  10659. SignedUpperLimit := $7FFFFFFF;
  10660. SignedUpperLimitBottom := -2147483648;
  10661. MinSize := S_W;
  10662. MaxSize := S_L;
  10663. end;
  10664. {$ifdef x86_64}
  10665. S_LQ:
  10666. begin
  10667. { Both the lower and upper limits are set to 32-bit. If a limit
  10668. is breached, then optimisation is impossible }
  10669. LowerLimit := $FFFFFFFF;
  10670. SignedLowerLimit := $7FFFFFFF;
  10671. SignedLowerLimitBottom := -2147483648;
  10672. UpperLimit := $FFFFFFFF;
  10673. SignedUpperLimit := $7FFFFFFF;
  10674. SignedUpperLimitBottom := -2147483648;
  10675. MinSize := S_L;
  10676. MaxSize := S_L;
  10677. end;
  10678. {$endif x86_64}
  10679. else
  10680. InternalError(2020112301);
  10681. end;
  10682. TestValMin := 0;
  10683. TestValMax := LowerLimit;
  10684. TestValSignedMax := SignedLowerLimit;
  10685. TryShiftDownLimit := LowerLimit;
  10686. TryShiftDown := S_NO;
  10687. ShiftDownOverflow := False;
  10688. RegChanged := False;
  10689. BitwiseOnly := True;
  10690. OrXorUsed := False;
  10691. UpperSignedOverflow := False;
  10692. LowerSignedOverflow := False;
  10693. UpperUnsignedOverflow := False;
  10694. LowerUnsignedOverflow := False;
  10695. hp1 := p;
  10696. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10697. (hp1.typ = ait_instruction) and
  10698. (
  10699. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10700. instruction that doesn't actually contain ThisReg }
  10701. (cs_opt_level3 in current_settings.optimizerswitches) or
  10702. { This allows this Movx optimisation to work through the SETcc instructions
  10703. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10704. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10705. skip over these SETcc instructions). }
  10706. (taicpu(hp1).opcode = A_SETcc) or
  10707. RegInInstruction(ThisReg, hp1)
  10708. ) do
  10709. begin
  10710. case taicpu(hp1).opcode of
  10711. A_INC,A_DEC:
  10712. begin
  10713. { Has to be an exact match on the register }
  10714. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10715. Break;
  10716. if taicpu(hp1).opcode = A_INC then
  10717. begin
  10718. Inc(TestValMin);
  10719. Inc(TestValMax);
  10720. Inc(TestValSignedMax);
  10721. end
  10722. else
  10723. begin
  10724. Dec(TestValMin);
  10725. Dec(TestValMax);
  10726. Dec(TestValSignedMax);
  10727. end;
  10728. end;
  10729. A_TEST, A_CMP:
  10730. begin
  10731. if (
  10732. { Too high a risk of non-linear behaviour that breaks DFA
  10733. here, unless it's cmp $0,%reg, which is equivalent to
  10734. test %reg,%reg }
  10735. OrXorUsed and
  10736. (taicpu(hp1).opcode = A_CMP) and
  10737. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10738. ) or
  10739. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10740. { Has to be an exact match on the register }
  10741. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10742. (
  10743. { Permit "test %reg,%reg" }
  10744. (taicpu(hp1).opcode = A_TEST) and
  10745. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10746. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10747. ) or
  10748. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10749. { Make sure the comparison value is not smaller than the
  10750. smallest allowed signed value for the minimum size (e.g.
  10751. -128 for 8-bit) }
  10752. not (
  10753. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10754. { Is it in the negative range? }
  10755. (
  10756. (taicpu(hp1).oper[0]^.val < 0) and
  10757. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10758. )
  10759. ) then
  10760. Break;
  10761. { Check to see if the active register is used afterwards }
  10762. TransferUsedRegs(TmpUsedRegs);
  10763. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10764. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10765. begin
  10766. { Make sure the comparison or any previous instructions
  10767. hasn't pushed the test values outside of the range of
  10768. MinSize }
  10769. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10770. begin
  10771. { Exceeded lower bound but not upper bound }
  10772. Exit;
  10773. end
  10774. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10775. begin
  10776. { Size didn't exceed lower bound }
  10777. TargetSize := MinSize;
  10778. end
  10779. else
  10780. Break;
  10781. case TargetSize of
  10782. S_B:
  10783. TargetSubReg := R_SUBL;
  10784. S_W:
  10785. TargetSubReg := R_SUBW;
  10786. S_L:
  10787. TargetSubReg := R_SUBD;
  10788. else
  10789. InternalError(2021051002);
  10790. end;
  10791. if TargetSize <> MaxSize then
  10792. begin
  10793. { Update the register to its new size }
  10794. setsubreg(ThisReg, TargetSubReg);
  10795. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10796. taicpu(hp1).oper[1]^.reg := ThisReg;
  10797. taicpu(hp1).opsize := TargetSize;
  10798. { Convert the input MOVZX to a MOV if necessary }
  10799. AdjustInitialLoadAndSize;
  10800. if (InstrMax >= 0) then
  10801. begin
  10802. for Index := 0 to InstrMax do
  10803. begin
  10804. { If p_removed is true, then the original MOV/Z was removed
  10805. and removing the AND instruction may not be safe if it
  10806. appears first }
  10807. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10808. InternalError(2020112311);
  10809. if InstrList[Index].oper[0]^.typ = top_reg then
  10810. InstrList[Index].oper[0]^.reg := ThisReg;
  10811. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10812. InstrList[Index].opsize := MinSize;
  10813. end;
  10814. end;
  10815. Result := True;
  10816. end;
  10817. Exit;
  10818. end;
  10819. end;
  10820. A_SETcc:
  10821. begin
  10822. { This allows this Movx optimisation to work through the SETcc instructions
  10823. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10824. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10825. skip over these SETcc instructions). }
  10826. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10827. { Of course, break out if the current register is used }
  10828. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10829. Break
  10830. else
  10831. { We must use Continue so the instruction doesn't get added
  10832. to InstrList }
  10833. Continue;
  10834. end;
  10835. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10836. begin
  10837. if
  10838. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10839. { Has to be an exact match on the register }
  10840. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10841. (
  10842. (
  10843. (taicpu(hp1).oper[0]^.typ = top_const) and
  10844. (
  10845. (
  10846. (taicpu(hp1).opcode = A_SHL) and
  10847. (
  10848. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10849. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10850. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10851. )
  10852. ) or (
  10853. (taicpu(hp1).opcode <> A_SHL) and
  10854. (
  10855. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10856. { Is it in the negative range? }
  10857. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10858. )
  10859. )
  10860. )
  10861. ) or (
  10862. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10863. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10864. )
  10865. ) then
  10866. Break;
  10867. { Only process OR and XOR if there are only bitwise operations,
  10868. since otherwise they can too easily fool the data flow
  10869. analysis (they can cause non-linear behaviour) }
  10870. case taicpu(hp1).opcode of
  10871. A_ADD:
  10872. begin
  10873. if OrXorUsed then
  10874. { Too high a risk of non-linear behaviour that breaks DFA here }
  10875. Break
  10876. else
  10877. BitwiseOnly := False;
  10878. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10879. begin
  10880. TestValMin := TestValMin * 2;
  10881. TestValMax := TestValMax * 2;
  10882. TestValSignedMax := TestValSignedMax * 2;
  10883. end
  10884. else
  10885. begin
  10886. WorkingValue := taicpu(hp1).oper[0]^.val;
  10887. TestValMin := TestValMin + WorkingValue;
  10888. TestValMax := TestValMax + WorkingValue;
  10889. TestValSignedMax := TestValSignedMax + WorkingValue;
  10890. end;
  10891. end;
  10892. A_SUB:
  10893. begin
  10894. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10895. begin
  10896. TestValMin := 0;
  10897. TestValMax := 0;
  10898. TestValSignedMax := 0;
  10899. end
  10900. else
  10901. begin
  10902. if OrXorUsed then
  10903. { Too high a risk of non-linear behaviour that breaks DFA here }
  10904. Break
  10905. else
  10906. BitwiseOnly := False;
  10907. WorkingValue := taicpu(hp1).oper[0]^.val;
  10908. TestValMin := TestValMin - WorkingValue;
  10909. TestValMax := TestValMax - WorkingValue;
  10910. TestValSignedMax := TestValSignedMax - WorkingValue;
  10911. end;
  10912. end;
  10913. A_AND:
  10914. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10915. begin
  10916. { we might be able to go smaller if AND appears first }
  10917. if InstrMax = -1 then
  10918. case MinSize of
  10919. S_B:
  10920. ;
  10921. S_W:
  10922. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10923. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10924. begin
  10925. TryShiftDown := S_B;
  10926. TryShiftDownLimit := $FF;
  10927. end;
  10928. S_L:
  10929. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10930. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10931. begin
  10932. TryShiftDown := S_B;
  10933. TryShiftDownLimit := $FF;
  10934. end
  10935. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10936. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10937. begin
  10938. TryShiftDown := S_W;
  10939. TryShiftDownLimit := $FFFF;
  10940. end;
  10941. else
  10942. InternalError(2020112320);
  10943. end;
  10944. WorkingValue := taicpu(hp1).oper[0]^.val;
  10945. TestValMin := TestValMin and WorkingValue;
  10946. TestValMax := TestValMax and WorkingValue;
  10947. TestValSignedMax := TestValSignedMax and WorkingValue;
  10948. end;
  10949. A_OR:
  10950. begin
  10951. if not BitwiseOnly then
  10952. Break;
  10953. OrXorUsed := True;
  10954. WorkingValue := taicpu(hp1).oper[0]^.val;
  10955. TestValMin := TestValMin or WorkingValue;
  10956. TestValMax := TestValMax or WorkingValue;
  10957. TestValSignedMax := TestValSignedMax or WorkingValue;
  10958. end;
  10959. A_XOR:
  10960. begin
  10961. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10962. begin
  10963. TestValMin := 0;
  10964. TestValMax := 0;
  10965. TestValSignedMax := 0;
  10966. end
  10967. else
  10968. begin
  10969. if not BitwiseOnly then
  10970. Break;
  10971. OrXorUsed := True;
  10972. WorkingValue := taicpu(hp1).oper[0]^.val;
  10973. TestValMin := TestValMin xor WorkingValue;
  10974. TestValMax := TestValMax xor WorkingValue;
  10975. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10976. end;
  10977. end;
  10978. A_SHL:
  10979. begin
  10980. BitwiseOnly := False;
  10981. WorkingValue := taicpu(hp1).oper[0]^.val;
  10982. TestValMin := TestValMin shl WorkingValue;
  10983. TestValMax := TestValMax shl WorkingValue;
  10984. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10985. end;
  10986. A_SHR,
  10987. { The first instruction was MOVZX, so the value won't be negative }
  10988. A_SAR:
  10989. begin
  10990. if InstrMax <> -1 then
  10991. BitwiseOnly := False
  10992. else
  10993. { we might be able to go smaller if SHR appears first }
  10994. case MinSize of
  10995. S_B:
  10996. ;
  10997. S_W:
  10998. if (taicpu(hp1).oper[0]^.val >= 8) then
  10999. begin
  11000. TryShiftDown := S_B;
  11001. TryShiftDownLimit := $FF;
  11002. TryShiftDownSignedLimit := $7F;
  11003. TryShiftDownSignedLimitLower := -128;
  11004. end;
  11005. S_L:
  11006. if (taicpu(hp1).oper[0]^.val >= 24) then
  11007. begin
  11008. TryShiftDown := S_B;
  11009. TryShiftDownLimit := $FF;
  11010. TryShiftDownSignedLimit := $7F;
  11011. TryShiftDownSignedLimitLower := -128;
  11012. end
  11013. else if (taicpu(hp1).oper[0]^.val >= 16) then
  11014. begin
  11015. TryShiftDown := S_W;
  11016. TryShiftDownLimit := $FFFF;
  11017. TryShiftDownSignedLimit := $7FFF;
  11018. TryShiftDownSignedLimitLower := -32768;
  11019. end;
  11020. else
  11021. InternalError(2020112321);
  11022. end;
  11023. WorkingValue := taicpu(hp1).oper[0]^.val;
  11024. if taicpu(hp1).opcode = A_SAR then
  11025. begin
  11026. TestValMin := SarInt64(TestValMin, WorkingValue);
  11027. TestValMax := SarInt64(TestValMax, WorkingValue);
  11028. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  11029. end
  11030. else
  11031. begin
  11032. TestValMin := TestValMin shr WorkingValue;
  11033. TestValMax := TestValMax shr WorkingValue;
  11034. TestValSignedMax := TestValSignedMax shr WorkingValue;
  11035. end;
  11036. end;
  11037. else
  11038. InternalError(2020112303);
  11039. end;
  11040. end;
  11041. (*
  11042. A_IMUL:
  11043. case taicpu(hp1).ops of
  11044. 2:
  11045. begin
  11046. if not MatchOpType(hp1, top_reg, top_reg) or
  11047. { Has to be an exact match on the register }
  11048. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  11049. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  11050. Break;
  11051. TestValMin := TestValMin * TestValMin;
  11052. TestValMax := TestValMax * TestValMax;
  11053. TestValSignedMax := TestValSignedMax * TestValMax;
  11054. end;
  11055. 3:
  11056. begin
  11057. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11058. { Has to be an exact match on the register }
  11059. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11060. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11061. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11062. { Is it in the negative range? }
  11063. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11064. Break;
  11065. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  11066. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  11067. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  11068. end;
  11069. else
  11070. Break;
  11071. end;
  11072. A_IDIV:
  11073. case taicpu(hp1).ops of
  11074. 3:
  11075. begin
  11076. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11077. { Has to be an exact match on the register }
  11078. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11079. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11080. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11081. { Is it in the negative range? }
  11082. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11083. Break;
  11084. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  11085. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  11086. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  11087. end;
  11088. else
  11089. Break;
  11090. end;
  11091. *)
  11092. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11093. begin
  11094. { If there are no instructions in between, then we might be able to make a saving }
  11095. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11096. Break;
  11097. { We have something like:
  11098. movzbw %dl,%dx
  11099. ...
  11100. movswl %dx,%edx
  11101. Change the latter to a zero-extension then enter the
  11102. A_MOVZX case branch.
  11103. }
  11104. {$ifdef x86_64}
  11105. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11106. begin
  11107. { this becomes a zero extension from 32-bit to 64-bit, but
  11108. the upper 32 bits are already zero, so just delete the
  11109. instruction }
  11110. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11111. RemoveInstruction(hp1);
  11112. Result := True;
  11113. Exit;
  11114. end
  11115. else
  11116. {$endif x86_64}
  11117. begin
  11118. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11119. taicpu(hp1).opcode := A_MOVZX;
  11120. {$ifdef x86_64}
  11121. case taicpu(hp1).opsize of
  11122. S_BQ:
  11123. begin
  11124. taicpu(hp1).opsize := S_BL;
  11125. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11126. end;
  11127. S_WQ:
  11128. begin
  11129. taicpu(hp1).opsize := S_WL;
  11130. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11131. end;
  11132. S_LQ:
  11133. begin
  11134. taicpu(hp1).opcode := A_MOV;
  11135. taicpu(hp1).opsize := S_L;
  11136. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11137. { In this instance, we need to break out because the
  11138. instruction is no longer MOVZX or MOVSXD }
  11139. Result := True;
  11140. Exit;
  11141. end;
  11142. else
  11143. ;
  11144. end;
  11145. {$endif x86_64}
  11146. Result := CompressInstructions;
  11147. Exit;
  11148. end;
  11149. end;
  11150. A_MOVZX:
  11151. begin
  11152. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11153. Break;
  11154. if (InstrMax = -1) then
  11155. begin
  11156. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11157. begin
  11158. { Optimise around i40003 }
  11159. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  11160. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11161. {$ifndef x86_64}
  11162. and (
  11163. (taicpu(p).oper[0]^.typ <> top_reg) or
  11164. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11165. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11166. )
  11167. {$endif not x86_64}
  11168. then
  11169. begin
  11170. if (taicpu(p).oper[0]^.typ = top_reg) then
  11171. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11172. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11173. taicpu(p).opsize := S_BL;
  11174. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11175. RemoveInstruction(hp1);
  11176. Result := True;
  11177. Exit;
  11178. end;
  11179. end
  11180. else
  11181. begin
  11182. { Will return false if the second parameter isn't ThisReg
  11183. (can happen on -O2 and under) }
  11184. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11185. begin
  11186. { The two MOVZX instructions are adjacent, so remove the first one }
  11187. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11188. RemoveCurrentP(p);
  11189. Result := True;
  11190. Exit;
  11191. end;
  11192. Break;
  11193. end;
  11194. end;
  11195. Result := CompressInstructions;
  11196. Exit;
  11197. end;
  11198. else
  11199. { This includes ADC, SBB and IDIV }
  11200. Break;
  11201. end;
  11202. if not CheckOverflowConditions then
  11203. Break;
  11204. { Contains highest index (so instruction count - 1) }
  11205. Inc(InstrMax);
  11206. if InstrMax > High(InstrList) then
  11207. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11208. InstrList[InstrMax] := taicpu(hp1);
  11209. end;
  11210. end;
  11211. {$pop}
  11212. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11213. var
  11214. hp1 : tai;
  11215. begin
  11216. Result:=false;
  11217. if (taicpu(p).ops >= 2) and
  11218. ((taicpu(p).oper[0]^.typ = top_const) or
  11219. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11220. (taicpu(p).oper[1]^.typ = top_reg) and
  11221. ((taicpu(p).ops = 2) or
  11222. ((taicpu(p).oper[2]^.typ = top_reg) and
  11223. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11224. GetLastInstruction(p,hp1) and
  11225. MatchInstruction(hp1,A_MOV,[]) and
  11226. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11227. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11228. begin
  11229. TransferUsedRegs(TmpUsedRegs);
  11230. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11231. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11232. { change
  11233. mov reg1,reg2
  11234. imul y,reg2 to imul y,reg1,reg2 }
  11235. begin
  11236. taicpu(p).ops := 3;
  11237. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11238. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11239. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11240. RemoveInstruction(hp1);
  11241. result:=true;
  11242. end;
  11243. end;
  11244. end;
  11245. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11246. var
  11247. ThisLabel: TAsmLabel;
  11248. begin
  11249. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11250. ThisLabel.decrefs;
  11251. taicpu(p).condition := C_None;
  11252. taicpu(p).opcode := A_RET;
  11253. taicpu(p).is_jmp := false;
  11254. taicpu(p).ops := taicpu(ret_p).ops;
  11255. case taicpu(ret_p).ops of
  11256. 0:
  11257. taicpu(p).clearop(0);
  11258. 1:
  11259. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11260. else
  11261. internalerror(2016041301);
  11262. end;
  11263. { If the original label is now dead, it might turn out that the label
  11264. immediately follows p. As a result, everything beyond it, which will
  11265. be just some final register configuration and a RET instruction, is
  11266. now dead code. [Kit] }
  11267. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11268. running RemoveDeadCodeAfterJump for each RET instruction, because
  11269. this optimisation rarely happens and most RETs appear at the end of
  11270. routines where there is nothing that can be stripped. [Kit] }
  11271. if not ThisLabel.is_used then
  11272. RemoveDeadCodeAfterJump(p);
  11273. end;
  11274. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11275. var
  11276. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11277. Unconditional, PotentialModified: Boolean;
  11278. OperPtr: POper;
  11279. NewRef: TReference;
  11280. InstrList: array of taicpu;
  11281. InstrMax, Index: Integer;
  11282. const
  11283. {$ifdef DEBUG_AOPTCPU}
  11284. SNoFlags: shortstring = ' so the flags aren''t modified';
  11285. {$else DEBUG_AOPTCPU}
  11286. SNoFlags = '';
  11287. {$endif DEBUG_AOPTCPU}
  11288. begin
  11289. Result:=false;
  11290. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11291. begin
  11292. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11293. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11294. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11295. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11296. GetNextInstruction(hp1, hp2) and
  11297. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11298. { Change from: To:
  11299. set(C) %reg j(~C) label
  11300. test %reg,%reg/cmp $0,%reg
  11301. je label
  11302. set(C) %reg j(C) label
  11303. test %reg,%reg/cmp $0,%reg
  11304. jne label
  11305. (Also do something similar with sete/setne instead of je/jne)
  11306. }
  11307. begin
  11308. { Before we do anything else, we need to check the instructions
  11309. in between SETcc and TEST to make sure they don't modify the
  11310. FLAGS register - if -O2 or under, there won't be any
  11311. instructions between SET and TEST }
  11312. TransferUsedRegs(TmpUsedRegs);
  11313. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11314. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11315. begin
  11316. next := p;
  11317. SetLength(InstrList, 0);
  11318. InstrMax := -1;
  11319. PotentialModified := False;
  11320. { Make a note of every instruction that modifies the FLAGS
  11321. register }
  11322. while GetNextInstruction(next, next) and (next <> hp1) do
  11323. begin
  11324. if next.typ <> ait_instruction then
  11325. { GetNextInstructionUsingReg should have returned False }
  11326. InternalError(2021051701);
  11327. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11328. begin
  11329. case taicpu(next).opcode of
  11330. A_SETcc,
  11331. A_CMOVcc,
  11332. A_Jcc:
  11333. begin
  11334. if PotentialModified then
  11335. { Not safe because the flags were modified earlier }
  11336. Exit
  11337. else
  11338. { Condition is the same as the initial SETcc, so this is safe
  11339. (don't add to instruction list though) }
  11340. Continue;
  11341. end;
  11342. A_ADD:
  11343. begin
  11344. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11345. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11346. (taicpu(next).oper[1]^.typ <> top_reg) or
  11347. { Must write to a register }
  11348. (taicpu(next).oper[0]^.typ = top_ref) then
  11349. { Require a constant or a register }
  11350. Exit;
  11351. PotentialModified := True;
  11352. end;
  11353. A_SUB:
  11354. begin
  11355. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11356. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11357. (taicpu(next).oper[1]^.typ <> top_reg) or
  11358. { Must write to a register }
  11359. (taicpu(next).oper[0]^.typ <> top_const) or
  11360. (taicpu(next).oper[0]^.val = $80000000) then
  11361. { Can't subtract a register with LEA - also
  11362. check that the value isn't -2^31, as this
  11363. can't be negated }
  11364. Exit;
  11365. PotentialModified := True;
  11366. end;
  11367. A_SAL,
  11368. A_SHL:
  11369. begin
  11370. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11371. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11372. (taicpu(next).oper[1]^.typ <> top_reg) or
  11373. { Must write to a register }
  11374. (taicpu(next).oper[0]^.typ <> top_const) or
  11375. (taicpu(next).oper[0]^.val < 0) or
  11376. (taicpu(next).oper[0]^.val > 3) then
  11377. Exit;
  11378. PotentialModified := True;
  11379. end;
  11380. A_IMUL:
  11381. begin
  11382. if (taicpu(next).ops <> 3) or
  11383. (taicpu(next).oper[1]^.typ <> top_reg) or
  11384. { Must write to a register }
  11385. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11386. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11387. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11388. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11389. Exit
  11390. else
  11391. PotentialModified := True;
  11392. end;
  11393. else
  11394. { Don't know how to change this, so abort }
  11395. Exit;
  11396. end;
  11397. { Contains highest index (so instruction count - 1) }
  11398. Inc(InstrMax);
  11399. if InstrMax > High(InstrList) then
  11400. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11401. InstrList[InstrMax] := taicpu(next);
  11402. end;
  11403. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11404. end;
  11405. if not Assigned(next) or (next <> hp1) then
  11406. { It should be equal to hp1 }
  11407. InternalError(2021051702);
  11408. { Cycle through each instruction and check to see if we can
  11409. change them to versions that don't modify the flags }
  11410. if (InstrMax >= 0) then
  11411. begin
  11412. for Index := 0 to InstrMax do
  11413. case InstrList[Index].opcode of
  11414. A_ADD:
  11415. begin
  11416. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11417. InstrList[Index].opcode := A_LEA;
  11418. reference_reset(NewRef, 1, []);
  11419. NewRef.base := InstrList[Index].oper[1]^.reg;
  11420. if InstrList[Index].oper[0]^.typ = top_reg then
  11421. begin
  11422. NewRef.index := InstrList[Index].oper[0]^.reg;
  11423. NewRef.scalefactor := 1;
  11424. end
  11425. else
  11426. NewRef.offset := InstrList[Index].oper[0]^.val;
  11427. InstrList[Index].loadref(0, NewRef);
  11428. end;
  11429. A_SUB:
  11430. begin
  11431. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11432. InstrList[Index].opcode := A_LEA;
  11433. reference_reset(NewRef, 1, []);
  11434. NewRef.base := InstrList[Index].oper[1]^.reg;
  11435. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11436. InstrList[Index].loadref(0, NewRef);
  11437. end;
  11438. A_SHL,
  11439. A_SAL:
  11440. begin
  11441. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11442. InstrList[Index].opcode := A_LEA;
  11443. reference_reset(NewRef, 1, []);
  11444. NewRef.index := InstrList[Index].oper[1]^.reg;
  11445. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11446. InstrList[Index].loadref(0, NewRef);
  11447. end;
  11448. A_IMUL:
  11449. begin
  11450. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11451. InstrList[Index].opcode := A_LEA;
  11452. reference_reset(NewRef, 1, []);
  11453. NewRef.index := InstrList[Index].oper[1]^.reg;
  11454. case InstrList[Index].oper[0]^.val of
  11455. 2, 4, 8:
  11456. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11457. else {3, 5 and 9}
  11458. begin
  11459. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11460. NewRef.base := InstrList[Index].oper[1]^.reg;
  11461. end;
  11462. end;
  11463. InstrList[Index].loadref(0, NewRef);
  11464. end;
  11465. else
  11466. InternalError(2021051710);
  11467. end;
  11468. end;
  11469. { Mark the FLAGS register as used across this whole block }
  11470. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11471. end;
  11472. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11473. JumpC := taicpu(hp2).condition;
  11474. Unconditional := False;
  11475. if conditions_equal(JumpC, C_E) then
  11476. SetC := inverse_cond(taicpu(p).condition)
  11477. else if conditions_equal(JumpC, C_NE) then
  11478. SetC := taicpu(p).condition
  11479. else
  11480. { We've got something weird here (and inefficent) }
  11481. begin
  11482. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11483. SetC := C_NONE;
  11484. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11485. if condition_in(C_AE, JumpC) then
  11486. Unconditional := True
  11487. else
  11488. { Not sure what to do with this jump - drop out }
  11489. Exit;
  11490. end;
  11491. RemoveInstruction(hp1);
  11492. if Unconditional then
  11493. MakeUnconditional(taicpu(hp2))
  11494. else
  11495. begin
  11496. if SetC = C_NONE then
  11497. InternalError(2018061402);
  11498. taicpu(hp2).SetCondition(SetC);
  11499. end;
  11500. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11501. TmpUsedRegs }
  11502. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11503. begin
  11504. RemoveCurrentp(p, hp2);
  11505. if taicpu(hp2).opcode = A_SETcc then
  11506. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11507. else
  11508. begin
  11509. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11510. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11511. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11512. end;
  11513. end
  11514. else
  11515. if taicpu(hp2).opcode = A_SETcc then
  11516. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11517. else
  11518. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11519. Result := True;
  11520. end
  11521. else if
  11522. { Make sure the instructions are adjacent }
  11523. (
  11524. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11525. GetNextInstruction(p, hp1)
  11526. ) and
  11527. MatchInstruction(hp1, A_MOV, [S_B]) and
  11528. { Writing to memory is allowed }
  11529. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11530. begin
  11531. {
  11532. Watch out for sequences such as:
  11533. set(c)b %regb
  11534. movb %regb,(ref)
  11535. movb $0,1(ref)
  11536. movb $0,2(ref)
  11537. movb $0,3(ref)
  11538. Much more efficient to turn it into:
  11539. movl $0,%regl
  11540. set(c)b %regb
  11541. movl %regl,(ref)
  11542. Or:
  11543. set(c)b %regb
  11544. movzbl %regb,%regl
  11545. movl %regl,(ref)
  11546. }
  11547. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11548. GetNextInstruction(hp1, hp2) and
  11549. MatchInstruction(hp2, A_MOV, [S_B]) and
  11550. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11551. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11552. begin
  11553. { Don't do anything else except set Result to True }
  11554. end
  11555. else
  11556. begin
  11557. if taicpu(p).oper[0]^.typ = top_reg then
  11558. begin
  11559. TransferUsedRegs(TmpUsedRegs);
  11560. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11561. end;
  11562. { If it's not a register, it's a memory address }
  11563. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11564. begin
  11565. { Even if the register is still in use, we can minimise the
  11566. pipeline stall by changing the MOV into another SETcc. }
  11567. taicpu(hp1).opcode := A_SETcc;
  11568. taicpu(hp1).condition := taicpu(p).condition;
  11569. if taicpu(hp1).oper[1]^.typ = top_ref then
  11570. begin
  11571. { Swapping the operand pointers like this is probably a
  11572. bit naughty, but it is far faster than using loadoper
  11573. to transfer the reference from oper[1] to oper[0] if
  11574. you take into account the extra procedure calls and
  11575. the memory allocation and deallocation required }
  11576. OperPtr := taicpu(hp1).oper[1];
  11577. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11578. taicpu(hp1).oper[0] := OperPtr;
  11579. end
  11580. else
  11581. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11582. taicpu(hp1).clearop(1);
  11583. taicpu(hp1).ops := 1;
  11584. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11585. end
  11586. else
  11587. begin
  11588. if taicpu(hp1).oper[1]^.typ = top_reg then
  11589. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11590. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11591. RemoveInstruction(hp1);
  11592. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11593. end
  11594. end;
  11595. Result := True;
  11596. end;
  11597. end;
  11598. end;
  11599. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11600. var
  11601. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11602. TargetReg: TRegister;
  11603. condition, inverted_condition: TAsmCond;
  11604. FoundMOV: Boolean;
  11605. begin
  11606. Result := False;
  11607. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11608. create the most optimial instructions possible due to limited
  11609. register availability, and there are situations where two
  11610. complementary "simple" CMOV blocks are created which, after the fact
  11611. can be merged into a "double" block. For example:
  11612. movw $257,%ax
  11613. movw $2,%r8w
  11614. xorl r9d,%r9d
  11615. testw $16,18(%rcx)
  11616. cmovew %ax,%dx
  11617. cmovew %r8w,%bx
  11618. cmovel %r9d,%r14d
  11619. movw $1283,%ax
  11620. movw $4,%r8w
  11621. movl $9,%r9d
  11622. cmovnew %ax,%dx
  11623. cmovnew %r8w,%bx
  11624. cmovnel %r9d,%r14d
  11625. The CMOVNE instructions at the end can be removed, and the
  11626. destination registers copied into the MOV instructions directly
  11627. above them, before finally being moved to before the first CMOVE
  11628. instructions, to produce:
  11629. movw $257,%ax
  11630. movw $2,%r8w
  11631. xorl r9d,%r9d
  11632. testw $16,18(%rcx)
  11633. movw $1283,%dx
  11634. movw $4,%bx
  11635. movl $9,%r14d
  11636. cmovew %ax,%dx
  11637. cmovew %r8w,%bx
  11638. cmovel %r9d,%r14d
  11639. Which can then be later optimised to:
  11640. movw $257,%ax
  11641. movw $2,%r8w
  11642. xorl r9d,%r9d
  11643. movw $1283,%dx
  11644. movw $4,%bx
  11645. movl $9,%r14d
  11646. testw $16,18(%rcx)
  11647. cmovew %ax,%dx
  11648. cmovew %r8w,%bx
  11649. cmovel %r9d,%r14d
  11650. }
  11651. TargetReg := taicpu(hp1).oper[1]^.reg;
  11652. condition := taicpu(hp1).condition;
  11653. inverted_condition := inverse_cond(condition);
  11654. pFirstMov := nil;
  11655. pLastMov := nil;
  11656. pCMOV := nil;
  11657. if (p.typ = ait_instruction) then
  11658. pCond := p
  11659. else if not GetNextInstruction(p, pCond) then
  11660. InternalError(2024012501);
  11661. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11662. { We should get the CMP or TEST instructeion }
  11663. InternalError(2024012502);
  11664. if (
  11665. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11666. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11667. ) then
  11668. begin
  11669. { We have to tread carefully here, hence why we're not using
  11670. GetNextInstructionUsingReg... we can only accept MOV and other
  11671. CMOV instructions. Anything else and we must drop out}
  11672. hp2 := hp1;
  11673. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11674. begin
  11675. if (hp2.typ <> ait_instruction) then
  11676. Exit;
  11677. case taicpu(hp2).opcode of
  11678. A_MOV:
  11679. begin
  11680. if not Assigned(pFirstMov) then
  11681. pFirstMov := hp2;
  11682. pLastMOV := hp2;
  11683. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11684. { Something different - drop out }
  11685. Exit;
  11686. { Otherwise, leave it for now }
  11687. end;
  11688. A_CMOVcc:
  11689. begin
  11690. if taicpu(hp2).condition = inverted_condition then
  11691. begin
  11692. { We found what we're looking for }
  11693. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11694. begin
  11695. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11696. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11697. begin
  11698. pCMOV := hp2;
  11699. Break;
  11700. end
  11701. else
  11702. { Unsafe reference - drop out }
  11703. Exit;
  11704. end;
  11705. end
  11706. else if taicpu(hp2).condition <> condition then
  11707. { Something weird - drop out }
  11708. Exit;
  11709. end;
  11710. else
  11711. { Invalid }
  11712. Exit;
  11713. end;
  11714. end;
  11715. if not Assigned(pCMOV) then
  11716. { No complementary CMOV found }
  11717. Exit;
  11718. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11719. begin
  11720. { Don't need to do anything special or search for a matching MOV }
  11721. Asml.Remove(pCMOV);
  11722. if RegInInstruction(TargetReg, pCond) then
  11723. { Make sure we don't overwrite the register if it's being used in the condition }
  11724. Asml.InsertAfter(pCMOV, pCond)
  11725. else
  11726. Asml.InsertBefore(pCMOV, pCond);
  11727. taicpu(pCMOV).opcode := A_MOV;
  11728. taicpu(pCMOV).condition := C_None;
  11729. { Don't need to worry about allocating new registers in these cases }
  11730. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11731. Result := True;
  11732. Exit;
  11733. end
  11734. else
  11735. begin
  11736. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11737. FoundMOV := False;
  11738. { Search for the MOV that sets the target register }
  11739. hp2 := pFirstMov;
  11740. repeat
  11741. if (taicpu(hp2).opcode = A_MOV) and
  11742. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11743. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11744. begin
  11745. { Change the destination }
  11746. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11747. if not FoundMOV then
  11748. begin
  11749. FoundMOV := True;
  11750. { Make sure the register is allocated }
  11751. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11752. end;
  11753. hp1 := tai(hp2.Previous);
  11754. Asml.Remove(hp2);
  11755. if RegInInstruction(TargetReg, pCond) then
  11756. { Make sure we don't overwrite the register if it's being used in the condition }
  11757. Asml.InsertAfter(hp2, pCond)
  11758. else
  11759. Asml.InsertBefore(hp2, pCond);
  11760. if (hp2 = pLastMov) then
  11761. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11762. Break;
  11763. hp2 := hp1;
  11764. end;
  11765. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11766. if FoundMOV then
  11767. { Delete the CMOV }
  11768. RemoveInstruction(pCMOV)
  11769. else
  11770. begin
  11771. { If no MOV was found, we have to actually move and transmute the CMOV }
  11772. Asml.Remove(pCMOV);
  11773. if RegInInstruction(TargetReg, pCond) then
  11774. { Make sure we don't overwrite the register if it's being used in the condition }
  11775. Asml.InsertAfter(pCMOV, pCond)
  11776. else
  11777. Asml.InsertBefore(pCMOV, pCond);
  11778. taicpu(pCMOV).opcode := A_MOV;
  11779. taicpu(pCMOV).condition := C_None;
  11780. end;
  11781. Result := True;
  11782. Exit;
  11783. end;
  11784. end;
  11785. end;
  11786. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11787. var
  11788. hp1, hp2, pCond: tai;
  11789. begin
  11790. Result := False;
  11791. { Search ahead for CMOV instructions }
  11792. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11793. begin
  11794. hp1 := p;
  11795. hp2 := p;
  11796. pCond := nil; { To prevent compiler warnings }
  11797. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11798. DEFAULTFLAGS }
  11799. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11800. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11801. pCond := p;
  11802. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11803. begin
  11804. if (hp1.typ <> ait_instruction) then
  11805. { Break out on markers and labels etc. }
  11806. Break;
  11807. case taicpu(hp1).opcode of
  11808. A_MOV:
  11809. { Ignore regular MOVs unless they are obviously not related
  11810. to a CMOV block }
  11811. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11812. Break;
  11813. A_CMOVcc:
  11814. if TryCmpCMovOpts(pCond, hp1) then
  11815. begin
  11816. hp1 := hp2;
  11817. { p itself isn't changed, and we're still inside a
  11818. while loop to catch subsequent CMOVs, so just flag
  11819. a new iteration }
  11820. Include(OptsToCheck, aoc_ForceNewIteration);
  11821. Continue;
  11822. end;
  11823. else
  11824. { Drop out if we find anything else }
  11825. Break;
  11826. end;
  11827. hp2 := hp1;
  11828. end;
  11829. end;
  11830. end;
  11831. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11832. var
  11833. hp1, hp2, pCond: tai;
  11834. SourceReg, TargetReg: TRegister;
  11835. begin
  11836. Result := False;
  11837. { In some situations, we end up with an inefficient arrangement of
  11838. instructions in the form of:
  11839. or %reg1,%reg2
  11840. (%reg1 deallocated)
  11841. test %reg2,%reg2
  11842. mov x,%reg2
  11843. we may be able to swap and rearrange the registers to produce:
  11844. or %reg2,%reg1
  11845. mov x,%reg2
  11846. test %reg1,%reg1
  11847. (%reg1 deallocated)
  11848. }
  11849. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11850. (taicpu(p).oper[1]^.typ = top_reg) and
  11851. (
  11852. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11853. MatchOperand(taicpu(p).oper[0]^, -1)
  11854. ) and
  11855. GetNextInstruction(p, hp1) and
  11856. MatchInstruction(hp1, A_MOV, []) and
  11857. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11858. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11859. begin
  11860. TargetReg := taicpu(p).oper[1]^.reg;
  11861. { Now look backwards to find a simple commutative operation: ADD,
  11862. IMUL (2-register version), OR, AND or XOR - whose destination
  11863. register is the same as TEST }
  11864. hp2 := p;
  11865. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11866. if RegInInstruction(TargetReg, hp2) then
  11867. begin
  11868. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11869. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11870. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11871. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11872. begin
  11873. SourceReg := taicpu(hp2).oper[0]^.reg;
  11874. if
  11875. { Make sure the MOV doesn't use the other register }
  11876. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11877. { And make sure the source register is not used afterwards }
  11878. not RegInUsedRegs(SourceReg, UsedRegs) then
  11879. begin
  11880. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11881. taicpu(hp2).oper[0]^.reg := TargetReg;
  11882. taicpu(hp2).oper[1]^.reg := SourceReg;
  11883. if taicpu(p).oper[0]^.typ = top_reg then
  11884. taicpu(p).oper[0]^.reg := SourceReg;
  11885. taicpu(p).oper[1]^.reg := SourceReg;
  11886. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11887. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11888. Include(OptsToCheck, aoc_ForceNewIteration);
  11889. { We can still check the following optimisations since
  11890. the instruction is still a TEST }
  11891. end;
  11892. end;
  11893. Break;
  11894. end;
  11895. end;
  11896. { Search ahead3 for CMOV instructions }
  11897. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11898. begin
  11899. hp1 := p;
  11900. hp2 := p;
  11901. pCond := nil; { To prevent compiler warnings }
  11902. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11903. DEFAULTFLAGS }
  11904. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11905. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11906. pCond := p;
  11907. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11908. begin
  11909. if (hp1.typ <> ait_instruction) then
  11910. { Break out on markers and labels etc. }
  11911. Break;
  11912. case taicpu(hp1).opcode of
  11913. A_MOV:
  11914. { Ignore regular MOVs unless they are obviously not related
  11915. to a CMOV block }
  11916. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11917. Break;
  11918. A_CMOVcc:
  11919. if TryCmpCMovOpts(pCond, hp1) then
  11920. begin
  11921. hp1 := hp2;
  11922. { p itself isn't changed, and we're still inside a
  11923. while loop to catch subsequent CMOVs, so just flag
  11924. a new iteration }
  11925. Include(OptsToCheck, aoc_ForceNewIteration);
  11926. Continue;
  11927. end;
  11928. else
  11929. { Drop out if we find anything else }
  11930. Break;
  11931. end;
  11932. hp2 := hp1;
  11933. end;
  11934. end;
  11935. end;
  11936. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11937. var
  11938. hp1: tai;
  11939. Count: Integer;
  11940. OrigLabel: TAsmLabel;
  11941. begin
  11942. result := False;
  11943. { Sometimes, the optimisations below can permit this }
  11944. RemoveDeadCodeAfterJump(p);
  11945. 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
  11946. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11947. begin
  11948. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11949. { Also a side-effect of optimisations }
  11950. if CollapseZeroDistJump(p, OrigLabel) then
  11951. begin
  11952. Result := True;
  11953. Exit;
  11954. end;
  11955. hp1 := GetLabelWithSym(OrigLabel);
  11956. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11957. begin
  11958. if taicpu(hp1).opcode = A_RET then
  11959. begin
  11960. {
  11961. change
  11962. jmp .L1
  11963. ...
  11964. .L1:
  11965. ret
  11966. into
  11967. ret
  11968. }
  11969. begin
  11970. ConvertJumpToRET(p, hp1);
  11971. result:=true;
  11972. end;
  11973. end
  11974. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11975. not (cs_opt_size in current_settings.optimizerswitches) and
  11976. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11977. begin
  11978. Result := True;
  11979. Exit;
  11980. end;
  11981. end;
  11982. end;
  11983. end;
  11984. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11985. begin
  11986. Result := assigned(p) and
  11987. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11988. (taicpu(p).oper[1]^.typ = top_reg) and
  11989. (
  11990. (taicpu(p).oper[0]^.typ = top_reg) or
  11991. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11992. it is not expected that this can cause a seg. violation }
  11993. (
  11994. (taicpu(p).oper[0]^.typ = top_ref) and
  11995. { TODO: Can we detect which references become constants at this
  11996. stage so we don't have to do a blanket ban? }
  11997. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11998. (
  11999. IsRefSafe(taicpu(p).oper[0]^.ref) or
  12000. (
  12001. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  12002. not RefModified and
  12003. { If the reference also appears in the condition, then we know it's safe, otherwise
  12004. any kind of access violation would have occurred already }
  12005. Assigned(cond_p) and
  12006. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12007. (cond_p.typ = ait_instruction) and
  12008. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  12009. { Just consider 2-operand comparison instructions for now to be safe }
  12010. (taicpu(cond_p).ops = 2) and
  12011. (
  12012. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  12013. (
  12014. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  12015. { Don't risk identical registers but different offsets, as we may have constructs
  12016. such as buffer streams with things like length fields that indicate whether
  12017. any more data follows. And there are probably some contrived examples where
  12018. writing to offsets behind the one being read also lead to access violations }
  12019. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  12020. (
  12021. { Check that we're not modifying a register that appears in the reference }
  12022. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  12023. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  12024. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  12025. )
  12026. )
  12027. )
  12028. )
  12029. )
  12030. )
  12031. );
  12032. end;
  12033. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  12034. begin
  12035. { Update integer registers, ignoring deallocations }
  12036. repeat
  12037. while assigned(p) and
  12038. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  12039. (p.typ = ait_label) or
  12040. ((p.typ = ait_marker) and
  12041. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  12042. p := tai(p.next);
  12043. while assigned(p) and
  12044. (p.typ=ait_RegAlloc) Do
  12045. begin
  12046. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  12047. begin
  12048. case tai_regalloc(p).ratype of
  12049. ra_alloc :
  12050. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  12051. else
  12052. ;
  12053. end;
  12054. end;
  12055. p := tai(p.next);
  12056. end;
  12057. until not(assigned(p)) or
  12058. (not(p.typ in SkipInstr) and
  12059. not((p.typ = ait_label) and
  12060. labelCanBeSkipped(tai_label(p))));
  12061. end;
  12062. {$ifndef 8086}
  12063. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  12064. begin
  12065. Result := False;
  12066. EndJump := nil;
  12067. BlockStop := nil;
  12068. while (BlockStart <> fOptimizer.BlockEnd) and
  12069. { stop on labels }
  12070. (BlockStart.typ <> ait_label) do
  12071. begin
  12072. { Keep track of all integer registers that are used }
  12073. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  12074. if BlockStart.typ = ait_instruction then
  12075. begin
  12076. if (taicpu(BlockStart).opcode = A_JMP) then
  12077. begin
  12078. if not IsJumpToLabel(taicpu(BlockStart)) or
  12079. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  12080. Exit;
  12081. EndJump := BlockStart;
  12082. Break;
  12083. end
  12084. { Check to see if we have a valid MOV instruction instead }
  12085. else if (taicpu(BlockStart).opcode <> A_MOV) or
  12086. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  12087. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12088. begin
  12089. Exit;
  12090. end
  12091. else
  12092. { This will be a valid MOV }
  12093. fAllocationRange := BlockStart;
  12094. end;
  12095. OneBeforeBlock := BlockStart;
  12096. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12097. end;
  12098. if (BlockStart = fOptimizer.BlockEnd) then
  12099. Exit;
  12100. BlockStop := BlockStart;
  12101. Result := True;
  12102. end;
  12103. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12104. var
  12105. hp1: tai;
  12106. RefModified: Boolean;
  12107. begin
  12108. Result := 0;
  12109. hp1 := BlockStart;
  12110. RefModified := False; { As long as the condition is inverted, this can be reset }
  12111. while assigned(hp1) and
  12112. (hp1 <> BlockStop) do
  12113. begin
  12114. case hp1.typ of
  12115. ait_instruction:
  12116. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12117. begin
  12118. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12119. begin
  12120. Inc(Result);
  12121. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12122. Assigned(fCondition) and
  12123. { Will have 2 operands }
  12124. (
  12125. (
  12126. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12127. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12128. ) or
  12129. (
  12130. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12131. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12132. )
  12133. ) then
  12134. { It is no longer safe to use the reference in the condition.
  12135. this prevents problems such as:
  12136. mov (%reg),%reg
  12137. mov (%reg),...
  12138. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12139. (fixes #40165)
  12140. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12141. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12142. }
  12143. RefModified := True;
  12144. end
  12145. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12146. { CMOV with constants grows the code size }
  12147. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12148. begin
  12149. { Register was reserved by TryCMOVConst and
  12150. stored on ConstRegs }
  12151. end
  12152. else
  12153. begin
  12154. Result := -1;
  12155. Exit;
  12156. end;
  12157. end
  12158. else
  12159. begin
  12160. Result := -1;
  12161. Exit;
  12162. end;
  12163. else
  12164. { Most likely an align };
  12165. end;
  12166. fOptimizer.GetNextInstruction(hp1, hp1);
  12167. end;
  12168. end;
  12169. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12170. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12171. (this is done as a separate stage because the double types are extensions of the branching type,
  12172. but we can't discount the conditional jump until the last step) }
  12173. procedure EvaluateBranchingType;
  12174. begin
  12175. Inc(CMOVScore);
  12176. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12177. { Too many instructions to be worthwhile }
  12178. fState := tsInvalid;
  12179. end;
  12180. var
  12181. hp1: tai;
  12182. Count: Integer;
  12183. begin
  12184. { Table of valid CMOV block types
  12185. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12186. ---------- --------- --------- --------- --------- ---------
  12187. tsSimple X Yes X X X
  12188. tsDetour = 1st X X X X
  12189. tsBranching <> Mid Yes X X X
  12190. tsDouble End-label Yes * Yes X Yes
  12191. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12192. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12193. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12194. * Only one reference allowed
  12195. }
  12196. hp1 := nil; { To prevent compiler warnings }
  12197. Optimizer.CopyUsedRegs(RegisterTracking);
  12198. fOptimizer := Optimizer;
  12199. fLabel := AFirstLabel;
  12200. CMOVScore := 0;
  12201. ConstCount := 0;
  12202. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12203. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12204. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12205. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12206. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12207. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12208. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12209. fInsertionPoint := p_initialjump;
  12210. fCondition := nil;
  12211. fInitialJump := p_initialjump;
  12212. fFirstMovBlock := p_initialmov;
  12213. fFirstMovBlockStop := nil;
  12214. fSecondJump := nil;
  12215. fSecondMovBlock := nil;
  12216. fSecondMovBlockStop := nil;
  12217. fMidLabel := nil;
  12218. fSecondJump := nil;
  12219. fSecondMovBlock := nil;
  12220. fEndLabel := nil;
  12221. fAllocationRange := nil;
  12222. { Assume it all goes horribly wrong! }
  12223. fState := tsInvalid;
  12224. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12225. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12226. 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
  12227. begin
  12228. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12229. for Count := 0 to 1 do
  12230. with taicpu(fCondition).oper[Count]^ do
  12231. case typ of
  12232. top_reg:
  12233. if getregtype(reg) = R_INTREGISTER then
  12234. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12235. top_ref:
  12236. begin
  12237. if
  12238. {$ifdef x86_64}
  12239. (ref^.base <> NR_RIP) and
  12240. {$endif x86_64}
  12241. (ref^.base <> NR_NO) then
  12242. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12243. if (ref^.index <> NR_NO) then
  12244. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12245. end
  12246. else
  12247. ;
  12248. end;
  12249. { When inserting instructions before hp_prev, try to insert them
  12250. before the allocation of the FLAGS register }
  12251. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12252. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12253. { If not found, set it equal to the condition so it's something sensible }
  12254. fInsertionPoint := fCondition;
  12255. { When dealing with a comparison against zero, take note of the
  12256. instruction before it to see if we can move instructions further
  12257. back in order to benefit PostPeepholeOptTestOr.
  12258. }
  12259. if (
  12260. (
  12261. (taicpu(fCondition).opcode = A_CMP) and
  12262. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12263. ) or
  12264. (
  12265. (taicpu(fCondition).opcode = A_TEST) and
  12266. (
  12267. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12268. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12269. )
  12270. )
  12271. ) and
  12272. Optimizer.GetLastInstruction(fCondition, hp1) then
  12273. begin
  12274. { These instructions set the zero flag if the result is zero }
  12275. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12276. begin
  12277. fInsertionPoint := hp1;
  12278. { Also mark all the registers in this previous instruction
  12279. as 'in use', even if they've just been deallocated }
  12280. for Count := 0 to 1 do
  12281. with taicpu(hp1).oper[Count]^ do
  12282. case typ of
  12283. top_reg:
  12284. if getregtype(reg) = R_INTREGISTER then
  12285. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12286. top_ref:
  12287. begin
  12288. if
  12289. {$ifdef x86_64}
  12290. (ref^.base <> NR_RIP) and
  12291. {$endif x86_64}
  12292. (ref^.base <> NR_NO) then
  12293. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12294. if (ref^.index <> NR_NO) then
  12295. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12296. end
  12297. else
  12298. ;
  12299. end;
  12300. end;
  12301. end;
  12302. end
  12303. else
  12304. fCondition := nil;
  12305. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12306. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12307. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12308. { If not found, set it equal to p so it's something sensible }
  12309. fInsertionPoint := hp1;
  12310. hp1 := p_initialmov;
  12311. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12312. Exit;
  12313. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12314. if (hp1.typ <> ait_label) then { should be on a jump }
  12315. begin
  12316. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12317. { Need a label afterwards }
  12318. Exit;
  12319. end
  12320. else
  12321. fMidLabel := hp1;
  12322. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12323. { Not the correct label }
  12324. fMidLabel := nil;
  12325. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12326. { If there's neither a 2nd jump nor correct label, then it's invalid
  12327. (see above table) }
  12328. Exit;
  12329. { Analyse the first block of MOVs more closely }
  12330. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12331. if Assigned(fSecondJump) then
  12332. begin
  12333. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12334. begin
  12335. fState := tsDetour
  12336. end
  12337. else
  12338. begin
  12339. { Need the correct mid-label for this one }
  12340. if not Assigned(fMidLabel) then
  12341. Exit;
  12342. fState := tsBranching;
  12343. end;
  12344. end
  12345. else
  12346. { No jump. but mid-label is present }
  12347. fState := tsSimple;
  12348. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12349. begin
  12350. { Invalid or too many instructions to be worthwhile }
  12351. fState := tsInvalid;
  12352. Exit;
  12353. end;
  12354. { check further for
  12355. jCC xxx
  12356. <several movs 1>
  12357. jmp yyy
  12358. xxx:
  12359. <several movs 2>
  12360. yyy:
  12361. etc.
  12362. }
  12363. if (fState = tsBranching) and
  12364. { Estimate for required savings for extra jump }
  12365. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12366. { Only one reference is allowed for double blocks }
  12367. (AFirstLabel.getrefs = 1) then
  12368. begin
  12369. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12370. fSecondMovBlock := hp1;
  12371. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12372. begin
  12373. EvaluateBranchingType;
  12374. Exit;
  12375. end;
  12376. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12377. if (hp1.typ <> ait_label) then { should be on a jump }
  12378. begin
  12379. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12380. begin
  12381. { Need a label afterwards }
  12382. EvaluateBranchingType;
  12383. Exit;
  12384. end;
  12385. end
  12386. else
  12387. fEndLabel := hp1;
  12388. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12389. { Second jump doesn't go to the end }
  12390. fEndLabel := nil;
  12391. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12392. begin
  12393. { If there's neither a 3rd jump nor correct end label, then it's
  12394. not a invalid double block, but is a valid single branching
  12395. block (see above table) }
  12396. EvaluateBranchingType;
  12397. Exit;
  12398. end;
  12399. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12400. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12401. { Invalid or too many instructions to be worthwhile }
  12402. Exit;
  12403. Inc(CMOVScore, Count);
  12404. if Assigned(fThirdJump) then
  12405. begin
  12406. if not Assigned(fSecondJump) then
  12407. fState := tsDoubleSecondBranching
  12408. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12409. fState := tsDoubleBranchSame
  12410. else
  12411. fState := tsDoubleBranchDifferent;
  12412. end
  12413. else
  12414. fState := tsDouble;
  12415. end;
  12416. if fState = tsBranching then
  12417. EvaluateBranchingType;
  12418. end;
  12419. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12420. new register to store the constant }
  12421. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12422. var
  12423. RegSize: TSubRegister;
  12424. CurrentVal: TCGInt;
  12425. ANewReg: TRegister;
  12426. X: ShortInt;
  12427. begin
  12428. Result := False;
  12429. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12430. Exit;
  12431. if ConstCount >= MAX_CMOV_REGISTERS then
  12432. { Arrays are full }
  12433. Exit;
  12434. { Remember that CMOV can't encode 8-bit registers }
  12435. case taicpu(p).opsize of
  12436. S_W:
  12437. RegSize := R_SUBW;
  12438. S_L:
  12439. RegSize := R_SUBD;
  12440. {$ifdef x86_64}
  12441. S_Q:
  12442. RegSize := R_SUBQ;
  12443. {$endif x86_64}
  12444. else
  12445. InternalError(2021100401);
  12446. end;
  12447. { See if the value has already been reserved for another CMOV instruction }
  12448. CurrentVal := taicpu(p).oper[0]^.val;
  12449. for X := 0 to ConstCount - 1 do
  12450. if ConstVals[X] = CurrentVal then
  12451. begin
  12452. ConstRegs[ConstCount] := ConstRegs[X];
  12453. ConstSizes[ConstCount] := RegSize;
  12454. ConstVals[ConstCount] := CurrentVal;
  12455. Inc(ConstCount);
  12456. Inc(Count);
  12457. Result := True;
  12458. Exit;
  12459. end;
  12460. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12461. if ANewReg = NR_NO then
  12462. { No free registers }
  12463. Exit;
  12464. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12465. up vying for the same register }
  12466. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12467. ConstRegs[ConstCount] := ANewReg;
  12468. ConstSizes[ConstCount] := RegSize;
  12469. ConstVals[ConstCount] := CurrentVal;
  12470. Inc(ConstCount);
  12471. Inc(Count);
  12472. Result := True;
  12473. end;
  12474. destructor TCMOVTracking.Done;
  12475. begin
  12476. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12477. end;
  12478. procedure TCMOVTracking.Process(out new_p: tai);
  12479. var
  12480. Count, Writes: LongInt;
  12481. RegMatch: Boolean;
  12482. hp1, hp_new: tai;
  12483. inverted_condition, condition: TAsmCond;
  12484. begin
  12485. if (fState in [tsInvalid, tsProcessed]) then
  12486. InternalError(2023110701);
  12487. { Repurpose RegisterTracking to mark registers that we've defined }
  12488. RegisterTracking[R_INTREGISTER].Clear;
  12489. Count := 0;
  12490. Writes := 0;
  12491. condition := taicpu(fInitialJump).condition;
  12492. inverted_condition := inverse_cond(condition);
  12493. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12494. doesn't get CMOVs in this case }
  12495. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12496. begin
  12497. { Include the jump in the flag tracking }
  12498. if Assigned(fThirdJump) then
  12499. begin
  12500. if (fState = tsDoubleBranchSame) then
  12501. begin
  12502. { Will be an unconditional jump, so track to the instruction before it }
  12503. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12504. InternalError(2023110710);
  12505. end
  12506. else
  12507. hp1 := fThirdJump;
  12508. end
  12509. else
  12510. hp1 := fSecondMovBlockStop;
  12511. end
  12512. else
  12513. begin
  12514. { Include a conditional jump in the flag tracking }
  12515. if Assigned(fSecondJump) then
  12516. begin
  12517. if (fState = tsDetour) then
  12518. begin
  12519. { Will be an unconditional jump, so track to the instruction before it }
  12520. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12521. InternalError(2023110711);
  12522. end
  12523. else
  12524. hp1 := fSecondJump;
  12525. end
  12526. else
  12527. hp1 := fFirstMovBlockStop;
  12528. end;
  12529. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12530. { Process the second set of MOVs first, because if a destination
  12531. register is shared between the first and second MOV sets, it is more
  12532. efficient to turn the first one into a MOV instruction and place it
  12533. before the CMP if possible, but we won't know which registers are
  12534. shared until we've processed at least one list, so we might as well
  12535. make it the second one since that won't be modified again. }
  12536. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12537. begin
  12538. hp1 := fSecondMovBlock;
  12539. repeat
  12540. if not Assigned(hp1) then
  12541. InternalError(2018062902);
  12542. if (hp1.typ = ait_instruction) then
  12543. begin
  12544. { Extra safeguard }
  12545. if (taicpu(hp1).opcode <> A_MOV) then
  12546. InternalError(2018062903);
  12547. { Note: tsDoubleBranchDifferent is essentially identical to
  12548. tsBranching and the 2nd block is best left largely
  12549. untouched, but we need to evaluate which registers the MOVs
  12550. write to in order to track what would be complementary CMOV
  12551. pairs that can be further optimised. [Kit] }
  12552. if fState <> tsDoubleBranchDifferent then
  12553. begin
  12554. if taicpu(hp1).oper[0]^.typ = top_const then
  12555. begin
  12556. RegMatch := False;
  12557. for Count := 0 to ConstCount - 1 do
  12558. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12559. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12560. begin
  12561. RegMatch := True;
  12562. { If it's in RegisterTracking, then this register
  12563. is being used more than once and hence has
  12564. already had its value defined (it gets added to
  12565. UsedRegs through AllocRegBetween below) }
  12566. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12567. begin
  12568. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12569. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12570. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12571. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12572. ConstMovs[Count] := hp_new;
  12573. end
  12574. else
  12575. { We just need an instruction between hp_prev and hp1
  12576. where we know the register is marked as in use }
  12577. hp_new := fSecondMovBlock;
  12578. { Keep track of largest write for this register so it can be optimised later }
  12579. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12580. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12581. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12582. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12583. Break;
  12584. end;
  12585. if not RegMatch then
  12586. InternalError(2021100411);
  12587. end;
  12588. taicpu(hp1).opcode := A_CMOVcc;
  12589. taicpu(hp1).condition := condition;
  12590. end;
  12591. { Store these writes to search for duplicates later on }
  12592. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12593. Inc(Writes);
  12594. end;
  12595. fOptimizer.GetNextInstruction(hp1, hp1);
  12596. until (hp1 = fSecondMovBlockStop);
  12597. end;
  12598. { Now do the first set of MOVs }
  12599. hp1 := fFirstMovBlock;
  12600. repeat
  12601. if not Assigned(hp1) then
  12602. InternalError(2018062904);
  12603. if (hp1.typ = ait_instruction) then
  12604. begin
  12605. RegMatch := False;
  12606. { Extra safeguard }
  12607. if (taicpu(hp1).opcode <> A_MOV) then
  12608. InternalError(2018062905);
  12609. { Search through the RegWrites list to see if there are any
  12610. opposing CMOV pairs that write to the same register }
  12611. for Count := 0 to Writes - 1 do
  12612. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12613. begin
  12614. { We have a match. Keep this as a MOV }
  12615. { Move ahead in preparation }
  12616. fOptimizer.GetNextInstruction(hp1, hp1);
  12617. RegMatch := True;
  12618. Break;
  12619. end;
  12620. if RegMatch then
  12621. Continue;
  12622. if taicpu(hp1).oper[0]^.typ = top_const then
  12623. begin
  12624. for Count := 0 to ConstCount - 1 do
  12625. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12626. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12627. begin
  12628. RegMatch := True;
  12629. { If it's in RegisterTracking, then this register is
  12630. being used more than once and hence has already had
  12631. its value defined (it gets added to UsedRegs through
  12632. AllocRegBetween below) }
  12633. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12634. begin
  12635. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12636. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12637. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12638. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12639. ConstMovs[Count] := hp_new;
  12640. end
  12641. else
  12642. { We just need an instruction between hp_prev and hp1
  12643. where we know the register is marked as in use }
  12644. hp_new := fFirstMovBlock;
  12645. { Keep track of largest write for this register so it can be optimised later }
  12646. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12647. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12648. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12649. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12650. Break;
  12651. end;
  12652. if not RegMatch then
  12653. InternalError(2021100412);
  12654. end;
  12655. taicpu(hp1).opcode := A_CMOVcc;
  12656. taicpu(hp1).condition := inverted_condition;
  12657. if (fState = tsDoubleBranchDifferent) then
  12658. begin
  12659. { Store these writes to search for duplicates later on }
  12660. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12661. Inc(Writes);
  12662. end;
  12663. end;
  12664. fOptimizer.GetNextInstruction(hp1, hp1);
  12665. until (hp1 = fFirstMovBlockStop);
  12666. { Update initialisation MOVs to the smallest possible size }
  12667. for Count := 0 to ConstCount - 1 do
  12668. if Assigned(ConstMovs[Count]) then
  12669. begin
  12670. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12671. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12672. end;
  12673. case fState of
  12674. tsSimple:
  12675. begin
  12676. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12677. { No branch to delete }
  12678. end;
  12679. tsDetour:
  12680. begin
  12681. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12682. { Preserve jump }
  12683. end;
  12684. tsBranching, tsDoubleBranchDifferent:
  12685. begin
  12686. if (fState = tsBranching) then
  12687. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12688. else
  12689. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12690. taicpu(fSecondJump).opcode := A_JCC;
  12691. taicpu(fSecondJump).condition := inverted_condition;
  12692. end;
  12693. tsDouble, tsDoubleBranchSame:
  12694. begin
  12695. if (fState = tsDouble) then
  12696. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12697. else
  12698. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12699. { Delete second jump }
  12700. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12701. fOptimizer.RemoveInstruction(fSecondJump);
  12702. end;
  12703. tsDoubleSecondBranching:
  12704. begin
  12705. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12706. { Delete second jump, preserve third jump as conditional }
  12707. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12708. fOptimizer.RemoveInstruction(fSecondJump);
  12709. taicpu(fThirdJump).opcode := A_JCC;
  12710. taicpu(fThirdJump).condition := condition;
  12711. end;
  12712. else
  12713. InternalError(2023110720);
  12714. end;
  12715. { Now we can safely decrement the reference count }
  12716. tasmlabel(fLabel).decrefs;
  12717. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12718. { Remove the original jump }
  12719. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12720. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12721. fState := tsProcessed;
  12722. end;
  12723. {$endif 8086}
  12724. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12725. var
  12726. hp1,hp2: tai;
  12727. carryadd_opcode : TAsmOp;
  12728. symbol: TAsmSymbol;
  12729. increg, tmpreg: TRegister;
  12730. {$ifndef i8086}
  12731. CMOVTracking: PCMOVTracking;
  12732. hp3,hp4,hp5: tai;
  12733. {$endif i8086}
  12734. TempBool: Boolean;
  12735. begin
  12736. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12737. DoJumpOptimizations(p, TempBool) then
  12738. Exit(True);
  12739. result:=false;
  12740. if GetNextInstruction(p,hp1) then
  12741. begin
  12742. if (hp1.typ=ait_label) then
  12743. begin
  12744. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12745. Exit;
  12746. end
  12747. else if (hp1.typ<>ait_instruction) then
  12748. Exit;
  12749. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12750. if (
  12751. (
  12752. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12753. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12754. (Taicpu(hp1).oper[0]^.val=1)
  12755. ) or
  12756. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12757. ) and
  12758. GetNextInstruction(hp1,hp2) and
  12759. FindLabel(TAsmLabel(symbol), hp2) then
  12760. { jb @@1 cmc
  12761. inc/dec operand --> adc/sbb operand,0
  12762. @@1:
  12763. ... and ...
  12764. jnb @@1
  12765. inc/dec operand --> adc/sbb operand,0
  12766. @@1: }
  12767. begin
  12768. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12769. begin
  12770. case taicpu(hp1).opcode of
  12771. A_INC,
  12772. A_ADD:
  12773. carryadd_opcode:=A_ADC;
  12774. A_DEC,
  12775. A_SUB:
  12776. carryadd_opcode:=A_SBB;
  12777. else
  12778. InternalError(2021011001);
  12779. end;
  12780. Taicpu(p).clearop(0);
  12781. Taicpu(p).ops:=0;
  12782. Taicpu(p).is_jmp:=false;
  12783. Taicpu(p).opcode:=A_CMC;
  12784. Taicpu(p).condition:=C_NONE;
  12785. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12786. Taicpu(hp1).ops:=2;
  12787. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12788. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12789. else
  12790. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12791. Taicpu(hp1).loadconst(0,0);
  12792. Taicpu(hp1).opcode:=carryadd_opcode;
  12793. result:=true;
  12794. exit;
  12795. end
  12796. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12797. begin
  12798. case taicpu(hp1).opcode of
  12799. A_INC,
  12800. A_ADD:
  12801. carryadd_opcode:=A_ADC;
  12802. A_DEC,
  12803. A_SUB:
  12804. carryadd_opcode:=A_SBB;
  12805. else
  12806. InternalError(2021011002);
  12807. end;
  12808. Taicpu(hp1).ops:=2;
  12809. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12810. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12811. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12812. else
  12813. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12814. Taicpu(hp1).loadconst(0,0);
  12815. Taicpu(hp1).opcode:=carryadd_opcode;
  12816. RemoveCurrentP(p, hp1);
  12817. result:=true;
  12818. exit;
  12819. end
  12820. {
  12821. jcc @@1 setcc tmpreg
  12822. inc/dec/add/sub operand -> (movzx tmpreg)
  12823. @@1: add/sub tmpreg,operand
  12824. While this increases code size slightly, it makes the code much faster if the
  12825. jump is unpredictable
  12826. }
  12827. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12828. begin
  12829. { search for an available register which is volatile }
  12830. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12831. if increg <> NR_NO then
  12832. begin
  12833. { We don't need to check if tmpreg is in hp1 or not, because
  12834. it will be marked as in use at p (if not, this is
  12835. indictive of a compiler bug). }
  12836. TAsmLabel(symbol).decrefs;
  12837. Taicpu(p).clearop(0);
  12838. Taicpu(p).ops:=1;
  12839. Taicpu(p).is_jmp:=false;
  12840. Taicpu(p).opcode:=A_SETcc;
  12841. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12842. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12843. Taicpu(p).loadreg(0,increg);
  12844. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12845. begin
  12846. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12847. R_SUBW:
  12848. begin
  12849. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12850. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12851. end;
  12852. R_SUBD:
  12853. begin
  12854. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12855. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12856. end;
  12857. {$ifdef x86_64}
  12858. R_SUBQ:
  12859. begin
  12860. { MOVZX doesn't have a 64-bit variant, because
  12861. the 32-bit version implicitly zeroes the
  12862. upper 32-bits of the destination register }
  12863. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12864. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12865. setsubreg(tmpreg, R_SUBQ);
  12866. end;
  12867. {$endif x86_64}
  12868. else
  12869. Internalerror(2020030601);
  12870. end;
  12871. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12872. asml.InsertAfter(hp2,p);
  12873. end
  12874. else
  12875. tmpreg := increg;
  12876. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12877. begin
  12878. Taicpu(hp1).ops:=2;
  12879. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12880. end;
  12881. Taicpu(hp1).loadreg(0,tmpreg);
  12882. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12883. Result := True;
  12884. { p is no longer a Jcc instruction, so exit }
  12885. Exit;
  12886. end;
  12887. end;
  12888. end;
  12889. { Detect the following:
  12890. jmp<cond> @Lbl1
  12891. jmp @Lbl2
  12892. ...
  12893. @Lbl1:
  12894. ret
  12895. Change to:
  12896. jmp<inv_cond> @Lbl2
  12897. ret
  12898. }
  12899. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12900. begin
  12901. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12902. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12903. MatchInstruction(hp2,A_RET,[S_NO]) then
  12904. begin
  12905. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12906. { Change label address to that of the unconditional jump }
  12907. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12908. TAsmLabel(symbol).DecRefs;
  12909. taicpu(hp1).opcode := A_RET;
  12910. taicpu(hp1).is_jmp := false;
  12911. taicpu(hp1).ops := taicpu(hp2).ops;
  12912. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12913. case taicpu(hp2).ops of
  12914. 0:
  12915. taicpu(hp1).clearop(0);
  12916. 1:
  12917. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12918. else
  12919. internalerror(2016041302);
  12920. end;
  12921. end;
  12922. {$ifndef i8086}
  12923. end
  12924. {
  12925. convert
  12926. j<c> .L1
  12927. mov 1,reg
  12928. jmp .L2
  12929. .L1
  12930. mov 0,reg
  12931. .L2
  12932. into
  12933. mov 0,reg
  12934. set<not(c)> reg
  12935. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12936. would destroy the flag contents
  12937. }
  12938. else if MatchInstruction(hp1,A_MOV,[]) and
  12939. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12940. {$ifdef i386}
  12941. (
  12942. { Under i386, ESI, EDI, EBP and ESP
  12943. don't have an 8-bit representation }
  12944. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12945. ) and
  12946. {$endif i386}
  12947. (taicpu(hp1).oper[0]^.val=1) and
  12948. GetNextInstruction(hp1,hp2) and
  12949. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12950. GetNextInstruction(hp2,hp3) and
  12951. (hp3.typ=ait_label) and
  12952. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12953. (tai_label(hp3).labsym.getrefs=1) and
  12954. GetNextInstruction(hp3,hp4) and
  12955. MatchInstruction(hp4,A_MOV,[]) and
  12956. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12957. (taicpu(hp4).oper[0]^.val=0) and
  12958. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12959. GetNextInstruction(hp4,hp5) and
  12960. (hp5.typ=ait_label) and
  12961. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12962. (tai_label(hp5).labsym.getrefs=1) then
  12963. begin
  12964. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12965. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12966. { remove last label }
  12967. RemoveInstruction(hp5);
  12968. { remove second label }
  12969. RemoveInstruction(hp3);
  12970. { remove jmp }
  12971. RemoveInstruction(hp2);
  12972. if taicpu(hp1).opsize=S_B then
  12973. RemoveInstruction(hp1)
  12974. else
  12975. taicpu(hp1).loadconst(0,0);
  12976. taicpu(hp4).opcode:=A_SETcc;
  12977. taicpu(hp4).opsize:=S_B;
  12978. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12979. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12980. taicpu(hp4).opercnt:=1;
  12981. taicpu(hp4).ops:=1;
  12982. taicpu(hp4).freeop(1);
  12983. RemoveCurrentP(p);
  12984. Result:=true;
  12985. exit;
  12986. end
  12987. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12988. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12989. begin
  12990. { check for
  12991. jCC xxx
  12992. <several movs>
  12993. xxx:
  12994. Also spot:
  12995. Jcc xxx
  12996. <several movs>
  12997. jmp xxx
  12998. Change to:
  12999. <several cmovs with inverted condition>
  13000. jmp xxx (only for the 2nd case)
  13001. }
  13002. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  13003. if CMOVTracking^.State <> tsInvalid then
  13004. begin
  13005. CMovTracking^.Process(p);
  13006. Result := True;
  13007. end;
  13008. CMOVTracking^.Done;
  13009. {$endif i8086}
  13010. end;
  13011. end;
  13012. end;
  13013. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  13014. var
  13015. hp1,hp2,hp3: tai;
  13016. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  13017. NewSize: TOpSize;
  13018. NewRegSize: TSubRegister;
  13019. Limit: TCgInt;
  13020. SwapOper: POper;
  13021. begin
  13022. result:=false;
  13023. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  13024. GetNextInstruction(p,hp1) and
  13025. (hp1.typ = ait_instruction);
  13026. if reg_and_hp1_is_instr and
  13027. (
  13028. (taicpu(hp1).opcode <> A_LEA) or
  13029. { If the LEA instruction can be converted into an arithmetic instruction,
  13030. it may be possible to then fold it. }
  13031. (
  13032. { If the flags register is in use, don't change the instruction
  13033. to an ADD otherwise this will scramble the flags. [Kit] }
  13034. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13035. ConvertLEA(taicpu(hp1))
  13036. )
  13037. ) and
  13038. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  13039. GetNextInstruction(hp1,hp2) and
  13040. MatchInstruction(hp2,A_MOV,[]) and
  13041. (taicpu(hp2).oper[0]^.typ = top_reg) and
  13042. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  13043. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  13044. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  13045. {$ifdef i386}
  13046. { not all registers have byte size sub registers on i386 }
  13047. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  13048. {$endif i386}
  13049. (((taicpu(hp1).ops=2) and
  13050. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  13051. ((taicpu(hp1).ops=1) and
  13052. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  13053. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  13054. begin
  13055. { change movsX/movzX reg/ref, reg2
  13056. add/sub/or/... reg3/$const, reg2
  13057. mov reg2 reg/ref
  13058. to add/sub/or/... reg3/$const, reg/ref }
  13059. { by example:
  13060. movswl %si,%eax movswl %si,%eax p
  13061. decl %eax addl %edx,%eax hp1
  13062. movw %ax,%si movw %ax,%si hp2
  13063. ->
  13064. movswl %si,%eax movswl %si,%eax p
  13065. decw %eax addw %edx,%eax hp1
  13066. movw %ax,%si movw %ax,%si hp2
  13067. }
  13068. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  13069. {
  13070. ->
  13071. movswl %si,%eax movswl %si,%eax p
  13072. decw %si addw %dx,%si hp1
  13073. movw %ax,%si movw %ax,%si hp2
  13074. }
  13075. case taicpu(hp1).ops of
  13076. 1:
  13077. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  13078. 2:
  13079. begin
  13080. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  13081. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  13082. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  13083. end;
  13084. else
  13085. internalerror(2008042702);
  13086. end;
  13087. {
  13088. ->
  13089. decw %si addw %dx,%si p
  13090. }
  13091. DebugMsg(SPeepholeOptimization + 'var3',p);
  13092. RemoveCurrentP(p, hp1);
  13093. RemoveInstruction(hp2);
  13094. Result := True;
  13095. Exit;
  13096. end;
  13097. if reg_and_hp1_is_instr and
  13098. (taicpu(hp1).opcode = A_MOV) and
  13099. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13100. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13101. {$ifdef x86_64}
  13102. { check for implicit extension to 64 bit }
  13103. or
  13104. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13105. (taicpu(hp1).opsize=S_Q) and
  13106. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13107. )
  13108. {$endif x86_64}
  13109. )
  13110. then
  13111. begin
  13112. { change
  13113. movx %reg1,%reg2
  13114. mov %reg2,%reg3
  13115. dealloc %reg2
  13116. into
  13117. movx %reg,%reg3
  13118. }
  13119. TransferUsedRegs(TmpUsedRegs);
  13120. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13121. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13122. begin
  13123. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13124. {$ifdef x86_64}
  13125. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13126. (taicpu(hp1).opsize=S_Q) then
  13127. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13128. else
  13129. {$endif x86_64}
  13130. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13131. RemoveInstruction(hp1);
  13132. Result := True;
  13133. Exit;
  13134. end;
  13135. end;
  13136. if reg_and_hp1_is_instr and
  13137. ((taicpu(hp1).opcode=A_MOV) or
  13138. (taicpu(hp1).opcode=A_ADD) or
  13139. (taicpu(hp1).opcode=A_SUB) or
  13140. (taicpu(hp1).opcode=A_CMP) or
  13141. (taicpu(hp1).opcode=A_OR) or
  13142. (taicpu(hp1).opcode=A_XOR) or
  13143. (taicpu(hp1).opcode=A_AND)
  13144. ) and
  13145. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13146. begin
  13147. AndTest := (taicpu(hp1).opcode=A_AND) and
  13148. GetNextInstruction(hp1, hp2) and
  13149. (hp2.typ = ait_instruction) and
  13150. (
  13151. (
  13152. (taicpu(hp2).opcode=A_TEST) and
  13153. (
  13154. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13155. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13156. (
  13157. { If the AND and TEST instructions share a constant, this is also valid }
  13158. (taicpu(hp1).oper[0]^.typ = top_const) and
  13159. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13160. )
  13161. ) and
  13162. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13163. ) or
  13164. (
  13165. (taicpu(hp2).opcode=A_CMP) and
  13166. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13167. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13168. )
  13169. );
  13170. { change
  13171. movx (oper),%reg2
  13172. and $x,%reg2
  13173. test %reg2,%reg2
  13174. dealloc %reg2
  13175. into
  13176. op %reg1,%reg3
  13177. if the second op accesses only the bits stored in reg1
  13178. }
  13179. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13180. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13181. (taicpu(hp1).oper[0]^.typ = top_const) and
  13182. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13183. AndTest then
  13184. begin
  13185. { Check if the AND constant is in range }
  13186. case taicpu(p).opsize of
  13187. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13188. begin
  13189. NewSize := S_B;
  13190. Limit := $FF;
  13191. end;
  13192. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13193. begin
  13194. NewSize := S_W;
  13195. Limit := $FFFF;
  13196. end;
  13197. {$ifdef x86_64}
  13198. S_LQ:
  13199. begin
  13200. NewSize := S_L;
  13201. Limit := $FFFFFFFF;
  13202. end;
  13203. {$endif x86_64}
  13204. else
  13205. InternalError(2021120303);
  13206. end;
  13207. if (
  13208. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13209. { Check for negative operands }
  13210. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13211. ) and
  13212. GetNextInstruction(hp2,hp3) and
  13213. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13214. (taicpu(hp3).condition in [C_E,C_NE]) then
  13215. begin
  13216. TransferUsedRegs(TmpUsedRegs);
  13217. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13218. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13219. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13220. begin
  13221. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13222. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13223. taicpu(hp1).opcode := A_TEST;
  13224. taicpu(hp1).opsize := NewSize;
  13225. RemoveInstruction(hp2);
  13226. RemoveCurrentP(p, hp1);
  13227. Result:=true;
  13228. exit;
  13229. end;
  13230. end;
  13231. end;
  13232. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13233. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13234. (taicpu(hp1).opsize=S_B)) or
  13235. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13236. (taicpu(hp1).opsize=S_W))
  13237. {$ifdef x86_64}
  13238. or ((taicpu(p).opsize=S_LQ) and
  13239. (taicpu(hp1).opsize=S_L))
  13240. {$endif x86_64}
  13241. ) and
  13242. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13243. begin
  13244. { change
  13245. movx %reg1,%reg2
  13246. op %reg2,%reg3
  13247. dealloc %reg2
  13248. into
  13249. op %reg1,%reg3
  13250. if the second op accesses only the bits stored in reg1
  13251. }
  13252. TransferUsedRegs(TmpUsedRegs);
  13253. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13254. if AndTest then
  13255. begin
  13256. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13257. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13258. end
  13259. else
  13260. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13261. if not RegUsed then
  13262. begin
  13263. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13264. if taicpu(p).oper[0]^.typ=top_reg then
  13265. begin
  13266. case taicpu(hp1).opsize of
  13267. S_B:
  13268. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13269. S_W:
  13270. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13271. S_L:
  13272. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13273. else
  13274. Internalerror(2020102301);
  13275. end;
  13276. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13277. end
  13278. else
  13279. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13280. RemoveCurrentP(p);
  13281. if AndTest then
  13282. RemoveInstruction(hp2);
  13283. result:=true;
  13284. exit;
  13285. end;
  13286. end
  13287. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13288. (
  13289. { Bitwise operations only }
  13290. (taicpu(hp1).opcode=A_AND) or
  13291. (taicpu(hp1).opcode=A_TEST) or
  13292. (
  13293. (taicpu(hp1).oper[0]^.typ = top_const) and
  13294. (
  13295. (taicpu(hp1).opcode=A_OR) or
  13296. (taicpu(hp1).opcode=A_XOR)
  13297. )
  13298. )
  13299. ) and
  13300. (
  13301. (taicpu(hp1).oper[0]^.typ = top_const) or
  13302. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13303. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13304. ) then
  13305. begin
  13306. { change
  13307. movx %reg2,%reg2
  13308. op const,%reg2
  13309. into
  13310. op const,%reg2 (smaller version)
  13311. movx %reg2,%reg2
  13312. also change
  13313. movx %reg1,%reg2
  13314. and/test (oper),%reg2
  13315. dealloc %reg2
  13316. into
  13317. and/test (oper),%reg1
  13318. }
  13319. case taicpu(p).opsize of
  13320. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13321. begin
  13322. NewSize := S_B;
  13323. NewRegSize := R_SUBL;
  13324. Limit := $FF;
  13325. end;
  13326. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13327. begin
  13328. NewSize := S_W;
  13329. NewRegSize := R_SUBW;
  13330. Limit := $FFFF;
  13331. end;
  13332. {$ifdef x86_64}
  13333. S_LQ:
  13334. begin
  13335. NewSize := S_L;
  13336. NewRegSize := R_SUBD;
  13337. Limit := $FFFFFFFF;
  13338. end;
  13339. {$endif x86_64}
  13340. else
  13341. Internalerror(2021120302);
  13342. end;
  13343. TransferUsedRegs(TmpUsedRegs);
  13344. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13345. if AndTest then
  13346. begin
  13347. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13348. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13349. end
  13350. else
  13351. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13352. if
  13353. (
  13354. (taicpu(p).opcode = A_MOVZX) and
  13355. (
  13356. (taicpu(hp1).opcode=A_AND) or
  13357. (taicpu(hp1).opcode=A_TEST)
  13358. ) and
  13359. not (
  13360. { If both are references, then the final instruction will have
  13361. both operands as references, which is not allowed }
  13362. (taicpu(p).oper[0]^.typ = top_ref) and
  13363. (taicpu(hp1).oper[0]^.typ = top_ref)
  13364. ) and
  13365. not RegUsed
  13366. ) or
  13367. (
  13368. (
  13369. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13370. not RegUsed
  13371. ) and
  13372. (taicpu(p).oper[0]^.typ = top_reg) and
  13373. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13374. (taicpu(hp1).oper[0]^.typ = top_const) and
  13375. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13376. ) then
  13377. begin
  13378. {$if defined(i386) or defined(i8086)}
  13379. { If the target size is 8-bit, make sure we can actually encode it }
  13380. 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
  13381. Exit;
  13382. {$endif i386 or i8086}
  13383. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13384. taicpu(hp1).opsize := NewSize;
  13385. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13386. if AndTest then
  13387. begin
  13388. RemoveInstruction(hp2);
  13389. if not RegUsed then
  13390. begin
  13391. taicpu(hp1).opcode := A_TEST;
  13392. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13393. begin
  13394. { Make sure the reference is the second operand }
  13395. SwapOper := taicpu(hp1).oper[0];
  13396. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13397. taicpu(hp1).oper[1] := SwapOper;
  13398. end;
  13399. end;
  13400. end;
  13401. case taicpu(hp1).oper[0]^.typ of
  13402. top_reg:
  13403. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13404. top_const:
  13405. { For the AND/TEST case }
  13406. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13407. else
  13408. ;
  13409. end;
  13410. if RegUsed then
  13411. begin
  13412. AsmL.Remove(p);
  13413. AsmL.InsertAfter(p, hp1);
  13414. p := hp1;
  13415. end
  13416. else
  13417. RemoveCurrentP(p, hp1);
  13418. result:=true;
  13419. exit;
  13420. end;
  13421. end;
  13422. end;
  13423. if reg_and_hp1_is_instr and
  13424. (taicpu(p).oper[0]^.typ = top_reg) and
  13425. (
  13426. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13427. ) and
  13428. (taicpu(hp1).oper[0]^.typ = top_const) and
  13429. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13430. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13431. { Minimum shift value allowed is the bit difference between the sizes }
  13432. (taicpu(hp1).oper[0]^.val >=
  13433. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13434. 8 * (
  13435. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13436. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13437. )
  13438. ) then
  13439. begin
  13440. { For:
  13441. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13442. shl/sal ##, %reg1
  13443. Remove the movsx/movzx instruction if the shift overwrites the
  13444. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13445. }
  13446. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13447. RemoveCurrentP(p, hp1);
  13448. Result := True;
  13449. Exit;
  13450. end
  13451. else if reg_and_hp1_is_instr and
  13452. (taicpu(p).oper[0]^.typ = top_reg) and
  13453. (
  13454. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13455. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13456. ) and
  13457. (taicpu(hp1).oper[0]^.typ = top_const) and
  13458. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13459. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13460. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13461. (taicpu(hp1).oper[0]^.val <
  13462. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13463. 8 * (
  13464. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13465. )
  13466. ) then
  13467. begin
  13468. { For:
  13469. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13470. sar ##, %reg1 shr ##, %reg1
  13471. Move the shift to before the movx instruction if the shift value
  13472. is not too large.
  13473. }
  13474. asml.Remove(hp1);
  13475. asml.InsertBefore(hp1, p);
  13476. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13477. case taicpu(p).opsize of
  13478. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13479. taicpu(hp1).opsize := S_B;
  13480. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13481. taicpu(hp1).opsize := S_W;
  13482. {$ifdef x86_64}
  13483. S_LQ:
  13484. taicpu(hp1).opsize := S_L;
  13485. {$endif}
  13486. else
  13487. InternalError(2020112401);
  13488. end;
  13489. if (taicpu(hp1).opcode = A_SHR) then
  13490. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13491. else
  13492. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13493. Result := True;
  13494. end;
  13495. if reg_and_hp1_is_instr and
  13496. (taicpu(p).oper[0]^.typ = top_reg) and
  13497. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13498. (
  13499. (taicpu(hp1).opcode = taicpu(p).opcode)
  13500. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13501. {$ifdef x86_64}
  13502. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13503. {$endif x86_64}
  13504. ) then
  13505. begin
  13506. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13507. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13508. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13509. begin
  13510. {
  13511. For example:
  13512. movzbw %al,%ax
  13513. movzwl %ax,%eax
  13514. Compress into:
  13515. movzbl %al,%eax
  13516. }
  13517. RegUsed := False;
  13518. case taicpu(p).opsize of
  13519. S_BW:
  13520. case taicpu(hp1).opsize of
  13521. S_WL:
  13522. begin
  13523. taicpu(p).opsize := S_BL;
  13524. RegUsed := True;
  13525. end;
  13526. {$ifdef x86_64}
  13527. S_WQ:
  13528. begin
  13529. if taicpu(p).opcode = A_MOVZX then
  13530. begin
  13531. taicpu(p).opsize := S_BL;
  13532. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13533. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13534. end
  13535. else
  13536. taicpu(p).opsize := S_BQ;
  13537. RegUsed := True;
  13538. end;
  13539. {$endif x86_64}
  13540. else
  13541. ;
  13542. end;
  13543. {$ifdef x86_64}
  13544. S_BL:
  13545. case taicpu(hp1).opsize of
  13546. S_LQ:
  13547. begin
  13548. if taicpu(p).opcode = A_MOVZX then
  13549. begin
  13550. taicpu(p).opsize := S_BL;
  13551. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13552. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13553. end
  13554. else
  13555. taicpu(p).opsize := S_BQ;
  13556. RegUsed := True;
  13557. end;
  13558. else
  13559. ;
  13560. end;
  13561. S_WL:
  13562. case taicpu(hp1).opsize of
  13563. S_LQ:
  13564. begin
  13565. if taicpu(p).opcode = A_MOVZX then
  13566. begin
  13567. taicpu(p).opsize := S_WL;
  13568. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13569. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13570. end
  13571. else
  13572. taicpu(p).opsize := S_WQ;
  13573. RegUsed := True;
  13574. end;
  13575. else
  13576. ;
  13577. end;
  13578. {$endif x86_64}
  13579. else
  13580. ;
  13581. end;
  13582. if RegUsed then
  13583. begin
  13584. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13585. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13586. RemoveInstruction(hp1);
  13587. Result := True;
  13588. Exit;
  13589. end;
  13590. end;
  13591. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13592. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13593. GetNextInstruction(hp1, hp2) and
  13594. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13595. (
  13596. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13597. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13598. {$ifdef x86_64}
  13599. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13600. {$endif x86_64}
  13601. ) and
  13602. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13603. (
  13604. (
  13605. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13606. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13607. ) or
  13608. (
  13609. { Only allow the operands in reverse order for TEST instructions }
  13610. (taicpu(hp2).opcode = A_TEST) and
  13611. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13612. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13613. )
  13614. ) then
  13615. begin
  13616. {
  13617. For example:
  13618. movzbl %al,%eax
  13619. movzbl (ref),%edx
  13620. andl %edx,%eax
  13621. (%edx deallocated)
  13622. Change to:
  13623. andb (ref),%al
  13624. movzbl %al,%eax
  13625. Rules are:
  13626. - First two instructions have the same opcode and opsize
  13627. - First instruction's operands are the same super-register
  13628. - Second instruction operates on a different register
  13629. - Third instruction is AND, OR, XOR or TEST
  13630. - Third instruction's operands are the destination registers of the first two instructions
  13631. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13632. - Second instruction's destination register is deallocated afterwards
  13633. }
  13634. TransferUsedRegs(TmpUsedRegs);
  13635. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13636. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13637. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13638. begin
  13639. case taicpu(p).opsize of
  13640. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13641. NewSize := S_B;
  13642. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13643. NewSize := S_W;
  13644. {$ifdef x86_64}
  13645. S_LQ:
  13646. NewSize := S_L;
  13647. {$endif x86_64}
  13648. else
  13649. InternalError(2021120301);
  13650. end;
  13651. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13652. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13653. taicpu(hp2).opsize := NewSize;
  13654. RemoveInstruction(hp1);
  13655. { With TEST, it's best to keep the MOVX instruction at the top }
  13656. if (taicpu(hp2).opcode <> A_TEST) then
  13657. begin
  13658. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13659. asml.Remove(p);
  13660. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13661. asml.InsertAfter(p, hp2);
  13662. p := hp2;
  13663. end
  13664. else
  13665. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13666. Result := True;
  13667. Exit;
  13668. end;
  13669. end;
  13670. end;
  13671. if taicpu(p).opcode=A_MOVZX then
  13672. begin
  13673. { removes superfluous And's after movzx's }
  13674. if reg_and_hp1_is_instr and
  13675. (taicpu(hp1).opcode = A_AND) and
  13676. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13677. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13678. {$ifdef x86_64}
  13679. { check for implicit extension to 64 bit }
  13680. or
  13681. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13682. (taicpu(hp1).opsize=S_Q) and
  13683. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13684. )
  13685. {$endif x86_64}
  13686. )
  13687. then
  13688. begin
  13689. case taicpu(p).opsize Of
  13690. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13691. if (taicpu(hp1).oper[0]^.val = $ff) then
  13692. begin
  13693. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13694. RemoveInstruction(hp1);
  13695. Result:=true;
  13696. exit;
  13697. end;
  13698. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13699. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13700. begin
  13701. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13702. RemoveInstruction(hp1);
  13703. Result:=true;
  13704. exit;
  13705. end;
  13706. {$ifdef x86_64}
  13707. S_LQ:
  13708. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13709. begin
  13710. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13711. RemoveInstruction(hp1);
  13712. Result:=true;
  13713. exit;
  13714. end;
  13715. {$endif x86_64}
  13716. else
  13717. ;
  13718. end;
  13719. { we cannot get rid of the and, but can we get rid of the movz ?}
  13720. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13721. begin
  13722. case taicpu(p).opsize Of
  13723. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13724. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13725. begin
  13726. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13727. RemoveCurrentP(p,hp1);
  13728. Result:=true;
  13729. exit;
  13730. end;
  13731. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13732. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13733. begin
  13734. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13735. RemoveCurrentP(p,hp1);
  13736. Result:=true;
  13737. exit;
  13738. end;
  13739. {$ifdef x86_64}
  13740. S_LQ:
  13741. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13742. begin
  13743. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13744. RemoveCurrentP(p,hp1);
  13745. Result:=true;
  13746. exit;
  13747. end;
  13748. {$endif x86_64}
  13749. else
  13750. ;
  13751. end;
  13752. end;
  13753. end;
  13754. { changes some movzx constructs to faster synonyms (all examples
  13755. are given with eax/ax, but are also valid for other registers)}
  13756. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13757. begin
  13758. case taicpu(p).opsize of
  13759. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13760. (the machine code is equivalent to movzbl %al,%eax), but the
  13761. code generator still generates that assembler instruction and
  13762. it is silently converted. This should probably be checked.
  13763. [Kit] }
  13764. S_BW:
  13765. begin
  13766. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13767. (
  13768. not IsMOVZXAcceptable
  13769. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13770. or (
  13771. (cs_opt_size in current_settings.optimizerswitches) and
  13772. (taicpu(p).oper[1]^.reg = NR_AX)
  13773. )
  13774. ) then
  13775. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13776. begin
  13777. DebugMsg(SPeepholeOptimization + 'var7',p);
  13778. taicpu(p).opcode := A_AND;
  13779. taicpu(p).changeopsize(S_W);
  13780. taicpu(p).loadConst(0,$ff);
  13781. Result := True;
  13782. end
  13783. else if not IsMOVZXAcceptable and
  13784. GetNextInstruction(p, hp1) and
  13785. (tai(hp1).typ = ait_instruction) and
  13786. (taicpu(hp1).opcode = A_AND) and
  13787. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13788. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13789. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13790. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13791. begin
  13792. DebugMsg(SPeepholeOptimization + 'var8',p);
  13793. taicpu(p).opcode := A_MOV;
  13794. taicpu(p).changeopsize(S_W);
  13795. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13796. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13797. Result := True;
  13798. end;
  13799. end;
  13800. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13801. S_BL:
  13802. if not IsMOVZXAcceptable then
  13803. begin
  13804. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13805. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13806. begin
  13807. DebugMsg(SPeepholeOptimization + 'var9',p);
  13808. taicpu(p).opcode := A_AND;
  13809. taicpu(p).changeopsize(S_L);
  13810. taicpu(p).loadConst(0,$ff);
  13811. Result := True;
  13812. end
  13813. else if GetNextInstruction(p, hp1) and
  13814. (tai(hp1).typ = ait_instruction) and
  13815. (taicpu(hp1).opcode = A_AND) and
  13816. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13817. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13818. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13819. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13820. begin
  13821. DebugMsg(SPeepholeOptimization + 'var10',p);
  13822. taicpu(p).opcode := A_MOV;
  13823. taicpu(p).changeopsize(S_L);
  13824. { do not use R_SUBWHOLE
  13825. as movl %rdx,%eax
  13826. is invalid in assembler PM }
  13827. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13828. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13829. Result := True;
  13830. end;
  13831. end;
  13832. {$endif i8086}
  13833. S_WL:
  13834. if not IsMOVZXAcceptable then
  13835. begin
  13836. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13837. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13838. begin
  13839. DebugMsg(SPeepholeOptimization + 'var11',p);
  13840. taicpu(p).opcode := A_AND;
  13841. taicpu(p).changeopsize(S_L);
  13842. taicpu(p).loadConst(0,$ffff);
  13843. Result := True;
  13844. end
  13845. else if GetNextInstruction(p, hp1) and
  13846. (tai(hp1).typ = ait_instruction) and
  13847. (taicpu(hp1).opcode = A_AND) and
  13848. (taicpu(hp1).oper[0]^.typ = top_const) and
  13849. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13850. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13851. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13852. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13853. begin
  13854. DebugMsg(SPeepholeOptimization + 'var12',p);
  13855. taicpu(p).opcode := A_MOV;
  13856. taicpu(p).changeopsize(S_L);
  13857. { do not use R_SUBWHOLE
  13858. as movl %rdx,%eax
  13859. is invalid in assembler PM }
  13860. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13861. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13862. Result := True;
  13863. end;
  13864. end;
  13865. else
  13866. InternalError(2017050705);
  13867. end;
  13868. end
  13869. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13870. begin
  13871. if GetNextInstruction(p, hp1) and
  13872. (tai(hp1).typ = ait_instruction) and
  13873. (taicpu(hp1).opcode = A_AND) and
  13874. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13875. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13876. begin
  13877. case taicpu(p).opsize Of
  13878. S_BL:
  13879. if (taicpu(hp1).opsize <> S_L) or
  13880. (taicpu(hp1).oper[0]^.val > $FF) then
  13881. begin
  13882. DebugMsg(SPeepholeOptimization + 'var13',p);
  13883. taicpu(hp1).changeopsize(S_L);
  13884. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13885. Include(OptsToCheck, aoc_ForceNewIteration);
  13886. end;
  13887. S_WL:
  13888. if (taicpu(hp1).opsize <> S_L) or
  13889. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13890. begin
  13891. DebugMsg(SPeepholeOptimization + 'var14',p);
  13892. taicpu(hp1).changeopsize(S_L);
  13893. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13894. Include(OptsToCheck, aoc_ForceNewIteration);
  13895. end;
  13896. S_BW:
  13897. if (taicpu(hp1).opsize <> S_W) or
  13898. (taicpu(hp1).oper[0]^.val > $FF) then
  13899. begin
  13900. DebugMsg(SPeepholeOptimization + 'var15',p);
  13901. taicpu(hp1).changeopsize(S_W);
  13902. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13903. Include(OptsToCheck, aoc_ForceNewIteration);
  13904. end;
  13905. else
  13906. Internalerror(2017050704)
  13907. end;
  13908. end;
  13909. end;
  13910. end;
  13911. end;
  13912. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13913. var
  13914. hp1, hp2 : tai;
  13915. MaskLength : Cardinal;
  13916. MaskedBits : TCgInt;
  13917. ActiveReg : TRegister;
  13918. begin
  13919. Result:=false;
  13920. { There are no optimisations for reference targets }
  13921. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13922. Exit;
  13923. while GetNextInstruction(p, hp1) and
  13924. (hp1.typ = ait_instruction) do
  13925. begin
  13926. if (taicpu(p).oper[0]^.typ = top_const) then
  13927. begin
  13928. case taicpu(hp1).opcode of
  13929. A_AND:
  13930. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13931. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13932. { the second register must contain the first one, so compare their subreg types }
  13933. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13934. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13935. { change
  13936. and const1, reg
  13937. and const2, reg
  13938. to
  13939. and (const1 and const2), reg
  13940. }
  13941. begin
  13942. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13943. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13944. RemoveCurrentP(p, hp1);
  13945. Result:=true;
  13946. exit;
  13947. end;
  13948. A_CMP:
  13949. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13950. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13951. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13952. { Just check that the condition on the next instruction is compatible }
  13953. GetNextInstruction(hp1, hp2) and
  13954. (hp2.typ = ait_instruction) and
  13955. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13956. then
  13957. { change
  13958. and 2^n, reg
  13959. cmp 2^n, reg
  13960. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13961. to
  13962. and 2^n, reg
  13963. test reg, reg
  13964. j(~c) / set(~c) / cmov(~c)
  13965. }
  13966. begin
  13967. { Keep TEST instruction in, rather than remove it, because
  13968. it may trigger other optimisations such as MovAndTest2Test }
  13969. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13970. taicpu(hp1).opcode := A_TEST;
  13971. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13972. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13973. Result := True;
  13974. Exit;
  13975. end
  13976. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13977. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13978. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13979. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13980. { change
  13981. and $ff/$ff/$ffff, reg
  13982. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13983. dealloc reg
  13984. to
  13985. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13986. }
  13987. begin
  13988. TransferUsedRegs(TmpUsedRegs);
  13989. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13990. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13991. begin
  13992. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13993. case taicpu(p).oper[0]^.val of
  13994. $ff:
  13995. begin
  13996. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13997. taicpu(hp1).opsize:=S_B;
  13998. end;
  13999. $ffff:
  14000. begin
  14001. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  14002. taicpu(hp1).opsize:=S_W;
  14003. end;
  14004. $ffffffff:
  14005. begin
  14006. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  14007. taicpu(hp1).opsize:=S_L;
  14008. end;
  14009. else
  14010. Internalerror(2023030401);
  14011. end;
  14012. RemoveCurrentP(p);
  14013. Result := True;
  14014. Exit;
  14015. end;
  14016. end;
  14017. A_MOVZX:
  14018. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  14019. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  14020. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14021. (
  14022. (
  14023. (taicpu(p).opsize=S_W) and
  14024. (taicpu(hp1).opsize=S_BW)
  14025. ) or
  14026. (
  14027. (taicpu(p).opsize=S_L) and
  14028. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  14029. )
  14030. {$ifdef x86_64}
  14031. or
  14032. (
  14033. (taicpu(p).opsize=S_Q) and
  14034. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  14035. )
  14036. {$endif x86_64}
  14037. ) then
  14038. begin
  14039. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14040. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  14041. ) or
  14042. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14043. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  14044. then
  14045. begin
  14046. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  14047. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  14048. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  14049. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  14050. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  14051. }
  14052. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  14053. RemoveInstruction(hp1);
  14054. { See if there are other optimisations possible }
  14055. Continue;
  14056. end;
  14057. end;
  14058. A_SHL:
  14059. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14060. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  14061. begin
  14062. {$ifopt R+}
  14063. {$define RANGE_WAS_ON}
  14064. {$R-}
  14065. {$endif}
  14066. { get length of potential and mask }
  14067. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  14068. { really a mask? }
  14069. {$ifdef RANGE_WAS_ON}
  14070. {$R+}
  14071. {$endif}
  14072. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  14073. { unmasked part shifted out? }
  14074. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  14075. begin
  14076. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  14077. RemoveCurrentP(p, hp1);
  14078. Result:=true;
  14079. exit;
  14080. end;
  14081. end;
  14082. A_SHR:
  14083. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14084. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  14085. (taicpu(hp1).oper[0]^.val <= 63) then
  14086. begin
  14087. { Does SHR combined with the AND cover all the bits?
  14088. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  14089. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  14090. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  14091. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  14092. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  14093. begin
  14094. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  14095. RemoveCurrentP(p, hp1);
  14096. Result := True;
  14097. Exit;
  14098. end;
  14099. end;
  14100. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14101. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14102. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14103. begin
  14104. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14105. (
  14106. (
  14107. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14108. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14109. ) or (
  14110. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14111. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14112. {$ifdef x86_64}
  14113. ) or (
  14114. (taicpu(hp1).opsize = S_LQ) and
  14115. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14116. {$endif x86_64}
  14117. )
  14118. ) then
  14119. begin
  14120. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14121. begin
  14122. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14123. RemoveInstruction(hp1);
  14124. { See if there are other optimisations possible }
  14125. Continue;
  14126. end;
  14127. { The super-registers are the same though.
  14128. Note that this change by itself doesn't improve
  14129. code speed, but it opens up other optimisations. }
  14130. {$ifdef x86_64}
  14131. { Convert 64-bit register to 32-bit }
  14132. case taicpu(hp1).opsize of
  14133. S_BQ:
  14134. begin
  14135. taicpu(hp1).opsize := S_BL;
  14136. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14137. end;
  14138. S_WQ:
  14139. begin
  14140. taicpu(hp1).opsize := S_WL;
  14141. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14142. end
  14143. else
  14144. ;
  14145. end;
  14146. {$endif x86_64}
  14147. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14148. taicpu(hp1).opcode := A_MOVZX;
  14149. { See if there are other optimisations possible }
  14150. Continue;
  14151. end;
  14152. end;
  14153. else
  14154. ;
  14155. end;
  14156. end
  14157. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14158. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14159. begin
  14160. {$ifdef x86_64}
  14161. if (taicpu(p).opsize = S_Q) then
  14162. begin
  14163. { Never necessary }
  14164. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14165. RemoveCurrentP(p, hp1);
  14166. Result := True;
  14167. Exit;
  14168. end;
  14169. {$endif x86_64}
  14170. { Forward check to determine necessity of and %reg,%reg }
  14171. TransferUsedRegs(TmpUsedRegs);
  14172. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14173. { Saves on a bunch of dereferences }
  14174. ActiveReg := taicpu(p).oper[1]^.reg;
  14175. case taicpu(hp1).opcode of
  14176. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14177. if (
  14178. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14179. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14180. ) and
  14181. (
  14182. (taicpu(hp1).opcode <> A_MOV) or
  14183. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14184. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14185. ) and
  14186. not (
  14187. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14188. (taicpu(hp1).opcode = A_MOV) and
  14189. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14190. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14191. ) and
  14192. (
  14193. (
  14194. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14195. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14196. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14197. ) or
  14198. (
  14199. {$ifdef x86_64}
  14200. (
  14201. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14202. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14203. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14204. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14205. ) and
  14206. {$endif x86_64}
  14207. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14208. )
  14209. ) then
  14210. begin
  14211. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14212. RemoveCurrentP(p, hp1);
  14213. Result := True;
  14214. Exit;
  14215. end;
  14216. A_ADD,
  14217. A_AND,
  14218. A_BSF,
  14219. A_BSR,
  14220. A_BTC,
  14221. A_BTR,
  14222. A_BTS,
  14223. A_OR,
  14224. A_SUB,
  14225. A_XOR:
  14226. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14227. if (
  14228. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14229. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14230. ) and
  14231. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14232. begin
  14233. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14234. RemoveCurrentP(p, hp1);
  14235. Result := True;
  14236. Exit;
  14237. end;
  14238. A_CMP,
  14239. A_TEST:
  14240. if (
  14241. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14242. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14243. ) and
  14244. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14245. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14246. begin
  14247. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14248. RemoveCurrentP(p, hp1);
  14249. Result := True;
  14250. Exit;
  14251. end;
  14252. A_BSWAP,
  14253. A_NEG,
  14254. A_NOT:
  14255. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14256. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14257. begin
  14258. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14259. RemoveCurrentP(p, hp1);
  14260. Result := True;
  14261. Exit;
  14262. end;
  14263. else
  14264. ;
  14265. end;
  14266. end;
  14267. if (taicpu(hp1).is_jmp) and
  14268. (taicpu(hp1).opcode<>A_JMP) and
  14269. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14270. begin
  14271. { change
  14272. and x, reg
  14273. jxx
  14274. to
  14275. test x, reg
  14276. jxx
  14277. if reg is deallocated before the
  14278. jump, but only if it's a conditional jump (PFV)
  14279. }
  14280. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14281. taicpu(p).opcode := A_TEST;
  14282. Exit;
  14283. end;
  14284. Break;
  14285. end;
  14286. { Lone AND tests }
  14287. if (taicpu(p).oper[0]^.typ = top_const) then
  14288. begin
  14289. {
  14290. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14291. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14292. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14293. }
  14294. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14295. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14296. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14297. begin
  14298. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14299. if taicpu(p).opsize = S_L then
  14300. begin
  14301. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14302. Result := True;
  14303. end;
  14304. end;
  14305. end;
  14306. { Backward check to determine necessity of and %reg,%reg }
  14307. if (taicpu(p).oper[0]^.typ = top_reg) and
  14308. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14309. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14310. GetLastInstruction(p, hp2) and
  14311. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14312. { Check size of adjacent instruction to determine if the AND is
  14313. effectively a null operation }
  14314. (
  14315. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14316. { Note: Don't include S_Q }
  14317. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14318. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14319. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14320. ) then
  14321. begin
  14322. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14323. { If GetNextInstruction returned False, hp1 will be nil }
  14324. RemoveCurrentP(p, hp1);
  14325. Result := True;
  14326. Exit;
  14327. end;
  14328. end;
  14329. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14330. var
  14331. hp1, hp2: tai;
  14332. NewRef: TReference;
  14333. Distance: Cardinal;
  14334. TempTracking: TAllUsedRegs;
  14335. DoAddMov2Lea: Boolean;
  14336. { This entire nested function is used in an if-statement below, but we
  14337. want to avoid all the used reg transfers and GetNextInstruction calls
  14338. until we really have to check }
  14339. function MemRegisterNotUsedLater: Boolean; inline;
  14340. var
  14341. hp2: tai;
  14342. begin
  14343. TransferUsedRegs(TmpUsedRegs);
  14344. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14345. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14346. else
  14347. { p and hp1 will be adjacent }
  14348. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14349. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14350. end;
  14351. begin
  14352. Result := False;
  14353. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14354. (taicpu(p).oper[1]^.typ = top_reg) then
  14355. begin
  14356. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14357. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14358. (hp1.typ <> ait_instruction) or
  14359. not
  14360. (
  14361. (cs_opt_level3 in current_settings.optimizerswitches) or
  14362. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14363. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14364. ) then
  14365. Exit;
  14366. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14367. addq $x, %rax
  14368. movq %rax, %rdx
  14369. sarq $63, %rdx
  14370. (%rax still in use)
  14371. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14372. leaq $x(%rax),%rdx
  14373. addq $x, %rax
  14374. sarq $63, %rdx
  14375. ...which is okay since it breaks the dependency chain between
  14376. addq and movq, but if OptPass2MOV is called first:
  14377. addq $x, %rax
  14378. cqto
  14379. ...which is better in all ways, taking only 2 cycles to execute
  14380. and much smaller in code size.
  14381. }
  14382. { The extra register tracking is quite strenuous }
  14383. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14384. MatchInstruction(hp1, A_MOV, []) then
  14385. begin
  14386. { Update the register tracking to the MOV instruction }
  14387. CopyUsedRegs(TempTracking);
  14388. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14389. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14390. else
  14391. { p and hp1 will be adjacent }
  14392. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14393. hp2 := hp1;
  14394. if OptPass2MOV(hp1) then
  14395. Include(OptsToCheck, aoc_ForceNewIteration);
  14396. { Reset the tracking to the current instruction }
  14397. RestoreUsedRegs(TempTracking);
  14398. ReleaseUsedRegs(TempTracking);
  14399. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14400. OptPass2ADD get called again }
  14401. if (hp1 <> hp2) then
  14402. begin
  14403. Result := True;
  14404. Exit;
  14405. end;
  14406. end;
  14407. { Change:
  14408. add %reg2,%reg1
  14409. (%reg2 not modified in between)
  14410. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14411. To:
  14412. mov/s/z #(%reg1,%reg2),%reg1
  14413. }
  14414. if (taicpu(p).oper[0]^.typ = top_reg) and
  14415. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14416. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14417. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14418. (
  14419. (
  14420. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14421. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14422. { r/esp cannot be an index }
  14423. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14424. ) or (
  14425. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14426. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14427. )
  14428. ) and (
  14429. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14430. (
  14431. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14432. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14433. MemRegisterNotUsedLater
  14434. )
  14435. ) then
  14436. begin
  14437. if (
  14438. { Instructions are guaranteed to be adjacent on -O2 and under }
  14439. (cs_opt_level3 in current_settings.optimizerswitches) and
  14440. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14441. ) then
  14442. begin
  14443. { If the other register is used in between, move the MOV
  14444. instruction to right after the ADD instruction so a
  14445. saving can still be made }
  14446. Asml.Remove(hp1);
  14447. Asml.InsertAfter(hp1, p);
  14448. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14449. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14450. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14451. RemoveCurrentp(p, hp1);
  14452. end
  14453. else
  14454. begin
  14455. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14456. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14457. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14458. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14459. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14460. { hp1 may not be the immediate next instruction under -O3 }
  14461. RemoveCurrentp(p)
  14462. else
  14463. RemoveCurrentp(p, hp1);
  14464. end;
  14465. Result := True;
  14466. Exit;
  14467. end;
  14468. { Change:
  14469. addl/q $x,%reg1
  14470. movl/q %reg1,%reg2
  14471. To:
  14472. leal/q $x(%reg1),%reg2
  14473. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14474. Breaks the dependency chain.
  14475. }
  14476. if (taicpu(p).oper[0]^.typ = top_const) and
  14477. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14478. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14479. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14480. (
  14481. { Instructions are guaranteed to be adjacent on -O2 and under }
  14482. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14483. (
  14484. { If the flags are used, don't make the optimisation,
  14485. otherwise they will be scrambled. Fixes #41148 }
  14486. (
  14487. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14488. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14489. ) and
  14490. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14491. )
  14492. ) then
  14493. begin
  14494. TransferUsedRegs(TmpUsedRegs);
  14495. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14496. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14497. else
  14498. { p and hp1 will be adjacent }
  14499. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14500. if (
  14501. SetAndTest(
  14502. (
  14503. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14504. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14505. ),
  14506. DoAddMov2Lea
  14507. ) or
  14508. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14509. not (cs_opt_size in current_settings.optimizerswitches)
  14510. ) then
  14511. begin
  14512. { Change the MOV instruction to a LEA instruction, and update the
  14513. first operand }
  14514. reference_reset(NewRef, 1, []);
  14515. NewRef.base := taicpu(p).oper[1]^.reg;
  14516. NewRef.scalefactor := 1;
  14517. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14518. taicpu(hp1).opcode := A_LEA;
  14519. taicpu(hp1).loadref(0, NewRef);
  14520. if DoAddMov2Lea then
  14521. begin
  14522. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14523. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14524. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14525. { hp1 may not be the immediate next instruction under -O3 }
  14526. RemoveCurrentp(p)
  14527. else
  14528. RemoveCurrentp(p, hp1);
  14529. end
  14530. else
  14531. begin
  14532. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14533. { Move what is now the LEA instruction to before the ADD instruction }
  14534. Asml.Remove(hp1);
  14535. Asml.InsertBefore(hp1, p);
  14536. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14537. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14538. p := hp1;
  14539. end;
  14540. Result := True;
  14541. end;
  14542. end;
  14543. end;
  14544. end;
  14545. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14546. var
  14547. SubReg: TSubRegister;
  14548. hp1, hp2: tai;
  14549. CallJmp: Boolean;
  14550. begin
  14551. Result := False;
  14552. CallJmp := False;
  14553. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14554. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14555. with taicpu(p).oper[0]^.ref^ do
  14556. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14557. if (offset = 0) then
  14558. begin
  14559. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14560. begin
  14561. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14562. taicpu(p).opcode := A_ADD;
  14563. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14564. Result := True;
  14565. end
  14566. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14567. begin
  14568. if (base <> NR_NO) then
  14569. begin
  14570. if (scalefactor <= 1) then
  14571. begin
  14572. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14573. taicpu(p).opcode := A_ADD;
  14574. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14575. Result := True;
  14576. end;
  14577. end
  14578. else
  14579. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14580. if (scalefactor in [2, 4, 8]) then
  14581. begin
  14582. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14583. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14584. taicpu(p).opcode := A_SHL;
  14585. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14586. Result := True;
  14587. end;
  14588. end;
  14589. end
  14590. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14591. lot of latency, so break off the offset if %reg3 is used soon
  14592. afterwards }
  14593. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14594. { If 3-component addresses don't have additional latency, don't
  14595. perform this optimisation }
  14596. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14597. GetNextInstruction(p, hp1) and
  14598. (hp1.typ = ait_instruction) and
  14599. (
  14600. (
  14601. { Permit jumps and calls since they have a larger degree of overhead }
  14602. (
  14603. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14604. (
  14605. { ... unless the register specifies the location }
  14606. (taicpu(hp1).ops > 0) and
  14607. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14608. )
  14609. ) and
  14610. (
  14611. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14612. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14613. )
  14614. )
  14615. or
  14616. (
  14617. { Check up to two instructions ahead }
  14618. GetNextInstruction(hp1, hp2) and
  14619. (hp2.typ = ait_instruction) and
  14620. (
  14621. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14622. (
  14623. { Same as above }
  14624. (taicpu(hp2).ops > 0) and
  14625. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14626. )
  14627. ) and
  14628. (
  14629. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14630. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14631. )
  14632. )
  14633. ) then
  14634. begin
  14635. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14636. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14637. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14638. offset := 0;
  14639. if Assigned(symbol) or Assigned(relsymbol) then
  14640. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14641. else
  14642. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14643. { Inserting before the next instruction rather than after the
  14644. current instruction gives more accurate register tracking }
  14645. asml.InsertBefore(hp2, hp1);
  14646. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14647. Result := True;
  14648. end;
  14649. end;
  14650. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14651. var
  14652. hp1, hp2: tai;
  14653. NewRef: TReference;
  14654. Distance: Cardinal;
  14655. TempTracking: TAllUsedRegs;
  14656. DoSubMov2Lea: Boolean;
  14657. begin
  14658. Result := False;
  14659. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14660. MatchOpType(taicpu(p),top_const,top_reg) then
  14661. begin
  14662. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14663. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14664. (hp1.typ <> ait_instruction) or
  14665. not
  14666. (
  14667. (cs_opt_level3 in current_settings.optimizerswitches) or
  14668. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14669. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14670. ) then
  14671. Exit;
  14672. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14673. subq $x, %rax
  14674. movq %rax, %rdx
  14675. sarq $63, %rdx
  14676. (%rax still in use)
  14677. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14678. leaq $-x(%rax),%rdx
  14679. movq $x, %rax
  14680. sarq $63, %rdx
  14681. ...which is okay since it breaks the dependency chain between
  14682. subq and movq, but if OptPass2MOV is called first:
  14683. subq $x, %rax
  14684. cqto
  14685. ...which is better in all ways, taking only 2 cycles to execute
  14686. and much smaller in code size.
  14687. }
  14688. { The extra register tracking is quite strenuous }
  14689. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14690. MatchInstruction(hp1, A_MOV, []) then
  14691. begin
  14692. { Update the register tracking to the MOV instruction }
  14693. CopyUsedRegs(TempTracking);
  14694. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14695. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14696. else
  14697. { p and hp1 will be adjacent }
  14698. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14699. hp2 := hp1;
  14700. if OptPass2MOV(hp1) then
  14701. Include(OptsToCheck, aoc_ForceNewIteration);
  14702. { Reset the tracking to the current instruction }
  14703. RestoreUsedRegs(TempTracking);
  14704. ReleaseUsedRegs(TempTracking);
  14705. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14706. OptPass2SUB get called again }
  14707. if (hp1 <> hp2) then
  14708. begin
  14709. Result := True;
  14710. Exit;
  14711. end;
  14712. end;
  14713. { Change:
  14714. subl/q $x,%reg1
  14715. movl/q %reg1,%reg2
  14716. To:
  14717. leal/q $-x(%reg1),%reg2
  14718. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14719. Breaks the dependency chain and potentially permits the removal of
  14720. a CMP instruction if one follows.
  14721. }
  14722. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14723. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14724. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14725. (
  14726. { Instructions are guaranteed to be adjacent on -O2 and under }
  14727. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14728. (
  14729. { If the flags are used, don't make the optimisation,
  14730. otherwise they will be scrambled. Fixes #41148 }
  14731. (
  14732. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14733. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14734. ) and
  14735. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14736. )
  14737. ) then
  14738. begin
  14739. TransferUsedRegs(TmpUsedRegs);
  14740. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14741. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14742. else
  14743. { p and hp1 will be adjacent }
  14744. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14745. if (
  14746. SetAndTest(
  14747. (
  14748. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14749. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14750. ),
  14751. DoSubMov2Lea
  14752. ) or
  14753. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14754. not (cs_opt_size in current_settings.optimizerswitches)
  14755. ) then
  14756. begin
  14757. { Change the MOV instruction to a LEA instruction, and update the
  14758. first operand }
  14759. reference_reset(NewRef, 1, []);
  14760. NewRef.base := taicpu(p).oper[1]^.reg;
  14761. NewRef.scalefactor := 1;
  14762. NewRef.offset := -taicpu(p).oper[0]^.val;
  14763. taicpu(hp1).opcode := A_LEA;
  14764. taicpu(hp1).loadref(0, NewRef);
  14765. if DoSubMov2Lea then
  14766. begin
  14767. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14768. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14769. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14770. { hp1 may not be the immediate next instruction under -O3 }
  14771. RemoveCurrentp(p)
  14772. else
  14773. RemoveCurrentp(p, hp1);
  14774. end
  14775. else
  14776. begin
  14777. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14778. { Move what is now the LEA instruction to before the SUB instruction }
  14779. Asml.Remove(hp1);
  14780. Asml.InsertBefore(hp1, p);
  14781. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14782. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14783. p := hp1;
  14784. end;
  14785. Result := True;
  14786. end;
  14787. end;
  14788. end;
  14789. end;
  14790. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14791. begin
  14792. { we can skip all instructions not messing with the stack pointer }
  14793. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14794. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14795. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14796. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14797. ({(taicpu(hp1).ops=0) or }
  14798. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14799. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14800. ) and }
  14801. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14802. )
  14803. ) do
  14804. GetNextInstruction(hp1,hp1);
  14805. Result:=assigned(hp1);
  14806. end;
  14807. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14808. var
  14809. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14810. begin
  14811. Result:=false;
  14812. hp5:=nil;
  14813. hp6:=nil;
  14814. hp7:=nil;
  14815. hp8:=nil;
  14816. { replace
  14817. leal(q) x(<stackpointer>),<stackpointer>
  14818. <optional .seh_stackalloc ...>
  14819. <optional .seh_endprologue ...>
  14820. call procname
  14821. <optional NOP>
  14822. leal(q) -x(<stackpointer>),<stackpointer>
  14823. <optional VZEROUPPER>
  14824. ret
  14825. by
  14826. jmp procname
  14827. but do it only on level 4 because it destroys stack back traces
  14828. }
  14829. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14830. MatchOpType(taicpu(p),top_ref,top_reg) and
  14831. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14832. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14833. { the -8, -24, -40 are not required, but bail out early if possible,
  14834. higher values are unlikely }
  14835. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14836. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14837. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14838. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14839. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14840. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14841. GetNextInstruction(p, hp1) and
  14842. { Take a copy of hp1 }
  14843. SetAndTest(hp1, hp4) and
  14844. { trick to skip label }
  14845. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14846. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14847. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14848. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14849. SkipSimpleInstructions(hp1) and
  14850. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14851. GetNextInstruction(hp1, hp2) and
  14852. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14853. { skip nop instruction on win64 }
  14854. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14855. SetAndTest(hp2,hp6) and
  14856. GetNextInstruction(hp2,hp2) and
  14857. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14858. ) and
  14859. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14860. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14861. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14862. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14863. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14864. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14865. { Segment register will be NR_NO }
  14866. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14867. GetNextInstruction(hp2, hp3) and
  14868. { trick to skip label }
  14869. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14870. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14871. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14872. SetAndTest(hp3,hp5) and
  14873. GetNextInstruction(hp3,hp3) and
  14874. MatchInstruction(hp3,A_RET,[S_NO])
  14875. )
  14876. ) and
  14877. (taicpu(hp3).ops=0) then
  14878. begin
  14879. taicpu(hp1).opcode := A_JMP;
  14880. taicpu(hp1).is_jmp := true;
  14881. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14882. { search for the stackalloc directive and remove it }
  14883. hp7:=tai(p.next);
  14884. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14885. begin
  14886. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14887. begin
  14888. { sanity check }
  14889. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14890. Internalerror(2024012201);
  14891. hp8:=tai(hp7.next);
  14892. RemoveInstruction(tai(hp7));
  14893. hp7:=hp8;
  14894. break;
  14895. end
  14896. else
  14897. hp7:=tai(hp7.next);
  14898. end;
  14899. RemoveCurrentP(p, hp4);
  14900. RemoveInstruction(hp2);
  14901. RemoveInstruction(hp3);
  14902. { if there is a vzeroupper instruction then move it before the jmp }
  14903. if Assigned(hp5) then
  14904. begin
  14905. AsmL.Remove(hp5);
  14906. ASmL.InsertBefore(hp5,hp1)
  14907. end;
  14908. { remove nop on win64 }
  14909. if Assigned(hp6) then
  14910. RemoveInstruction(hp6);
  14911. Result:=true;
  14912. end;
  14913. end;
  14914. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14915. {$ifdef x86_64}
  14916. var
  14917. hp1, hp2, hp3, hp4, hp5: tai;
  14918. {$endif x86_64}
  14919. begin
  14920. Result:=false;
  14921. {$ifdef x86_64}
  14922. hp5:=nil;
  14923. { replace
  14924. push %rax
  14925. call procname
  14926. pop %rcx
  14927. ret
  14928. by
  14929. jmp procname
  14930. but do it only on level 4 because it destroys stack back traces
  14931. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14932. for all supported calling conventions
  14933. }
  14934. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14935. MatchOpType(taicpu(p),top_reg) and
  14936. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14937. GetNextInstruction(p, hp1) and
  14938. { Take a copy of hp1 }
  14939. SetAndTest(hp1, hp4) and
  14940. { trick to skip label }
  14941. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14942. SkipSimpleInstructions(hp1) and
  14943. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14944. GetNextInstruction(hp1, hp2) and
  14945. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14946. MatchOpType(taicpu(hp2),top_reg) and
  14947. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14948. GetNextInstruction(hp2, hp3) and
  14949. { trick to skip label }
  14950. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14951. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14952. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14953. SetAndTest(hp3,hp5) and
  14954. GetNextInstruction(hp3,hp3) and
  14955. MatchInstruction(hp3,A_RET,[S_NO])
  14956. )
  14957. ) and
  14958. (taicpu(hp3).ops=0) then
  14959. begin
  14960. taicpu(hp1).opcode := A_JMP;
  14961. taicpu(hp1).is_jmp := true;
  14962. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14963. RemoveCurrentP(p, hp4);
  14964. RemoveInstruction(hp2);
  14965. RemoveInstruction(hp3);
  14966. if Assigned(hp5) then
  14967. begin
  14968. AsmL.Remove(hp5);
  14969. ASmL.InsertBefore(hp5,hp1)
  14970. end;
  14971. Result:=true;
  14972. end;
  14973. {$endif x86_64}
  14974. end;
  14975. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14976. var
  14977. Value, RegName: string;
  14978. hp1: tai;
  14979. begin
  14980. Result:=false;
  14981. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14982. begin
  14983. case taicpu(p).oper[0]^.val of
  14984. 0:
  14985. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14986. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14987. (
  14988. { See if we can still convert the instruction }
  14989. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14990. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14991. ) then
  14992. begin
  14993. { change "mov $0,%reg" into "xor %reg,%reg" }
  14994. taicpu(p).opcode := A_XOR;
  14995. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14996. Result := True;
  14997. {$ifdef x86_64}
  14998. end
  14999. else if (taicpu(p).opsize = S_Q) then
  15000. begin
  15001. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15002. { The actual optimization }
  15003. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15004. taicpu(p).changeopsize(S_L);
  15005. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15006. Result := True;
  15007. end;
  15008. $1..$FFFFFFFF:
  15009. begin
  15010. { Code size reduction by J. Gareth "Kit" Moreton }
  15011. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  15012. case taicpu(p).opsize of
  15013. S_Q:
  15014. begin
  15015. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15016. Value := debug_tostr(taicpu(p).oper[0]^.val);
  15017. { The actual optimization }
  15018. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15019. taicpu(p).changeopsize(S_L);
  15020. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15021. Result := True;
  15022. end;
  15023. else
  15024. { Do nothing };
  15025. end;
  15026. {$endif x86_64}
  15027. end;
  15028. -1:
  15029. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  15030. if (cs_opt_size in current_settings.optimizerswitches) and
  15031. (taicpu(p).opsize <> S_B) and
  15032. (
  15033. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15034. (
  15035. { See if we can still convert the instruction }
  15036. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15037. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15038. )
  15039. ) then
  15040. begin
  15041. { change "mov $-1,%reg" into "or $-1,%reg" }
  15042. { NOTES:
  15043. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  15044. - This operation creates a false dependency on the register, so only do it when optimising for size
  15045. - 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
  15046. }
  15047. taicpu(p).opcode := A_OR;
  15048. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  15049. Result := True;
  15050. end;
  15051. else
  15052. { Do nothing };
  15053. end;
  15054. end;
  15055. end;
  15056. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  15057. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  15058. begin
  15059. Result := False;
  15060. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  15061. Exit;
  15062. { For sizes less than S_L, the byte size is equal or larger with BTx,
  15063. so don't bother optimising }
  15064. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  15065. Exit;
  15066. if (taicpu(p).oper[0]^.typ <> top_const) or
  15067. { If the value can fit into an 8-bit signed integer, a smaller
  15068. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  15069. falls within this range }
  15070. (
  15071. (taicpu(p).oper[0]^.val > -128) and
  15072. (taicpu(p).oper[0]^.val <= 127)
  15073. ) then
  15074. Exit;
  15075. { If we're optimising for size, this is acceptable }
  15076. if (cs_opt_size in current_settings.optimizerswitches) then
  15077. Exit(True);
  15078. if (taicpu(p).oper[1]^.typ = top_reg) and
  15079. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15080. Exit(True);
  15081. if (taicpu(p).oper[1]^.typ <> top_reg) and
  15082. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15083. Exit(True);
  15084. end;
  15085. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  15086. var
  15087. hp1: tai;
  15088. Value: TCGInt;
  15089. begin
  15090. Result := False;
  15091. if MatchOpType(taicpu(p), top_const, top_reg) then
  15092. begin
  15093. { Detect:
  15094. andw x, %ax (0 <= x < $8000)
  15095. ...
  15096. movzwl %ax,%eax
  15097. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15098. }
  15099. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15100. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15101. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15102. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15103. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15104. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15105. begin
  15106. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15107. taicpu(hp1).opcode := A_CWDE;
  15108. taicpu(hp1).clearop(0);
  15109. taicpu(hp1).clearop(1);
  15110. taicpu(hp1).ops := 0;
  15111. { A change was made, but not with p, so don't set Result, but
  15112. notify the compiler that a change was made }
  15113. Include(OptsToCheck, aoc_ForceNewIteration);
  15114. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15115. end;
  15116. end;
  15117. { If "not x" is a power of 2 (popcnt = 1), change:
  15118. and $x, %reg/ref
  15119. To:
  15120. btr lb(x), %reg/ref
  15121. }
  15122. if IsBTXAcceptable(p) and
  15123. (
  15124. { Make sure a TEST doesn't follow that plays with the register }
  15125. not GetNextInstruction(p, hp1) or
  15126. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15127. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15128. ) then
  15129. begin
  15130. {$push}{$R-}{$Q-}
  15131. { Value is a sign-extended 32-bit integer - just correct it
  15132. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15133. checks to see if this operand is an immediate. }
  15134. Value := not taicpu(p).oper[0]^.val;
  15135. {$pop}
  15136. {$ifdef x86_64}
  15137. if taicpu(p).opsize = S_L then
  15138. {$endif x86_64}
  15139. Value := Value and $FFFFFFFF;
  15140. if (PopCnt(QWord(Value)) = 1) then
  15141. begin
  15142. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15143. taicpu(p).opcode := A_BTR;
  15144. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15145. Result := True;
  15146. Exit;
  15147. end;
  15148. end;
  15149. end;
  15150. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15151. begin
  15152. Result := False;
  15153. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15154. Exit;
  15155. { Convert:
  15156. movswl %ax,%eax -> cwtl
  15157. movslq %eax,%rax -> cdqe
  15158. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15159. refer to the same opcode and depends only on the assembler's
  15160. current operand-size attribute. [Kit]
  15161. }
  15162. with taicpu(p) do
  15163. case opsize of
  15164. S_WL:
  15165. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15166. begin
  15167. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15168. opcode := A_CWDE;
  15169. clearop(0);
  15170. clearop(1);
  15171. ops := 0;
  15172. Result := True;
  15173. end;
  15174. {$ifdef x86_64}
  15175. S_LQ:
  15176. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15177. begin
  15178. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15179. opcode := A_CDQE;
  15180. clearop(0);
  15181. clearop(1);
  15182. ops := 0;
  15183. Result := True;
  15184. end;
  15185. {$endif x86_64}
  15186. else
  15187. ;
  15188. end;
  15189. end;
  15190. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15191. var
  15192. hp1: tai;
  15193. begin
  15194. Result := False;
  15195. { All these optimisations work on "shr const,%reg" }
  15196. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15197. Exit;
  15198. if HandleSHRMerge(p, True) then
  15199. begin
  15200. Result := True;
  15201. Exit;
  15202. end;
  15203. { Detect the following (looking backwards):
  15204. shr %cl,%reg
  15205. shr x, %reg
  15206. Swap the two SHR instructions to minimise a pipeline stall.
  15207. }
  15208. if GetLastInstruction(p, hp1) and
  15209. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15210. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15211. { First operand will be %cl }
  15212. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15213. { Just to be sure }
  15214. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15215. begin
  15216. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15217. { Moving the entries this way ensures the register tracking remains correct }
  15218. Asml.Remove(p);
  15219. Asml.InsertBefore(p, hp1);
  15220. p := hp1;
  15221. { Don't set Result to True because the current instruction is now
  15222. "shr %cl,%reg" and there's nothing more we can do with it }
  15223. end;
  15224. end;
  15225. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15226. var
  15227. hp1, hp2: tai;
  15228. Opposite, SecondOpposite: TAsmOp;
  15229. NewCond: TAsmCond;
  15230. begin
  15231. Result := False;
  15232. { Change:
  15233. add/sub 128,(dest)
  15234. To:
  15235. sub/add -128,(dest)
  15236. This generaally takes fewer bytes to encode because -128 can be stored
  15237. in a signed byte, whereas +128 cannot.
  15238. }
  15239. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15240. begin
  15241. if taicpu(p).opcode = A_ADD then
  15242. Opposite := A_SUB
  15243. else
  15244. Opposite := A_ADD;
  15245. { Be careful if the flags are in use, because the CF flag inverts
  15246. when changing from ADD to SUB and vice versa }
  15247. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15248. GetNextInstruction(p, hp1) then
  15249. begin
  15250. TransferUsedRegs(TmpUsedRegs);
  15251. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15252. hp2 := hp1;
  15253. { Scan ahead to check if everything's safe }
  15254. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15255. begin
  15256. if (hp1.typ <> ait_instruction) then
  15257. { Probably unsafe since the flags are still in use }
  15258. Exit;
  15259. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15260. { Stop searching at an unconditional jump }
  15261. Break;
  15262. if not
  15263. (
  15264. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15265. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15266. ) and
  15267. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15268. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15269. Exit;
  15270. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15271. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15272. { Move to the next instruction }
  15273. GetNextInstruction(hp1, hp1);
  15274. end;
  15275. while Assigned(hp2) and (hp2 <> hp1) do
  15276. begin
  15277. NewCond := C_None;
  15278. case taicpu(hp2).condition of
  15279. C_A, C_NBE:
  15280. NewCond := C_BE;
  15281. C_B, C_C, C_NAE:
  15282. NewCond := C_AE;
  15283. C_AE, C_NB, C_NC:
  15284. NewCond := C_B;
  15285. C_BE, C_NA:
  15286. NewCond := C_A;
  15287. else
  15288. { No change needed };
  15289. end;
  15290. if NewCond <> C_None then
  15291. begin
  15292. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15293. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15294. taicpu(hp2).condition := NewCond;
  15295. end
  15296. else
  15297. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15298. begin
  15299. { Because of the flipping of the carry bit, to ensure
  15300. the operation remains equivalent, ADC becomes SBB
  15301. and vice versa, and the constant is not-inverted.
  15302. If multiple ADCs or SBBs appear in a row, each one
  15303. changed causes the carry bit to invert, so they all
  15304. need to be flipped }
  15305. if taicpu(hp2).opcode = A_ADC then
  15306. SecondOpposite := A_SBB
  15307. else
  15308. SecondOpposite := A_ADC;
  15309. if taicpu(hp2).oper[0]^.typ <> top_const then
  15310. { Should have broken out of this optimisation already }
  15311. InternalError(2021112901);
  15312. 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]^) + ' -> ' +
  15313. 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);
  15314. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15315. taicpu(hp2).opcode := SecondOpposite;
  15316. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15317. end;
  15318. { Move to the next instruction }
  15319. GetNextInstruction(hp2, hp2);
  15320. end;
  15321. if (hp2 <> hp1) then
  15322. InternalError(2021111501);
  15323. end;
  15324. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15325. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15326. taicpu(p).opcode := Opposite;
  15327. taicpu(p).oper[0]^.val := -128;
  15328. { No further optimisations can be made on this instruction, so move
  15329. onto the next one to save time }
  15330. p := tai(p.Next);
  15331. UpdateUsedRegs(p);
  15332. Result := True;
  15333. Exit;
  15334. end;
  15335. { Detect:
  15336. add/sub %reg2,(dest)
  15337. add/sub x, (dest)
  15338. (dest can be a register or a reference)
  15339. Swap the instructions to minimise a pipeline stall. This reverses the
  15340. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15341. optimisations could be made.
  15342. }
  15343. if (taicpu(p).oper[0]^.typ = top_reg) and
  15344. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15345. (
  15346. (
  15347. (taicpu(p).oper[1]^.typ = top_reg) and
  15348. { We can try searching further ahead if we're writing to a register }
  15349. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15350. ) or
  15351. (
  15352. (taicpu(p).oper[1]^.typ = top_ref) and
  15353. GetNextInstruction(p, hp1)
  15354. )
  15355. ) and
  15356. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15357. (taicpu(hp1).oper[0]^.typ = top_const) and
  15358. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15359. begin
  15360. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15361. TransferUsedRegs(TmpUsedRegs);
  15362. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15363. hp2 := p;
  15364. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15365. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15366. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15367. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15368. begin
  15369. asml.remove(hp1);
  15370. asml.InsertBefore(hp1, p);
  15371. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15372. Result := True;
  15373. end;
  15374. end;
  15375. end;
  15376. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15377. var
  15378. hp1: tai;
  15379. begin
  15380. Result:=false;
  15381. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15382. while GetNextInstruction(p, hp1) and
  15383. TrySwapMovCmp(p, hp1) do
  15384. begin
  15385. if MatchInstruction(hp1, A_MOV, []) then
  15386. begin
  15387. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15388. begin
  15389. { A little hacky, but since CMP doesn't read the flags, only
  15390. modify them, it's safe if they get scrambled by MOV -> XOR }
  15391. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15392. Result := PostPeepholeOptMov(hp1);
  15393. {$ifdef x86_64}
  15394. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15395. { Used to shrink instruction size }
  15396. PostPeepholeOptXor(hp1);
  15397. {$endif x86_64}
  15398. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15399. end
  15400. else
  15401. begin
  15402. Result := PostPeepholeOptMov(hp1);
  15403. {$ifdef x86_64}
  15404. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15405. { Used to shrink instruction size }
  15406. PostPeepholeOptXor(hp1);
  15407. {$endif x86_64}
  15408. end;
  15409. end;
  15410. { Enabling this flag is actually a null operation, but it marks
  15411. the code as 'modified' during this pass }
  15412. Include(OptsToCheck, aoc_ForceNewIteration);
  15413. end;
  15414. { change "cmp $0, %reg" to "test %reg, %reg" }
  15415. if MatchOpType(taicpu(p),top_const,top_reg) and
  15416. (taicpu(p).oper[0]^.val = 0) then
  15417. begin
  15418. taicpu(p).opcode := A_TEST;
  15419. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15420. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15421. Result:=true;
  15422. end;
  15423. end;
  15424. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15425. var
  15426. IsTestConstX, IsValid : Boolean;
  15427. hp1,hp2 : tai;
  15428. begin
  15429. Result:=false;
  15430. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15431. if (taicpu(p).opcode = A_TEST) then
  15432. while GetNextInstruction(p, hp1) and
  15433. TrySwapMovCmp(p, hp1) do
  15434. begin
  15435. if MatchInstruction(hp1, A_MOV, []) then
  15436. begin
  15437. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15438. begin
  15439. { A little hacky, but since TEST doesn't read the flags, only
  15440. modify them, it's safe if they get scrambled by MOV -> XOR }
  15441. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15442. Result := PostPeepholeOptMov(hp1);
  15443. {$ifdef x86_64}
  15444. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15445. { Used to shrink instruction size }
  15446. PostPeepholeOptXor(hp1);
  15447. {$endif x86_64}
  15448. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15449. end
  15450. else
  15451. begin
  15452. Result := PostPeepholeOptMov(hp1);
  15453. {$ifdef x86_64}
  15454. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15455. { Used to shrink instruction size }
  15456. PostPeepholeOptXor(hp1);
  15457. {$endif x86_64}
  15458. end;
  15459. end;
  15460. { Enabling this flag is actually a null operation, but it marks
  15461. the code as 'modified' during this pass }
  15462. Include(OptsToCheck, aoc_ForceNewIteration);
  15463. end;
  15464. { If x is a power of 2 (popcnt = 1), change:
  15465. or $x, %reg/ref
  15466. To:
  15467. bts lb(x), %reg/ref
  15468. }
  15469. if (taicpu(p).opcode = A_OR) and
  15470. IsBTXAcceptable(p) and
  15471. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15472. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15473. (
  15474. { Don't optimise if a test instruction follows }
  15475. not GetNextInstruction(p, hp1) or
  15476. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15477. ) then
  15478. begin
  15479. 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);
  15480. taicpu(p).opcode := A_BTS;
  15481. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15482. Result := True;
  15483. Exit;
  15484. end;
  15485. { If x is a power of 2 (popcnt = 1), change:
  15486. test $x, %reg/ref
  15487. je / sete / cmove (or jne / setne)
  15488. To:
  15489. bt lb(x), %reg/ref
  15490. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15491. }
  15492. if (taicpu(p).opcode = A_TEST) and
  15493. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15494. (taicpu(p).oper[0]^.typ = top_const) and
  15495. (
  15496. (cs_opt_size in current_settings.optimizerswitches) or
  15497. (
  15498. (taicpu(p).oper[1]^.typ = top_reg) and
  15499. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15500. ) or
  15501. (
  15502. (taicpu(p).oper[1]^.typ <> top_reg) and
  15503. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15504. )
  15505. ) and
  15506. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15507. { For sizes less than S_L, the byte size is equal or larger with BT,
  15508. so don't bother optimising }
  15509. (taicpu(p).opsize >= S_L) then
  15510. begin
  15511. IsValid := True;
  15512. { Check the next set of instructions, watching the FLAGS register
  15513. and the conditions used }
  15514. TransferUsedRegs(TmpUsedRegs);
  15515. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15516. hp1 := p;
  15517. hp2 := nil;
  15518. while GetNextInstruction(hp1, hp1) do
  15519. begin
  15520. if not Assigned(hp2) then
  15521. { The first instruction after TEST }
  15522. hp2 := hp1;
  15523. if (hp1.typ <> ait_instruction) then
  15524. begin
  15525. { If the flags are no longer in use, everything is fine }
  15526. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15527. IsValid := False;
  15528. Break;
  15529. end;
  15530. case taicpu(hp1).condition of
  15531. C_None:
  15532. begin
  15533. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15534. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15535. { Something is not quite normal, so play safe and don't change }
  15536. IsValid := False;
  15537. Break;
  15538. end;
  15539. C_E, C_Z, C_NE, C_NZ:
  15540. { This is fine };
  15541. else
  15542. begin
  15543. { Unsupported condition }
  15544. IsValid := False;
  15545. Break;
  15546. end;
  15547. end;
  15548. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15549. end;
  15550. if IsValid then
  15551. begin
  15552. while hp2 <> hp1 do
  15553. begin
  15554. case taicpu(hp2).condition of
  15555. C_Z, C_E:
  15556. taicpu(hp2).condition := C_NC;
  15557. C_NZ, C_NE:
  15558. taicpu(hp2).condition := C_C;
  15559. else
  15560. { Should not get this by this point }
  15561. InternalError(2022110701);
  15562. end;
  15563. GetNextInstruction(hp2, hp2);
  15564. end;
  15565. 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);
  15566. taicpu(p).opcode := A_BT;
  15567. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15568. Result := True;
  15569. Exit;
  15570. end;
  15571. end;
  15572. { removes the line marked with (x) from the sequence
  15573. and/or/xor/add/sub/... $x, %y
  15574. test/or %y, %y | test $-1, %y (x)
  15575. j(n)z _Label
  15576. as the first instruction already adjusts the ZF
  15577. %y operand may also be a reference }
  15578. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15579. MatchOperand(taicpu(p).oper[0]^,-1);
  15580. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15581. GetLastInstruction(p, hp1) and
  15582. (tai(hp1).typ = ait_instruction) and
  15583. GetNextInstruction(p,hp2) and
  15584. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15585. case taicpu(hp1).opcode Of
  15586. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15587. { These two instructions set the zero flag if the result is zero }
  15588. A_POPCNT, A_LZCNT:
  15589. begin
  15590. if (
  15591. { With POPCNT, an input of zero will set the zero flag
  15592. because the population count of zero is zero }
  15593. (taicpu(hp1).opcode = A_POPCNT) and
  15594. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15595. (
  15596. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15597. { Faster than going through the second half of the 'or'
  15598. condition below }
  15599. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15600. )
  15601. ) or (
  15602. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15603. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15604. { and in case of carry for A(E)/B(E)/C/NC }
  15605. (
  15606. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15607. (
  15608. (taicpu(hp1).opcode <> A_ADD) and
  15609. (taicpu(hp1).opcode <> A_SUB) and
  15610. (taicpu(hp1).opcode <> A_LZCNT)
  15611. )
  15612. )
  15613. ) then
  15614. begin
  15615. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15616. RemoveCurrentP(p, hp2);
  15617. Result:=true;
  15618. Exit;
  15619. end;
  15620. end;
  15621. A_SHL, A_SAL, A_SHR, A_SAR:
  15622. begin
  15623. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15624. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15625. { therefore, it's only safe to do this optimization for }
  15626. { shifts by a (nonzero) constant }
  15627. (taicpu(hp1).oper[0]^.typ = top_const) and
  15628. (taicpu(hp1).oper[0]^.val <> 0) and
  15629. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15630. { and in case of carry for A(E)/B(E)/C/NC }
  15631. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15632. begin
  15633. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15634. RemoveCurrentP(p, hp2);
  15635. Result:=true;
  15636. Exit;
  15637. end;
  15638. end;
  15639. A_DEC, A_INC, A_NEG:
  15640. begin
  15641. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15642. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15643. { and in case of carry for A(E)/B(E)/C/NC }
  15644. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15645. begin
  15646. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15647. RemoveCurrentP(p, hp2);
  15648. Result:=true;
  15649. Exit;
  15650. end;
  15651. end;
  15652. A_ANDN, A_BZHI:
  15653. begin
  15654. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15655. { Only the zero and sign flags are consistent with what the result is }
  15656. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15657. begin
  15658. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15659. RemoveCurrentP(p, hp2);
  15660. Result:=true;
  15661. Exit;
  15662. end;
  15663. end;
  15664. A_BEXTR:
  15665. begin
  15666. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15667. { Only the zero flag is set }
  15668. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15669. begin
  15670. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15671. RemoveCurrentP(p, hp2);
  15672. Result:=true;
  15673. Exit;
  15674. end;
  15675. end;
  15676. else
  15677. ;
  15678. end; { case }
  15679. { change "test $-1,%reg" into "test %reg,%reg" }
  15680. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15681. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15682. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15683. if MatchInstruction(p, A_OR, []) and
  15684. { Can only match if they're both registers }
  15685. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15686. begin
  15687. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15688. taicpu(p).opcode := A_TEST;
  15689. { No need to set Result to True, as we've done all the optimisations we can }
  15690. end;
  15691. end;
  15692. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15693. var
  15694. hp1,hp3 : tai;
  15695. {$ifndef x86_64}
  15696. hp2 : taicpu;
  15697. {$endif x86_64}
  15698. begin
  15699. Result:=false;
  15700. hp3:=nil;
  15701. {$ifndef x86_64}
  15702. { don't do this on modern CPUs, this really hurts them due to
  15703. broken call/ret pairing }
  15704. if (current_settings.optimizecputype < cpu_Pentium2) and
  15705. not(cs_create_pic in current_settings.moduleswitches) and
  15706. GetNextInstruction(p, hp1) and
  15707. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15708. MatchOpType(taicpu(hp1),top_ref) and
  15709. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15710. begin
  15711. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15712. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15713. InsertLLItem(p.previous, p, hp2);
  15714. taicpu(p).opcode := A_JMP;
  15715. taicpu(p).is_jmp := true;
  15716. RemoveInstruction(hp1);
  15717. Result:=true;
  15718. end
  15719. else
  15720. {$endif x86_64}
  15721. { replace
  15722. call procname
  15723. ret
  15724. by
  15725. jmp procname
  15726. but do it only on level 4 because it destroys stack back traces
  15727. else if the subroutine is marked as no return, remove the ret
  15728. }
  15729. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15730. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15731. GetNextInstruction(p, hp1) and
  15732. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15733. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15734. SetAndTest(hp1,hp3) and
  15735. GetNextInstruction(hp1,hp1) and
  15736. MatchInstruction(hp1,A_RET,[S_NO])
  15737. )
  15738. ) and
  15739. (taicpu(hp1).ops=0) then
  15740. begin
  15741. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15742. { we might destroy stack alignment here if we do not do a call }
  15743. (target_info.stackalign<=sizeof(SizeUInt)) then
  15744. begin
  15745. taicpu(p).opcode := A_JMP;
  15746. taicpu(p).is_jmp := true;
  15747. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15748. end
  15749. else
  15750. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15751. RemoveInstruction(hp1);
  15752. if Assigned(hp3) then
  15753. begin
  15754. AsmL.Remove(hp3);
  15755. AsmL.InsertBefore(hp3,p)
  15756. end;
  15757. Result:=true;
  15758. end;
  15759. end;
  15760. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15761. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15762. begin
  15763. case OpSize of
  15764. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15765. Result := (Val <= $FF) and (Val >= -128);
  15766. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15767. Result := (Val <= $FFFF) and (Val >= -32768);
  15768. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15769. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15770. else
  15771. Result := True;
  15772. end;
  15773. end;
  15774. var
  15775. hp1, hp2 : tai;
  15776. SizeChange: Boolean;
  15777. PreMessage: string;
  15778. begin
  15779. Result := False;
  15780. if (taicpu(p).oper[0]^.typ = top_reg) and
  15781. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15782. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15783. begin
  15784. { Change (using movzbl %al,%eax as an example):
  15785. movzbl %al, %eax movzbl %al, %eax
  15786. cmpl x, %eax testl %eax,%eax
  15787. To:
  15788. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15789. movzbl %al, %eax movzbl %al, %eax
  15790. Smaller instruction and minimises pipeline stall as the CPU
  15791. doesn't have to wait for the register to get zero-extended. [Kit]
  15792. Also allow if the smaller of the two registers is being checked,
  15793. as this still removes the false dependency.
  15794. }
  15795. if
  15796. (
  15797. (
  15798. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15799. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15800. ) or (
  15801. { If MatchOperand returns True, they must both be registers }
  15802. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15803. )
  15804. ) and
  15805. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15806. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15807. begin
  15808. 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);
  15809. asml.Remove(hp1);
  15810. asml.InsertBefore(hp1, p);
  15811. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15812. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15813. begin
  15814. taicpu(hp1).opcode := A_TEST;
  15815. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15816. end;
  15817. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15818. case taicpu(p).opsize of
  15819. S_BW, S_BL:
  15820. begin
  15821. SizeChange := taicpu(hp1).opsize <> S_B;
  15822. taicpu(hp1).changeopsize(S_B);
  15823. end;
  15824. S_WL:
  15825. begin
  15826. SizeChange := taicpu(hp1).opsize <> S_W;
  15827. taicpu(hp1).changeopsize(S_W);
  15828. end
  15829. else
  15830. InternalError(2020112701);
  15831. end;
  15832. UpdateUsedRegs(tai(p.Next));
  15833. { Check if the register is used aferwards - if not, we can
  15834. remove the movzx instruction completely }
  15835. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15836. begin
  15837. { Hp1 is a better position than p for debugging purposes }
  15838. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15839. RemoveCurrentp(p, hp1);
  15840. Result := True;
  15841. end;
  15842. if SizeChange then
  15843. DebugMsg(SPeepholeOptimization + PreMessage +
  15844. 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)
  15845. else
  15846. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15847. Exit;
  15848. end;
  15849. { Change (using movzwl %ax,%eax as an example):
  15850. movzwl %ax, %eax
  15851. movb %al, (dest) (Register is smaller than read register in movz)
  15852. To:
  15853. movb %al, (dest) (Move one back to avoid a false dependency)
  15854. movzwl %ax, %eax
  15855. }
  15856. if (taicpu(hp1).opcode = A_MOV) and
  15857. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15858. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15859. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15860. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15861. begin
  15862. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15863. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15864. asml.Remove(hp1);
  15865. asml.InsertBefore(hp1, p);
  15866. if taicpu(hp1).oper[1]^.typ = top_reg then
  15867. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15868. { Check if the register is used aferwards - if not, we can
  15869. remove the movzx instruction completely }
  15870. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15871. begin
  15872. { Hp1 is a better position than p for debugging purposes }
  15873. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15874. RemoveCurrentp(p, hp1);
  15875. Result := True;
  15876. end;
  15877. Exit;
  15878. end;
  15879. end;
  15880. end;
  15881. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15882. var
  15883. hp1: tai;
  15884. {$ifdef x86_64}
  15885. PreMessage, RegName: string;
  15886. {$endif x86_64}
  15887. begin
  15888. Result := False;
  15889. { If x is a power of 2 (popcnt = 1), change:
  15890. xor $x, %reg/ref
  15891. To:
  15892. btc lb(x), %reg/ref
  15893. }
  15894. if IsBTXAcceptable(p) and
  15895. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15896. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15897. (
  15898. { Don't optimise if a test instruction follows }
  15899. not GetNextInstruction(p, hp1) or
  15900. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15901. ) then
  15902. begin
  15903. 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);
  15904. taicpu(p).opcode := A_BTC;
  15905. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15906. Result := True;
  15907. Exit;
  15908. end;
  15909. {$ifdef x86_64}
  15910. { Code size reduction by J. Gareth "Kit" Moreton }
  15911. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15912. as this removes the REX prefix }
  15913. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15914. Exit;
  15915. if taicpu(p).oper[0]^.typ <> top_reg then
  15916. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15917. InternalError(2018011500);
  15918. case taicpu(p).opsize of
  15919. S_Q:
  15920. begin
  15921. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15922. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15923. { The actual optimization }
  15924. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15925. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15926. taicpu(p).changeopsize(S_L);
  15927. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15928. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15929. end;
  15930. else
  15931. ;
  15932. end;
  15933. {$endif x86_64}
  15934. end;
  15935. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15936. var
  15937. XReg: TRegister;
  15938. begin
  15939. Result := False;
  15940. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15941. Smaller encoding and slightly faster on some platforms (also works for
  15942. ZMM-sized registers) }
  15943. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15944. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15945. begin
  15946. XReg := taicpu(p).oper[0]^.reg;
  15947. if (taicpu(p).oper[1]^.reg = XReg) then
  15948. begin
  15949. taicpu(p).changeopsize(S_XMM);
  15950. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15951. if (cs_opt_size in current_settings.optimizerswitches) then
  15952. begin
  15953. { Change input registers to %xmm0 to reduce size. Note that
  15954. there's a risk of a false dependency doing this, so only
  15955. optimise for size here }
  15956. XReg := NR_XMM0;
  15957. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15958. end
  15959. else
  15960. begin
  15961. setsubreg(XReg, R_SUBMMX);
  15962. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15963. end;
  15964. taicpu(p).oper[0]^.reg := XReg;
  15965. taicpu(p).oper[1]^.reg := XReg;
  15966. Result := True;
  15967. end;
  15968. end;
  15969. end;
  15970. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15971. var
  15972. hp1, p_new: tai;
  15973. begin
  15974. Result := False;
  15975. { Check for:
  15976. ret
  15977. .Lbl:
  15978. ret
  15979. Remove first 'ret'
  15980. }
  15981. if GetNextInstruction(p, hp1) and
  15982. { Remember where the label is }
  15983. SetAndTest(hp1, p_new) and
  15984. (hp1.typ in [ait_align, ait_label]) and
  15985. SkipLabels(hp1, hp1) and
  15986. MatchInstruction(hp1, A_RET, []) and
  15987. { To be safe, make sure the RET instructions are identical }
  15988. (taicpu(p).ops = taicpu(hp1).ops) and
  15989. (
  15990. (taicpu(p).ops = 0) or
  15991. (
  15992. (taicpu(p).ops = 1) and
  15993. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15994. )
  15995. ) then
  15996. begin
  15997. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15998. UpdateUsedRegs(tai(p.Next));
  15999. RemoveCurrentP(p, p_new);
  16000. Result := True;
  16001. Exit;
  16002. end;
  16003. end;
  16004. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  16005. var
  16006. OperIdx: Integer;
  16007. begin
  16008. for OperIdx := 0 to p.ops - 1 do
  16009. if p.oper[OperIdx]^.typ = top_ref then
  16010. optimize_ref(p.oper[OperIdx]^.ref^, False);
  16011. end;
  16012. end.