aoptx86.pas 581 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1, hp2 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1418. asml.InsertAfter(hp1, p);
  1419. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1420. RemoveCurrentP(p, hp1);
  1421. Result := True;
  1422. end
  1423. else if ((taicpu(p).ops <= 2) or
  1424. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1425. not(cs_opt_size in current_settings.optimizerswitches) and
  1426. (not(GetNextInstruction(p, hp1)) or
  1427. not((tai(hp1).typ = ait_instruction) and
  1428. ((taicpu(hp1).opcode=A_Jcc) and
  1429. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1430. begin
  1431. {
  1432. imul X, reg1, reg2 to
  1433. lea (reg1,reg1,Y), reg2
  1434. shl ZZ,reg2
  1435. imul XX, reg1 to
  1436. lea (reg1,reg1,YY), reg1
  1437. shl ZZ,reg2
  1438. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1439. it does not exist as a separate optimization target in FPC though.
  1440. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1441. at most two zeros
  1442. }
  1443. reference_reset(tmpref,1,[]);
  1444. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1445. begin
  1446. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1447. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1448. TmpRef.base := taicpu(p).oper[1]^.reg;
  1449. TmpRef.index := taicpu(p).oper[1]^.reg;
  1450. if not(BaseValue in [3,5,9]) then
  1451. Internalerror(2018110101);
  1452. TmpRef.ScaleFactor := BaseValue-1;
  1453. if (taicpu(p).ops = 2) then
  1454. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1455. else
  1456. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1457. AsmL.InsertAfter(hp1,p);
  1458. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1459. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1460. RemoveCurrentP(p, hp1);
  1461. if ShiftValue>0 then
  1462. begin
  1463. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1464. AsmL.InsertAfter(hp2,hp1);
  1465. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1466. end;
  1467. Result := True;
  1468. end;
  1469. end;
  1470. end;
  1471. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1472. begin
  1473. Result := False;
  1474. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1475. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1476. begin
  1477. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1478. taicpu(p).opcode := A_MOV;
  1479. Result := True;
  1480. end;
  1481. end;
  1482. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1483. var
  1484. p: taicpu absolute hp; { Implicit typecast }
  1485. i: Integer;
  1486. begin
  1487. Result := False;
  1488. if not assigned(hp) or
  1489. (hp.typ <> ait_instruction) then
  1490. Exit;
  1491. Prefetch(insprop[p.opcode]);
  1492. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1493. with insprop[p.opcode] do
  1494. begin
  1495. case getsubreg(reg) of
  1496. R_SUBW,R_SUBD,R_SUBQ:
  1497. Result:=
  1498. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1499. uncommon flags are checked first }
  1500. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1501. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1502. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1503. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1504. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1505. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1506. R_SUBFLAGCARRY:
  1507. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGPARITY:
  1509. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGAUXILIARY:
  1511. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGZERO:
  1513. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGSIGN:
  1515. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1516. R_SUBFLAGOVERFLOW:
  1517. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1518. R_SUBFLAGINTERRUPT:
  1519. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1520. R_SUBFLAGDIRECTION:
  1521. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1522. else
  1523. internalerror(2017050501);
  1524. end;
  1525. exit;
  1526. end;
  1527. { Handle special cases first }
  1528. case p.opcode of
  1529. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1530. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1531. begin
  1532. Result :=
  1533. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1534. (p.oper[1]^.typ = top_reg) and
  1535. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1536. (
  1537. (p.oper[0]^.typ = top_const) or
  1538. (
  1539. (p.oper[0]^.typ = top_reg) and
  1540. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1541. ) or (
  1542. (p.oper[0]^.typ = top_ref) and
  1543. not RegInRef(reg,p.oper[0]^.ref^)
  1544. )
  1545. );
  1546. end;
  1547. A_MUL, A_IMUL:
  1548. Result :=
  1549. (
  1550. (p.ops=3) and { IMUL only }
  1551. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1552. (
  1553. (
  1554. (p.oper[1]^.typ=top_reg) and
  1555. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1556. ) or (
  1557. (p.oper[1]^.typ=top_ref) and
  1558. not RegInRef(reg,p.oper[1]^.ref^)
  1559. )
  1560. )
  1561. ) or (
  1562. (
  1563. (p.ops=1) and
  1564. (
  1565. (
  1566. (
  1567. (p.oper[0]^.typ=top_reg) and
  1568. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1569. )
  1570. ) or (
  1571. (p.oper[0]^.typ=top_ref) and
  1572. not RegInRef(reg,p.oper[0]^.ref^)
  1573. )
  1574. ) and (
  1575. (
  1576. (p.opsize=S_B) and
  1577. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1578. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1579. ) or (
  1580. (p.opsize=S_W) and
  1581. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1582. ) or (
  1583. (p.opsize=S_L) and
  1584. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1585. {$ifdef x86_64}
  1586. ) or (
  1587. (p.opsize=S_Q) and
  1588. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1589. {$endif x86_64}
  1590. )
  1591. )
  1592. )
  1593. );
  1594. A_CBW:
  1595. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1596. {$ifndef x86_64}
  1597. A_LDS:
  1598. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1599. A_LES:
  1600. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1601. {$endif not x86_64}
  1602. A_LFS:
  1603. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1604. A_LGS:
  1605. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1606. A_LSS:
  1607. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1608. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1609. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1610. A_LODSB:
  1611. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1612. A_LODSW:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1614. {$ifdef x86_64}
  1615. A_LODSQ:
  1616. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1617. {$endif x86_64}
  1618. A_LODSD:
  1619. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1620. A_FSTSW, A_FNSTSW:
  1621. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1622. else
  1623. begin
  1624. with insprop[p.opcode] do
  1625. begin
  1626. if (
  1627. { xor %reg,%reg etc. is classed as a new value }
  1628. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1629. MatchOpType(p, top_reg, top_reg) and
  1630. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1631. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1632. ) then
  1633. begin
  1634. Result := True;
  1635. Exit;
  1636. end;
  1637. { Make sure the entire register is overwritten }
  1638. if (getregtype(reg) = R_INTREGISTER) then
  1639. begin
  1640. if (p.ops > 0) then
  1641. begin
  1642. if RegInOp(reg, p.oper[0]^) then
  1643. begin
  1644. if (p.oper[0]^.typ = top_ref) then
  1645. begin
  1646. if RegInRef(reg, p.oper[0]^.ref^) then
  1647. begin
  1648. Result := False;
  1649. Exit;
  1650. end;
  1651. end
  1652. else if (p.oper[0]^.typ = top_reg) then
  1653. begin
  1654. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1655. begin
  1656. Result := False;
  1657. Exit;
  1658. end
  1659. else if ([Ch_WOp1]*Ch<>[]) then
  1660. begin
  1661. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1662. Result := True
  1663. else
  1664. begin
  1665. Result := False;
  1666. Exit;
  1667. end;
  1668. end;
  1669. end;
  1670. end;
  1671. if (p.ops > 1) then
  1672. begin
  1673. if RegInOp(reg, p.oper[1]^) then
  1674. begin
  1675. if (p.oper[1]^.typ = top_ref) then
  1676. begin
  1677. if RegInRef(reg, p.oper[1]^.ref^) then
  1678. begin
  1679. Result := False;
  1680. Exit;
  1681. end;
  1682. end
  1683. else if (p.oper[1]^.typ = top_reg) then
  1684. begin
  1685. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1686. begin
  1687. Result := False;
  1688. Exit;
  1689. end
  1690. else if ([Ch_WOp2]*Ch<>[]) then
  1691. begin
  1692. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1693. Result := True
  1694. else
  1695. begin
  1696. Result := False;
  1697. Exit;
  1698. end;
  1699. end;
  1700. end;
  1701. end;
  1702. if (p.ops > 2) then
  1703. begin
  1704. if RegInOp(reg, p.oper[2]^) then
  1705. begin
  1706. if (p.oper[2]^.typ = top_ref) then
  1707. begin
  1708. if RegInRef(reg, p.oper[2]^.ref^) then
  1709. begin
  1710. Result := False;
  1711. Exit;
  1712. end;
  1713. end
  1714. else if (p.oper[2]^.typ = top_reg) then
  1715. begin
  1716. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1717. begin
  1718. Result := False;
  1719. Exit;
  1720. end
  1721. else if ([Ch_WOp3]*Ch<>[]) then
  1722. begin
  1723. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1724. Result := True
  1725. else
  1726. begin
  1727. Result := False;
  1728. Exit;
  1729. end;
  1730. end;
  1731. end;
  1732. end;
  1733. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1734. begin
  1735. if (p.oper[3]^.typ = top_ref) then
  1736. begin
  1737. if RegInRef(reg, p.oper[3]^.ref^) then
  1738. begin
  1739. Result := False;
  1740. Exit;
  1741. end;
  1742. end
  1743. else if (p.oper[3]^.typ = top_reg) then
  1744. begin
  1745. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1746. begin
  1747. Result := False;
  1748. Exit;
  1749. end
  1750. else if ([Ch_WOp4]*Ch<>[]) then
  1751. begin
  1752. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1753. Result := True
  1754. else
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end;
  1759. end;
  1760. end;
  1761. end;
  1762. end;
  1763. end;
  1764. end;
  1765. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1766. case getsupreg(reg) of
  1767. RS_EAX:
  1768. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_ECX:
  1774. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EDX:
  1780. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_EBX:
  1786. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_ESP:
  1792. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_EBP:
  1798. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_ESI:
  1804. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. RS_EDI:
  1810. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1811. begin
  1812. Result := True;
  1813. Exit;
  1814. end;
  1815. else
  1816. ;
  1817. end;
  1818. end;
  1819. end;
  1820. end;
  1821. end;
  1822. end;
  1823. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1824. var
  1825. hp2,hp3 : tai;
  1826. begin
  1827. { some x86-64 issue a NOP before the real exit code }
  1828. if MatchInstruction(p,A_NOP,[]) then
  1829. GetNextInstruction(p,p);
  1830. result:=assigned(p) and (p.typ=ait_instruction) and
  1831. ((taicpu(p).opcode = A_RET) or
  1832. ((taicpu(p).opcode=A_LEAVE) and
  1833. GetNextInstruction(p,hp2) and
  1834. MatchInstruction(hp2,A_RET,[S_NO])
  1835. ) or
  1836. (((taicpu(p).opcode=A_LEA) and
  1837. MatchOpType(taicpu(p),top_ref,top_reg) and
  1838. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1839. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1840. ) and
  1841. GetNextInstruction(p,hp2) and
  1842. MatchInstruction(hp2,A_RET,[S_NO])
  1843. ) or
  1844. ((((taicpu(p).opcode=A_MOV) and
  1845. MatchOpType(taicpu(p),top_reg,top_reg) and
  1846. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1847. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1848. ((taicpu(p).opcode=A_LEA) and
  1849. MatchOpType(taicpu(p),top_ref,top_reg) and
  1850. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1851. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1852. )
  1853. ) and
  1854. GetNextInstruction(p,hp2) and
  1855. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1856. MatchOpType(taicpu(hp2),top_reg) and
  1857. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1858. GetNextInstruction(hp2,hp3) and
  1859. MatchInstruction(hp3,A_RET,[S_NO])
  1860. )
  1861. );
  1862. end;
  1863. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1864. begin
  1865. isFoldableArithOp := False;
  1866. case hp1.opcode of
  1867. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1868. isFoldableArithOp :=
  1869. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1870. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1872. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1873. (taicpu(hp1).oper[1]^.reg = reg);
  1874. A_INC,A_DEC,A_NEG,A_NOT:
  1875. isFoldableArithOp :=
  1876. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1877. (taicpu(hp1).oper[0]^.reg = reg);
  1878. else
  1879. ;
  1880. end;
  1881. end;
  1882. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1883. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1884. var
  1885. hp2: tai;
  1886. begin
  1887. hp2 := p;
  1888. repeat
  1889. hp2 := tai(hp2.previous);
  1890. if assigned(hp2) and
  1891. (hp2.typ = ait_regalloc) and
  1892. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1893. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1894. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1895. begin
  1896. RemoveInstruction(hp2);
  1897. break;
  1898. end;
  1899. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1900. end;
  1901. begin
  1902. case current_procinfo.procdef.returndef.typ of
  1903. arraydef,recorddef,pointerdef,
  1904. stringdef,enumdef,procdef,objectdef,errordef,
  1905. filedef,setdef,procvardef,
  1906. classrefdef,forwarddef:
  1907. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1908. orddef:
  1909. if current_procinfo.procdef.returndef.size <> 0 then
  1910. begin
  1911. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1912. { for int64/qword }
  1913. if current_procinfo.procdef.returndef.size = 8 then
  1914. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1915. end;
  1916. else
  1917. ;
  1918. end;
  1919. end;
  1920. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1921. var
  1922. hp1,hp2 : tai;
  1923. begin
  1924. result:=false;
  1925. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1926. begin
  1927. { vmova* reg1,reg1
  1928. =>
  1929. <nop> }
  1930. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1931. begin
  1932. RemoveCurrentP(p);
  1933. result:=true;
  1934. exit;
  1935. end
  1936. else if GetNextInstruction(p,hp1) then
  1937. begin
  1938. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1939. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1940. begin
  1941. { vmova* reg1,reg2
  1942. vmova* reg2,reg3
  1943. dealloc reg2
  1944. =>
  1945. vmova* reg1,reg3 }
  1946. TransferUsedRegs(TmpUsedRegs);
  1947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1948. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1949. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1950. begin
  1951. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1952. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1953. RemoveInstruction(hp1);
  1954. result:=true;
  1955. exit;
  1956. end
  1957. { special case:
  1958. vmova* reg1,<op>
  1959. vmova* <op>,reg1
  1960. =>
  1961. vmova* reg1,<op> }
  1962. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1963. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1964. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1965. ) then
  1966. begin
  1967. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1968. RemoveInstruction(hp1);
  1969. result:=true;
  1970. exit;
  1971. end
  1972. end
  1973. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1974. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1975. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1976. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1977. ) and
  1978. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1979. begin
  1980. { vmova* reg1,reg2
  1981. vmovs* reg2,<op>
  1982. dealloc reg2
  1983. =>
  1984. vmovs* reg1,reg3 }
  1985. TransferUsedRegs(TmpUsedRegs);
  1986. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1987. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1988. begin
  1989. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1990. taicpu(p).opcode:=taicpu(hp1).opcode;
  1991. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1992. RemoveInstruction(hp1);
  1993. result:=true;
  1994. exit;
  1995. end
  1996. end;
  1997. end;
  1998. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1999. begin
  2000. if MatchInstruction(hp1,[A_VFMADDPD,
  2001. A_VFMADD132PD,
  2002. A_VFMADD132PS,
  2003. A_VFMADD132SD,
  2004. A_VFMADD132SS,
  2005. A_VFMADD213PD,
  2006. A_VFMADD213PS,
  2007. A_VFMADD213SD,
  2008. A_VFMADD213SS,
  2009. A_VFMADD231PD,
  2010. A_VFMADD231PS,
  2011. A_VFMADD231SD,
  2012. A_VFMADD231SS,
  2013. A_VFMADDSUB132PD,
  2014. A_VFMADDSUB132PS,
  2015. A_VFMADDSUB213PD,
  2016. A_VFMADDSUB213PS,
  2017. A_VFMADDSUB231PD,
  2018. A_VFMADDSUB231PS,
  2019. A_VFMSUB132PD,
  2020. A_VFMSUB132PS,
  2021. A_VFMSUB132SD,
  2022. A_VFMSUB132SS,
  2023. A_VFMSUB213PD,
  2024. A_VFMSUB213PS,
  2025. A_VFMSUB213SD,
  2026. A_VFMSUB213SS,
  2027. A_VFMSUB231PD,
  2028. A_VFMSUB231PS,
  2029. A_VFMSUB231SD,
  2030. A_VFMSUB231SS,
  2031. A_VFMSUBADD132PD,
  2032. A_VFMSUBADD132PS,
  2033. A_VFMSUBADD213PD,
  2034. A_VFMSUBADD213PS,
  2035. A_VFMSUBADD231PD,
  2036. A_VFMSUBADD231PS,
  2037. A_VFNMADD132PD,
  2038. A_VFNMADD132PS,
  2039. A_VFNMADD132SD,
  2040. A_VFNMADD132SS,
  2041. A_VFNMADD213PD,
  2042. A_VFNMADD213PS,
  2043. A_VFNMADD213SD,
  2044. A_VFNMADD213SS,
  2045. A_VFNMADD231PD,
  2046. A_VFNMADD231PS,
  2047. A_VFNMADD231SD,
  2048. A_VFNMADD231SS,
  2049. A_VFNMSUB132PD,
  2050. A_VFNMSUB132PS,
  2051. A_VFNMSUB132SD,
  2052. A_VFNMSUB132SS,
  2053. A_VFNMSUB213PD,
  2054. A_VFNMSUB213PS,
  2055. A_VFNMSUB213SD,
  2056. A_VFNMSUB213SS,
  2057. A_VFNMSUB231PD,
  2058. A_VFNMSUB231PS,
  2059. A_VFNMSUB231SD,
  2060. A_VFNMSUB231SS],[S_NO]) and
  2061. { we mix single and double opperations here because we assume that the compiler
  2062. generates vmovapd only after double operations and vmovaps only after single operations }
  2063. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2064. GetNextInstruction(hp1,hp2) and
  2065. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2066. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2067. begin
  2068. TransferUsedRegs(TmpUsedRegs);
  2069. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2070. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2071. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2072. begin
  2073. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2074. RemoveCurrentP(p);
  2075. RemoveInstruction(hp2);
  2076. end;
  2077. end
  2078. else if (hp1.typ = ait_instruction) and
  2079. GetNextInstruction(hp1, hp2) and
  2080. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2081. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2082. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2083. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2084. (((taicpu(p).opcode=A_MOVAPS) and
  2085. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2086. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2087. ((taicpu(p).opcode=A_MOVAPD) and
  2088. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2089. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2090. ) then
  2091. { change
  2092. movapX reg,reg2
  2093. addsX/subsX/... reg3, reg2
  2094. movapX reg2,reg
  2095. to
  2096. addsX/subsX/... reg3,reg
  2097. }
  2098. begin
  2099. TransferUsedRegs(TmpUsedRegs);
  2100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2101. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2102. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2105. debug_op2str(taicpu(p).opcode)+' '+
  2106. debug_op2str(taicpu(hp1).opcode)+' '+
  2107. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2108. { we cannot eliminate the first move if
  2109. the operations uses the same register for source and dest }
  2110. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2111. { Remember that hp1 is not necessarily the immediate
  2112. next instruction }
  2113. RemoveCurrentP(p);
  2114. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2115. RemoveInstruction(hp2);
  2116. result:=true;
  2117. end;
  2118. end
  2119. else if (hp1.typ = ait_instruction) and
  2120. (((taicpu(p).opcode=A_VMOVAPD) and
  2121. (taicpu(hp1).opcode=A_VCOMISD)) or
  2122. ((taicpu(p).opcode=A_VMOVAPS) and
  2123. ((taicpu(hp1).opcode=A_VCOMISS))
  2124. )
  2125. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2126. { change
  2127. movapX reg,reg1
  2128. vcomisX reg1,reg1
  2129. to
  2130. vcomisX reg,reg
  2131. }
  2132. begin
  2133. TransferUsedRegs(TmpUsedRegs);
  2134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2135. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2136. begin
  2137. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2138. debug_op2str(taicpu(p).opcode)+' '+
  2139. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2140. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2141. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2142. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2143. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2144. RemoveCurrentP(p);
  2145. result:=true;
  2146. exit;
  2147. end;
  2148. end
  2149. end;
  2150. end;
  2151. end;
  2152. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2153. var
  2154. hp1 : tai;
  2155. begin
  2156. result:=false;
  2157. { replace
  2158. V<Op>X %mreg1,%mreg2,%mreg3
  2159. VMovX %mreg3,%mreg4
  2160. dealloc %mreg3
  2161. by
  2162. V<Op>X %mreg1,%mreg2,%mreg4
  2163. ?
  2164. }
  2165. if GetNextInstruction(p,hp1) and
  2166. { we mix single and double operations here because we assume that the compiler
  2167. generates vmovapd only after double operations and vmovaps only after single operations }
  2168. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2169. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2170. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2171. begin
  2172. TransferUsedRegs(TmpUsedRegs);
  2173. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2174. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2175. begin
  2176. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2177. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2178. RemoveInstruction(hp1);
  2179. result:=true;
  2180. end;
  2181. end;
  2182. end;
  2183. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2184. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2185. begin
  2186. Result := False;
  2187. { For safety reasons, only check for exact register matches }
  2188. { Check base register }
  2189. if (ref.base = AOldReg) then
  2190. begin
  2191. ref.base := ANewReg;
  2192. Result := True;
  2193. end;
  2194. { Check index register }
  2195. if (ref.index = AOldReg) then
  2196. begin
  2197. ref.index := ANewReg;
  2198. Result := True;
  2199. end;
  2200. end;
  2201. { Replaces all references to AOldReg in an operand to ANewReg }
  2202. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2203. var
  2204. OldSupReg, NewSupReg: TSuperRegister;
  2205. OldSubReg, NewSubReg: TSubRegister;
  2206. OldRegType: TRegisterType;
  2207. ThisOper: POper;
  2208. begin
  2209. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2210. Result := False;
  2211. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2212. InternalError(2020011801);
  2213. OldSupReg := getsupreg(AOldReg);
  2214. OldSubReg := getsubreg(AOldReg);
  2215. OldRegType := getregtype(AOldReg);
  2216. NewSupReg := getsupreg(ANewReg);
  2217. NewSubReg := getsubreg(ANewReg);
  2218. if OldRegType <> getregtype(ANewReg) then
  2219. InternalError(2020011802);
  2220. if OldSubReg <> NewSubReg then
  2221. InternalError(2020011803);
  2222. case ThisOper^.typ of
  2223. top_reg:
  2224. if (
  2225. (ThisOper^.reg = AOldReg) or
  2226. (
  2227. (OldRegType = R_INTREGISTER) and
  2228. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2229. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2230. (
  2231. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2232. {$ifndef x86_64}
  2233. and (
  2234. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2235. don't have an 8-bit representation }
  2236. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2237. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2238. )
  2239. {$endif x86_64}
  2240. )
  2241. )
  2242. ) then
  2243. begin
  2244. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2245. Result := True;
  2246. end;
  2247. top_ref:
  2248. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2249. Result := True;
  2250. else
  2251. ;
  2252. end;
  2253. end;
  2254. { Replaces all references to AOldReg in an instruction to ANewReg }
  2255. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2256. const
  2257. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2258. var
  2259. OperIdx: Integer;
  2260. begin
  2261. Result := False;
  2262. for OperIdx := 0 to p.ops - 1 do
  2263. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2264. begin
  2265. { The shift and rotate instructions can only use CL }
  2266. if not (
  2267. (OperIdx = 0) and
  2268. { This second condition just helps to avoid unnecessarily
  2269. calling MatchInstruction for 10 different opcodes }
  2270. (p.oper[0]^.reg = NR_CL) and
  2271. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2272. ) then
  2273. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2274. end
  2275. else if p.oper[OperIdx]^.typ = top_ref then
  2276. { It's okay to replace registers in references that get written to }
  2277. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2278. end;
  2279. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2280. begin
  2281. with ref^ do
  2282. Result :=
  2283. (index = NR_NO) and
  2284. (
  2285. {$ifdef x86_64}
  2286. (
  2287. (base = NR_RIP) and
  2288. (refaddr in [addr_pic, addr_pic_no_got])
  2289. ) or
  2290. {$endif x86_64}
  2291. (base = NR_STACK_POINTER_REG) or
  2292. (base = current_procinfo.framepointer)
  2293. );
  2294. end;
  2295. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2296. var
  2297. l: asizeint;
  2298. begin
  2299. Result := False;
  2300. { Should have been checked previously }
  2301. if p.opcode <> A_LEA then
  2302. InternalError(2020072501);
  2303. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2304. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2305. not(cs_opt_size in current_settings.optimizerswitches) then
  2306. exit;
  2307. with p.oper[0]^.ref^ do
  2308. begin
  2309. if (base <> p.oper[1]^.reg) or
  2310. (index <> NR_NO) or
  2311. assigned(symbol) then
  2312. exit;
  2313. l:=offset;
  2314. if (l=1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_INC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2320. end
  2321. else if (l=-1) and UseIncDec then
  2322. begin
  2323. p.opcode:=A_DEC;
  2324. p.loadreg(0,p.oper[1]^.reg);
  2325. p.ops:=1;
  2326. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2327. end
  2328. else
  2329. begin
  2330. if (l<0) and (l<>-2147483648) then
  2331. begin
  2332. p.opcode:=A_SUB;
  2333. p.loadConst(0,-l);
  2334. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2335. end
  2336. else
  2337. begin
  2338. p.opcode:=A_ADD;
  2339. p.loadConst(0,l);
  2340. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2341. end;
  2342. end;
  2343. end;
  2344. Result := True;
  2345. end;
  2346. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2347. var
  2348. CurrentReg, ReplaceReg: TRegister;
  2349. begin
  2350. Result := False;
  2351. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2352. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2353. case hp.opcode of
  2354. A_FSTSW, A_FNSTSW,
  2355. A_IN, A_INS, A_OUT, A_OUTS,
  2356. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2357. { These routines have explicit operands, but they are restricted in
  2358. what they can be (e.g. IN and OUT can only read from AL, AX or
  2359. EAX. }
  2360. Exit;
  2361. A_IMUL:
  2362. begin
  2363. { The 1-operand version writes to implicit registers
  2364. The 2-operand version reads from the first operator, and reads
  2365. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2366. the 3-operand version reads from a register that it doesn't write to
  2367. }
  2368. case hp.ops of
  2369. 1:
  2370. if (
  2371. (
  2372. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2373. ) or
  2374. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2375. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2376. begin
  2377. Result := True;
  2378. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2379. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2380. end;
  2381. 2:
  2382. { Only modify the first parameter }
  2383. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2384. begin
  2385. Result := True;
  2386. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2387. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2388. end;
  2389. 3:
  2390. { Only modify the second parameter }
  2391. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2392. begin
  2393. Result := True;
  2394. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2395. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2396. end;
  2397. else
  2398. InternalError(2020012901);
  2399. end;
  2400. end;
  2401. else
  2402. if (hp.ops > 0) and
  2403. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2404. begin
  2405. Result := True;
  2406. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2407. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2408. end;
  2409. end;
  2410. end;
  2411. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2412. var
  2413. hp1, hp2, hp3: tai;
  2414. DoOptimisation, TempBool: Boolean;
  2415. {$ifdef x86_64}
  2416. NewConst: TCGInt;
  2417. {$endif x86_64}
  2418. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2419. begin
  2420. if taicpu(hp1).opcode = signed_movop then
  2421. begin
  2422. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2423. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2424. end
  2425. else
  2426. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2427. end;
  2428. function TryConstMerge(var p1, p2: tai): Boolean;
  2429. var
  2430. ThisRef: TReference;
  2431. begin
  2432. Result := False;
  2433. ThisRef := taicpu(p2).oper[1]^.ref^;
  2434. { Only permit writes to the stack, since we can guarantee alignment with that }
  2435. if (ThisRef.index = NR_NO) and
  2436. (
  2437. (ThisRef.base = NR_STACK_POINTER_REG) or
  2438. (ThisRef.base = current_procinfo.framepointer)
  2439. ) then
  2440. begin
  2441. case taicpu(p).opsize of
  2442. S_B:
  2443. begin
  2444. { Word writes must be on a 2-byte boundary }
  2445. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2446. begin
  2447. { Reduce offset of second reference to see if it is sequential with the first }
  2448. Dec(ThisRef.offset, 1);
  2449. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2450. begin
  2451. { Make sure the constants aren't represented as a
  2452. negative number, as these won't merge properly }
  2453. taicpu(p1).opsize := S_W;
  2454. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2455. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2456. RemoveInstruction(p2);
  2457. Result := True;
  2458. end;
  2459. end;
  2460. end;
  2461. S_W:
  2462. begin
  2463. { Longword writes must be on a 4-byte boundary }
  2464. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2465. begin
  2466. { Reduce offset of second reference to see if it is sequential with the first }
  2467. Dec(ThisRef.offset, 2);
  2468. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2469. begin
  2470. { Make sure the constants aren't represented as a
  2471. negative number, as these won't merge properly }
  2472. taicpu(p1).opsize := S_L;
  2473. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2474. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2475. RemoveInstruction(p2);
  2476. Result := True;
  2477. end;
  2478. end;
  2479. end;
  2480. {$ifdef x86_64}
  2481. S_L:
  2482. begin
  2483. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2484. see if the constants can be encoded this way. }
  2485. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2486. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2487. { Quadword writes must be on an 8-byte boundary }
  2488. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2489. begin
  2490. { Reduce offset of second reference to see if it is sequential with the first }
  2491. Dec(ThisRef.offset, 4);
  2492. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2493. begin
  2494. { Make sure the constants aren't represented as a
  2495. negative number, as these won't merge properly }
  2496. taicpu(p1).opsize := S_Q;
  2497. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2498. taicpu(p1).oper[0]^.val := NewConst;
  2499. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2500. RemoveInstruction(p2);
  2501. Result := True;
  2502. end;
  2503. end;
  2504. end;
  2505. {$endif x86_64}
  2506. else
  2507. ;
  2508. end;
  2509. end;
  2510. end;
  2511. var
  2512. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2513. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2514. NewSize: topsize;
  2515. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2516. SourceRef, TargetRef: TReference;
  2517. MovAligned, MovUnaligned: TAsmOp;
  2518. ThisRef: TReference;
  2519. JumpTracking: TLinkedList;
  2520. begin
  2521. Result:=false;
  2522. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2523. { remove mov reg1,reg1? }
  2524. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2525. then
  2526. begin
  2527. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2528. { take care of the register (de)allocs following p }
  2529. RemoveCurrentP(p, hp1);
  2530. Result:=true;
  2531. exit;
  2532. end;
  2533. { All the next optimisations require a next instruction }
  2534. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2535. Exit;
  2536. { Prevent compiler warnings }
  2537. p_TargetReg := NR_NO;
  2538. if taicpu(p).oper[1]^.typ = top_reg then
  2539. begin
  2540. { Saves on a large number of dereferences }
  2541. p_TargetReg := taicpu(p).oper[1]^.reg;
  2542. { Look for:
  2543. mov %reg1,%reg2
  2544. ??? %reg2,r/m
  2545. Change to:
  2546. mov %reg1,%reg2
  2547. ??? %reg1,r/m
  2548. }
  2549. if taicpu(p).oper[0]^.typ = top_reg then
  2550. begin
  2551. if RegReadByInstruction(p_TargetReg, hp1) and
  2552. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2553. begin
  2554. { A change has occurred, just not in p }
  2555. Result := True;
  2556. TransferUsedRegs(TmpUsedRegs);
  2557. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2559. { Just in case something didn't get modified (e.g. an
  2560. implicit register) }
  2561. not RegReadByInstruction(p_TargetReg, hp1) then
  2562. begin
  2563. { We can remove the original MOV }
  2564. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2565. RemoveCurrentp(p, hp1);
  2566. { UsedRegs got updated by RemoveCurrentp }
  2567. Result := True;
  2568. Exit;
  2569. end;
  2570. { If we know a MOV instruction has become a null operation, we might as well
  2571. get rid of it now to save time. }
  2572. if (taicpu(hp1).opcode = A_MOV) and
  2573. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2574. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2575. { Just being a register is enough to confirm it's a null operation }
  2576. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2577. begin
  2578. Result := True;
  2579. { Speed-up to reduce a pipeline stall... if we had something like...
  2580. movl %eax,%edx
  2581. movw %dx,%ax
  2582. ... the second instruction would change to movw %ax,%ax, but
  2583. given that it is now %ax that's active rather than %eax,
  2584. penalties might occur due to a partial register write, so instead,
  2585. change it to a MOVZX instruction when optimising for speed.
  2586. }
  2587. if not (cs_opt_size in current_settings.optimizerswitches) and
  2588. IsMOVZXAcceptable and
  2589. (taicpu(hp1).opsize < taicpu(p).opsize)
  2590. {$ifdef x86_64}
  2591. { operations already implicitly set the upper 64 bits to zero }
  2592. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2593. {$endif x86_64}
  2594. then
  2595. begin
  2596. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2597. case taicpu(p).opsize of
  2598. S_W:
  2599. if taicpu(hp1).opsize = S_B then
  2600. taicpu(hp1).opsize := S_BL
  2601. else
  2602. InternalError(2020012911);
  2603. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2604. case taicpu(hp1).opsize of
  2605. S_B:
  2606. taicpu(hp1).opsize := S_BL;
  2607. S_W:
  2608. taicpu(hp1).opsize := S_WL;
  2609. else
  2610. InternalError(2020012912);
  2611. end;
  2612. else
  2613. InternalError(2020012910);
  2614. end;
  2615. taicpu(hp1).opcode := A_MOVZX;
  2616. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2617. end
  2618. else
  2619. begin
  2620. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2621. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2622. RemoveInstruction(hp1);
  2623. { The instruction after what was hp1 is now the immediate next instruction,
  2624. so we can continue to make optimisations if it's present }
  2625. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2626. Exit;
  2627. hp1 := hp2;
  2628. end;
  2629. end;
  2630. end;
  2631. end;
  2632. end;
  2633. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2634. overwrites the original destination register. e.g.
  2635. movl ###,%reg2d
  2636. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2637. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2638. }
  2639. if (taicpu(p).oper[1]^.typ = top_reg) and
  2640. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2641. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2642. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2643. begin
  2644. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2645. begin
  2646. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2647. case taicpu(p).oper[0]^.typ of
  2648. top_const:
  2649. { We have something like:
  2650. movb $x, %regb
  2651. movzbl %regb,%regd
  2652. Change to:
  2653. movl $x, %regd
  2654. }
  2655. begin
  2656. case taicpu(hp1).opsize of
  2657. S_BW:
  2658. begin
  2659. convert_mov_value(A_MOVSX, $FF);
  2660. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2661. taicpu(p).opsize := S_W;
  2662. end;
  2663. S_BL:
  2664. begin
  2665. convert_mov_value(A_MOVSX, $FF);
  2666. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2667. taicpu(p).opsize := S_L;
  2668. end;
  2669. S_WL:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FFFF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2673. taicpu(p).opsize := S_L;
  2674. end;
  2675. {$ifdef x86_64}
  2676. S_BQ:
  2677. begin
  2678. convert_mov_value(A_MOVSX, $FF);
  2679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2680. taicpu(p).opsize := S_Q;
  2681. end;
  2682. S_WQ:
  2683. begin
  2684. convert_mov_value(A_MOVSX, $FFFF);
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2686. taicpu(p).opsize := S_Q;
  2687. end;
  2688. S_LQ:
  2689. begin
  2690. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2692. taicpu(p).opsize := S_Q;
  2693. end;
  2694. {$endif x86_64}
  2695. else
  2696. { If hp1 was a MOV instruction, it should have been
  2697. optimised already }
  2698. InternalError(2020021001);
  2699. end;
  2700. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2701. RemoveInstruction(hp1);
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. top_ref:
  2706. begin
  2707. { We have something like:
  2708. movb mem, %regb
  2709. movzbl %regb,%regd
  2710. Change to:
  2711. movzbl mem, %regd
  2712. }
  2713. ThisRef := taicpu(p).oper[0]^.ref^;
  2714. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2715. begin
  2716. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2717. taicpu(hp1).loadref(0, ThisRef);
  2718. { Make sure any registers in the references are properly tracked }
  2719. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2720. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2721. if (ThisRef.index <> NR_NO) then
  2722. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2723. RemoveCurrentP(p, hp1);
  2724. Result := True;
  2725. Exit;
  2726. end;
  2727. end;
  2728. else
  2729. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2730. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2731. Exit;
  2732. end;
  2733. end
  2734. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2735. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2736. optimised }
  2737. else
  2738. begin
  2739. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2740. RemoveCurrentP(p, hp1);
  2741. Result := True;
  2742. Exit;
  2743. end;
  2744. end;
  2745. if (taicpu(hp1).opcode = A_AND) and
  2746. (taicpu(p).oper[1]^.typ = top_reg) and
  2747. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2748. begin
  2749. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2750. begin
  2751. case taicpu(p).opsize of
  2752. S_L:
  2753. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2754. begin
  2755. { Optimize out:
  2756. mov x, %reg
  2757. and ffffffffh, %reg
  2758. }
  2759. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2760. RemoveInstruction(hp1);
  2761. Result:=true;
  2762. exit;
  2763. end;
  2764. S_Q: { TODO: Confirm if this is even possible }
  2765. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2766. begin
  2767. { Optimize out:
  2768. mov x, %reg
  2769. and ffffffffffffffffh, %reg
  2770. }
  2771. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2772. RemoveInstruction(hp1);
  2773. Result:=true;
  2774. exit;
  2775. end;
  2776. else
  2777. ;
  2778. end;
  2779. if (
  2780. (taicpu(p).oper[0]^.typ=top_reg) or
  2781. (
  2782. (taicpu(p).oper[0]^.typ=top_ref) and
  2783. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2784. )
  2785. ) and
  2786. GetNextInstruction(hp1,hp2) and
  2787. MatchInstruction(hp2,A_TEST,[]) and
  2788. (
  2789. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2790. (
  2791. { If the register being tested is smaller than the one
  2792. that received a bitwise AND, permit it if the constant
  2793. fits into the smaller size }
  2794. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2795. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2796. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2797. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2798. (
  2799. (
  2800. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2801. (taicpu(hp1).oper[0]^.val <= $FF)
  2802. ) or
  2803. (
  2804. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2805. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2806. {$ifdef x86_64}
  2807. ) or
  2808. (
  2809. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2810. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2811. {$endif x86_64}
  2812. )
  2813. )
  2814. )
  2815. ) and
  2816. (
  2817. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2818. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2819. ) and
  2820. GetNextInstruction(hp2,hp3) and
  2821. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2822. (taicpu(hp3).condition in [C_E,C_NE]) then
  2823. begin
  2824. TransferUsedRegs(TmpUsedRegs);
  2825. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2826. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2827. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2828. begin
  2829. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2830. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2831. taicpu(hp1).opcode:=A_TEST;
  2832. { Shrink the TEST instruction down to the smallest possible size }
  2833. case taicpu(hp1).oper[0]^.val of
  2834. 0..255:
  2835. if (taicpu(hp1).opsize <> S_B)
  2836. {$ifndef x86_64}
  2837. and (
  2838. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2839. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2840. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2841. )
  2842. {$endif x86_64}
  2843. then
  2844. begin
  2845. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2846. { Only print debug message if the TEST instruction
  2847. is a different size before and after }
  2848. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2849. taicpu(hp1).opsize := S_B;
  2850. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2851. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2852. end;
  2853. 256..65535:
  2854. if (taicpu(hp1).opsize <> S_W) then
  2855. begin
  2856. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2857. { Only print debug message if the TEST instruction
  2858. is a different size before and after }
  2859. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2860. taicpu(hp1).opsize := S_W;
  2861. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2862. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2863. end;
  2864. {$ifdef x86_64}
  2865. 65536..$7FFFFFFF:
  2866. if (taicpu(hp1).opsize <> S_L) then
  2867. begin
  2868. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2869. { Only print debug message if the TEST instruction
  2870. is a different size before and after }
  2871. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2872. taicpu(hp1).opsize := S_L;
  2873. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2874. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2875. end;
  2876. {$endif x86_64}
  2877. else
  2878. ;
  2879. end;
  2880. RemoveInstruction(hp2);
  2881. RemoveCurrentP(p, hp1);
  2882. Result:=true;
  2883. exit;
  2884. end;
  2885. end;
  2886. end
  2887. else if IsMOVZXAcceptable and
  2888. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2889. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2890. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2891. then
  2892. begin
  2893. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2894. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2895. case taicpu(p).opsize of
  2896. S_B:
  2897. if (taicpu(hp1).oper[0]^.val = $ff) then
  2898. begin
  2899. { Convert:
  2900. movb x, %regl movb x, %regl
  2901. andw ffh, %regw andl ffh, %regd
  2902. To:
  2903. movzbw x, %regd movzbl x, %regd
  2904. (Identical registers, just different sizes)
  2905. }
  2906. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2907. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2908. case taicpu(hp1).opsize of
  2909. S_W: NewSize := S_BW;
  2910. S_L: NewSize := S_BL;
  2911. {$ifdef x86_64}
  2912. S_Q: NewSize := S_BQ;
  2913. {$endif x86_64}
  2914. else
  2915. InternalError(2018011510);
  2916. end;
  2917. end
  2918. else
  2919. NewSize := S_NO;
  2920. S_W:
  2921. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2922. begin
  2923. { Convert:
  2924. movw x, %regw
  2925. andl ffffh, %regd
  2926. To:
  2927. movzwl x, %regd
  2928. (Identical registers, just different sizes)
  2929. }
  2930. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2931. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2932. case taicpu(hp1).opsize of
  2933. S_L: NewSize := S_WL;
  2934. {$ifdef x86_64}
  2935. S_Q: NewSize := S_WQ;
  2936. {$endif x86_64}
  2937. else
  2938. InternalError(2018011511);
  2939. end;
  2940. end
  2941. else
  2942. NewSize := S_NO;
  2943. else
  2944. NewSize := S_NO;
  2945. end;
  2946. if NewSize <> S_NO then
  2947. begin
  2948. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2949. { The actual optimization }
  2950. taicpu(p).opcode := A_MOVZX;
  2951. taicpu(p).changeopsize(NewSize);
  2952. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2953. { Safeguard if "and" is followed by a conditional command }
  2954. TransferUsedRegs(TmpUsedRegs);
  2955. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2956. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2957. begin
  2958. { At this point, the "and" command is effectively equivalent to
  2959. "test %reg,%reg". This will be handled separately by the
  2960. Peephole Optimizer. [Kit] }
  2961. DebugMsg(SPeepholeOptimization + PreMessage +
  2962. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2963. end
  2964. else
  2965. begin
  2966. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2967. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2968. RemoveInstruction(hp1);
  2969. end;
  2970. Result := True;
  2971. Exit;
  2972. end;
  2973. end;
  2974. end;
  2975. if (taicpu(hp1).opcode = A_OR) and
  2976. (taicpu(p).oper[1]^.typ = top_reg) and
  2977. MatchOperand(taicpu(p).oper[0]^, 0) and
  2978. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2979. begin
  2980. { mov 0, %reg
  2981. or ###,%reg
  2982. Change to (only if the flags are not used):
  2983. mov ###,%reg
  2984. }
  2985. TransferUsedRegs(TmpUsedRegs);
  2986. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2987. DoOptimisation := True;
  2988. { Even if the flags are used, we might be able to do the optimisation
  2989. if the conditions are predictable }
  2990. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2991. begin
  2992. { Only perform if ### = %reg (the same register) or equal to 0,
  2993. so %reg is guaranteed to still have a value of zero }
  2994. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2995. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2996. begin
  2997. hp2 := hp1;
  2998. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2999. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3000. GetNextInstruction(hp2, hp3) do
  3001. begin
  3002. { Don't continue modifying if the flags state is getting changed }
  3003. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3004. Break;
  3005. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3006. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3007. begin
  3008. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3009. begin
  3010. { Condition is always true }
  3011. case taicpu(hp3).opcode of
  3012. A_Jcc:
  3013. begin
  3014. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3015. { Check for jump shortcuts before we destroy the condition }
  3016. DoJumpOptimizations(hp3, TempBool);
  3017. MakeUnconditional(taicpu(hp3));
  3018. Result := True;
  3019. end;
  3020. A_CMOVcc:
  3021. begin
  3022. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3023. taicpu(hp3).opcode := A_MOV;
  3024. taicpu(hp3).condition := C_None;
  3025. Result := True;
  3026. end;
  3027. A_SETcc:
  3028. begin
  3029. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3030. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3031. taicpu(hp3).opcode := A_MOV;
  3032. taicpu(hp3).ops := 2;
  3033. taicpu(hp3).condition := C_None;
  3034. taicpu(hp3).opsize := S_B;
  3035. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3036. taicpu(hp3).loadconst(0, 1);
  3037. Result := True;
  3038. end;
  3039. else
  3040. InternalError(2021090701);
  3041. end;
  3042. end
  3043. 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
  3044. begin
  3045. { Condition is always false }
  3046. case taicpu(hp3).opcode of
  3047. A_Jcc:
  3048. begin
  3049. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3050. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3051. RemoveInstruction(hp3);
  3052. Result := True;
  3053. { Since hp3 was deleted, hp2 must not be updated }
  3054. Continue;
  3055. end;
  3056. A_CMOVcc:
  3057. begin
  3058. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3059. RemoveInstruction(hp3);
  3060. Result := True;
  3061. { Since hp3 was deleted, hp2 must not be updated }
  3062. Continue;
  3063. end;
  3064. A_SETcc:
  3065. begin
  3066. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3067. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3068. taicpu(hp3).opcode := A_MOV;
  3069. taicpu(hp3).ops := 2;
  3070. taicpu(hp3).condition := C_None;
  3071. taicpu(hp3).opsize := S_B;
  3072. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3073. taicpu(hp3).loadconst(0, 0);
  3074. Result := True;
  3075. end;
  3076. else
  3077. InternalError(2021090702);
  3078. end;
  3079. end
  3080. else
  3081. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3082. DoOptimisation := False;
  3083. end;
  3084. hp2 := hp3;
  3085. end;
  3086. { Flags are still in use - don't optimise }
  3087. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3088. DoOptimisation := False;
  3089. end
  3090. else
  3091. DoOptimisation := False;
  3092. end;
  3093. if DoOptimisation then
  3094. begin
  3095. {$ifdef x86_64}
  3096. { OR only supports 32-bit sign-extended constants for 64-bit
  3097. instructions, so compensate for this if the constant is
  3098. encoded as a value greater than or equal to 2^31 }
  3099. if (taicpu(hp1).opsize = S_Q) and
  3100. (taicpu(hp1).oper[0]^.typ = top_const) and
  3101. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3102. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3103. {$endif x86_64}
  3104. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3105. taicpu(hp1).opcode := A_MOV;
  3106. RemoveCurrentP(p, hp1);
  3107. Result := True;
  3108. Exit;
  3109. end;
  3110. end;
  3111. { Next instruction is also a MOV ? }
  3112. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3113. begin
  3114. if MatchOpType(taicpu(p), top_const, top_ref) and
  3115. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3116. TryConstMerge(p, hp1) then
  3117. begin
  3118. Result := True;
  3119. { In case we have four byte writes in a row, check for 2 more
  3120. right now so we don't have to wait for another iteration of
  3121. pass 1
  3122. }
  3123. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3124. case taicpu(p).opsize of
  3125. S_W:
  3126. begin
  3127. if GetNextInstruction(p, hp1) and
  3128. MatchInstruction(hp1, A_MOV, [S_B]) and
  3129. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3130. GetNextInstruction(hp1, hp2) and
  3131. MatchInstruction(hp2, A_MOV, [S_B]) and
  3132. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3133. { Try to merge the two bytes }
  3134. TryConstMerge(hp1, hp2) then
  3135. { Now try to merge the two words (hp2 will get deleted) }
  3136. TryConstMerge(p, hp1);
  3137. end;
  3138. S_L:
  3139. begin
  3140. { Though this only really benefits x86_64 and not i386, it
  3141. gets a potential optimisation done faster and hence
  3142. reduces the number of times OptPass1MOV is entered }
  3143. if GetNextInstruction(p, hp1) and
  3144. MatchInstruction(hp1, A_MOV, [S_W]) and
  3145. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3146. GetNextInstruction(hp1, hp2) and
  3147. MatchInstruction(hp2, A_MOV, [S_W]) and
  3148. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3149. { Try to merge the two words }
  3150. TryConstMerge(hp1, hp2) then
  3151. { This will always fail on i386, so don't bother
  3152. calling it unless we're doing x86_64 }
  3153. {$ifdef x86_64}
  3154. { Now try to merge the two longwords (hp2 will get deleted) }
  3155. TryConstMerge(p, hp1)
  3156. {$endif x86_64}
  3157. ;
  3158. end;
  3159. else
  3160. ;
  3161. end;
  3162. Exit;
  3163. end;
  3164. if (taicpu(p).oper[1]^.typ = top_reg) and
  3165. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3166. begin
  3167. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3168. TransferUsedRegs(TmpUsedRegs);
  3169. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3170. { we have
  3171. mov x, %treg
  3172. mov %treg, y
  3173. }
  3174. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3175. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3176. { we've got
  3177. mov x, %treg
  3178. mov %treg, y
  3179. with %treg is not used after }
  3180. case taicpu(p).oper[0]^.typ Of
  3181. { top_reg is covered by DeepMOVOpt }
  3182. top_const:
  3183. begin
  3184. { change
  3185. mov const, %treg
  3186. mov %treg, y
  3187. to
  3188. mov const, y
  3189. }
  3190. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3191. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3192. begin
  3193. if taicpu(hp1).oper[1]^.typ=top_reg then
  3194. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3195. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3196. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3197. RemoveInstruction(hp1);
  3198. Result:=true;
  3199. Exit;
  3200. end;
  3201. end;
  3202. top_ref:
  3203. case taicpu(hp1).oper[1]^.typ of
  3204. top_reg:
  3205. begin
  3206. { change
  3207. mov mem, %treg
  3208. mov %treg, %reg
  3209. to
  3210. mov mem, %reg"
  3211. }
  3212. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3213. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3214. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3215. RemoveInstruction(hp1);
  3216. Result:=true;
  3217. Exit;
  3218. end;
  3219. top_ref:
  3220. begin
  3221. {$ifdef x86_64}
  3222. { Look for the following to simplify:
  3223. mov x(mem1), %reg
  3224. mov %reg, y(mem2)
  3225. mov x+8(mem1), %reg
  3226. mov %reg, y+8(mem2)
  3227. Change to:
  3228. movdqu x(mem1), %xmmreg
  3229. movdqu %xmmreg, y(mem2)
  3230. ...but only as long as the memory blocks don't overlap
  3231. }
  3232. SourceRef := taicpu(p).oper[0]^.ref^;
  3233. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3234. if (taicpu(p).opsize = S_Q) and
  3235. GetNextInstruction(hp1, hp2) and
  3236. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3237. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3238. begin
  3239. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3240. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3241. Inc(SourceRef.offset, 8);
  3242. if UseAVX then
  3243. begin
  3244. MovAligned := A_VMOVDQA;
  3245. MovUnaligned := A_VMOVDQU;
  3246. end
  3247. else
  3248. begin
  3249. MovAligned := A_MOVDQA;
  3250. MovUnaligned := A_MOVDQU;
  3251. end;
  3252. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3253. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3254. begin
  3255. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3256. Inc(TargetRef.offset, 8);
  3257. if GetNextInstruction(hp2, hp3) and
  3258. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3259. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3260. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3261. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3262. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3263. begin
  3264. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3265. if NewMMReg <> NR_NO then
  3266. begin
  3267. { Remember that the offsets are 8 ahead }
  3268. if ((SourceRef.offset mod 16) = 8) and
  3269. (
  3270. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3271. (SourceRef.base = current_procinfo.framepointer) or
  3272. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3273. ) then
  3274. taicpu(p).opcode := MovAligned
  3275. else
  3276. taicpu(p).opcode := MovUnaligned;
  3277. taicpu(p).opsize := S_XMM;
  3278. taicpu(p).oper[1]^.reg := NewMMReg;
  3279. if ((TargetRef.offset mod 16) = 8) and
  3280. (
  3281. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3282. (TargetRef.base = current_procinfo.framepointer) or
  3283. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3284. ) then
  3285. taicpu(hp1).opcode := MovAligned
  3286. else
  3287. taicpu(hp1).opcode := MovUnaligned;
  3288. taicpu(hp1).opsize := S_XMM;
  3289. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3290. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3291. RemoveInstruction(hp2);
  3292. RemoveInstruction(hp3);
  3293. Result := True;
  3294. Exit;
  3295. end;
  3296. end;
  3297. end
  3298. else
  3299. begin
  3300. { See if the next references are 8 less rather than 8 greater }
  3301. Dec(SourceRef.offset, 16); { -8 the other way }
  3302. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3303. begin
  3304. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3305. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3306. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3307. GetNextInstruction(hp2, hp3) and
  3308. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3309. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3310. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3311. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3312. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3313. begin
  3314. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3315. if NewMMReg <> NR_NO then
  3316. begin
  3317. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3318. if ((SourceRef.offset mod 16) = 0) and
  3319. (
  3320. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3321. (SourceRef.base = current_procinfo.framepointer) or
  3322. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3323. ) then
  3324. taicpu(hp2).opcode := MovAligned
  3325. else
  3326. taicpu(hp2).opcode := MovUnaligned;
  3327. taicpu(hp2).opsize := S_XMM;
  3328. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3329. if ((TargetRef.offset mod 16) = 0) and
  3330. (
  3331. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3332. (TargetRef.base = current_procinfo.framepointer) or
  3333. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3334. ) then
  3335. taicpu(hp3).opcode := MovAligned
  3336. else
  3337. taicpu(hp3).opcode := MovUnaligned;
  3338. taicpu(hp3).opsize := S_XMM;
  3339. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3340. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3341. RemoveInstruction(hp1);
  3342. RemoveCurrentP(p, hp2);
  3343. Result := True;
  3344. Exit;
  3345. end;
  3346. end;
  3347. end;
  3348. end;
  3349. end;
  3350. {$endif x86_64}
  3351. end;
  3352. else
  3353. { The write target should be a reg or a ref }
  3354. InternalError(2021091601);
  3355. end;
  3356. else
  3357. ;
  3358. end
  3359. else
  3360. { %treg is used afterwards, but all eventualities
  3361. other than the first MOV instruction being a constant
  3362. are covered by DeepMOVOpt, so only check for that }
  3363. if (taicpu(p).oper[0]^.typ = top_const) and
  3364. (
  3365. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3366. not (cs_opt_size in current_settings.optimizerswitches) or
  3367. (taicpu(hp1).opsize = S_B)
  3368. ) and
  3369. (
  3370. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3371. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3372. ) then
  3373. begin
  3374. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3375. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3376. end;
  3377. end;
  3378. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3379. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3380. { mov reg1, mem1 or mov mem1, reg1
  3381. mov mem2, reg2 mov reg2, mem2}
  3382. begin
  3383. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3384. { mov reg1, mem1 or mov mem1, reg1
  3385. mov mem2, reg1 mov reg2, mem1}
  3386. begin
  3387. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3388. { Removes the second statement from
  3389. mov reg1, mem1/reg2
  3390. mov mem1/reg2, reg1 }
  3391. begin
  3392. if taicpu(p).oper[0]^.typ=top_reg then
  3393. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3394. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3395. RemoveInstruction(hp1);
  3396. Result:=true;
  3397. exit;
  3398. end
  3399. else
  3400. begin
  3401. TransferUsedRegs(TmpUsedRegs);
  3402. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3403. if (taicpu(p).oper[1]^.typ = top_ref) and
  3404. { mov reg1, mem1
  3405. mov mem2, reg1 }
  3406. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3407. GetNextInstruction(hp1, hp2) and
  3408. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3409. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3410. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3411. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3412. { change to
  3413. mov reg1, mem1 mov reg1, mem1
  3414. mov mem2, reg1 cmp reg1, mem2
  3415. cmp mem1, reg1
  3416. }
  3417. begin
  3418. RemoveInstruction(hp2);
  3419. taicpu(hp1).opcode := A_CMP;
  3420. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3421. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3422. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3423. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3424. end;
  3425. end;
  3426. end
  3427. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3428. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3429. begin
  3430. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3431. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3432. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3433. end
  3434. else
  3435. begin
  3436. TransferUsedRegs(TmpUsedRegs);
  3437. if GetNextInstruction(hp1, hp2) and
  3438. MatchOpType(taicpu(p),top_ref,top_reg) and
  3439. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3440. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3441. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3442. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3443. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3444. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3445. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3446. { mov mem1, %reg1
  3447. mov %reg1, mem2
  3448. mov mem2, reg2
  3449. to:
  3450. mov mem1, reg2
  3451. mov reg2, mem2}
  3452. begin
  3453. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3454. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3455. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3456. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3457. RemoveInstruction(hp2);
  3458. Result := True;
  3459. end
  3460. {$ifdef i386}
  3461. { this is enabled for i386 only, as the rules to create the reg sets below
  3462. are too complicated for x86-64, so this makes this code too error prone
  3463. on x86-64
  3464. }
  3465. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3466. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3467. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3468. { mov mem1, reg1 mov mem1, reg1
  3469. mov reg1, mem2 mov reg1, mem2
  3470. mov mem2, reg2 mov mem2, reg1
  3471. to: to:
  3472. mov mem1, reg1 mov mem1, reg1
  3473. mov mem1, reg2 mov reg1, mem2
  3474. mov reg1, mem2
  3475. or (if mem1 depends on reg1
  3476. and/or if mem2 depends on reg2)
  3477. to:
  3478. mov mem1, reg1
  3479. mov reg1, mem2
  3480. mov reg1, reg2
  3481. }
  3482. begin
  3483. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3484. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3485. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3486. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3487. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3488. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3489. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3490. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3491. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3492. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3493. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3494. end
  3495. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3496. begin
  3497. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3498. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3499. end
  3500. else
  3501. begin
  3502. RemoveInstruction(hp2);
  3503. end
  3504. {$endif i386}
  3505. ;
  3506. end;
  3507. end
  3508. { movl [mem1],reg1
  3509. movl [mem1],reg2
  3510. to
  3511. movl [mem1],reg1
  3512. movl reg1,reg2
  3513. }
  3514. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3515. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3516. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3517. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3518. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3519. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3520. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3521. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3522. begin
  3523. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3524. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3525. end;
  3526. { movl const1,[mem1]
  3527. movl [mem1],reg1
  3528. to
  3529. movl const1,reg1
  3530. movl reg1,[mem1]
  3531. }
  3532. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3533. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3534. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3535. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3536. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3537. begin
  3538. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3539. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3540. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3541. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3542. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3543. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3544. Result:=true;
  3545. exit;
  3546. end;
  3547. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3548. { Change:
  3549. movl %reg1,%reg2
  3550. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3551. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3552. To:
  3553. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3554. movl x(%reg1),%reg1
  3555. movl %reg1,%regX
  3556. }
  3557. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3558. begin
  3559. p_SourceReg := taicpu(p).oper[0]^.reg;
  3560. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3561. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3562. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3563. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3564. GetNextInstruction(hp1, hp2) and
  3565. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3566. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3567. begin
  3568. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3569. if RegInRef(p_TargetReg, SourceRef) and
  3570. { If %reg1 also appears in the second reference, then it will
  3571. not refer to the same memory block as the first reference }
  3572. not RegInRef(p_SourceReg, SourceRef) then
  3573. begin
  3574. { Check to see if the references match if %reg2 is changed to %reg1 }
  3575. if SourceRef.base = p_TargetReg then
  3576. SourceRef.base := p_SourceReg;
  3577. if SourceRef.index = p_TargetReg then
  3578. SourceRef.index := p_SourceReg;
  3579. { RefsEqual also checks to ensure both references are non-volatile }
  3580. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3581. begin
  3582. taicpu(hp2).loadreg(0, p_SourceReg);
  3583. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3584. Result := True;
  3585. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3586. begin
  3587. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3588. RemoveCurrentP(p, hp1);
  3589. Exit;
  3590. end
  3591. else
  3592. begin
  3593. { Check to see if %reg2 is no longer in use }
  3594. TransferUsedRegs(TmpUsedRegs);
  3595. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3596. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3597. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3598. begin
  3599. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3600. RemoveCurrentP(p, hp1);
  3601. Exit;
  3602. end;
  3603. end;
  3604. { If we reach this point, p and hp1 weren't actually modified,
  3605. so we can do a bit more work on this pass }
  3606. end;
  3607. end;
  3608. end;
  3609. end;
  3610. end;
  3611. { search further than the next instruction for a mov (as long as it's not a jump) }
  3612. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3613. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3614. (taicpu(p).oper[1]^.typ = top_reg) and
  3615. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3616. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3617. begin
  3618. { we work with hp2 here, so hp1 can be still used later on when
  3619. checking for GetNextInstruction_p }
  3620. hp3 := hp1;
  3621. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3622. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3623. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3626. if NotFirstIteration then
  3627. JumpTracking := TLinkedList.Create
  3628. else
  3629. JumpTracking := nil;
  3630. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3631. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3632. (hp2.typ=ait_instruction) do
  3633. begin
  3634. case taicpu(hp2).opcode of
  3635. A_POP:
  3636. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3637. begin
  3638. if not CrossJump and
  3639. not RegUsedBetween(p_TargetReg, p, hp2) then
  3640. begin
  3641. { We can remove the original MOV since the register
  3642. wasn't used between it and its popping from the stack }
  3643. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3644. RemoveCurrentp(p, hp1);
  3645. Result := True;
  3646. JumpTracking.Free;
  3647. Exit;
  3648. end;
  3649. { Can't go any further }
  3650. Break;
  3651. end;
  3652. A_MOV:
  3653. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3654. ((taicpu(p).oper[0]^.typ=top_const) or
  3655. ((taicpu(p).oper[0]^.typ=top_reg) and
  3656. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3657. )
  3658. ) then
  3659. begin
  3660. { we have
  3661. mov x, %treg
  3662. mov %treg, y
  3663. }
  3664. { We don't need to call UpdateUsedRegs for every instruction between
  3665. p and hp2 because the register we're concerned about will not
  3666. become deallocated (otherwise GetNextInstructionUsingReg would
  3667. have stopped at an earlier instruction). [Kit] }
  3668. TempRegUsed :=
  3669. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3670. RegReadByInstruction(p_TargetReg, hp3) or
  3671. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3672. case taicpu(p).oper[0]^.typ Of
  3673. top_reg:
  3674. begin
  3675. { change
  3676. mov %reg, %treg
  3677. mov %treg, y
  3678. to
  3679. mov %reg, y
  3680. }
  3681. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3682. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3683. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3684. begin
  3685. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3686. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3687. if TempRegUsed then
  3688. begin
  3689. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3690. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3691. { Set the start of the next GetNextInstructionUsingRegCond search
  3692. to start at the entry right before hp2 (which is about to be removed) }
  3693. hp3 := tai(hp2.Previous);
  3694. RemoveInstruction(hp2);
  3695. { See if there's more we can optimise }
  3696. Continue;
  3697. end
  3698. else
  3699. begin
  3700. RemoveInstruction(hp2);
  3701. { We can remove the original MOV too }
  3702. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3703. RemoveCurrentP(p, hp1);
  3704. Result:=true;
  3705. JumpTracking.Free;
  3706. Exit;
  3707. end;
  3708. end
  3709. else
  3710. begin
  3711. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3712. taicpu(hp2).loadReg(0, p_SourceReg);
  3713. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3714. { Check to see if the register also appears in the reference }
  3715. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3716. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3717. { Don't remove the first instruction if the temporary register is in use }
  3718. if not TempRegUsed and
  3719. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3720. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3721. begin
  3722. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3723. RemoveCurrentP(p, hp1);
  3724. Result:=true;
  3725. JumpTracking.Free;
  3726. Exit;
  3727. end;
  3728. { No need to set Result to True here. If there's another instruction later
  3729. on that can be optimised, it will be detected when the main Pass 1 loop
  3730. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3731. end;
  3732. end;
  3733. top_const:
  3734. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3735. begin
  3736. { change
  3737. mov const, %treg
  3738. mov %treg, y
  3739. to
  3740. mov const, y
  3741. }
  3742. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3743. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3744. begin
  3745. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3746. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3747. if TempRegUsed then
  3748. begin
  3749. { Don't remove the first instruction if the temporary register is in use }
  3750. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3751. { No need to set Result to True. If there's another instruction later on
  3752. that can be optimised, it will be detected when the main Pass 1 loop
  3753. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3754. end
  3755. else
  3756. begin
  3757. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3758. RemoveCurrentP(p, hp1);
  3759. Result:=true;
  3760. Exit;
  3761. end;
  3762. end;
  3763. end;
  3764. else
  3765. Internalerror(2019103001);
  3766. end;
  3767. end
  3768. else
  3769. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3770. begin
  3771. if not CrossJump and
  3772. not RegUsedBetween(p_TargetReg, p, hp2) and
  3773. not RegReadByInstruction(p_TargetReg, hp2) then
  3774. begin
  3775. { Register is not used before it is overwritten }
  3776. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3777. RemoveCurrentp(p, hp1);
  3778. Result := True;
  3779. Exit;
  3780. end;
  3781. if (taicpu(p).oper[0]^.typ = top_const) and
  3782. (taicpu(hp2).oper[0]^.typ = top_const) then
  3783. begin
  3784. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3785. begin
  3786. { Same value - register hasn't changed }
  3787. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3788. RemoveInstruction(hp2);
  3789. Result := True;
  3790. { See if there's more we can optimise }
  3791. Continue;
  3792. end;
  3793. end;
  3794. end;
  3795. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3796. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3797. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3798. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3799. begin
  3800. {
  3801. Change from:
  3802. mov ###, %reg
  3803. ...
  3804. movs/z %reg,%reg (Same register, just different sizes)
  3805. To:
  3806. movs/z ###, %reg (Longer version)
  3807. ...
  3808. (remove)
  3809. }
  3810. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3811. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3812. { Keep the first instruction as mov if ### is a constant }
  3813. if taicpu(p).oper[0]^.typ = top_const then
  3814. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3815. else
  3816. begin
  3817. taicpu(p).opcode := taicpu(hp2).opcode;
  3818. taicpu(p).opsize := taicpu(hp2).opsize;
  3819. end;
  3820. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3821. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3822. RemoveInstruction(hp2);
  3823. Result := True;
  3824. JumpTracking.Free;
  3825. Exit;
  3826. end;
  3827. else
  3828. { Move down to the MatchOpType if-block below };
  3829. end;
  3830. { Also catches MOV/S/Z instructions that aren't modified }
  3831. if taicpu(p).oper[0]^.typ = top_reg then
  3832. begin
  3833. p_SourceReg := taicpu(p).oper[0]^.reg;
  3834. if
  3835. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3836. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3837. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3838. begin
  3839. Result := True;
  3840. { Just in case something didn't get modified (e.g. an
  3841. implicit register). Also, if it does read from this
  3842. register, then there's no longer an advantage to
  3843. changing the register on subsequent instructions.}
  3844. if not RegReadByInstruction(p_TargetReg, hp2) then
  3845. begin
  3846. { If a conditional jump was crossed, do not delete
  3847. the original MOV no matter what }
  3848. if not CrossJump and
  3849. { RegEndOfLife returns True if the register is
  3850. deallocated before the next instruction or has
  3851. been loaded with a new value }
  3852. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3853. begin
  3854. { We can remove the original MOV }
  3855. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3856. RemoveCurrentp(p, hp1);
  3857. JumpTracking.Free;
  3858. Result := True;
  3859. Exit;
  3860. end;
  3861. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3862. begin
  3863. { See if there's more we can optimise }
  3864. hp3 := hp2;
  3865. Continue;
  3866. end;
  3867. end;
  3868. end;
  3869. end;
  3870. { Break out of the while loop under normal circumstances }
  3871. Break;
  3872. end;
  3873. JumpTracking.Free;
  3874. end;
  3875. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3876. (taicpu(p).oper[1]^.typ = top_reg) and
  3877. (taicpu(p).opsize = S_L) and
  3878. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3879. (hp2.typ = ait_instruction) and
  3880. (taicpu(hp2).opcode = A_AND) and
  3881. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3882. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3883. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3884. ) then
  3885. begin
  3886. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3887. begin
  3888. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3889. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3890. begin
  3891. { Optimize out:
  3892. mov x, %reg
  3893. and ffffffffh, %reg
  3894. }
  3895. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3896. RemoveInstruction(hp2);
  3897. Result:=true;
  3898. exit;
  3899. end;
  3900. end;
  3901. end;
  3902. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3903. x >= RetOffset) as it doesn't do anything (it writes either to a
  3904. parameter or to the temporary storage room for the function
  3905. result)
  3906. }
  3907. if IsExitCode(hp1) and
  3908. (taicpu(p).oper[1]^.typ = top_ref) and
  3909. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3910. (
  3911. (
  3912. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3913. not (
  3914. assigned(current_procinfo.procdef.funcretsym) and
  3915. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3916. )
  3917. ) or
  3918. { Also discard writes to the stack that are below the base pointer,
  3919. as this is temporary storage rather than a function result on the
  3920. stack, say. }
  3921. (
  3922. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3923. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3924. )
  3925. ) then
  3926. begin
  3927. RemoveCurrentp(p, hp1);
  3928. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3929. RemoveLastDeallocForFuncRes(p);
  3930. Result:=true;
  3931. exit;
  3932. end;
  3933. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3934. begin
  3935. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3936. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3937. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3938. begin
  3939. { change
  3940. mov reg1, mem1
  3941. test/cmp x, mem1
  3942. to
  3943. mov reg1, mem1
  3944. test/cmp x, reg1
  3945. }
  3946. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3947. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3948. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3949. Result := True;
  3950. Exit;
  3951. end;
  3952. if DoMovCmpMemOpt(p, hp1, True) then
  3953. begin
  3954. Result := True;
  3955. Exit;
  3956. end;
  3957. end;
  3958. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3959. { If the flags register is in use, don't change the instruction to an
  3960. ADD otherwise this will scramble the flags. [Kit] }
  3961. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3962. begin
  3963. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3964. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3965. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3966. ) or
  3967. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3968. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3969. )
  3970. ) then
  3971. { mov reg1,ref
  3972. lea reg2,[reg1,reg2]
  3973. to
  3974. add reg2,ref}
  3975. begin
  3976. TransferUsedRegs(TmpUsedRegs);
  3977. { reg1 may not be used afterwards }
  3978. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3979. begin
  3980. Taicpu(hp1).opcode:=A_ADD;
  3981. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3982. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3983. RemoveCurrentp(p, hp1);
  3984. result:=true;
  3985. exit;
  3986. end;
  3987. end;
  3988. { If the LEA instruction can be converted into an arithmetic instruction,
  3989. it may be possible to then fold it in the next optimisation, otherwise
  3990. there's nothing more that can be optimised here. }
  3991. if not ConvertLEA(taicpu(hp1)) then
  3992. Exit;
  3993. end;
  3994. if (taicpu(p).oper[1]^.typ = top_reg) and
  3995. (hp1.typ = ait_instruction) and
  3996. GetNextInstruction(hp1, hp2) and
  3997. MatchInstruction(hp2,A_MOV,[]) and
  3998. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3999. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4000. (
  4001. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4002. {$ifdef x86_64}
  4003. or
  4004. (
  4005. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4006. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4007. )
  4008. {$endif x86_64}
  4009. ) then
  4010. begin
  4011. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4012. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4013. { change movsX/movzX reg/ref, reg2
  4014. add/sub/or/... reg3/$const, reg2
  4015. mov reg2 reg/ref
  4016. dealloc reg2
  4017. to
  4018. add/sub/or/... reg3/$const, reg/ref }
  4019. begin
  4020. TransferUsedRegs(TmpUsedRegs);
  4021. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4022. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4023. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4024. begin
  4025. { by example:
  4026. movswl %si,%eax movswl %si,%eax p
  4027. decl %eax addl %edx,%eax hp1
  4028. movw %ax,%si movw %ax,%si hp2
  4029. ->
  4030. movswl %si,%eax movswl %si,%eax p
  4031. decw %eax addw %edx,%eax hp1
  4032. movw %ax,%si movw %ax,%si hp2
  4033. }
  4034. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4035. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4036. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4037. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4038. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4039. {
  4040. ->
  4041. movswl %si,%eax movswl %si,%eax p
  4042. decw %si addw %dx,%si hp1
  4043. movw %ax,%si movw %ax,%si hp2
  4044. }
  4045. case taicpu(hp1).ops of
  4046. 1:
  4047. begin
  4048. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4049. if taicpu(hp1).oper[0]^.typ=top_reg then
  4050. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4051. end;
  4052. 2:
  4053. begin
  4054. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4055. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4056. (taicpu(hp1).opcode<>A_SHL) and
  4057. (taicpu(hp1).opcode<>A_SHR) and
  4058. (taicpu(hp1).opcode<>A_SAR) then
  4059. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4060. end;
  4061. else
  4062. internalerror(2008042701);
  4063. end;
  4064. {
  4065. ->
  4066. decw %si addw %dx,%si p
  4067. }
  4068. RemoveInstruction(hp2);
  4069. RemoveCurrentP(p, hp1);
  4070. Result:=True;
  4071. Exit;
  4072. end;
  4073. end;
  4074. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4075. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4076. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4077. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4078. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4079. )
  4080. {$ifdef i386}
  4081. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4082. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4083. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4084. {$endif i386}
  4085. then
  4086. { change movsX/movzX reg/ref, reg2
  4087. add/sub/or/... regX/$const, reg2
  4088. mov reg2, reg3
  4089. dealloc reg2
  4090. to
  4091. movsX/movzX reg/ref, reg3
  4092. add/sub/or/... reg3/$const, reg3
  4093. }
  4094. begin
  4095. TransferUsedRegs(TmpUsedRegs);
  4096. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4097. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4098. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4099. begin
  4100. { by example:
  4101. movswl %si,%eax movswl %si,%eax p
  4102. decl %eax addl %edx,%eax hp1
  4103. movw %ax,%si movw %ax,%si hp2
  4104. ->
  4105. movswl %si,%eax movswl %si,%eax p
  4106. decw %eax addw %edx,%eax hp1
  4107. movw %ax,%si movw %ax,%si hp2
  4108. }
  4109. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4110. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4111. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4112. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4113. { limit size of constants as well to avoid assembler errors, but
  4114. check opsize to avoid overflow when left shifting the 1 }
  4115. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4116. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4117. {$ifdef x86_64}
  4118. { Be careful of, for example:
  4119. movl %reg1,%reg2
  4120. addl %reg3,%reg2
  4121. movq %reg2,%reg4
  4122. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4123. }
  4124. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4125. begin
  4126. taicpu(hp2).changeopsize(S_L);
  4127. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4128. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4129. end;
  4130. {$endif x86_64}
  4131. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4132. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4133. if taicpu(p).oper[0]^.typ=top_reg then
  4134. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4135. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4136. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4137. {
  4138. ->
  4139. movswl %si,%eax movswl %si,%eax p
  4140. decw %si addw %dx,%si hp1
  4141. movw %ax,%si movw %ax,%si hp2
  4142. }
  4143. case taicpu(hp1).ops of
  4144. 1:
  4145. begin
  4146. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4147. if taicpu(hp1).oper[0]^.typ=top_reg then
  4148. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4149. end;
  4150. 2:
  4151. begin
  4152. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4153. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4154. (taicpu(hp1).opcode<>A_SHL) and
  4155. (taicpu(hp1).opcode<>A_SHR) and
  4156. (taicpu(hp1).opcode<>A_SAR) then
  4157. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4158. end;
  4159. else
  4160. internalerror(2018111801);
  4161. end;
  4162. {
  4163. ->
  4164. decw %si addw %dx,%si p
  4165. }
  4166. RemoveInstruction(hp2);
  4167. end;
  4168. end;
  4169. end;
  4170. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4171. GetNextInstruction(hp1, hp2) and
  4172. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4173. MatchOperand(Taicpu(p).oper[0]^,0) and
  4174. (Taicpu(p).oper[1]^.typ = top_reg) and
  4175. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4176. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4177. { mov reg1,0
  4178. bts reg1,operand1 --> mov reg1,operand2
  4179. or reg1,operand2 bts reg1,operand1}
  4180. begin
  4181. Taicpu(hp2).opcode:=A_MOV;
  4182. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4183. asml.remove(hp1);
  4184. insertllitem(hp2,hp2.next,hp1);
  4185. RemoveCurrentp(p, hp1);
  4186. Result:=true;
  4187. exit;
  4188. end;
  4189. {
  4190. mov ref,reg0
  4191. <op> reg0,reg1
  4192. dealloc reg0
  4193. to
  4194. <op> ref,reg1
  4195. }
  4196. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4197. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4198. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4199. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4200. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4201. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4202. begin
  4203. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4204. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4205. RemoveCurrentp(p, hp1);
  4206. Result:=true;
  4207. exit;
  4208. end;
  4209. {$ifdef x86_64}
  4210. { Convert:
  4211. movq x(ref),%reg64
  4212. shrq y,%reg64
  4213. To:
  4214. movl x+4(ref),%reg32
  4215. shrl y-32,%reg32 (Remove if y = 32)
  4216. }
  4217. if (taicpu(p).opsize = S_Q) and
  4218. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4219. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4220. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4221. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4222. (taicpu(hp1).oper[0]^.val >= 32) and
  4223. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4224. begin
  4225. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4226. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4227. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4228. { Convert to 32-bit }
  4229. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4230. taicpu(p).opsize := S_L;
  4231. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4232. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4233. if (taicpu(hp1).oper[0]^.val = 32) then
  4234. begin
  4235. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4236. RemoveInstruction(hp1);
  4237. end
  4238. else
  4239. begin
  4240. { This will potentially open up more arithmetic operations since
  4241. the peephole optimizer now has a big hint that only the lower
  4242. 32 bits are currently in use (and opcodes are smaller in size) }
  4243. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4244. taicpu(hp1).opsize := S_L;
  4245. Dec(taicpu(hp1).oper[0]^.val, 32);
  4246. DebugMsg(SPeepholeOptimization + PreMessage +
  4247. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4248. end;
  4249. Result := True;
  4250. Exit;
  4251. end;
  4252. {$endif x86_64}
  4253. { Backward optimisation. If we have:
  4254. func. %reg1,%reg2
  4255. mov %reg2,%reg3
  4256. (dealloc %reg2)
  4257. Change to:
  4258. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4259. }
  4260. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4261. begin
  4262. p_SourceReg := taicpu(p).oper[0]^.reg;
  4263. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4264. TransferUsedRegs(TmpUsedRegs);
  4265. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4266. GetLastInstruction(p, hp2) and
  4267. (hp2.typ = ait_instruction) and
  4268. { Have to make sure it's an instruction that only reads from
  4269. operand 1 and only writes (not reads or modifies) from operand 2;
  4270. in essence, a one-operand pure function such as BSR or POPCNT }
  4271. (taicpu(hp2).ops = 2) and
  4272. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4273. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4274. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4275. begin
  4276. case taicpu(hp2).opcode of
  4277. A_FSTSW, A_FNSTSW,
  4278. A_IN, A_INS, A_OUT, A_OUTS,
  4279. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4280. { These routines have explicit operands, but they are restricted in
  4281. what they can be (e.g. IN and OUT can only read from AL, AX or
  4282. EAX. }
  4283. ;
  4284. else
  4285. begin
  4286. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4287. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4288. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4289. RemoveCurrentp(p, hp1);
  4290. Result := True;
  4291. Exit;
  4292. end;
  4293. end;
  4294. end;
  4295. end;
  4296. end;
  4297. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4298. var
  4299. hp1 : tai;
  4300. begin
  4301. Result:=false;
  4302. if taicpu(p).ops <> 2 then
  4303. exit;
  4304. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4305. GetNextInstruction(p,hp1) then
  4306. begin
  4307. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4308. (taicpu(hp1).ops = 2) then
  4309. begin
  4310. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4311. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4312. { movXX reg1, mem1 or movXX mem1, reg1
  4313. movXX mem2, reg2 movXX reg2, mem2}
  4314. begin
  4315. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4316. { movXX reg1, mem1 or movXX mem1, reg1
  4317. movXX mem2, reg1 movXX reg2, mem1}
  4318. begin
  4319. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4320. begin
  4321. { Removes the second statement from
  4322. movXX reg1, mem1/reg2
  4323. movXX mem1/reg2, reg1
  4324. }
  4325. if taicpu(p).oper[0]^.typ=top_reg then
  4326. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4327. { Removes the second statement from
  4328. movXX mem1/reg1, reg2
  4329. movXX reg2, mem1/reg1
  4330. }
  4331. if (taicpu(p).oper[1]^.typ=top_reg) and
  4332. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4333. begin
  4334. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4335. RemoveInstruction(hp1);
  4336. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4337. Result:=true;
  4338. exit;
  4339. end
  4340. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4341. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4342. begin
  4343. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4344. RemoveInstruction(hp1);
  4345. Result:=true;
  4346. exit;
  4347. end;
  4348. end
  4349. end;
  4350. end;
  4351. end;
  4352. end;
  4353. end;
  4354. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4355. var
  4356. hp1 : tai;
  4357. begin
  4358. result:=false;
  4359. { replace
  4360. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4361. MovX %mreg2,%mreg1
  4362. dealloc %mreg2
  4363. by
  4364. <Op>X %mreg2,%mreg1
  4365. ?
  4366. }
  4367. if GetNextInstruction(p,hp1) and
  4368. { we mix single and double opperations here because we assume that the compiler
  4369. generates vmovapd only after double operations and vmovaps only after single operations }
  4370. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4371. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4372. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4373. (taicpu(p).oper[0]^.typ=top_reg) then
  4374. begin
  4375. TransferUsedRegs(TmpUsedRegs);
  4376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4377. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4378. begin
  4379. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4380. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4381. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4382. RemoveInstruction(hp1);
  4383. result:=true;
  4384. end;
  4385. end;
  4386. end;
  4387. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4388. var
  4389. hp1, p_label, p_dist, hp1_dist: tai;
  4390. JumpLabel, JumpLabel_dist: TAsmLabel;
  4391. FirstValue, SecondValue: TCGInt;
  4392. begin
  4393. Result := False;
  4394. if (taicpu(p).oper[0]^.typ = top_const) and
  4395. (taicpu(p).oper[0]^.val <> -1) then
  4396. begin
  4397. { Convert unsigned maximum constants to -1 to aid optimisation }
  4398. case taicpu(p).opsize of
  4399. S_B:
  4400. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4401. begin
  4402. taicpu(p).oper[0]^.val := -1;
  4403. Result := True;
  4404. Exit;
  4405. end;
  4406. S_W:
  4407. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4408. begin
  4409. taicpu(p).oper[0]^.val := -1;
  4410. Result := True;
  4411. Exit;
  4412. end;
  4413. S_L:
  4414. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4415. begin
  4416. taicpu(p).oper[0]^.val := -1;
  4417. Result := True;
  4418. Exit;
  4419. end;
  4420. {$ifdef x86_64}
  4421. S_Q:
  4422. { Storing anything greater than $7FFFFFFF is not possible so do
  4423. nothing };
  4424. {$endif x86_64}
  4425. else
  4426. InternalError(2021121001);
  4427. end;
  4428. end;
  4429. if GetNextInstruction(p, hp1) and
  4430. TrySwapMovCmp(p, hp1) then
  4431. begin
  4432. Result := True;
  4433. Exit;
  4434. end;
  4435. { Search for:
  4436. test $x,(reg/ref)
  4437. jne @lbl1
  4438. test $y,(reg/ref) (same register or reference)
  4439. jne @lbl1
  4440. Change to:
  4441. test $(x or y),(reg/ref)
  4442. jne @lbl1
  4443. (Note, this doesn't work with je instead of jne)
  4444. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4445. Also search for:
  4446. test $x,(reg/ref)
  4447. je @lbl1
  4448. test $y,(reg/ref)
  4449. je/jne @lbl2
  4450. If (x or y) = x, then the second jump is deterministic
  4451. }
  4452. if (
  4453. (
  4454. (taicpu(p).oper[0]^.typ = top_const) or
  4455. (
  4456. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4457. (taicpu(p).oper[0]^.typ = top_reg) and
  4458. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4459. )
  4460. ) and
  4461. MatchInstruction(hp1, A_JCC, [])
  4462. ) then
  4463. begin
  4464. if (taicpu(p).oper[0]^.typ = top_reg) and
  4465. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4466. FirstValue := -1
  4467. else
  4468. FirstValue := taicpu(p).oper[0]^.val;
  4469. { If we have several test/jne's in a row, it might be the case that
  4470. the second label doesn't go to the same location, but the one
  4471. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4472. so accommodate for this with a while loop.
  4473. }
  4474. hp1_dist := hp1;
  4475. if GetNextInstruction(hp1, p_dist) and
  4476. (p_dist.typ = ait_instruction) and
  4477. (
  4478. (
  4479. (taicpu(p_dist).opcode = A_TEST) and
  4480. (
  4481. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4482. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4483. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4484. )
  4485. ) or
  4486. (
  4487. { cmp 0,%reg = test %reg,%reg }
  4488. (taicpu(p_dist).opcode = A_CMP) and
  4489. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4490. )
  4491. ) and
  4492. { Make sure the destination operands are actually the same }
  4493. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4494. GetNextInstruction(p_dist, hp1_dist) and
  4495. MatchInstruction(hp1_dist, A_JCC, []) then
  4496. begin
  4497. if
  4498. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4499. (
  4500. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4501. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4502. ) then
  4503. SecondValue := -1
  4504. else
  4505. SecondValue := taicpu(p_dist).oper[0]^.val;
  4506. { If both of the TEST constants are identical, delete the second
  4507. TEST that is unnecessary. }
  4508. if (FirstValue = SecondValue) then
  4509. begin
  4510. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4511. RemoveInstruction(p_dist);
  4512. { Don't let the flags register become deallocated and reallocated between the jumps }
  4513. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4514. Result := True;
  4515. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4516. begin
  4517. { Since the second jump's condition is a subset of the first, we
  4518. know it will never branch because the first jump dominates it.
  4519. Get it out of the way now rather than wait for the jump
  4520. optimisations for a speed boost. }
  4521. if IsJumpToLabel(taicpu(hp1_dist)) then
  4522. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4523. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4524. RemoveInstruction(hp1_dist);
  4525. end
  4526. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4527. begin
  4528. { If the inverse of the first condition is a subset of the second,
  4529. the second one will definitely branch if the first one doesn't }
  4530. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4531. MakeUnconditional(taicpu(hp1_dist));
  4532. RemoveDeadCodeAfterJump(hp1_dist);
  4533. end;
  4534. Exit;
  4535. end;
  4536. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4537. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4538. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4539. then the second jump will never branch, so it can also be
  4540. removed regardless of where it goes }
  4541. (
  4542. (FirstValue = -1) or
  4543. (SecondValue = -1) or
  4544. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4545. ) then
  4546. begin
  4547. { Same jump location... can be a register since nothing's changed }
  4548. { If any of the entries are equivalent to test %reg,%reg, then the
  4549. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4550. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4551. if IsJumpToLabel(taicpu(hp1_dist)) then
  4552. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4553. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4554. RemoveInstruction(hp1_dist);
  4555. { Only remove the second test if no jumps or other conditional instructions follow }
  4556. TransferUsedRegs(TmpUsedRegs);
  4557. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4558. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4559. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4560. RemoveInstruction(p_dist);
  4561. Result := True;
  4562. Exit;
  4563. end;
  4564. end;
  4565. end;
  4566. { Search for:
  4567. test %reg,%reg
  4568. j(c1) @lbl1
  4569. ...
  4570. @lbl:
  4571. test %reg,%reg (same register)
  4572. j(c2) @lbl2
  4573. If c2 is a subset of c1, change to:
  4574. test %reg,%reg
  4575. j(c1) @lbl2
  4576. (@lbl1 may become a dead label as a result)
  4577. }
  4578. if (taicpu(p).oper[1]^.typ = top_reg) and
  4579. (taicpu(p).oper[0]^.typ = top_reg) and
  4580. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4581. MatchInstruction(hp1, A_JCC, []) and
  4582. IsJumpToLabel(taicpu(hp1)) then
  4583. begin
  4584. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4585. p_label := nil;
  4586. if Assigned(JumpLabel) then
  4587. p_label := getlabelwithsym(JumpLabel);
  4588. if Assigned(p_label) and
  4589. GetNextInstruction(p_label, p_dist) and
  4590. MatchInstruction(p_dist, A_TEST, []) and
  4591. { It's fine if the second test uses smaller sub-registers }
  4592. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4593. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4594. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4595. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4596. GetNextInstruction(p_dist, hp1_dist) and
  4597. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4598. begin
  4599. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4600. if JumpLabel = JumpLabel_dist then
  4601. { This is an infinite loop }
  4602. Exit;
  4603. { Best optimisation when the first condition is a subset (or equal) of the second }
  4604. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4605. begin
  4606. { Any registers used here will already be allocated }
  4607. if Assigned(JumpLabel) then
  4608. JumpLabel.DecRefs;
  4609. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4610. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4611. Result := True;
  4612. Exit;
  4613. end;
  4614. end;
  4615. end;
  4616. end;
  4617. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4618. var
  4619. hp1, hp2: tai;
  4620. ActiveReg: TRegister;
  4621. OldOffset: asizeint;
  4622. ThisConst: TCGInt;
  4623. function RegDeallocated: Boolean;
  4624. begin
  4625. TransferUsedRegs(TmpUsedRegs);
  4626. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4627. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4628. end;
  4629. begin
  4630. result:=false;
  4631. hp1 := nil;
  4632. { replace
  4633. addX const,%reg1
  4634. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4635. dealloc %reg1
  4636. by
  4637. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4638. }
  4639. if MatchOpType(taicpu(p),top_const,top_reg) then
  4640. begin
  4641. ActiveReg := taicpu(p).oper[1]^.reg;
  4642. { Ensures the entire register was updated }
  4643. if (taicpu(p).opsize >= S_L) and
  4644. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4645. MatchInstruction(hp1,A_LEA,[]) and
  4646. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4647. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4648. (
  4649. { Cover the case where the register in the reference is also the destination register }
  4650. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4651. (
  4652. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4653. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4654. RegDeallocated
  4655. )
  4656. ) then
  4657. begin
  4658. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4659. {$push}
  4660. {$R-}{$Q-}
  4661. { Explicitly disable overflow checking for these offset calculation
  4662. as those do not matter for the final result }
  4663. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4664. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4665. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4666. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4667. {$pop}
  4668. {$ifdef x86_64}
  4669. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4670. begin
  4671. { Overflow; abort }
  4672. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4673. end
  4674. else
  4675. {$endif x86_64}
  4676. begin
  4677. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4678. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4679. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4680. RemoveCurrentP(p, hp1)
  4681. else
  4682. RemoveCurrentP(p);
  4683. result:=true;
  4684. Exit;
  4685. end;
  4686. end;
  4687. if (
  4688. { Save calling GetNextInstructionUsingReg again }
  4689. Assigned(hp1) or
  4690. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4691. ) and
  4692. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4693. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4694. begin
  4695. if taicpu(hp1).oper[0]^.typ = top_const then
  4696. begin
  4697. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4698. if taicpu(hp1).opcode = A_ADD then
  4699. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4700. else
  4701. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4702. Result := True;
  4703. { Handle any overflows }
  4704. case taicpu(p).opsize of
  4705. S_B:
  4706. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4707. S_W:
  4708. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4709. S_L:
  4710. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4711. {$ifdef x86_64}
  4712. S_Q:
  4713. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4714. { Overflow; abort }
  4715. Result := False
  4716. else
  4717. taicpu(p).oper[0]^.val := ThisConst;
  4718. {$endif x86_64}
  4719. else
  4720. InternalError(2021102610);
  4721. end;
  4722. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4723. if Result then
  4724. begin
  4725. if (taicpu(p).oper[0]^.val < 0) and
  4726. (
  4727. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4728. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4729. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4730. ) then
  4731. begin
  4732. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4733. taicpu(p).opcode := A_SUB;
  4734. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4735. end
  4736. else
  4737. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4738. RemoveInstruction(hp1);
  4739. end;
  4740. end
  4741. else
  4742. begin
  4743. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4744. TransferUsedRegs(TmpUsedRegs);
  4745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4746. hp2 := p;
  4747. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4748. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4749. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4750. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4751. begin
  4752. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4753. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4754. Asml.Remove(p);
  4755. Asml.InsertAfter(p, hp1);
  4756. p := hp1;
  4757. Result := True;
  4758. end;
  4759. end;
  4760. end;
  4761. end;
  4762. end;
  4763. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4764. var
  4765. hp1: tai;
  4766. ref: Integer;
  4767. saveref: treference;
  4768. Multiple: TCGInt;
  4769. Adjacent: Boolean;
  4770. begin
  4771. Result:=false;
  4772. { play save and throw an error if LEA uses a seg register prefix,
  4773. this is most likely an error somewhere else }
  4774. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4775. internalerror(2022022001);
  4776. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4777. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4778. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4779. (
  4780. { do not mess with leas accessing the stack pointer
  4781. unless it's a null operation }
  4782. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4783. (
  4784. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4785. (taicpu(p).oper[0]^.ref^.offset = 0)
  4786. )
  4787. ) and
  4788. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4789. begin
  4790. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4791. begin
  4792. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4793. begin
  4794. taicpu(p).opcode := A_MOV;
  4795. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4796. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4797. end
  4798. else
  4799. begin
  4800. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4801. RemoveCurrentP(p);
  4802. end;
  4803. Result:=true;
  4804. exit;
  4805. end
  4806. else if (
  4807. { continue to use lea to adjust the stack pointer,
  4808. it is the recommended way, but only if not optimizing for size }
  4809. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4810. (cs_opt_size in current_settings.optimizerswitches)
  4811. ) and
  4812. { If the flags register is in use, don't change the instruction
  4813. to an ADD otherwise this will scramble the flags. [Kit] }
  4814. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4815. ConvertLEA(taicpu(p)) then
  4816. begin
  4817. Result:=true;
  4818. exit;
  4819. end;
  4820. end;
  4821. { Don't optimise if the stack or frame pointer is the destination register }
  4822. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4823. Exit;
  4824. if GetNextInstruction(p,hp1) and
  4825. (hp1.typ=ait_instruction) then
  4826. begin
  4827. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4828. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4829. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4830. begin
  4831. TransferUsedRegs(TmpUsedRegs);
  4832. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4833. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4834. begin
  4835. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4836. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4837. RemoveInstruction(hp1);
  4838. result:=true;
  4839. exit;
  4840. end;
  4841. end;
  4842. { changes
  4843. lea <ref1>, reg1
  4844. <op> ...,<ref. with reg1>,...
  4845. to
  4846. <op> ...,<ref1>,... }
  4847. { find a reference which uses reg1 }
  4848. 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
  4849. ref:=0
  4850. 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
  4851. ref:=1
  4852. else
  4853. ref:=-1;
  4854. if (ref<>-1) and
  4855. { reg1 must be either the base or the index }
  4856. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4857. begin
  4858. { reg1 can be removed from the reference }
  4859. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4860. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4861. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4862. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4863. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4864. else
  4865. Internalerror(2019111201);
  4866. { check if the can insert all data of the lea into the second instruction }
  4867. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4868. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4869. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4870. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4871. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4872. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4873. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4874. {$ifdef x86_64}
  4875. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4876. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4877. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4878. )
  4879. {$endif x86_64}
  4880. then
  4881. begin
  4882. { reg1 might not used by the second instruction after it is remove from the reference }
  4883. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4884. begin
  4885. TransferUsedRegs(TmpUsedRegs);
  4886. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4887. { reg1 is not updated so it might not be used afterwards }
  4888. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4889. begin
  4890. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4891. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4892. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4893. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4894. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4895. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4896. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4897. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4898. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4899. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4900. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4901. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4902. RemoveCurrentP(p, hp1);
  4903. result:=true;
  4904. exit;
  4905. end
  4906. end;
  4907. end;
  4908. { recover }
  4909. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4910. end;
  4911. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4912. if Adjacent or
  4913. { Check further ahead (up to 2 instructions ahead for -O2) }
  4914. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4915. begin
  4916. { Check common LEA/LEA conditions }
  4917. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4918. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4919. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4920. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4921. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4922. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4923. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4924. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4925. (
  4926. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4927. calling it (since it calls GetNextInstruction) }
  4928. Adjacent or
  4929. (
  4930. (
  4931. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4932. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4933. ) and (
  4934. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4935. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4936. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4937. )
  4938. )
  4939. ) then
  4940. begin
  4941. { changes
  4942. lea (regX,scale), reg1
  4943. lea offset(reg1,reg1), reg1
  4944. to
  4945. lea offset(regX,scale*2), reg1
  4946. and
  4947. lea (regX,scale1), reg1
  4948. lea offset(reg1,scale2), reg1
  4949. to
  4950. lea offset(regX,scale1*scale2), reg1
  4951. ... so long as the final scale does not exceed 8
  4952. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4953. }
  4954. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4955. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4956. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4957. (
  4958. (
  4959. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4960. ) or (
  4961. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4962. (
  4963. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4964. (
  4965. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4966. Adjacent or
  4967. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4968. )
  4969. )
  4970. )
  4971. ) and (
  4972. (
  4973. { lea (reg1,scale2), reg1 variant }
  4974. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4975. (
  4976. (
  4977. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4978. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4979. ) or (
  4980. { lea (regX,regX), reg1 variant }
  4981. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4982. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4983. )
  4984. )
  4985. ) or (
  4986. { lea (reg1,reg1), reg1 variant }
  4987. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4988. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4989. )
  4990. ) then
  4991. begin
  4992. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4993. { Make everything homogeneous to make calculations easier }
  4994. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4995. begin
  4996. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4997. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4998. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4999. else
  5000. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5001. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5002. end;
  5003. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5004. begin
  5005. { Just to prevent miscalculations }
  5006. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5007. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5008. else
  5009. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5010. end
  5011. else
  5012. begin
  5013. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5014. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5015. end;
  5016. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5017. RemoveCurrentP(p);
  5018. result:=true;
  5019. exit;
  5020. end
  5021. { changes
  5022. lea offset1(regX), reg1
  5023. lea offset2(reg1), reg1
  5024. to
  5025. lea offset1+offset2(regX), reg1 }
  5026. else if
  5027. (
  5028. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5029. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5030. ) or (
  5031. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5032. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5033. (
  5034. (
  5035. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5036. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5037. ) or (
  5038. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5039. (
  5040. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5041. (
  5042. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5043. (
  5044. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5045. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5046. )
  5047. )
  5048. )
  5049. )
  5050. )
  5051. ) then
  5052. begin
  5053. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5054. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5055. begin
  5056. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5057. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5058. { if the register is used as index and base, we have to increase for base as well
  5059. and adapt base }
  5060. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5061. begin
  5062. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5063. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5064. end;
  5065. end
  5066. else
  5067. begin
  5068. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5069. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5070. end;
  5071. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5072. begin
  5073. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5074. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5075. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5076. end;
  5077. RemoveCurrentP(p);
  5078. result:=true;
  5079. exit;
  5080. end;
  5081. end;
  5082. { Change:
  5083. leal/q $x(%reg1),%reg2
  5084. ...
  5085. shll/q $y,%reg2
  5086. To:
  5087. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5088. }
  5089. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5090. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5091. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5092. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5093. (taicpu(hp1).oper[0]^.val <= 3) then
  5094. begin
  5095. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5096. TransferUsedRegs(TmpUsedRegs);
  5097. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5098. if
  5099. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5100. (this works even if scalefactor is zero) }
  5101. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5102. { Ensure offset doesn't go out of bounds }
  5103. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5104. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5105. (
  5106. (
  5107. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5108. (
  5109. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5110. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5111. (
  5112. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5113. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5114. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5115. )
  5116. )
  5117. ) or (
  5118. (
  5119. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5120. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5121. ) and
  5122. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5123. )
  5124. ) then
  5125. begin
  5126. repeat
  5127. with taicpu(p).oper[0]^.ref^ do
  5128. begin
  5129. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5130. if index = base then
  5131. begin
  5132. if Multiple > 4 then
  5133. { Optimisation will no longer work because resultant
  5134. scale factor will exceed 8 }
  5135. Break;
  5136. base := NR_NO;
  5137. scalefactor := 2;
  5138. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5139. end
  5140. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5141. begin
  5142. { Scale factor only works on the index register }
  5143. index := base;
  5144. base := NR_NO;
  5145. end;
  5146. { For safety }
  5147. if scalefactor <= 1 then
  5148. begin
  5149. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5150. scalefactor := Multiple;
  5151. end
  5152. else
  5153. begin
  5154. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5155. scalefactor := scalefactor * Multiple;
  5156. end;
  5157. offset := offset * Multiple;
  5158. end;
  5159. RemoveInstruction(hp1);
  5160. Result := True;
  5161. Exit;
  5162. { This repeat..until loop exists for the benefit of Break }
  5163. until True;
  5164. end;
  5165. end;
  5166. end;
  5167. end;
  5168. end;
  5169. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5170. var
  5171. hp1 : tai;
  5172. begin
  5173. DoSubAddOpt := False;
  5174. if taicpu(p).oper[0]^.typ <> top_const then
  5175. { Should have been confirmed before calling }
  5176. InternalError(2021102601);
  5177. if GetLastInstruction(p, hp1) and
  5178. (hp1.typ = ait_instruction) and
  5179. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5180. case taicpu(hp1).opcode Of
  5181. A_DEC:
  5182. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5183. begin
  5184. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5185. RemoveInstruction(hp1);
  5186. end;
  5187. A_SUB:
  5188. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5189. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5190. begin
  5191. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5192. RemoveInstruction(hp1);
  5193. end;
  5194. A_ADD:
  5195. begin
  5196. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5197. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5198. begin
  5199. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5200. RemoveInstruction(hp1);
  5201. if (taicpu(p).oper[0]^.val = 0) then
  5202. begin
  5203. hp1 := tai(p.next);
  5204. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5205. if not GetLastInstruction(hp1, p) then
  5206. p := hp1;
  5207. DoSubAddOpt := True;
  5208. end
  5209. end;
  5210. end;
  5211. else
  5212. ;
  5213. end;
  5214. end;
  5215. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5216. begin
  5217. Result := False;
  5218. if UpdateTmpUsedRegs then
  5219. TransferUsedRegs(TmpUsedRegs);
  5220. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5221. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5222. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5223. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5224. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5225. (
  5226. (
  5227. (taicpu(hp1).opcode = A_TEST)
  5228. ) or (
  5229. (taicpu(hp1).opcode = A_CMP) and
  5230. { A sanity check more than anything }
  5231. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5232. )
  5233. ) then
  5234. begin
  5235. { change
  5236. mov mem, %reg
  5237. cmp/test x, %reg / test %reg,%reg
  5238. (reg deallocated)
  5239. to
  5240. cmp/test x, mem / cmp 0, mem
  5241. }
  5242. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5243. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5244. begin
  5245. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5246. if (taicpu(hp1).opcode = A_TEST) and
  5247. (
  5248. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5249. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5250. ) then
  5251. begin
  5252. taicpu(hp1).opcode := A_CMP;
  5253. taicpu(hp1).loadconst(0, 0);
  5254. end;
  5255. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5256. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5257. RemoveCurrentP(p, hp1);
  5258. Result := True;
  5259. Exit;
  5260. end;
  5261. end;
  5262. end;
  5263. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5264. var
  5265. hp2, hp3, hp4, hp5, hp6: tai;
  5266. ThisReg: TRegister;
  5267. JumpLoc: TAsmLabel;
  5268. begin
  5269. Result := False;
  5270. {
  5271. Convert:
  5272. j<c> .L1
  5273. .L2:
  5274. mov 1,reg
  5275. jmp .L3 (or ret, although it might not be a RET yet)
  5276. .L1:
  5277. mov 0,reg
  5278. jmp .L3 (or ret)
  5279. ( As long as .L3 <> .L1 or .L2)
  5280. To:
  5281. mov 0,reg
  5282. set<not(c)> reg
  5283. jmp .L3 (or ret)
  5284. .L2:
  5285. mov 1,reg
  5286. jmp .L3 (or ret)
  5287. .L1:
  5288. mov 0,reg
  5289. jmp .L3 (or ret)
  5290. }
  5291. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5292. Exit;
  5293. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5294. if GetNextInstruction(hp_label, hp2) and
  5295. MatchInstruction(hp2,A_MOV,[]) and
  5296. (taicpu(hp2).oper[0]^.typ = top_const) and
  5297. (
  5298. (
  5299. (taicpu(hp2).oper[1]^.typ = top_reg)
  5300. {$ifdef i386}
  5301. { Under i386, ESI, EDI, EBP and ESP
  5302. don't have an 8-bit representation }
  5303. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5304. {$endif i386}
  5305. ) or (
  5306. {$ifdef i386}
  5307. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5308. {$endif i386}
  5309. (taicpu(hp2).opsize = S_B)
  5310. )
  5311. ) and
  5312. GetNextInstruction(hp2, hp3) and
  5313. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5314. (
  5315. (taicpu(hp3).opcode=A_RET) or
  5316. (
  5317. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5318. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5319. )
  5320. ) and
  5321. GetNextInstruction(hp3, hp4) and
  5322. SkipAligns(hp4, hp4) and
  5323. (hp4.typ=ait_label) and
  5324. (tai_label(hp4).labsym=JumpLoc) and
  5325. (
  5326. not (cs_opt_size in current_settings.optimizerswitches) or
  5327. { If the initial jump is the label's only reference, then it will
  5328. become a dead label if the other conditions are met and hence
  5329. remove at least 2 instructions, including a jump }
  5330. (JumpLoc.getrefs = 1)
  5331. ) and
  5332. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5333. that will be optimised out }
  5334. GetNextInstruction(hp4, hp5) and
  5335. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5336. (taicpu(hp5).oper[0]^.typ = top_const) and
  5337. (
  5338. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5339. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5340. ) and
  5341. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5342. GetNextInstruction(hp5,hp6) and
  5343. (
  5344. (hp6.typ<>ait_label) or
  5345. SkipLabels(hp6, hp6)
  5346. ) and
  5347. (hp6.typ=ait_instruction) then
  5348. begin
  5349. { First, let's look at the two jumps that are hp3 and hp6 }
  5350. if not
  5351. (
  5352. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5353. (
  5354. (taicpu(hp6).opcode=A_RET) or
  5355. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5356. )
  5357. ) then
  5358. { If condition is False, then the JMP/RET instructions matched conventionally }
  5359. begin
  5360. { See if one of the jumps can be instantly converted into a RET }
  5361. if (taicpu(hp3).opcode=A_JMP) then
  5362. begin
  5363. { Reuse hp5 }
  5364. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5365. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5366. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5367. Exit;
  5368. if MatchInstruction(hp5, A_RET, []) then
  5369. begin
  5370. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5371. ConvertJumpToRET(hp3, hp5);
  5372. Result := True;
  5373. end
  5374. else
  5375. Exit;
  5376. end;
  5377. if (taicpu(hp6).opcode=A_JMP) then
  5378. begin
  5379. { Reuse hp5 }
  5380. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5381. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5382. Exit;
  5383. if MatchInstruction(hp5, A_RET, []) then
  5384. begin
  5385. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5386. ConvertJumpToRET(hp6, hp5);
  5387. Result := True;
  5388. end
  5389. else
  5390. Exit;
  5391. end;
  5392. if not
  5393. (
  5394. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5395. (
  5396. (taicpu(hp6).opcode=A_RET) or
  5397. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5398. )
  5399. ) then
  5400. { Still doesn't match }
  5401. Exit;
  5402. end;
  5403. if (taicpu(hp2).oper[0]^.val = 1) then
  5404. begin
  5405. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5406. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5407. end
  5408. else
  5409. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5410. if taicpu(hp2).opsize=S_B then
  5411. begin
  5412. if taicpu(hp2).oper[1]^.typ = top_reg then
  5413. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5414. else
  5415. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5416. hp2 := p;
  5417. end
  5418. else
  5419. begin
  5420. { Will be a register because the size can't be S_B otherwise }
  5421. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5422. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5423. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5424. taicpu(hp2).fileinfo:=taicpu(p).fileinfo;
  5425. { Inserting it right before p will guarantee that the flags are also tracked }
  5426. Asml.InsertBefore(hp2, p);
  5427. end;
  5428. taicpu(hp4).fileinfo := taicpu(hp2).fileinfo;
  5429. taicpu(hp4).condition := taicpu(p).condition;
  5430. asml.InsertBefore(hp4, hp2);
  5431. JumpLoc.decrefs;
  5432. if taicpu(hp3).opcode = A_JMP then
  5433. begin
  5434. MakeUnconditional(taicpu(p));
  5435. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5436. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5437. end
  5438. else
  5439. begin
  5440. taicpu(p).condition := C_None;
  5441. taicpu(p).opcode := A_RET;
  5442. taicpu(p).clearop(0);
  5443. taicpu(p).ops := 0;
  5444. end;
  5445. if (JumpLoc.getrefs = 0) then
  5446. RemoveDeadCodeAfterJump(hp3);
  5447. Result:=true;
  5448. exit;
  5449. end;
  5450. end;
  5451. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5452. var
  5453. hp1, hp2: tai;
  5454. ActiveReg: TRegister;
  5455. OldOffset: asizeint;
  5456. ThisConst: TCGInt;
  5457. function RegDeallocated: Boolean;
  5458. begin
  5459. TransferUsedRegs(TmpUsedRegs);
  5460. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5461. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5462. end;
  5463. begin
  5464. Result:=false;
  5465. hp1 := nil;
  5466. { replace
  5467. subX const,%reg1
  5468. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5469. dealloc %reg1
  5470. by
  5471. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5472. }
  5473. if MatchOpType(taicpu(p),top_const,top_reg) then
  5474. begin
  5475. ActiveReg := taicpu(p).oper[1]^.reg;
  5476. { Ensures the entire register was updated }
  5477. if (taicpu(p).opsize >= S_L) and
  5478. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5479. MatchInstruction(hp1,A_LEA,[]) and
  5480. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5481. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5482. (
  5483. { Cover the case where the register in the reference is also the destination register }
  5484. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5485. (
  5486. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5487. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5488. RegDeallocated
  5489. )
  5490. ) then
  5491. begin
  5492. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5493. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5494. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5495. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5496. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5497. {$ifdef x86_64}
  5498. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5499. begin
  5500. { Overflow; abort }
  5501. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5502. end
  5503. else
  5504. {$endif x86_64}
  5505. begin
  5506. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5507. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5508. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5509. RemoveCurrentP(p, hp1)
  5510. else
  5511. RemoveCurrentP(p);
  5512. result:=true;
  5513. Exit;
  5514. end;
  5515. end;
  5516. if (
  5517. { Save calling GetNextInstructionUsingReg again }
  5518. Assigned(hp1) or
  5519. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5520. ) and
  5521. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5522. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5523. begin
  5524. if taicpu(hp1).oper[0]^.typ = top_const then
  5525. begin
  5526. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5527. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5528. Result := True;
  5529. { Handle any overflows }
  5530. case taicpu(p).opsize of
  5531. S_B:
  5532. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5533. S_W:
  5534. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5535. S_L:
  5536. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5537. {$ifdef x86_64}
  5538. S_Q:
  5539. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5540. { Overflow; abort }
  5541. Result := False
  5542. else
  5543. taicpu(p).oper[0]^.val := ThisConst;
  5544. {$endif x86_64}
  5545. else
  5546. InternalError(2021102611);
  5547. end;
  5548. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5549. if Result then
  5550. begin
  5551. if (taicpu(p).oper[0]^.val < 0) and
  5552. (
  5553. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5554. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5555. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5556. ) then
  5557. begin
  5558. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5559. taicpu(p).opcode := A_SUB;
  5560. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5561. end
  5562. else
  5563. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5564. RemoveInstruction(hp1);
  5565. end;
  5566. end
  5567. else
  5568. begin
  5569. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5570. TransferUsedRegs(TmpUsedRegs);
  5571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5572. hp2 := p;
  5573. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5574. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5575. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5576. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5577. begin
  5578. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5579. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5580. Asml.Remove(p);
  5581. Asml.InsertAfter(p, hp1);
  5582. p := hp1;
  5583. Result := True;
  5584. Exit;
  5585. end;
  5586. end;
  5587. end;
  5588. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5589. { * change "sub/add const1, reg" or "dec reg" followed by
  5590. "sub const2, reg" to one "sub ..., reg" }
  5591. {$ifdef i386}
  5592. if (taicpu(p).oper[0]^.val = 2) and
  5593. (ActiveReg = NR_ESP) and
  5594. { Don't do the sub/push optimization if the sub }
  5595. { comes from setting up the stack frame (JM) }
  5596. (not(GetLastInstruction(p,hp1)) or
  5597. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5598. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5599. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5600. begin
  5601. hp1 := tai(p.next);
  5602. while Assigned(hp1) and
  5603. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5604. not RegReadByInstruction(NR_ESP,hp1) and
  5605. not RegModifiedByInstruction(NR_ESP,hp1) do
  5606. hp1 := tai(hp1.next);
  5607. if Assigned(hp1) and
  5608. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5609. begin
  5610. taicpu(hp1).changeopsize(S_L);
  5611. if taicpu(hp1).oper[0]^.typ=top_reg then
  5612. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5613. hp1 := tai(p.next);
  5614. RemoveCurrentp(p, hp1);
  5615. Result:=true;
  5616. exit;
  5617. end;
  5618. end;
  5619. {$endif i386}
  5620. if DoSubAddOpt(p) then
  5621. Result:=true;
  5622. end;
  5623. end;
  5624. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5625. var
  5626. TmpBool1,TmpBool2 : Boolean;
  5627. tmpref : treference;
  5628. hp1,hp2: tai;
  5629. mask: tcgint;
  5630. begin
  5631. Result:=false;
  5632. { All these optimisations work on "shl/sal const,%reg" }
  5633. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5634. Exit;
  5635. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5636. (taicpu(p).oper[0]^.val <= 3) then
  5637. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5638. begin
  5639. { should we check the next instruction? }
  5640. TmpBool1 := True;
  5641. { have we found an add/sub which could be
  5642. integrated in the lea? }
  5643. TmpBool2 := False;
  5644. reference_reset(tmpref,2,[]);
  5645. TmpRef.index := taicpu(p).oper[1]^.reg;
  5646. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5647. while TmpBool1 and
  5648. GetNextInstruction(p, hp1) and
  5649. (tai(hp1).typ = ait_instruction) and
  5650. ((((taicpu(hp1).opcode = A_ADD) or
  5651. (taicpu(hp1).opcode = A_SUB)) and
  5652. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5653. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5654. (((taicpu(hp1).opcode = A_INC) or
  5655. (taicpu(hp1).opcode = A_DEC)) and
  5656. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5657. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5658. ((taicpu(hp1).opcode = A_LEA) and
  5659. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5660. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5661. (not GetNextInstruction(hp1,hp2) or
  5662. not instrReadsFlags(hp2)) Do
  5663. begin
  5664. TmpBool1 := False;
  5665. if taicpu(hp1).opcode=A_LEA then
  5666. begin
  5667. if (TmpRef.base = NR_NO) and
  5668. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5669. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5670. { Segment register isn't a concern here }
  5671. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5672. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5673. begin
  5674. TmpBool1 := True;
  5675. TmpBool2 := True;
  5676. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5677. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5678. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5679. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5680. RemoveInstruction(hp1);
  5681. end
  5682. end
  5683. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5684. begin
  5685. TmpBool1 := True;
  5686. TmpBool2 := True;
  5687. case taicpu(hp1).opcode of
  5688. A_ADD:
  5689. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5690. A_SUB:
  5691. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5692. else
  5693. internalerror(2019050536);
  5694. end;
  5695. RemoveInstruction(hp1);
  5696. end
  5697. else
  5698. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5699. (((taicpu(hp1).opcode = A_ADD) and
  5700. (TmpRef.base = NR_NO)) or
  5701. (taicpu(hp1).opcode = A_INC) or
  5702. (taicpu(hp1).opcode = A_DEC)) then
  5703. begin
  5704. TmpBool1 := True;
  5705. TmpBool2 := True;
  5706. case taicpu(hp1).opcode of
  5707. A_ADD:
  5708. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5709. A_INC:
  5710. inc(TmpRef.offset);
  5711. A_DEC:
  5712. dec(TmpRef.offset);
  5713. else
  5714. internalerror(2019050535);
  5715. end;
  5716. RemoveInstruction(hp1);
  5717. end;
  5718. end;
  5719. if TmpBool2
  5720. {$ifndef x86_64}
  5721. or
  5722. ((current_settings.optimizecputype < cpu_Pentium2) and
  5723. (taicpu(p).oper[0]^.val <= 3) and
  5724. not(cs_opt_size in current_settings.optimizerswitches))
  5725. {$endif x86_64}
  5726. then
  5727. begin
  5728. if not(TmpBool2) and
  5729. (taicpu(p).oper[0]^.val=1) then
  5730. begin
  5731. taicpu(p).opcode := A_ADD;
  5732. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5733. end
  5734. else
  5735. begin
  5736. taicpu(p).opcode := A_LEA;
  5737. taicpu(p).loadref(0, TmpRef);
  5738. end;
  5739. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5740. Result := True;
  5741. end;
  5742. end
  5743. {$ifndef x86_64}
  5744. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5745. begin
  5746. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5747. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5748. (unlike shl, which is only Tairable in the U pipe) }
  5749. if taicpu(p).oper[0]^.val=1 then
  5750. begin
  5751. taicpu(p).opcode := A_ADD;
  5752. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5753. Result := True;
  5754. end
  5755. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5756. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5757. else if (taicpu(p).opsize = S_L) and
  5758. (taicpu(p).oper[0]^.val<= 3) then
  5759. begin
  5760. reference_reset(tmpref,2,[]);
  5761. TmpRef.index := taicpu(p).oper[1]^.reg;
  5762. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5763. taicpu(p).opcode := A_LEA;
  5764. taicpu(p).loadref(0, TmpRef);
  5765. Result := True;
  5766. end;
  5767. end
  5768. {$endif x86_64}
  5769. else if
  5770. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5771. (
  5772. (
  5773. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5774. SetAndTest(hp1, hp2)
  5775. {$ifdef x86_64}
  5776. ) or
  5777. (
  5778. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5779. GetNextInstruction(hp1, hp2) and
  5780. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5781. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5782. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5783. {$endif x86_64}
  5784. )
  5785. ) and
  5786. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5787. begin
  5788. { Change:
  5789. shl x, %reg1
  5790. mov -(1<<x), %reg2
  5791. and %reg2, %reg1
  5792. Or:
  5793. shl x, %reg1
  5794. and -(1<<x), %reg1
  5795. To just:
  5796. shl x, %reg1
  5797. Since the and operation only zeroes bits that are already zero from the shl operation
  5798. }
  5799. case taicpu(p).oper[0]^.val of
  5800. 8:
  5801. mask:=$FFFFFFFFFFFFFF00;
  5802. 16:
  5803. mask:=$FFFFFFFFFFFF0000;
  5804. 32:
  5805. mask:=$FFFFFFFF00000000;
  5806. 63:
  5807. { Constant pre-calculated to prevent overflow errors with Int64 }
  5808. mask:=$8000000000000000;
  5809. else
  5810. begin
  5811. if taicpu(p).oper[0]^.val >= 64 then
  5812. { Shouldn't happen realistically, since the register
  5813. is guaranteed to be set to zero at this point }
  5814. mask := 0
  5815. else
  5816. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5817. end;
  5818. end;
  5819. if taicpu(hp1).oper[0]^.val = mask then
  5820. begin
  5821. { Everything checks out, perform the optimisation, as long as
  5822. the FLAGS register isn't being used}
  5823. TransferUsedRegs(TmpUsedRegs);
  5824. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5825. {$ifdef x86_64}
  5826. if (hp1 <> hp2) then
  5827. begin
  5828. { "shl/mov/and" version }
  5829. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5830. { Don't do the optimisation if the FLAGS register is in use }
  5831. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5832. begin
  5833. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5834. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5835. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5836. begin
  5837. RemoveInstruction(hp1);
  5838. Result := True;
  5839. end;
  5840. { Only set Result to True if the 'mov' instruction was removed }
  5841. RemoveInstruction(hp2);
  5842. end;
  5843. end
  5844. else
  5845. {$endif x86_64}
  5846. begin
  5847. { "shl/and" version }
  5848. { Don't do the optimisation if the FLAGS register is in use }
  5849. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5850. begin
  5851. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5852. RemoveInstruction(hp1);
  5853. Result := True;
  5854. end;
  5855. end;
  5856. Exit;
  5857. end
  5858. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5859. begin
  5860. { Even if the mask doesn't allow for its removal, we might be
  5861. able to optimise the mask for the "shl/and" version, which
  5862. may permit other peephole optimisations }
  5863. {$ifdef DEBUG_AOPTCPU}
  5864. mask := taicpu(hp1).oper[0]^.val and mask;
  5865. if taicpu(hp1).oper[0]^.val <> mask then
  5866. begin
  5867. DebugMsg(
  5868. SPeepholeOptimization +
  5869. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5870. ' to $' + debug_tostr(mask) +
  5871. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5872. taicpu(hp1).oper[0]^.val := mask;
  5873. end;
  5874. {$else DEBUG_AOPTCPU}
  5875. { If debugging is off, just set the operand even if it's the same }
  5876. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5877. {$endif DEBUG_AOPTCPU}
  5878. end;
  5879. end;
  5880. {
  5881. change
  5882. shl/sal const,reg
  5883. <op> ...(...,reg,1),...
  5884. into
  5885. <op> ...(...,reg,1 shl const),...
  5886. if const in 1..3
  5887. }
  5888. if MatchOpType(taicpu(p), top_const, top_reg) and
  5889. (taicpu(p).oper[0]^.val in [1..3]) and
  5890. GetNextInstruction(p, hp1) and
  5891. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5892. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5893. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5894. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5895. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5896. begin
  5897. TransferUsedRegs(TmpUsedRegs);
  5898. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5899. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5900. begin
  5901. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5902. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5903. RemoveCurrentP(p);
  5904. Result:=true;
  5905. end;
  5906. end;
  5907. end;
  5908. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5909. var
  5910. CurrentRef: TReference;
  5911. FullReg: TRegister;
  5912. hp1, hp2: tai;
  5913. begin
  5914. Result := False;
  5915. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5916. Exit;
  5917. { We assume you've checked if the operand is actually a reference by
  5918. this point. If it isn't, you'll most likely get an access violation }
  5919. CurrentRef := first_mov.oper[1]^.ref^;
  5920. { Memory must be aligned }
  5921. if (CurrentRef.offset mod 4) <> 0 then
  5922. Exit;
  5923. Inc(CurrentRef.offset);
  5924. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5925. if MatchOperand(second_mov.oper[0]^, 0) and
  5926. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5927. GetNextInstruction(second_mov, hp1) and
  5928. (hp1.typ = ait_instruction) and
  5929. (taicpu(hp1).opcode = A_MOV) and
  5930. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5931. (taicpu(hp1).oper[0]^.val = 0) then
  5932. begin
  5933. Inc(CurrentRef.offset);
  5934. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5935. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5936. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5937. begin
  5938. case taicpu(hp1).opsize of
  5939. S_B:
  5940. if GetNextInstruction(hp1, hp2) and
  5941. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5942. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5943. (taicpu(hp2).oper[0]^.val = 0) then
  5944. begin
  5945. Inc(CurrentRef.offset);
  5946. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5947. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5948. (taicpu(hp2).opsize = S_B) then
  5949. begin
  5950. RemoveInstruction(hp1);
  5951. RemoveInstruction(hp2);
  5952. first_mov.opsize := S_L;
  5953. if first_mov.oper[0]^.typ = top_reg then
  5954. begin
  5955. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5956. { Reuse second_mov as a MOVZX instruction }
  5957. second_mov.opcode := A_MOVZX;
  5958. second_mov.opsize := S_BL;
  5959. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5960. second_mov.loadreg(1, FullReg);
  5961. first_mov.oper[0]^.reg := FullReg;
  5962. asml.Remove(second_mov);
  5963. asml.InsertBefore(second_mov, first_mov);
  5964. end
  5965. else
  5966. { It's a value }
  5967. begin
  5968. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5969. RemoveInstruction(second_mov);
  5970. end;
  5971. Result := True;
  5972. Exit;
  5973. end;
  5974. end;
  5975. S_W:
  5976. begin
  5977. RemoveInstruction(hp1);
  5978. first_mov.opsize := S_L;
  5979. if first_mov.oper[0]^.typ = top_reg then
  5980. begin
  5981. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5982. { Reuse second_mov as a MOVZX instruction }
  5983. second_mov.opcode := A_MOVZX;
  5984. second_mov.opsize := S_BL;
  5985. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5986. second_mov.loadreg(1, FullReg);
  5987. first_mov.oper[0]^.reg := FullReg;
  5988. asml.Remove(second_mov);
  5989. asml.InsertBefore(second_mov, first_mov);
  5990. end
  5991. else
  5992. { It's a value }
  5993. begin
  5994. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5995. RemoveInstruction(second_mov);
  5996. end;
  5997. Result := True;
  5998. Exit;
  5999. end;
  6000. else
  6001. ;
  6002. end;
  6003. end;
  6004. end;
  6005. end;
  6006. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6007. { returns true if a "continue" should be done after this optimization }
  6008. var
  6009. hp1, hp2: tai;
  6010. begin
  6011. Result := false;
  6012. if MatchOpType(taicpu(p),top_ref) and
  6013. GetNextInstruction(p, hp1) and
  6014. (hp1.typ = ait_instruction) and
  6015. (((taicpu(hp1).opcode = A_FLD) and
  6016. (taicpu(p).opcode = A_FSTP)) or
  6017. ((taicpu(p).opcode = A_FISTP) and
  6018. (taicpu(hp1).opcode = A_FILD))) and
  6019. MatchOpType(taicpu(hp1),top_ref) and
  6020. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6021. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6022. begin
  6023. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6024. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6025. GetNextInstruction(hp1, hp2) and
  6026. (((hp2.typ = ait_instruction) and
  6027. IsExitCode(hp2) and
  6028. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6029. not(assigned(current_procinfo.procdef.funcretsym) and
  6030. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6031. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6032. { fstp <temp>
  6033. fld <temp>
  6034. <dealloc> <temp>
  6035. }
  6036. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6037. (tai_tempalloc(hp2).allocation=false) and
  6038. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6039. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6040. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6041. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6042. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6043. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6044. )
  6045. )
  6046. ) then
  6047. begin
  6048. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6049. RemoveInstruction(hp1);
  6050. RemoveCurrentP(p, hp2);
  6051. { first case: exit code }
  6052. if hp2.typ = ait_instruction then
  6053. RemoveLastDeallocForFuncRes(p);
  6054. Result := true;
  6055. end
  6056. else
  6057. { we can do this only in fast math mode as fstp is rounding ...
  6058. ... still disabled as it breaks the compiler and/or rtl }
  6059. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6060. { ... or if another fstp equal to the first one follows }
  6061. (GetNextInstruction(hp1,hp2) and
  6062. (hp2.typ = ait_instruction) and
  6063. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6064. (taicpu(p).opsize=taicpu(hp2).opsize))
  6065. ) and
  6066. { fst can't store an extended/comp value }
  6067. (taicpu(p).opsize <> S_FX) and
  6068. (taicpu(p).opsize <> S_IQ) then
  6069. begin
  6070. if (taicpu(p).opcode = A_FSTP) then
  6071. taicpu(p).opcode := A_FST
  6072. else
  6073. taicpu(p).opcode := A_FIST;
  6074. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6075. RemoveInstruction(hp1);
  6076. end;
  6077. end;
  6078. end;
  6079. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6080. var
  6081. hp1, hp2: tai;
  6082. begin
  6083. result:=false;
  6084. if MatchOpType(taicpu(p),top_reg) and
  6085. GetNextInstruction(p, hp1) and
  6086. (hp1.typ = Ait_Instruction) and
  6087. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6088. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6089. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6090. { change to
  6091. fld reg fxxx reg,st
  6092. fxxxp st, st1 (hp1)
  6093. Remark: non commutative operations must be reversed!
  6094. }
  6095. begin
  6096. case taicpu(hp1).opcode Of
  6097. A_FMULP,A_FADDP,
  6098. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6099. begin
  6100. case taicpu(hp1).opcode Of
  6101. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6102. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6103. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6104. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6105. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6106. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6107. else
  6108. internalerror(2019050534);
  6109. end;
  6110. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6111. taicpu(hp1).oper[1]^.reg := NR_ST;
  6112. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6113. RemoveCurrentP(p, hp1);
  6114. Result:=true;
  6115. exit;
  6116. end;
  6117. else
  6118. ;
  6119. end;
  6120. end
  6121. else
  6122. if MatchOpType(taicpu(p),top_ref) and
  6123. GetNextInstruction(p, hp2) and
  6124. (hp2.typ = Ait_Instruction) and
  6125. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6126. (taicpu(p).opsize in [S_FS, S_FL]) and
  6127. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6128. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6129. if GetLastInstruction(p, hp1) and
  6130. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6131. MatchOpType(taicpu(hp1),top_ref) and
  6132. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6133. if ((taicpu(hp2).opcode = A_FMULP) or
  6134. (taicpu(hp2).opcode = A_FADDP)) then
  6135. { change to
  6136. fld/fst mem1 (hp1) fld/fst mem1
  6137. fld mem1 (p) fadd/
  6138. faddp/ fmul st, st
  6139. fmulp st, st1 (hp2) }
  6140. begin
  6141. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6142. RemoveCurrentP(p, hp1);
  6143. if (taicpu(hp2).opcode = A_FADDP) then
  6144. taicpu(hp2).opcode := A_FADD
  6145. else
  6146. taicpu(hp2).opcode := A_FMUL;
  6147. taicpu(hp2).oper[1]^.reg := NR_ST;
  6148. end
  6149. else
  6150. { change to
  6151. fld/fst mem1 (hp1) fld/fst mem1
  6152. fld mem1 (p) fld st
  6153. }
  6154. begin
  6155. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6156. taicpu(p).changeopsize(S_FL);
  6157. taicpu(p).loadreg(0,NR_ST);
  6158. end
  6159. else
  6160. begin
  6161. case taicpu(hp2).opcode Of
  6162. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6163. { change to
  6164. fld/fst mem1 (hp1) fld/fst mem1
  6165. fld mem2 (p) fxxx mem2
  6166. fxxxp st, st1 (hp2) }
  6167. begin
  6168. case taicpu(hp2).opcode Of
  6169. A_FADDP: taicpu(p).opcode := A_FADD;
  6170. A_FMULP: taicpu(p).opcode := A_FMUL;
  6171. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6172. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6173. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6174. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6175. else
  6176. internalerror(2019050533);
  6177. end;
  6178. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6179. RemoveInstruction(hp2);
  6180. end
  6181. else
  6182. ;
  6183. end
  6184. end
  6185. end;
  6186. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6187. begin
  6188. Result := condition_in(cond1, cond2) or
  6189. { Not strictly subsets due to the actual flags checked, but because we're
  6190. comparing integers, E is a subset of AE and GE and their aliases }
  6191. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6192. end;
  6193. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6194. var
  6195. v: TCGInt;
  6196. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6197. FirstMatch: Boolean;
  6198. NewReg: TRegister;
  6199. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6200. begin
  6201. Result:=false;
  6202. { All these optimisations need a next instruction }
  6203. if not GetNextInstruction(p, hp1) then
  6204. Exit;
  6205. { Search for:
  6206. cmp ###,###
  6207. j(c1) @lbl1
  6208. ...
  6209. @lbl:
  6210. cmp ###,### (same comparison as above)
  6211. j(c2) @lbl2
  6212. If c1 is a subset of c2, change to:
  6213. cmp ###,###
  6214. j(c1) @lbl2
  6215. (@lbl1 may become a dead label as a result)
  6216. }
  6217. { Also handle cases where there are multiple jumps in a row }
  6218. p_jump := hp1;
  6219. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6220. begin
  6221. if IsJumpToLabel(taicpu(p_jump)) then
  6222. begin
  6223. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6224. p_label := nil;
  6225. if Assigned(JumpLabel) then
  6226. p_label := getlabelwithsym(JumpLabel);
  6227. if Assigned(p_label) and
  6228. GetNextInstruction(p_label, p_dist) and
  6229. MatchInstruction(p_dist, A_CMP, []) and
  6230. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6231. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6232. GetNextInstruction(p_dist, hp1_dist) and
  6233. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6234. begin
  6235. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6236. if JumpLabel = JumpLabel_dist then
  6237. { This is an infinite loop }
  6238. Exit;
  6239. { Best optimisation when the first condition is a subset (or equal) of the second }
  6240. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6241. begin
  6242. { Any registers used here will already be allocated }
  6243. if Assigned(JumpLabel) then
  6244. JumpLabel.DecRefs;
  6245. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6246. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6247. Result := True;
  6248. { Don't exit yet. Since p and p_jump haven't actually been
  6249. removed, we can check for more on this iteration }
  6250. end
  6251. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6252. GetNextInstruction(hp1_dist, hp1_label) and
  6253. SkipAligns(hp1_label, hp1_label) and
  6254. (hp1_label.typ = ait_label) then
  6255. begin
  6256. JumpLabel_far := tai_label(hp1_label).labsym;
  6257. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6258. { This is an infinite loop }
  6259. Exit;
  6260. if Assigned(JumpLabel_far) then
  6261. begin
  6262. { In this situation, if the first jump branches, the second one will never,
  6263. branch so change the destination label to after the second jump }
  6264. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6265. if Assigned(JumpLabel) then
  6266. JumpLabel.DecRefs;
  6267. JumpLabel_far.IncRefs;
  6268. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6269. Result := True;
  6270. { Don't exit yet. Since p and p_jump haven't actually been
  6271. removed, we can check for more on this iteration }
  6272. Continue;
  6273. end;
  6274. end;
  6275. end;
  6276. end;
  6277. { Search for:
  6278. cmp ###,###
  6279. j(c1) @lbl1
  6280. cmp ###,### (same as first)
  6281. Remove second cmp
  6282. }
  6283. if GetNextInstruction(p_jump, hp2) and
  6284. (
  6285. (
  6286. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6287. (
  6288. (
  6289. MatchOpType(taicpu(p), top_const, top_reg) and
  6290. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6291. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6292. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6293. ) or (
  6294. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6295. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6296. )
  6297. )
  6298. ) or (
  6299. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6300. MatchOperand(taicpu(p).oper[0]^, 0) and
  6301. (taicpu(p).oper[1]^.typ = top_reg) and
  6302. MatchInstruction(hp2, A_TEST, []) and
  6303. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6304. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6305. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6306. )
  6307. ) then
  6308. begin
  6309. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6310. RemoveInstruction(hp2);
  6311. Result := True;
  6312. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6313. end;
  6314. GetNextInstruction(p_jump, p_jump);
  6315. end;
  6316. {
  6317. Try to optimise the following:
  6318. cmp $x,### ($x and $y can be registers or constants)
  6319. je @lbl1 (only reference)
  6320. cmp $y,### (### are identical)
  6321. @Lbl:
  6322. sete %reg1
  6323. Change to:
  6324. cmp $x,###
  6325. sete %reg2 (allocate new %reg2)
  6326. cmp $y,###
  6327. sete %reg1
  6328. orb %reg2,%reg1
  6329. (dealloc %reg2)
  6330. This adds an instruction (so don't perform under -Os), but it removes
  6331. a conditional branch.
  6332. }
  6333. if not (cs_opt_size in current_settings.optimizerswitches) and
  6334. (
  6335. (hp1 = p_jump) or
  6336. GetNextInstruction(p, hp1)
  6337. ) and
  6338. MatchInstruction(hp1, A_Jcc, []) and
  6339. IsJumpToLabel(taicpu(hp1)) and
  6340. (taicpu(hp1).condition in [C_E, C_Z]) and
  6341. GetNextInstruction(hp1, hp2) and
  6342. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6343. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6344. { The first operand of CMP instructions can only be a register or
  6345. immediate anyway, so no need to check }
  6346. GetNextInstruction(hp2, p_label) and
  6347. (
  6348. (p_label.typ = ait_label) or
  6349. (
  6350. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6351. to potentially cut down on the iterations of Pass 1 }
  6352. MatchInstruction(p_label, A_Jcc, []) and
  6353. IsJumpToLabel(taicpu(p_label)) and
  6354. { Use p_dist to hold the jump briefly }
  6355. SetAndTest(p_label, p_dist) and
  6356. GetNextInstruction(p_dist, p_label) and
  6357. (p_label.typ = ait_label) and
  6358. (tai_label(p_label).labsym.getrefs >= 2) and
  6359. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6360. { We might as well collapse the jump now }
  6361. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6362. )
  6363. ) and
  6364. (tai_label(p_label).labsym.getrefs = 1) and
  6365. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6366. GetNextInstruction(p_label, p_dist) and
  6367. MatchInstruction(p_dist, A_SETcc, []) and
  6368. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6369. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6370. { Get the instruction after the SETcc instruction so we can
  6371. allocate a new register over the entire range }
  6372. GetNextInstruction(p_dist, hp1_dist) then
  6373. begin
  6374. TransferUsedRegs(TmpUsedRegs);
  6375. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6376. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6377. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6378. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6379. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6380. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6381. begin
  6382. { Register can appear in p if it's not used afterwards, so only
  6383. allocate between hp1 and hp1_dist }
  6384. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6385. if NewReg <> NR_NO then
  6386. begin
  6387. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6388. { Change the jump instruction into a SETcc instruction }
  6389. taicpu(hp1).opcode := A_SETcc;
  6390. taicpu(hp1).opsize := S_B;
  6391. taicpu(hp1).loadreg(0, NewReg);
  6392. { This is now a dead label }
  6393. tai_label(p_label).labsym.decrefs;
  6394. { Prefer adding before the next instruction so the FLAGS
  6395. register is deallocated first }
  6396. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6397. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6398. AsmL.InsertBefore(
  6399. hp2,
  6400. hp1_dist
  6401. );
  6402. { Make sure the new register is in use over the new instruction
  6403. (long-winded, but things work best when the FLAGS register
  6404. is not allocated here) }
  6405. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6406. Result := True;
  6407. { Don't exit yet, as p wasn't changed and hp1, while
  6408. modified, is still intact and might be optimised by the
  6409. SETcc optimisation below }
  6410. end;
  6411. end;
  6412. end;
  6413. if taicpu(p).oper[0]^.typ = top_const then
  6414. begin
  6415. if (taicpu(p).oper[0]^.val = 0) and
  6416. (taicpu(p).oper[1]^.typ = top_reg) and
  6417. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6418. begin
  6419. hp2 := p;
  6420. FirstMatch := True;
  6421. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6422. anything meaningful once it's converted to "test %reg,%reg";
  6423. additionally, some jumps will always (or never) branch, so
  6424. evaluate every jump immediately following the
  6425. comparison, optimising the conditions if possible.
  6426. Similarly with SETcc... those that are always set to 0 or 1
  6427. are changed to MOV instructions }
  6428. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6429. (
  6430. GetNextInstruction(hp2, hp1) and
  6431. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6432. ) do
  6433. begin
  6434. FirstMatch := False;
  6435. case taicpu(hp1).condition of
  6436. C_B, C_C, C_NAE, C_O:
  6437. { For B/NAE:
  6438. Will never branch since an unsigned integer can never be below zero
  6439. For C/O:
  6440. Result cannot overflow because 0 is being subtracted
  6441. }
  6442. begin
  6443. if taicpu(hp1).opcode = A_Jcc then
  6444. begin
  6445. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6446. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6447. RemoveInstruction(hp1);
  6448. { Since hp1 was deleted, hp2 must not be updated }
  6449. Continue;
  6450. end
  6451. else
  6452. begin
  6453. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6454. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6455. taicpu(hp1).opcode := A_MOV;
  6456. taicpu(hp1).ops := 2;
  6457. taicpu(hp1).condition := C_None;
  6458. taicpu(hp1).opsize := S_B;
  6459. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6460. taicpu(hp1).loadconst(0, 0);
  6461. end;
  6462. end;
  6463. C_BE, C_NA:
  6464. begin
  6465. { Will only branch if equal to zero }
  6466. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6467. taicpu(hp1).condition := C_E;
  6468. end;
  6469. C_A, C_NBE:
  6470. begin
  6471. { Will only branch if not equal to zero }
  6472. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6473. taicpu(hp1).condition := C_NE;
  6474. end;
  6475. C_AE, C_NB, C_NC, C_NO:
  6476. begin
  6477. { Will always branch }
  6478. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6479. if taicpu(hp1).opcode = A_Jcc then
  6480. begin
  6481. MakeUnconditional(taicpu(hp1));
  6482. { Any jumps/set that follow will now be dead code }
  6483. RemoveDeadCodeAfterJump(taicpu(hp1));
  6484. Break;
  6485. end
  6486. else
  6487. begin
  6488. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6489. taicpu(hp1).opcode := A_MOV;
  6490. taicpu(hp1).ops := 2;
  6491. taicpu(hp1).condition := C_None;
  6492. taicpu(hp1).opsize := S_B;
  6493. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6494. taicpu(hp1).loadconst(0, 1);
  6495. end;
  6496. end;
  6497. C_None:
  6498. InternalError(2020012201);
  6499. C_P, C_PE, C_NP, C_PO:
  6500. { We can't handle parity checks and they should never be generated
  6501. after a general-purpose CMP (it's used in some floating-point
  6502. comparisons that don't use CMP) }
  6503. InternalError(2020012202);
  6504. else
  6505. { Zero/Equality, Sign, their complements and all of the
  6506. signed comparisons do not need to be converted };
  6507. end;
  6508. hp2 := hp1;
  6509. end;
  6510. { Convert the instruction to a TEST }
  6511. taicpu(p).opcode := A_TEST;
  6512. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6513. Result := True;
  6514. Exit;
  6515. end
  6516. else if (taicpu(p).oper[0]^.val = 1) and
  6517. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6518. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6519. begin
  6520. { Convert; To:
  6521. cmp $1,r/m cmp $0,r/m
  6522. jl @lbl jle @lbl
  6523. }
  6524. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6525. taicpu(p).oper[0]^.val := 0;
  6526. taicpu(hp1).condition := C_LE;
  6527. { If the instruction is now "cmp $0,%reg", convert it to a
  6528. TEST (and effectively do the work of the "cmp $0,%reg" in
  6529. the block above)
  6530. If it's a reference, we can get away with not setting
  6531. Result to True because he haven't evaluated the jump
  6532. in this pass yet.
  6533. }
  6534. if (taicpu(p).oper[1]^.typ = top_reg) then
  6535. begin
  6536. taicpu(p).opcode := A_TEST;
  6537. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6538. Result := True;
  6539. end;
  6540. Exit;
  6541. end
  6542. else if (taicpu(p).oper[1]^.typ = top_reg)
  6543. {$ifdef x86_64}
  6544. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6545. {$endif x86_64}
  6546. then
  6547. begin
  6548. { cmp register,$8000 neg register
  6549. je target --> jo target
  6550. .... only if register is deallocated before jump.}
  6551. case Taicpu(p).opsize of
  6552. S_B: v:=$80;
  6553. S_W: v:=$8000;
  6554. S_L: v:=qword($80000000);
  6555. else
  6556. internalerror(2013112905);
  6557. end;
  6558. if (taicpu(p).oper[0]^.val=v) and
  6559. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6560. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6561. begin
  6562. TransferUsedRegs(TmpUsedRegs);
  6563. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6564. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6565. begin
  6566. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6567. Taicpu(p).opcode:=A_NEG;
  6568. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6569. Taicpu(p).clearop(1);
  6570. Taicpu(p).ops:=1;
  6571. if Taicpu(hp1).condition=C_E then
  6572. Taicpu(hp1).condition:=C_O
  6573. else
  6574. Taicpu(hp1).condition:=C_NO;
  6575. Result:=true;
  6576. exit;
  6577. end;
  6578. end;
  6579. end;
  6580. end;
  6581. if TrySwapMovCmp(p, hp1) then
  6582. begin
  6583. Result := True;
  6584. Exit;
  6585. end;
  6586. end;
  6587. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6588. var
  6589. hp1: tai;
  6590. begin
  6591. {
  6592. remove the second (v)pxor from
  6593. pxor reg,reg
  6594. ...
  6595. pxor reg,reg
  6596. }
  6597. Result:=false;
  6598. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6599. MatchOpType(taicpu(p),top_reg,top_reg) and
  6600. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6601. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6602. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6603. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6604. begin
  6605. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6606. RemoveInstruction(hp1);
  6607. Result:=true;
  6608. Exit;
  6609. end
  6610. {
  6611. replace
  6612. pxor reg1,reg1
  6613. movapd/s reg1,reg2
  6614. dealloc reg1
  6615. by
  6616. pxor reg2,reg2
  6617. }
  6618. else if GetNextInstruction(p,hp1) and
  6619. { we mix single and double opperations here because we assume that the compiler
  6620. generates vmovapd only after double operations and vmovaps only after single operations }
  6621. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6622. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6623. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6624. (taicpu(p).oper[0]^.typ=top_reg) then
  6625. begin
  6626. TransferUsedRegs(TmpUsedRegs);
  6627. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6628. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6629. begin
  6630. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6631. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6632. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6633. RemoveInstruction(hp1);
  6634. result:=true;
  6635. end;
  6636. end;
  6637. end;
  6638. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6639. var
  6640. hp1: tai;
  6641. begin
  6642. {
  6643. remove the second (v)pxor from
  6644. (v)pxor reg,reg
  6645. ...
  6646. (v)pxor reg,reg
  6647. }
  6648. Result:=false;
  6649. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6650. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6651. begin
  6652. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6653. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6654. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6655. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6656. begin
  6657. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6658. RemoveInstruction(hp1);
  6659. Result:=true;
  6660. Exit;
  6661. end;
  6662. {$ifdef x86_64}
  6663. {
  6664. replace
  6665. vpxor reg1,reg1,reg1
  6666. vmov reg,mem
  6667. by
  6668. movq $0,mem
  6669. }
  6670. if GetNextInstruction(p,hp1) and
  6671. MatchInstruction(hp1,A_VMOVSD,[]) and
  6672. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6673. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6674. begin
  6675. TransferUsedRegs(TmpUsedRegs);
  6676. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6677. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6678. begin
  6679. taicpu(hp1).loadconst(0,0);
  6680. taicpu(hp1).opcode:=A_MOV;
  6681. taicpu(hp1).opsize:=S_Q;
  6682. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6683. RemoveCurrentP(p);
  6684. result:=true;
  6685. Exit;
  6686. end;
  6687. end;
  6688. {$endif x86_64}
  6689. end
  6690. {
  6691. replace
  6692. vpxor reg1,reg1,reg2
  6693. by
  6694. vpxor reg2,reg2,reg2
  6695. to avoid unncessary data dependencies
  6696. }
  6697. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6698. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6699. begin
  6700. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6701. { avoid unncessary data dependency }
  6702. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6703. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6704. result:=true;
  6705. exit;
  6706. end;
  6707. Result:=OptPass1VOP(p);
  6708. end;
  6709. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6710. var
  6711. hp1 : tai;
  6712. begin
  6713. result:=false;
  6714. { replace
  6715. IMul const,%mreg1,%mreg2
  6716. Mov %reg2,%mreg3
  6717. dealloc %mreg3
  6718. by
  6719. Imul const,%mreg1,%mreg23
  6720. }
  6721. if (taicpu(p).ops=3) and
  6722. GetNextInstruction(p,hp1) and
  6723. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6724. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6725. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6726. begin
  6727. TransferUsedRegs(TmpUsedRegs);
  6728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6729. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6730. begin
  6731. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6732. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6733. RemoveInstruction(hp1);
  6734. result:=true;
  6735. end;
  6736. end;
  6737. end;
  6738. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6739. var
  6740. hp1 : tai;
  6741. begin
  6742. result:=false;
  6743. { replace
  6744. IMul %reg0,%reg1,%reg2
  6745. Mov %reg2,%reg3
  6746. dealloc %reg2
  6747. by
  6748. Imul %reg0,%reg1,%reg3
  6749. }
  6750. if GetNextInstruction(p,hp1) and
  6751. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6752. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6753. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6754. begin
  6755. TransferUsedRegs(TmpUsedRegs);
  6756. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6757. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6758. begin
  6759. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6760. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6761. RemoveInstruction(hp1);
  6762. result:=true;
  6763. end;
  6764. end;
  6765. end;
  6766. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6767. var
  6768. hp1: tai;
  6769. begin
  6770. Result:=false;
  6771. { get rid of
  6772. (v)cvtss2sd reg0,<reg1,>reg2
  6773. (v)cvtss2sd reg2,<reg2,>reg0
  6774. }
  6775. if GetNextInstruction(p,hp1) and
  6776. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6777. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6778. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6779. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6780. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6781. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6782. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6783. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6784. )
  6785. ) then
  6786. begin
  6787. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6788. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6789. begin
  6790. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6791. RemoveCurrentP(p);
  6792. RemoveInstruction(hp1);
  6793. end
  6794. else
  6795. begin
  6796. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6797. if taicpu(hp1).opcode=A_CVTSD2SS then
  6798. begin
  6799. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6800. taicpu(p).opcode:=A_MOVAPS;
  6801. end
  6802. else
  6803. begin
  6804. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6805. taicpu(p).opcode:=A_VMOVAPS;
  6806. end;
  6807. taicpu(p).ops:=2;
  6808. RemoveInstruction(hp1);
  6809. end;
  6810. Result:=true;
  6811. Exit;
  6812. end;
  6813. end;
  6814. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6815. var
  6816. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6817. ThisReg: TRegister;
  6818. begin
  6819. Result := False;
  6820. if not GetNextInstruction(p,hp1) then
  6821. Exit;
  6822. {
  6823. convert
  6824. j<c> .L1
  6825. mov 1,reg
  6826. jmp .L2
  6827. .L1
  6828. mov 0,reg
  6829. .L2
  6830. into
  6831. mov 0,reg
  6832. set<not(c)> reg
  6833. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6834. would destroy the flag contents
  6835. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6836. executed at the same time as a previous comparison.
  6837. set<not(c)> reg
  6838. movzx reg, reg
  6839. }
  6840. if MatchInstruction(hp1,A_MOV,[]) and
  6841. (taicpu(hp1).oper[0]^.typ = top_const) and
  6842. (
  6843. (
  6844. (taicpu(hp1).oper[1]^.typ = top_reg)
  6845. {$ifdef i386}
  6846. { Under i386, ESI, EDI, EBP and ESP
  6847. don't have an 8-bit representation }
  6848. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6849. {$endif i386}
  6850. ) or (
  6851. {$ifdef i386}
  6852. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6853. {$endif i386}
  6854. (taicpu(hp1).opsize = S_B)
  6855. )
  6856. ) and
  6857. GetNextInstruction(hp1,hp2) and
  6858. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6859. GetNextInstruction(hp2,hp3) and
  6860. SkipAligns(hp3, hp3) and
  6861. (hp3.typ=ait_label) and
  6862. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6863. GetNextInstruction(hp3,hp4) and
  6864. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6865. (taicpu(hp4).oper[0]^.typ = top_const) and
  6866. (
  6867. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6868. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6869. ) and
  6870. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6871. GetNextInstruction(hp4,hp5) and
  6872. SkipAligns(hp5, hp5) and
  6873. (hp5.typ=ait_label) and
  6874. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6875. begin
  6876. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6877. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6878. tai_label(hp3).labsym.DecRefs;
  6879. { If this isn't the only reference to the middle label, we can
  6880. still make a saving - only that the first jump and everything
  6881. that follows will remain. }
  6882. if (tai_label(hp3).labsym.getrefs = 0) then
  6883. begin
  6884. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6885. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6886. else
  6887. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6888. { remove jump, first label and second MOV (also catching any aligns) }
  6889. repeat
  6890. if not GetNextInstruction(hp2, hp3) then
  6891. InternalError(2021040810);
  6892. RemoveInstruction(hp2);
  6893. hp2 := hp3;
  6894. until hp2 = hp5;
  6895. { Don't decrement reference count before the removal loop
  6896. above, otherwise GetNextInstruction won't stop on the
  6897. the label }
  6898. tai_label(hp5).labsym.DecRefs;
  6899. end
  6900. else
  6901. begin
  6902. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6903. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6904. else
  6905. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6906. end;
  6907. taicpu(p).opcode:=A_SETcc;
  6908. taicpu(p).opsize:=S_B;
  6909. taicpu(p).is_jmp:=False;
  6910. if taicpu(hp1).opsize=S_B then
  6911. begin
  6912. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6913. if taicpu(hp1).oper[1]^.typ = top_reg then
  6914. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6915. RemoveInstruction(hp1);
  6916. end
  6917. else
  6918. begin
  6919. { Will be a register because the size can't be S_B otherwise }
  6920. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6921. taicpu(p).loadreg(0, ThisReg);
  6922. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6923. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6924. begin
  6925. case taicpu(hp1).opsize of
  6926. S_W:
  6927. taicpu(hp1).opsize := S_BW;
  6928. S_L:
  6929. taicpu(hp1).opsize := S_BL;
  6930. {$ifdef x86_64}
  6931. S_Q:
  6932. begin
  6933. taicpu(hp1).opsize := S_BL;
  6934. { Change the destination register to 32-bit }
  6935. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6936. end;
  6937. {$endif x86_64}
  6938. else
  6939. InternalError(2021040820);
  6940. end;
  6941. taicpu(hp1).opcode := A_MOVZX;
  6942. taicpu(hp1).loadreg(0, ThisReg);
  6943. end
  6944. else
  6945. begin
  6946. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6947. { hp1 is already a MOV instruction with the correct register }
  6948. taicpu(hp1).loadconst(0, 0);
  6949. { Inserting it right before p will guarantee that the flags are also tracked }
  6950. asml.Remove(hp1);
  6951. asml.InsertBefore(hp1, p);
  6952. end;
  6953. end;
  6954. Result:=true;
  6955. exit;
  6956. end
  6957. else if (hp1.typ = ait_label) then
  6958. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6959. end;
  6960. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6961. var
  6962. hp1, hp2, hp3: tai;
  6963. SourceRef, TargetRef: TReference;
  6964. CurrentReg: TRegister;
  6965. begin
  6966. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6967. if not UseAVX then
  6968. InternalError(2021100501);
  6969. Result := False;
  6970. { Look for the following to simplify:
  6971. vmovdqa/u x(mem1), %xmmreg
  6972. vmovdqa/u %xmmreg, y(mem2)
  6973. vmovdqa/u x+16(mem1), %xmmreg
  6974. vmovdqa/u %xmmreg, y+16(mem2)
  6975. Change to:
  6976. vmovdqa/u x(mem1), %ymmreg
  6977. vmovdqa/u %ymmreg, y(mem2)
  6978. vpxor %ymmreg, %ymmreg, %ymmreg
  6979. ( The VPXOR instruction is to zero the upper half, thus removing the
  6980. need to call the potentially expensive VZEROUPPER instruction. Other
  6981. peephole optimisations can remove VPXOR if it's unnecessary )
  6982. }
  6983. TransferUsedRegs(TmpUsedRegs);
  6984. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6985. { NOTE: In the optimisations below, if the references dictate that an
  6986. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6987. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6988. if (taicpu(p).opsize = S_XMM) and
  6989. MatchOpType(taicpu(p), top_ref, top_reg) and
  6990. GetNextInstruction(p, hp1) and
  6991. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6992. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6993. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6994. begin
  6995. SourceRef := taicpu(p).oper[0]^.ref^;
  6996. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6997. if GetNextInstruction(hp1, hp2) and
  6998. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6999. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7000. begin
  7001. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7002. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7003. Inc(SourceRef.offset, 16);
  7004. { Reuse the register in the first block move }
  7005. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7006. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7007. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7008. begin
  7009. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7010. Inc(TargetRef.offset, 16);
  7011. if GetNextInstruction(hp2, hp3) and
  7012. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7013. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7014. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7015. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7016. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7017. begin
  7018. { Update the register tracking to the new size }
  7019. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7020. { Remember that the offsets are 16 ahead }
  7021. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7022. if not (
  7023. ((SourceRef.offset mod 32) = 16) and
  7024. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7025. ) then
  7026. taicpu(p).opcode := A_VMOVDQU;
  7027. taicpu(p).opsize := S_YMM;
  7028. taicpu(p).oper[1]^.reg := CurrentReg;
  7029. if not (
  7030. ((TargetRef.offset mod 32) = 16) and
  7031. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7032. ) then
  7033. taicpu(hp1).opcode := A_VMOVDQU;
  7034. taicpu(hp1).opsize := S_YMM;
  7035. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7036. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7037. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7038. if (pi_uses_ymm in current_procinfo.flags) then
  7039. RemoveInstruction(hp2)
  7040. else
  7041. begin
  7042. taicpu(hp2).opcode := A_VPXOR;
  7043. taicpu(hp2).opsize := S_YMM;
  7044. taicpu(hp2).loadreg(0, CurrentReg);
  7045. taicpu(hp2).loadreg(1, CurrentReg);
  7046. taicpu(hp2).loadreg(2, CurrentReg);
  7047. taicpu(hp2).ops := 3;
  7048. end;
  7049. RemoveInstruction(hp3);
  7050. Result := True;
  7051. Exit;
  7052. end;
  7053. end
  7054. else
  7055. begin
  7056. { See if the next references are 16 less rather than 16 greater }
  7057. Dec(SourceRef.offset, 32); { -16 the other way }
  7058. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7059. begin
  7060. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7061. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7062. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7063. GetNextInstruction(hp2, hp3) and
  7064. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7065. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7066. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7067. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7068. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7069. begin
  7070. { Update the register tracking to the new size }
  7071. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7072. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7073. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7074. if not(
  7075. ((SourceRef.offset mod 32) = 0) and
  7076. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7077. ) then
  7078. taicpu(hp2).opcode := A_VMOVDQU;
  7079. taicpu(hp2).opsize := S_YMM;
  7080. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7081. if not (
  7082. ((TargetRef.offset mod 32) = 0) and
  7083. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7084. ) then
  7085. taicpu(hp3).opcode := A_VMOVDQU;
  7086. taicpu(hp3).opsize := S_YMM;
  7087. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7088. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7089. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7090. if (pi_uses_ymm in current_procinfo.flags) then
  7091. RemoveInstruction(hp1)
  7092. else
  7093. begin
  7094. taicpu(hp1).opcode := A_VPXOR;
  7095. taicpu(hp1).opsize := S_YMM;
  7096. taicpu(hp1).loadreg(0, CurrentReg);
  7097. taicpu(hp1).loadreg(1, CurrentReg);
  7098. taicpu(hp1).loadreg(2, CurrentReg);
  7099. taicpu(hp1).ops := 3;
  7100. Asml.Remove(hp1);
  7101. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7102. end;
  7103. RemoveCurrentP(p, hp2);
  7104. Result := True;
  7105. Exit;
  7106. end;
  7107. end;
  7108. end;
  7109. end;
  7110. end;
  7111. end;
  7112. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7113. var
  7114. hp2, hp3, first_assignment: tai;
  7115. IncCount, OperIdx: Integer;
  7116. OrigLabel: TAsmLabel;
  7117. begin
  7118. Count := 0;
  7119. Result := False;
  7120. first_assignment := nil;
  7121. if (LoopCount >= 20) then
  7122. begin
  7123. { Guard against infinite loops }
  7124. Exit;
  7125. end;
  7126. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7127. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7128. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7129. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7130. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7131. Exit;
  7132. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7133. {
  7134. change
  7135. jmp .L1
  7136. ...
  7137. .L1:
  7138. mov ##, ## ( multiple movs possible )
  7139. jmp/ret
  7140. into
  7141. mov ##, ##
  7142. jmp/ret
  7143. }
  7144. if not Assigned(hp1) then
  7145. begin
  7146. hp1 := GetLabelWithSym(OrigLabel);
  7147. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7148. Exit;
  7149. end;
  7150. hp2 := hp1;
  7151. while Assigned(hp2) do
  7152. begin
  7153. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7154. SkipLabels(hp2,hp2);
  7155. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7156. Break;
  7157. case taicpu(hp2).opcode of
  7158. A_MOVSS:
  7159. begin
  7160. if taicpu(hp2).ops = 0 then
  7161. { Wrong MOVSS }
  7162. Break;
  7163. Inc(Count);
  7164. if Count >= 5 then
  7165. { Too many to be worthwhile }
  7166. Break;
  7167. GetNextInstruction(hp2, hp2);
  7168. Continue;
  7169. end;
  7170. A_MOV,
  7171. A_MOVD,
  7172. A_MOVQ,
  7173. A_MOVSX,
  7174. {$ifdef x86_64}
  7175. A_MOVSXD,
  7176. {$endif x86_64}
  7177. A_MOVZX,
  7178. A_MOVAPS,
  7179. A_MOVUPS,
  7180. A_MOVSD,
  7181. A_MOVAPD,
  7182. A_MOVUPD,
  7183. A_MOVDQA,
  7184. A_MOVDQU,
  7185. A_VMOVSS,
  7186. A_VMOVAPS,
  7187. A_VMOVUPS,
  7188. A_VMOVSD,
  7189. A_VMOVAPD,
  7190. A_VMOVUPD,
  7191. A_VMOVDQA,
  7192. A_VMOVDQU:
  7193. begin
  7194. Inc(Count);
  7195. if Count >= 5 then
  7196. { Too many to be worthwhile }
  7197. Break;
  7198. GetNextInstruction(hp2, hp2);
  7199. Continue;
  7200. end;
  7201. A_JMP:
  7202. begin
  7203. { Guard against infinite loops }
  7204. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7205. Exit;
  7206. { Analyse this jump first in case it also duplicates assignments }
  7207. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7208. begin
  7209. { Something did change! }
  7210. Result := True;
  7211. Inc(Count, IncCount);
  7212. if Count >= 5 then
  7213. begin
  7214. { Too many to be worthwhile }
  7215. Exit;
  7216. end;
  7217. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7218. Break;
  7219. end;
  7220. Result := True;
  7221. Break;
  7222. end;
  7223. A_RET:
  7224. begin
  7225. Result := True;
  7226. Break;
  7227. end;
  7228. else
  7229. Break;
  7230. end;
  7231. end;
  7232. if Result then
  7233. begin
  7234. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7235. if Count = 0 then
  7236. begin
  7237. Result := False;
  7238. Exit;
  7239. end;
  7240. hp3 := p;
  7241. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7242. while True do
  7243. begin
  7244. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7245. SkipLabels(hp1,hp1);
  7246. if (hp1.typ <> ait_instruction) then
  7247. InternalError(2021040720);
  7248. case taicpu(hp1).opcode of
  7249. A_JMP:
  7250. begin
  7251. { Change the original jump to the new destination }
  7252. OrigLabel.decrefs;
  7253. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7254. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7255. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7256. if not Assigned(first_assignment) then
  7257. InternalError(2021040810)
  7258. else
  7259. p := first_assignment;
  7260. Exit;
  7261. end;
  7262. A_RET:
  7263. begin
  7264. { Now change the jump into a RET instruction }
  7265. ConvertJumpToRET(p, hp1);
  7266. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7267. if not Assigned(first_assignment) then
  7268. InternalError(2021040811)
  7269. else
  7270. p := first_assignment;
  7271. Exit;
  7272. end;
  7273. else
  7274. begin
  7275. { Duplicate the MOV instruction }
  7276. hp3:=tai(hp1.getcopy);
  7277. if first_assignment = nil then
  7278. first_assignment := hp3;
  7279. asml.InsertBefore(hp3, p);
  7280. { Make sure the compiler knows about any final registers written here }
  7281. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7282. with taicpu(hp3).oper[OperIdx]^ do
  7283. begin
  7284. case typ of
  7285. top_ref:
  7286. begin
  7287. if (ref^.base <> NR_NO) and
  7288. (getsupreg(ref^.base) <> RS_ESP) and
  7289. (getsupreg(ref^.base) <> RS_EBP)
  7290. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7291. then
  7292. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7293. if (ref^.index <> NR_NO) and
  7294. (getsupreg(ref^.index) <> RS_ESP) and
  7295. (getsupreg(ref^.index) <> RS_EBP)
  7296. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7297. (ref^.index <> ref^.base) then
  7298. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7299. end;
  7300. top_reg:
  7301. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7302. else
  7303. ;
  7304. end;
  7305. end;
  7306. end;
  7307. end;
  7308. if not GetNextInstruction(hp1, hp1) then
  7309. { Should have dropped out earlier }
  7310. InternalError(2021040710);
  7311. end;
  7312. end;
  7313. end;
  7314. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7315. var
  7316. hp2: tai;
  7317. X: Integer;
  7318. const
  7319. WriteOp: array[0..3] of set of TInsChange = (
  7320. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7321. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7322. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7323. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7324. RegWriteFlags: array[0..7] of set of TInsChange = (
  7325. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7326. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7327. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7328. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7329. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7330. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7331. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7332. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7333. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7334. begin
  7335. { If we have something like:
  7336. cmp ###,%reg1
  7337. mov 0,%reg2
  7338. And no modified registers are shared, move the instruction to before
  7339. the comparison as this means it can be optimised without worrying
  7340. about the FLAGS register. (CMP/MOV is generated by
  7341. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7342. As long as the second instruction doesn't use the flags or one of the
  7343. registers used by CMP or TEST (also check any references that use the
  7344. registers), then it can be moved prior to the comparison.
  7345. }
  7346. Result := False;
  7347. if (hp1.typ <> ait_instruction) or
  7348. taicpu(hp1).is_jmp or
  7349. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7350. Exit;
  7351. { NOP is a pipeline fence, likely marking the beginning of the function
  7352. epilogue, so drop out. Similarly, drop out if POP or RET are
  7353. encountered }
  7354. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7355. Exit;
  7356. if (taicpu(hp1).opcode = A_MOVSS) and
  7357. (taicpu(hp1).ops = 0) then
  7358. { Wrong MOVSS }
  7359. Exit;
  7360. { Check for writes to specific registers first }
  7361. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7362. for X := 0 to 7 do
  7363. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7364. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7365. Exit;
  7366. for X := 0 to taicpu(hp1).ops - 1 do
  7367. begin
  7368. { Check to see if this operand writes to something }
  7369. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7370. { And matches something in the CMP/TEST instruction }
  7371. (
  7372. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7373. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7374. (
  7375. { If it's a register, make sure the register written to doesn't
  7376. appear in the cmp instruction as part of a reference }
  7377. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7378. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7379. )
  7380. ) then
  7381. Exit;
  7382. end;
  7383. { The instruction can be safely moved }
  7384. asml.Remove(hp1);
  7385. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7386. can be optimised into "xor %reg,%reg" later }
  7387. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7388. asml.InsertBefore(hp1, hp2)
  7389. else
  7390. { Note, if p.Previous is nil (even if it should logically never be the
  7391. case), FindRegAllocBackward immediately exits with False and so we
  7392. safely land here (we can't just pass p because FindRegAllocBackward
  7393. immediately exits on an instruction). [Kit] }
  7394. asml.InsertBefore(hp1, p);
  7395. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7396. for X := 0 to taicpu(hp1).ops - 1 do
  7397. case taicpu(hp1).oper[X]^.typ of
  7398. top_reg:
  7399. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7400. top_ref:
  7401. begin
  7402. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7403. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7404. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7405. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7406. end;
  7407. else
  7408. ;
  7409. end;
  7410. if taicpu(hp1).opcode = A_LEA then
  7411. { The flags will be overwritten by the CMP/TEST instruction }
  7412. ConvertLEA(taicpu(hp1));
  7413. Result := True;
  7414. end;
  7415. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7416. function IsXCHGAcceptable: Boolean; inline;
  7417. begin
  7418. { Always accept if optimising for size }
  7419. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7420. (
  7421. {$ifdef x86_64}
  7422. { XCHG takes 3 cycles on AMD Athlon64 }
  7423. (current_settings.optimizecputype >= cpu_core_i)
  7424. {$else x86_64}
  7425. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7426. than 3, so it becomes a saving compared to three MOVs with two of
  7427. them able to execute simultaneously. [Kit] }
  7428. (current_settings.optimizecputype >= cpu_PentiumM)
  7429. {$endif x86_64}
  7430. );
  7431. end;
  7432. var
  7433. NewRef: TReference;
  7434. hp1, hp2, hp3, hp4: Tai;
  7435. {$ifndef x86_64}
  7436. OperIdx: Integer;
  7437. {$endif x86_64}
  7438. NewInstr : Taicpu;
  7439. NewAligh : Tai_align;
  7440. DestLabel: TAsmLabel;
  7441. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7442. var
  7443. NextInstr: tai;
  7444. begin
  7445. Result := False;
  7446. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7447. if not GetNextInstruction(InputInstr, NextInstr) or
  7448. (
  7449. { The FLAGS register isn't always tracked properly, so do not
  7450. perform this optimisation if a conditional statement follows }
  7451. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7452. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7453. ) then
  7454. begin
  7455. reference_reset(NewRef, 1, []);
  7456. NewRef.base := taicpu(p).oper[0]^.reg;
  7457. NewRef.scalefactor := 1;
  7458. if taicpu(InputInstr).opcode = A_ADD then
  7459. begin
  7460. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7461. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7462. end
  7463. else
  7464. begin
  7465. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7466. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7467. end;
  7468. taicpu(p).opcode := A_LEA;
  7469. taicpu(p).loadref(0, NewRef);
  7470. RemoveInstruction(InputInstr);
  7471. Result := True;
  7472. end;
  7473. end;
  7474. begin
  7475. Result:=false;
  7476. { This optimisation adds an instruction, so only do it for speed }
  7477. if not (cs_opt_size in current_settings.optimizerswitches) and
  7478. MatchOpType(taicpu(p), top_const, top_reg) and
  7479. (taicpu(p).oper[0]^.val = 0) then
  7480. begin
  7481. { To avoid compiler warning }
  7482. DestLabel := nil;
  7483. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7484. InternalError(2021040750);
  7485. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7486. Exit;
  7487. case hp1.typ of
  7488. ait_label:
  7489. begin
  7490. { Change:
  7491. mov $0,%reg mov $0,%reg
  7492. @Lbl1: @Lbl1:
  7493. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7494. je @Lbl2 jne @Lbl2
  7495. To: To:
  7496. mov $0,%reg mov $0,%reg
  7497. jmp @Lbl2 jmp @Lbl3
  7498. (align) (align)
  7499. @Lbl1: @Lbl1:
  7500. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7501. je @Lbl2 je @Lbl2
  7502. @Lbl3: <-- Only if label exists
  7503. (Not if it's optimised for size)
  7504. }
  7505. if not GetNextInstruction(hp1, hp2) then
  7506. Exit;
  7507. if not (cs_opt_size in current_settings.optimizerswitches) and
  7508. (hp2.typ = ait_instruction) and
  7509. (
  7510. { Register sizes must exactly match }
  7511. (
  7512. (taicpu(hp2).opcode = A_CMP) and
  7513. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7514. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7515. ) or (
  7516. (taicpu(hp2).opcode = A_TEST) and
  7517. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7518. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7519. )
  7520. ) and GetNextInstruction(hp2, hp3) and
  7521. (hp3.typ = ait_instruction) and
  7522. (taicpu(hp3).opcode = A_JCC) and
  7523. (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
  7524. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7525. begin
  7526. { Check condition of jump }
  7527. { Always true? }
  7528. if condition_in(C_E, taicpu(hp3).condition) then
  7529. begin
  7530. { Copy label symbol and obtain matching label entry for the
  7531. conditional jump, as this will be our destination}
  7532. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7533. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7534. Result := True;
  7535. end
  7536. { Always false? }
  7537. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7538. begin
  7539. { This is only worth it if there's a jump to take }
  7540. case hp2.typ of
  7541. ait_instruction:
  7542. begin
  7543. if taicpu(hp2).opcode = A_JMP then
  7544. begin
  7545. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7546. { An unconditional jump follows the conditional jump which will always be false,
  7547. so use this jump's destination for the new jump }
  7548. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7549. Result := True;
  7550. end
  7551. else if taicpu(hp2).opcode = A_JCC then
  7552. begin
  7553. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7554. if condition_in(C_E, taicpu(hp2).condition) then
  7555. begin
  7556. { A second conditional jump follows the conditional jump which will always be false,
  7557. while the second jump is always True, so use this jump's destination for the new jump }
  7558. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7559. Result := True;
  7560. end;
  7561. { Don't risk it if the jump isn't always true (Result remains False) }
  7562. end;
  7563. end;
  7564. else
  7565. { If anything else don't optimise };
  7566. end;
  7567. end;
  7568. if Result then
  7569. begin
  7570. { Just so we have something to insert as a paremeter}
  7571. reference_reset(NewRef, 1, []);
  7572. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7573. { Now actually load the correct parameter (this also
  7574. increases the reference count) }
  7575. NewInstr.loadsymbol(0, DestLabel, 0);
  7576. { Get instruction before original label (may not be p under -O3) }
  7577. if not GetLastInstruction(hp1, hp2) then
  7578. { Shouldn't fail here }
  7579. InternalError(2021040701);
  7580. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  7581. AsmL.InsertAfter(NewInstr, hp2);
  7582. { Add new alignment field }
  7583. (* AsmL.InsertAfter(
  7584. cai_align.create_max(
  7585. current_settings.alignment.jumpalign,
  7586. current_settings.alignment.jumpalignskipmax
  7587. ),
  7588. NewInstr
  7589. ); *)
  7590. end;
  7591. Exit;
  7592. end;
  7593. end;
  7594. else
  7595. ;
  7596. end;
  7597. end;
  7598. if not GetNextInstruction(p, hp1) then
  7599. Exit;
  7600. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7601. and DoMovCmpMemOpt(p, hp1, True) then
  7602. begin
  7603. Result := True;
  7604. Exit;
  7605. end
  7606. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7607. begin
  7608. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7609. further, but we can't just put this jump optimisation in pass 1
  7610. because it tends to perform worse when conditional jumps are
  7611. nearby (e.g. when converting CMOV instructions). [Kit] }
  7612. if OptPass2JMP(hp1) then
  7613. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7614. Result := OptPass1MOV(p)
  7615. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7616. returned True and the instruction is still a MOV, thus checking
  7617. the optimisations below }
  7618. { If OptPass2JMP returned False, no optimisations were done to
  7619. the jump and there are no further optimisations that can be done
  7620. to the MOV instruction on this pass }
  7621. end
  7622. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7623. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7624. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7625. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7626. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7627. begin
  7628. { Change:
  7629. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7630. addl/q $x,%reg2 subl/q $x,%reg2
  7631. To:
  7632. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7633. }
  7634. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7635. { be lazy, checking separately for sub would be slightly better }
  7636. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7637. begin
  7638. TransferUsedRegs(TmpUsedRegs);
  7639. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7640. if TryMovArith2Lea(hp1) then
  7641. begin
  7642. Result := True;
  7643. Exit;
  7644. end
  7645. end
  7646. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7647. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7648. { Same as above, but also adds or subtracts to %reg2 in between.
  7649. It's still valid as long as the flags aren't in use }
  7650. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7651. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7652. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7653. { be lazy, checking separately for sub would be slightly better }
  7654. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7655. begin
  7656. TransferUsedRegs(TmpUsedRegs);
  7657. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7658. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7659. if TryMovArith2Lea(hp2) then
  7660. begin
  7661. Result := True;
  7662. Exit;
  7663. end;
  7664. end;
  7665. end
  7666. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7667. {$ifdef x86_64}
  7668. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7669. {$else x86_64}
  7670. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7671. {$endif x86_64}
  7672. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7673. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7674. { mov reg1, reg2 mov reg1, reg2
  7675. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7676. begin
  7677. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7678. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7679. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7680. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7681. TransferUsedRegs(TmpUsedRegs);
  7682. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7683. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7684. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7685. then
  7686. begin
  7687. RemoveCurrentP(p, hp1);
  7688. Result:=true;
  7689. end;
  7690. exit;
  7691. end
  7692. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7693. IsXCHGAcceptable and
  7694. { XCHG doesn't support 8-byte registers }
  7695. (taicpu(p).opsize <> S_B) and
  7696. MatchInstruction(hp1, A_MOV, []) and
  7697. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7698. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7699. GetNextInstruction(hp1, hp2) and
  7700. MatchInstruction(hp2, A_MOV, []) and
  7701. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7702. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7703. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7704. begin
  7705. { mov %reg1,%reg2
  7706. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7707. mov %reg2,%reg3
  7708. (%reg2 not used afterwards)
  7709. Note that xchg takes 3 cycles to execute, and generally mov's take
  7710. only one cycle apiece, but the first two mov's can be executed in
  7711. parallel, only taking 2 cycles overall. Older processors should
  7712. therefore only optimise for size. [Kit]
  7713. }
  7714. TransferUsedRegs(TmpUsedRegs);
  7715. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7716. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7717. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7718. begin
  7719. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7720. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7721. taicpu(hp1).opcode := A_XCHG;
  7722. RemoveCurrentP(p, hp1);
  7723. RemoveInstruction(hp2);
  7724. Result := True;
  7725. Exit;
  7726. end;
  7727. end
  7728. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7729. MatchInstruction(hp1, A_SAR, []) then
  7730. begin
  7731. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7732. begin
  7733. { the use of %edx also covers the opsize being S_L }
  7734. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7735. begin
  7736. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7737. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7738. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7739. begin
  7740. { Change:
  7741. movl %eax,%edx
  7742. sarl $31,%edx
  7743. To:
  7744. cltd
  7745. }
  7746. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7747. RemoveInstruction(hp1);
  7748. taicpu(p).opcode := A_CDQ;
  7749. taicpu(p).opsize := S_NO;
  7750. taicpu(p).clearop(1);
  7751. taicpu(p).clearop(0);
  7752. taicpu(p).ops:=0;
  7753. Result := True;
  7754. end
  7755. else if (cs_opt_size in current_settings.optimizerswitches) and
  7756. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7757. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7758. begin
  7759. { Change:
  7760. movl %edx,%eax
  7761. sarl $31,%edx
  7762. To:
  7763. movl %edx,%eax
  7764. cltd
  7765. Note that this creates a dependency between the two instructions,
  7766. so only perform if optimising for size.
  7767. }
  7768. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7769. taicpu(hp1).opcode := A_CDQ;
  7770. taicpu(hp1).opsize := S_NO;
  7771. taicpu(hp1).clearop(1);
  7772. taicpu(hp1).clearop(0);
  7773. taicpu(hp1).ops:=0;
  7774. end;
  7775. {$ifndef x86_64}
  7776. end
  7777. { Don't bother if CMOV is supported, because a more optimal
  7778. sequence would have been generated for the Abs() intrinsic }
  7779. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7780. { the use of %eax also covers the opsize being S_L }
  7781. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7782. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7783. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7784. GetNextInstruction(hp1, hp2) and
  7785. MatchInstruction(hp2, A_XOR, [S_L]) and
  7786. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7787. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7788. GetNextInstruction(hp2, hp3) and
  7789. MatchInstruction(hp3, A_SUB, [S_L]) and
  7790. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7791. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7792. begin
  7793. { Change:
  7794. movl %eax,%edx
  7795. sarl $31,%eax
  7796. xorl %eax,%edx
  7797. subl %eax,%edx
  7798. (Instruction that uses %edx)
  7799. (%eax deallocated)
  7800. (%edx deallocated)
  7801. To:
  7802. cltd
  7803. xorl %edx,%eax <-- Note the registers have swapped
  7804. subl %edx,%eax
  7805. (Instruction that uses %eax) <-- %eax rather than %edx
  7806. }
  7807. TransferUsedRegs(TmpUsedRegs);
  7808. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7809. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7810. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7811. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7812. begin
  7813. if GetNextInstruction(hp3, hp4) and
  7814. not RegModifiedByInstruction(NR_EDX, hp4) and
  7815. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7816. begin
  7817. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7818. taicpu(p).opcode := A_CDQ;
  7819. taicpu(p).clearop(1);
  7820. taicpu(p).clearop(0);
  7821. taicpu(p).ops:=0;
  7822. RemoveInstruction(hp1);
  7823. taicpu(hp2).loadreg(0, NR_EDX);
  7824. taicpu(hp2).loadreg(1, NR_EAX);
  7825. taicpu(hp3).loadreg(0, NR_EDX);
  7826. taicpu(hp3).loadreg(1, NR_EAX);
  7827. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7828. { Convert references in the following instruction (hp4) from %edx to %eax }
  7829. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7830. with taicpu(hp4).oper[OperIdx]^ do
  7831. case typ of
  7832. top_reg:
  7833. if getsupreg(reg) = RS_EDX then
  7834. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7835. top_ref:
  7836. begin
  7837. if getsupreg(reg) = RS_EDX then
  7838. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7839. if getsupreg(reg) = RS_EDX then
  7840. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7841. end;
  7842. else
  7843. ;
  7844. end;
  7845. end;
  7846. end;
  7847. {$else x86_64}
  7848. end;
  7849. end
  7850. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7851. { the use of %rdx also covers the opsize being S_Q }
  7852. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7853. begin
  7854. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7855. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7856. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7857. begin
  7858. { Change:
  7859. movq %rax,%rdx
  7860. sarq $63,%rdx
  7861. To:
  7862. cqto
  7863. }
  7864. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7865. RemoveInstruction(hp1);
  7866. taicpu(p).opcode := A_CQO;
  7867. taicpu(p).opsize := S_NO;
  7868. taicpu(p).clearop(1);
  7869. taicpu(p).clearop(0);
  7870. taicpu(p).ops:=0;
  7871. Result := True;
  7872. end
  7873. else if (cs_opt_size in current_settings.optimizerswitches) and
  7874. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7875. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7876. begin
  7877. { Change:
  7878. movq %rdx,%rax
  7879. sarq $63,%rdx
  7880. To:
  7881. movq %rdx,%rax
  7882. cqto
  7883. Note that this creates a dependency between the two instructions,
  7884. so only perform if optimising for size.
  7885. }
  7886. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7887. taicpu(hp1).opcode := A_CQO;
  7888. taicpu(hp1).opsize := S_NO;
  7889. taicpu(hp1).clearop(1);
  7890. taicpu(hp1).clearop(0);
  7891. taicpu(hp1).ops:=0;
  7892. {$endif x86_64}
  7893. end;
  7894. end;
  7895. end
  7896. else if MatchInstruction(hp1, A_MOV, []) and
  7897. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7898. { Though "GetNextInstruction" could be factored out, along with
  7899. the instructions that depend on hp2, it is an expensive call that
  7900. should be delayed for as long as possible, hence we do cheaper
  7901. checks first that are likely to be False. [Kit] }
  7902. begin
  7903. if (
  7904. (
  7905. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7906. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7907. (
  7908. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7909. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7910. )
  7911. ) or
  7912. (
  7913. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7914. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7915. (
  7916. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7917. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7918. )
  7919. )
  7920. ) and
  7921. GetNextInstruction(hp1, hp2) and
  7922. MatchInstruction(hp2, A_SAR, []) and
  7923. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7924. begin
  7925. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7926. begin
  7927. { Change:
  7928. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7929. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7930. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7931. To:
  7932. movl r/m,%eax <- Note the change in register
  7933. cltd
  7934. }
  7935. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7936. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7937. taicpu(p).loadreg(1, NR_EAX);
  7938. taicpu(hp1).opcode := A_CDQ;
  7939. taicpu(hp1).clearop(1);
  7940. taicpu(hp1).clearop(0);
  7941. taicpu(hp1).ops:=0;
  7942. RemoveInstruction(hp2);
  7943. (*
  7944. {$ifdef x86_64}
  7945. end
  7946. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7947. { This code sequence does not get generated - however it might become useful
  7948. if and when 128-bit signed integer types make an appearance, so the code
  7949. is kept here for when it is eventually needed. [Kit] }
  7950. (
  7951. (
  7952. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7953. (
  7954. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7955. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7956. )
  7957. ) or
  7958. (
  7959. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7960. (
  7961. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7962. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7963. )
  7964. )
  7965. ) and
  7966. GetNextInstruction(hp1, hp2) and
  7967. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7968. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7969. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7970. begin
  7971. { Change:
  7972. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7973. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7974. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7975. To:
  7976. movq r/m,%rax <- Note the change in register
  7977. cqto
  7978. }
  7979. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7980. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7981. taicpu(p).loadreg(1, NR_RAX);
  7982. taicpu(hp1).opcode := A_CQO;
  7983. taicpu(hp1).clearop(1);
  7984. taicpu(hp1).clearop(0);
  7985. taicpu(hp1).ops:=0;
  7986. RemoveInstruction(hp2);
  7987. {$endif x86_64}
  7988. *)
  7989. end;
  7990. end;
  7991. {$ifdef x86_64}
  7992. end
  7993. else if (taicpu(p).opsize = S_L) and
  7994. (taicpu(p).oper[1]^.typ = top_reg) and
  7995. (
  7996. MatchInstruction(hp1, A_MOV,[]) and
  7997. (taicpu(hp1).opsize = S_L) and
  7998. (taicpu(hp1).oper[1]^.typ = top_reg)
  7999. ) and (
  8000. GetNextInstruction(hp1, hp2) and
  8001. (tai(hp2).typ=ait_instruction) and
  8002. (taicpu(hp2).opsize = S_Q) and
  8003. (
  8004. (
  8005. MatchInstruction(hp2, A_ADD,[]) and
  8006. (taicpu(hp2).opsize = S_Q) and
  8007. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8008. (
  8009. (
  8010. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8011. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8012. ) or (
  8013. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8014. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8015. )
  8016. )
  8017. ) or (
  8018. MatchInstruction(hp2, A_LEA,[]) and
  8019. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8020. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8021. (
  8022. (
  8023. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8024. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8025. ) or (
  8026. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8027. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8028. )
  8029. ) and (
  8030. (
  8031. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8032. ) or (
  8033. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8034. )
  8035. )
  8036. )
  8037. )
  8038. ) and (
  8039. GetNextInstruction(hp2, hp3) and
  8040. MatchInstruction(hp3, A_SHR,[]) and
  8041. (taicpu(hp3).opsize = S_Q) and
  8042. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8043. (taicpu(hp3).oper[0]^.val = 1) and
  8044. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8045. ) then
  8046. begin
  8047. { Change movl x, reg1d movl x, reg1d
  8048. movl y, reg2d movl y, reg2d
  8049. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8050. shrq $1, reg1q shrq $1, reg1q
  8051. ( reg1d and reg2d can be switched around in the first two instructions )
  8052. To movl x, reg1d
  8053. addl y, reg1d
  8054. rcrl $1, reg1d
  8055. This corresponds to the common expression (x + y) shr 1, where
  8056. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8057. smaller code, but won't account for x + y causing an overflow). [Kit]
  8058. }
  8059. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8060. { Change first MOV command to have the same register as the final output }
  8061. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8062. else
  8063. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8064. { Change second MOV command to an ADD command. This is easier than
  8065. converting the existing command because it means we don't have to
  8066. touch 'y', which might be a complicated reference, and also the
  8067. fact that the third command might either be ADD or LEA. [Kit] }
  8068. taicpu(hp1).opcode := A_ADD;
  8069. { Delete old ADD/LEA instruction }
  8070. RemoveInstruction(hp2);
  8071. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8072. taicpu(hp3).opcode := A_RCR;
  8073. taicpu(hp3).changeopsize(S_L);
  8074. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8075. {$endif x86_64}
  8076. end;
  8077. end;
  8078. {$push}
  8079. {$q-}{$r-}
  8080. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8081. var
  8082. ThisReg: TRegister;
  8083. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8084. TargetSubReg: TSubRegister;
  8085. hp1, hp2: tai;
  8086. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8087. { Store list of found instructions so we don't have to call
  8088. GetNextInstructionUsingReg multiple times }
  8089. InstrList: array of taicpu;
  8090. InstrMax, Index: Integer;
  8091. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8092. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8093. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8094. WorkingValue: TCgInt;
  8095. PreMessage: string;
  8096. { Data flow analysis }
  8097. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8098. BitwiseOnly, OrXorUsed,
  8099. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8100. function CheckOverflowConditions: Boolean;
  8101. begin
  8102. Result := True;
  8103. if (TestValSignedMax > SignedUpperLimit) then
  8104. UpperSignedOverflow := True;
  8105. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8106. LowerSignedOverflow := True;
  8107. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8108. LowerUnsignedOverflow := True;
  8109. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8110. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8111. begin
  8112. { Absolute overflow }
  8113. Result := False;
  8114. Exit;
  8115. end;
  8116. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8117. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8118. ShiftDownOverflow := True;
  8119. if (TestValMin < 0) or (TestValMax < 0) then
  8120. begin
  8121. LowerUnsignedOverflow := True;
  8122. UpperUnsignedOverflow := True;
  8123. end;
  8124. end;
  8125. function AdjustInitialLoadAndSize: Boolean;
  8126. begin
  8127. Result := False;
  8128. if not p_removed then
  8129. begin
  8130. if TargetSize = MinSize then
  8131. begin
  8132. { Convert the input MOVZX to a MOV }
  8133. if (taicpu(p).oper[0]^.typ = top_reg) and
  8134. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8135. begin
  8136. { Or remove it completely! }
  8137. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8138. RemoveCurrentP(p);
  8139. p_removed := True;
  8140. end
  8141. else
  8142. begin
  8143. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8144. taicpu(p).opcode := A_MOV;
  8145. taicpu(p).oper[1]^.reg := ThisReg;
  8146. taicpu(p).opsize := TargetSize;
  8147. end;
  8148. Result := True;
  8149. end
  8150. else if TargetSize <> MaxSize then
  8151. begin
  8152. case MaxSize of
  8153. S_L:
  8154. if TargetSize = S_W then
  8155. begin
  8156. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8157. taicpu(p).opsize := S_BW;
  8158. taicpu(p).oper[1]^.reg := ThisReg;
  8159. Result := True;
  8160. end
  8161. else
  8162. InternalError(2020112341);
  8163. S_W:
  8164. if TargetSize = S_L then
  8165. begin
  8166. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8167. taicpu(p).opsize := S_BL;
  8168. taicpu(p).oper[1]^.reg := ThisReg;
  8169. Result := True;
  8170. end
  8171. else
  8172. InternalError(2020112342);
  8173. else
  8174. ;
  8175. end;
  8176. end
  8177. else if not hp1_removed and not RegInUse then
  8178. begin
  8179. { If we have something like:
  8180. movzbl (oper),%regd
  8181. add x, %regd
  8182. movzbl %regb, %regd
  8183. We can reduce the register size to the input of the final
  8184. movzbl instruction. Overflows won't have any effect.
  8185. }
  8186. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8187. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8188. begin
  8189. TargetSize := S_B;
  8190. setsubreg(ThisReg, R_SUBL);
  8191. Result := True;
  8192. end
  8193. else if (taicpu(p).opsize = S_WL) and
  8194. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8195. begin
  8196. TargetSize := S_W;
  8197. setsubreg(ThisReg, R_SUBW);
  8198. Result := True;
  8199. end;
  8200. if Result then
  8201. begin
  8202. { Convert the input MOVZX to a MOV }
  8203. if (taicpu(p).oper[0]^.typ = top_reg) and
  8204. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8205. begin
  8206. { Or remove it completely! }
  8207. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8208. RemoveCurrentP(p);
  8209. p_removed := True;
  8210. end
  8211. else
  8212. begin
  8213. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8214. taicpu(p).opcode := A_MOV;
  8215. taicpu(p).oper[1]^.reg := ThisReg;
  8216. taicpu(p).opsize := TargetSize;
  8217. end;
  8218. end;
  8219. end;
  8220. end;
  8221. end;
  8222. procedure AdjustFinalLoad;
  8223. begin
  8224. if not LowerUnsignedOverflow then
  8225. begin
  8226. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8227. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8228. begin
  8229. { Convert the output MOVZX to a MOV }
  8230. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8231. begin
  8232. { Or remove it completely! }
  8233. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8234. { Be careful; if p = hp1 and p was also removed, p
  8235. will become a dangling pointer }
  8236. if p = hp1 then
  8237. begin
  8238. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8239. p_removed := True;
  8240. end
  8241. else
  8242. RemoveInstruction(hp1);
  8243. hp1_removed := True;
  8244. end
  8245. else
  8246. begin
  8247. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8248. taicpu(hp1).opcode := A_MOV;
  8249. taicpu(hp1).oper[0]^.reg := ThisReg;
  8250. taicpu(hp1).opsize := TargetSize;
  8251. end;
  8252. end
  8253. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8254. begin
  8255. { Need to change the size of the output }
  8256. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8257. taicpu(hp1).oper[0]^.reg := ThisReg;
  8258. taicpu(hp1).opsize := S_BL;
  8259. end;
  8260. end;
  8261. end;
  8262. function CompressInstructions: Boolean;
  8263. var
  8264. LocalIndex: Integer;
  8265. begin
  8266. Result := False;
  8267. { The objective here is to try to find a combination that
  8268. removes one of the MOV/Z instructions. }
  8269. if (
  8270. (taicpu(p).oper[0]^.typ <> top_reg) or
  8271. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8272. ) and
  8273. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8274. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8275. begin
  8276. { Make a preference to remove the second MOVZX instruction }
  8277. case taicpu(hp1).opsize of
  8278. S_BL, S_WL:
  8279. begin
  8280. TargetSize := S_L;
  8281. TargetSubReg := R_SUBD;
  8282. end;
  8283. S_BW:
  8284. begin
  8285. TargetSize := S_W;
  8286. TargetSubReg := R_SUBW;
  8287. end;
  8288. else
  8289. InternalError(2020112302);
  8290. end;
  8291. end
  8292. else
  8293. begin
  8294. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8295. begin
  8296. { Exceeded lower bound but not upper bound }
  8297. TargetSize := MaxSize;
  8298. end
  8299. else if not LowerUnsignedOverflow then
  8300. begin
  8301. { Size didn't exceed lower bound }
  8302. TargetSize := MinSize;
  8303. end
  8304. else
  8305. Exit;
  8306. end;
  8307. case TargetSize of
  8308. S_B:
  8309. TargetSubReg := R_SUBL;
  8310. S_W:
  8311. TargetSubReg := R_SUBW;
  8312. S_L:
  8313. TargetSubReg := R_SUBD;
  8314. else
  8315. InternalError(2020112350);
  8316. end;
  8317. { Update the register to its new size }
  8318. setsubreg(ThisReg, TargetSubReg);
  8319. RegInUse := False;
  8320. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8321. begin
  8322. { Check to see if the active register is used afterwards;
  8323. if not, we can change it and make a saving. }
  8324. TransferUsedRegs(TmpUsedRegs);
  8325. { The target register may be marked as in use to cross
  8326. a jump to a distant label, so exclude it }
  8327. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8328. hp2 := p;
  8329. repeat
  8330. { Explicitly check for the excluded register (don't include the first
  8331. instruction as it may be reading from here }
  8332. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8333. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8334. begin
  8335. RegInUse := True;
  8336. Break;
  8337. end;
  8338. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8339. if not GetNextInstruction(hp2, hp2) then
  8340. InternalError(2020112340);
  8341. until (hp2 = hp1);
  8342. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8343. { We might still be able to get away with this }
  8344. RegInUse := not
  8345. (
  8346. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8347. (hp2.typ = ait_instruction) and
  8348. (
  8349. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8350. instruction that doesn't actually contain ThisReg }
  8351. (cs_opt_level3 in current_settings.optimizerswitches) or
  8352. RegInInstruction(ThisReg, hp2)
  8353. ) and
  8354. RegLoadedWithNewValue(ThisReg, hp2)
  8355. );
  8356. if not RegInUse then
  8357. begin
  8358. { Force the register size to the same as this instruction so it can be removed}
  8359. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8360. begin
  8361. TargetSize := S_L;
  8362. TargetSubReg := R_SUBD;
  8363. end
  8364. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8365. begin
  8366. TargetSize := S_W;
  8367. TargetSubReg := R_SUBW;
  8368. end;
  8369. ThisReg := taicpu(hp1).oper[1]^.reg;
  8370. setsubreg(ThisReg, TargetSubReg);
  8371. RegChanged := True;
  8372. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8373. TransferUsedRegs(TmpUsedRegs);
  8374. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8375. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8376. if p = hp1 then
  8377. begin
  8378. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8379. p_removed := True;
  8380. end
  8381. else
  8382. RemoveInstruction(hp1);
  8383. hp1_removed := True;
  8384. { Instruction will become "mov %reg,%reg" }
  8385. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8386. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8387. begin
  8388. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8389. RemoveCurrentP(p);
  8390. p_removed := True;
  8391. end
  8392. else
  8393. taicpu(p).oper[1]^.reg := ThisReg;
  8394. Result := True;
  8395. end
  8396. else
  8397. begin
  8398. if TargetSize <> MaxSize then
  8399. begin
  8400. { Since the register is in use, we have to force it to
  8401. MaxSize otherwise part of it may become undefined later on }
  8402. TargetSize := MaxSize;
  8403. case TargetSize of
  8404. S_B:
  8405. TargetSubReg := R_SUBL;
  8406. S_W:
  8407. TargetSubReg := R_SUBW;
  8408. S_L:
  8409. TargetSubReg := R_SUBD;
  8410. else
  8411. InternalError(2020112351);
  8412. end;
  8413. setsubreg(ThisReg, TargetSubReg);
  8414. end;
  8415. AdjustFinalLoad;
  8416. end;
  8417. end
  8418. else
  8419. AdjustFinalLoad;
  8420. Result := AdjustInitialLoadAndSize or Result;
  8421. { Now go through every instruction we found and change the
  8422. size. If TargetSize = MaxSize, then almost no changes are
  8423. needed and Result can remain False if it hasn't been set
  8424. yet.
  8425. If RegChanged is True, then the register requires changing
  8426. and so the point about TargetSize = MaxSize doesn't apply. }
  8427. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8428. begin
  8429. for LocalIndex := 0 to InstrMax do
  8430. begin
  8431. { If p_removed is true, then the original MOV/Z was removed
  8432. and removing the AND instruction may not be safe if it
  8433. appears first }
  8434. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8435. InternalError(2020112310);
  8436. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8437. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8438. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8439. InstrList[LocalIndex].opsize := TargetSize;
  8440. end;
  8441. Result := True;
  8442. end;
  8443. end;
  8444. begin
  8445. Result := False;
  8446. p_removed := False;
  8447. hp1_removed := False;
  8448. ThisReg := taicpu(p).oper[1]^.reg;
  8449. { Check for:
  8450. movs/z ###,%ecx (or %cx or %rcx)
  8451. ...
  8452. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8453. (dealloc %ecx)
  8454. Change to:
  8455. mov ###,%cl (if ### = %cl, then remove completely)
  8456. ...
  8457. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8458. }
  8459. if (getsupreg(ThisReg) = RS_ECX) and
  8460. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8461. (hp1.typ = ait_instruction) and
  8462. (
  8463. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8464. instruction that doesn't actually contain ECX }
  8465. (cs_opt_level3 in current_settings.optimizerswitches) or
  8466. RegInInstruction(NR_ECX, hp1) or
  8467. (
  8468. { It's common for the shift/rotate's read/write register to be
  8469. initialised in between, so under -O2 and under, search ahead
  8470. one more instruction
  8471. }
  8472. GetNextInstruction(hp1, hp1) and
  8473. (hp1.typ = ait_instruction) and
  8474. RegInInstruction(NR_ECX, hp1)
  8475. )
  8476. ) and
  8477. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8478. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8479. begin
  8480. TransferUsedRegs(TmpUsedRegs);
  8481. hp2 := p;
  8482. repeat
  8483. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8484. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8485. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8486. begin
  8487. case taicpu(p).opsize of
  8488. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8489. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8490. begin
  8491. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8492. RemoveCurrentP(p);
  8493. end
  8494. else
  8495. begin
  8496. taicpu(p).opcode := A_MOV;
  8497. taicpu(p).opsize := S_B;
  8498. taicpu(p).oper[1]^.reg := NR_CL;
  8499. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8500. end;
  8501. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8502. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8503. begin
  8504. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8505. RemoveCurrentP(p);
  8506. end
  8507. else
  8508. begin
  8509. taicpu(p).opcode := A_MOV;
  8510. taicpu(p).opsize := S_W;
  8511. taicpu(p).oper[1]^.reg := NR_CX;
  8512. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8513. end;
  8514. {$ifdef x86_64}
  8515. S_LQ:
  8516. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8517. begin
  8518. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8519. RemoveCurrentP(p);
  8520. end
  8521. else
  8522. begin
  8523. taicpu(p).opcode := A_MOV;
  8524. taicpu(p).opsize := S_L;
  8525. taicpu(p).oper[1]^.reg := NR_ECX;
  8526. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8527. end;
  8528. {$endif x86_64}
  8529. else
  8530. InternalError(2021120401);
  8531. end;
  8532. Result := True;
  8533. Exit;
  8534. end;
  8535. end;
  8536. { This is anything but quick! }
  8537. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8538. Exit;
  8539. SetLength(InstrList, 0);
  8540. InstrMax := -1;
  8541. case taicpu(p).opsize of
  8542. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8543. begin
  8544. {$if defined(i386) or defined(i8086)}
  8545. { If the target size is 8-bit, make sure we can actually encode it }
  8546. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8547. Exit;
  8548. {$endif i386 or i8086}
  8549. LowerLimit := $FF;
  8550. SignedLowerLimit := $7F;
  8551. SignedLowerLimitBottom := -128;
  8552. MinSize := S_B;
  8553. if taicpu(p).opsize = S_BW then
  8554. begin
  8555. MaxSize := S_W;
  8556. UpperLimit := $FFFF;
  8557. SignedUpperLimit := $7FFF;
  8558. SignedUpperLimitBottom := -32768;
  8559. end
  8560. else
  8561. begin
  8562. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8563. MaxSize := S_L;
  8564. UpperLimit := $FFFFFFFF;
  8565. SignedUpperLimit := $7FFFFFFF;
  8566. SignedUpperLimitBottom := -2147483648;
  8567. end;
  8568. end;
  8569. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8570. begin
  8571. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8572. LowerLimit := $FFFF;
  8573. SignedLowerLimit := $7FFF;
  8574. SignedLowerLimitBottom := -32768;
  8575. UpperLimit := $FFFFFFFF;
  8576. SignedUpperLimit := $7FFFFFFF;
  8577. SignedUpperLimitBottom := -2147483648;
  8578. MinSize := S_W;
  8579. MaxSize := S_L;
  8580. end;
  8581. {$ifdef x86_64}
  8582. S_LQ:
  8583. begin
  8584. { Both the lower and upper limits are set to 32-bit. If a limit
  8585. is breached, then optimisation is impossible }
  8586. LowerLimit := $FFFFFFFF;
  8587. SignedLowerLimit := $7FFFFFFF;
  8588. SignedLowerLimitBottom := -2147483648;
  8589. UpperLimit := $FFFFFFFF;
  8590. SignedUpperLimit := $7FFFFFFF;
  8591. SignedUpperLimitBottom := -2147483648;
  8592. MinSize := S_L;
  8593. MaxSize := S_L;
  8594. end;
  8595. {$endif x86_64}
  8596. else
  8597. InternalError(2020112301);
  8598. end;
  8599. TestValMin := 0;
  8600. TestValMax := LowerLimit;
  8601. TestValSignedMax := SignedLowerLimit;
  8602. TryShiftDownLimit := LowerLimit;
  8603. TryShiftDown := S_NO;
  8604. ShiftDownOverflow := False;
  8605. RegChanged := False;
  8606. BitwiseOnly := True;
  8607. OrXorUsed := False;
  8608. UpperSignedOverflow := False;
  8609. LowerSignedOverflow := False;
  8610. UpperUnsignedOverflow := False;
  8611. LowerUnsignedOverflow := False;
  8612. hp1 := p;
  8613. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8614. (hp1.typ = ait_instruction) and
  8615. (
  8616. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8617. instruction that doesn't actually contain ThisReg }
  8618. (cs_opt_level3 in current_settings.optimizerswitches) or
  8619. { This allows this Movx optimisation to work through the SETcc instructions
  8620. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8621. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8622. skip over these SETcc instructions). }
  8623. (taicpu(hp1).opcode = A_SETcc) or
  8624. RegInInstruction(ThisReg, hp1)
  8625. ) do
  8626. begin
  8627. case taicpu(hp1).opcode of
  8628. A_INC,A_DEC:
  8629. begin
  8630. { Has to be an exact match on the register }
  8631. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8632. Break;
  8633. if taicpu(hp1).opcode = A_INC then
  8634. begin
  8635. Inc(TestValMin);
  8636. Inc(TestValMax);
  8637. Inc(TestValSignedMax);
  8638. end
  8639. else
  8640. begin
  8641. Dec(TestValMin);
  8642. Dec(TestValMax);
  8643. Dec(TestValSignedMax);
  8644. end;
  8645. end;
  8646. A_TEST, A_CMP:
  8647. begin
  8648. if (
  8649. { Too high a risk of non-linear behaviour that breaks DFA
  8650. here, unless it's cmp $0,%reg, which is equivalent to
  8651. test %reg,%reg }
  8652. OrXorUsed and
  8653. (taicpu(hp1).opcode = A_CMP) and
  8654. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8655. ) or
  8656. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8657. { Has to be an exact match on the register }
  8658. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8659. (
  8660. { Permit "test %reg,%reg" }
  8661. (taicpu(hp1).opcode = A_TEST) and
  8662. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8663. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8664. ) or
  8665. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8666. { Make sure the comparison value is not smaller than the
  8667. smallest allowed signed value for the minimum size (e.g.
  8668. -128 for 8-bit) }
  8669. not (
  8670. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8671. { Is it in the negative range? }
  8672. (
  8673. (taicpu(hp1).oper[0]^.val < 0) and
  8674. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8675. )
  8676. ) then
  8677. Break;
  8678. { Check to see if the active register is used afterwards }
  8679. TransferUsedRegs(TmpUsedRegs);
  8680. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8681. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8682. begin
  8683. { Make sure the comparison or any previous instructions
  8684. hasn't pushed the test values outside of the range of
  8685. MinSize }
  8686. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8687. begin
  8688. { Exceeded lower bound but not upper bound }
  8689. Exit;
  8690. end
  8691. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8692. begin
  8693. { Size didn't exceed lower bound }
  8694. TargetSize := MinSize;
  8695. end
  8696. else
  8697. Break;
  8698. case TargetSize of
  8699. S_B:
  8700. TargetSubReg := R_SUBL;
  8701. S_W:
  8702. TargetSubReg := R_SUBW;
  8703. S_L:
  8704. TargetSubReg := R_SUBD;
  8705. else
  8706. InternalError(2021051002);
  8707. end;
  8708. if TargetSize <> MaxSize then
  8709. begin
  8710. { Update the register to its new size }
  8711. setsubreg(ThisReg, TargetSubReg);
  8712. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8713. taicpu(hp1).oper[1]^.reg := ThisReg;
  8714. taicpu(hp1).opsize := TargetSize;
  8715. { Convert the input MOVZX to a MOV if necessary }
  8716. AdjustInitialLoadAndSize;
  8717. if (InstrMax >= 0) then
  8718. begin
  8719. for Index := 0 to InstrMax do
  8720. begin
  8721. { If p_removed is true, then the original MOV/Z was removed
  8722. and removing the AND instruction may not be safe if it
  8723. appears first }
  8724. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8725. InternalError(2020112311);
  8726. if InstrList[Index].oper[0]^.typ = top_reg then
  8727. InstrList[Index].oper[0]^.reg := ThisReg;
  8728. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8729. InstrList[Index].opsize := MinSize;
  8730. end;
  8731. end;
  8732. Result := True;
  8733. end;
  8734. Exit;
  8735. end;
  8736. end;
  8737. A_SETcc:
  8738. begin
  8739. { This allows this Movx optimisation to work through the SETcc instructions
  8740. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8741. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8742. skip over these SETcc instructions). }
  8743. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8744. { Of course, break out if the current register is used }
  8745. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8746. Break
  8747. else
  8748. { We must use Continue so the instruction doesn't get added
  8749. to InstrList }
  8750. Continue;
  8751. end;
  8752. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8753. begin
  8754. if
  8755. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8756. { Has to be an exact match on the register }
  8757. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8758. (
  8759. (
  8760. (taicpu(hp1).oper[0]^.typ = top_const) and
  8761. (
  8762. (
  8763. (taicpu(hp1).opcode = A_SHL) and
  8764. (
  8765. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8766. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8767. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8768. )
  8769. ) or (
  8770. (taicpu(hp1).opcode <> A_SHL) and
  8771. (
  8772. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8773. { Is it in the negative range? }
  8774. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8775. )
  8776. )
  8777. )
  8778. ) or (
  8779. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8780. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8781. )
  8782. ) then
  8783. Break;
  8784. { Only process OR and XOR if there are only bitwise operations,
  8785. since otherwise they can too easily fool the data flow
  8786. analysis (they can cause non-linear behaviour) }
  8787. case taicpu(hp1).opcode of
  8788. A_ADD:
  8789. begin
  8790. if OrXorUsed then
  8791. { Too high a risk of non-linear behaviour that breaks DFA here }
  8792. Break
  8793. else
  8794. BitwiseOnly := False;
  8795. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8796. begin
  8797. TestValMin := TestValMin * 2;
  8798. TestValMax := TestValMax * 2;
  8799. TestValSignedMax := TestValSignedMax * 2;
  8800. end
  8801. else
  8802. begin
  8803. WorkingValue := taicpu(hp1).oper[0]^.val;
  8804. TestValMin := TestValMin + WorkingValue;
  8805. TestValMax := TestValMax + WorkingValue;
  8806. TestValSignedMax := TestValSignedMax + WorkingValue;
  8807. end;
  8808. end;
  8809. A_SUB:
  8810. begin
  8811. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8812. begin
  8813. TestValMin := 0;
  8814. TestValMax := 0;
  8815. TestValSignedMax := 0;
  8816. end
  8817. else
  8818. begin
  8819. if OrXorUsed then
  8820. { Too high a risk of non-linear behaviour that breaks DFA here }
  8821. Break
  8822. else
  8823. BitwiseOnly := False;
  8824. WorkingValue := taicpu(hp1).oper[0]^.val;
  8825. TestValMin := TestValMin - WorkingValue;
  8826. TestValMax := TestValMax - WorkingValue;
  8827. TestValSignedMax := TestValSignedMax - WorkingValue;
  8828. end;
  8829. end;
  8830. A_AND:
  8831. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8832. begin
  8833. { we might be able to go smaller if AND appears first }
  8834. if InstrMax = -1 then
  8835. case MinSize of
  8836. S_B:
  8837. ;
  8838. S_W:
  8839. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8840. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8841. begin
  8842. TryShiftDown := S_B;
  8843. TryShiftDownLimit := $FF;
  8844. end;
  8845. S_L:
  8846. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8847. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8848. begin
  8849. TryShiftDown := S_B;
  8850. TryShiftDownLimit := $FF;
  8851. end
  8852. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8853. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8854. begin
  8855. TryShiftDown := S_W;
  8856. TryShiftDownLimit := $FFFF;
  8857. end;
  8858. else
  8859. InternalError(2020112320);
  8860. end;
  8861. WorkingValue := taicpu(hp1).oper[0]^.val;
  8862. TestValMin := TestValMin and WorkingValue;
  8863. TestValMax := TestValMax and WorkingValue;
  8864. TestValSignedMax := TestValSignedMax and WorkingValue;
  8865. end;
  8866. A_OR:
  8867. begin
  8868. if not BitwiseOnly then
  8869. Break;
  8870. OrXorUsed := True;
  8871. WorkingValue := taicpu(hp1).oper[0]^.val;
  8872. TestValMin := TestValMin or WorkingValue;
  8873. TestValMax := TestValMax or WorkingValue;
  8874. TestValSignedMax := TestValSignedMax or WorkingValue;
  8875. end;
  8876. A_XOR:
  8877. begin
  8878. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8879. begin
  8880. TestValMin := 0;
  8881. TestValMax := 0;
  8882. TestValSignedMax := 0;
  8883. end
  8884. else
  8885. begin
  8886. if not BitwiseOnly then
  8887. Break;
  8888. OrXorUsed := True;
  8889. WorkingValue := taicpu(hp1).oper[0]^.val;
  8890. TestValMin := TestValMin xor WorkingValue;
  8891. TestValMax := TestValMax xor WorkingValue;
  8892. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8893. end;
  8894. end;
  8895. A_SHL:
  8896. begin
  8897. BitwiseOnly := False;
  8898. WorkingValue := taicpu(hp1).oper[0]^.val;
  8899. TestValMin := TestValMin shl WorkingValue;
  8900. TestValMax := TestValMax shl WorkingValue;
  8901. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8902. end;
  8903. A_SHR,
  8904. { The first instruction was MOVZX, so the value won't be negative }
  8905. A_SAR:
  8906. begin
  8907. if InstrMax <> -1 then
  8908. BitwiseOnly := False
  8909. else
  8910. { we might be able to go smaller if SHR appears first }
  8911. case MinSize of
  8912. S_B:
  8913. ;
  8914. S_W:
  8915. if (taicpu(hp1).oper[0]^.val >= 8) then
  8916. begin
  8917. TryShiftDown := S_B;
  8918. TryShiftDownLimit := $FF;
  8919. TryShiftDownSignedLimit := $7F;
  8920. TryShiftDownSignedLimitLower := -128;
  8921. end;
  8922. S_L:
  8923. if (taicpu(hp1).oper[0]^.val >= 24) then
  8924. begin
  8925. TryShiftDown := S_B;
  8926. TryShiftDownLimit := $FF;
  8927. TryShiftDownSignedLimit := $7F;
  8928. TryShiftDownSignedLimitLower := -128;
  8929. end
  8930. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8931. begin
  8932. TryShiftDown := S_W;
  8933. TryShiftDownLimit := $FFFF;
  8934. TryShiftDownSignedLimit := $7FFF;
  8935. TryShiftDownSignedLimitLower := -32768;
  8936. end;
  8937. else
  8938. InternalError(2020112321);
  8939. end;
  8940. WorkingValue := taicpu(hp1).oper[0]^.val;
  8941. if taicpu(hp1).opcode = A_SAR then
  8942. begin
  8943. TestValMin := SarInt64(TestValMin, WorkingValue);
  8944. TestValMax := SarInt64(TestValMax, WorkingValue);
  8945. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8946. end
  8947. else
  8948. begin
  8949. TestValMin := TestValMin shr WorkingValue;
  8950. TestValMax := TestValMax shr WorkingValue;
  8951. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8952. end;
  8953. end;
  8954. else
  8955. InternalError(2020112303);
  8956. end;
  8957. end;
  8958. (*
  8959. A_IMUL:
  8960. case taicpu(hp1).ops of
  8961. 2:
  8962. begin
  8963. if not MatchOpType(hp1, top_reg, top_reg) or
  8964. { Has to be an exact match on the register }
  8965. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8966. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8967. Break;
  8968. TestValMin := TestValMin * TestValMin;
  8969. TestValMax := TestValMax * TestValMax;
  8970. TestValSignedMax := TestValSignedMax * TestValMax;
  8971. end;
  8972. 3:
  8973. begin
  8974. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8975. { Has to be an exact match on the register }
  8976. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8977. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8978. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8979. { Is it in the negative range? }
  8980. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8981. Break;
  8982. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8983. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8984. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8985. end;
  8986. else
  8987. Break;
  8988. end;
  8989. A_IDIV:
  8990. case taicpu(hp1).ops of
  8991. 3:
  8992. begin
  8993. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8994. { Has to be an exact match on the register }
  8995. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8996. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8997. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8998. { Is it in the negative range? }
  8999. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9000. Break;
  9001. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9002. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9003. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9004. end;
  9005. else
  9006. Break;
  9007. end;
  9008. *)
  9009. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9010. begin
  9011. { If there are no instructions in between, then we might be able to make a saving }
  9012. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9013. Break;
  9014. { We have something like:
  9015. movzbw %dl,%dx
  9016. ...
  9017. movswl %dx,%edx
  9018. Change the latter to a zero-extension then enter the
  9019. A_MOVZX case branch.
  9020. }
  9021. {$ifdef x86_64}
  9022. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9023. begin
  9024. { this becomes a zero extension from 32-bit to 64-bit, but
  9025. the upper 32 bits are already zero, so just delete the
  9026. instruction }
  9027. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9028. RemoveInstruction(hp1);
  9029. Result := True;
  9030. Exit;
  9031. end
  9032. else
  9033. {$endif x86_64}
  9034. begin
  9035. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9036. taicpu(hp1).opcode := A_MOVZX;
  9037. {$ifdef x86_64}
  9038. case taicpu(hp1).opsize of
  9039. S_BQ:
  9040. begin
  9041. taicpu(hp1).opsize := S_BL;
  9042. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9043. end;
  9044. S_WQ:
  9045. begin
  9046. taicpu(hp1).opsize := S_WL;
  9047. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9048. end;
  9049. S_LQ:
  9050. begin
  9051. taicpu(hp1).opcode := A_MOV;
  9052. taicpu(hp1).opsize := S_L;
  9053. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9054. { In this instance, we need to break out because the
  9055. instruction is no longer MOVZX or MOVSXD }
  9056. Result := True;
  9057. Exit;
  9058. end;
  9059. else
  9060. ;
  9061. end;
  9062. {$endif x86_64}
  9063. Result := CompressInstructions;
  9064. Exit;
  9065. end;
  9066. end;
  9067. A_MOVZX:
  9068. begin
  9069. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9070. Break;
  9071. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9072. begin
  9073. if (InstrMax = -1) and
  9074. { Will return false if the second parameter isn't ThisReg
  9075. (can happen on -O2 and under) }
  9076. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9077. begin
  9078. { The two MOVZX instructions are adjacent, so remove the first one }
  9079. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9080. RemoveCurrentP(p);
  9081. Result := True;
  9082. Exit;
  9083. end;
  9084. Break;
  9085. end;
  9086. Result := CompressInstructions;
  9087. Exit;
  9088. end;
  9089. else
  9090. { This includes ADC, SBB and IDIV }
  9091. Break;
  9092. end;
  9093. if not CheckOverflowConditions then
  9094. Break;
  9095. { Contains highest index (so instruction count - 1) }
  9096. Inc(InstrMax);
  9097. if InstrMax > High(InstrList) then
  9098. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9099. InstrList[InstrMax] := taicpu(hp1);
  9100. end;
  9101. end;
  9102. {$pop}
  9103. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9104. var
  9105. hp1 : tai;
  9106. begin
  9107. Result:=false;
  9108. if (taicpu(p).ops >= 2) and
  9109. ((taicpu(p).oper[0]^.typ = top_const) or
  9110. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9111. (taicpu(p).oper[1]^.typ = top_reg) and
  9112. ((taicpu(p).ops = 2) or
  9113. ((taicpu(p).oper[2]^.typ = top_reg) and
  9114. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9115. GetLastInstruction(p,hp1) and
  9116. MatchInstruction(hp1,A_MOV,[]) and
  9117. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9118. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9119. begin
  9120. TransferUsedRegs(TmpUsedRegs);
  9121. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9122. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9123. { change
  9124. mov reg1,reg2
  9125. imul y,reg2 to imul y,reg1,reg2 }
  9126. begin
  9127. taicpu(p).ops := 3;
  9128. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9129. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9130. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9131. RemoveInstruction(hp1);
  9132. result:=true;
  9133. end;
  9134. end;
  9135. end;
  9136. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9137. var
  9138. ThisLabel: TAsmLabel;
  9139. begin
  9140. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9141. ThisLabel.decrefs;
  9142. taicpu(p).opcode := A_RET;
  9143. taicpu(p).is_jmp := false;
  9144. taicpu(p).ops := taicpu(ret_p).ops;
  9145. case taicpu(ret_p).ops of
  9146. 0:
  9147. taicpu(p).clearop(0);
  9148. 1:
  9149. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9150. else
  9151. internalerror(2016041301);
  9152. end;
  9153. { If the original label is now dead, it might turn out that the label
  9154. immediately follows p. As a result, everything beyond it, which will
  9155. be just some final register configuration and a RET instruction, is
  9156. now dead code. [Kit] }
  9157. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9158. running RemoveDeadCodeAfterJump for each RET instruction, because
  9159. this optimisation rarely happens and most RETs appear at the end of
  9160. routines where there is nothing that can be stripped. [Kit] }
  9161. if not ThisLabel.is_used then
  9162. RemoveDeadCodeAfterJump(p);
  9163. end;
  9164. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9165. var
  9166. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9167. Unconditional, PotentialModified: Boolean;
  9168. OperPtr: POper;
  9169. NewRef: TReference;
  9170. InstrList: array of taicpu;
  9171. InstrMax, Index: Integer;
  9172. const
  9173. {$ifdef DEBUG_AOPTCPU}
  9174. SNoFlags: shortstring = ' so the flags aren''t modified';
  9175. {$else DEBUG_AOPTCPU}
  9176. SNoFlags = '';
  9177. {$endif DEBUG_AOPTCPU}
  9178. begin
  9179. Result:=false;
  9180. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9181. begin
  9182. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9183. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9184. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9185. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9186. GetNextInstruction(hp1, hp2) and
  9187. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9188. { Change from: To:
  9189. set(C) %reg j(~C) label
  9190. test %reg,%reg/cmp $0,%reg
  9191. je label
  9192. set(C) %reg j(C) label
  9193. test %reg,%reg/cmp $0,%reg
  9194. jne label
  9195. (Also do something similar with sete/setne instead of je/jne)
  9196. }
  9197. begin
  9198. { Before we do anything else, we need to check the instructions
  9199. in between SETcc and TEST to make sure they don't modify the
  9200. FLAGS register - if -O2 or under, there won't be any
  9201. instructions between SET and TEST }
  9202. TransferUsedRegs(TmpUsedRegs);
  9203. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9204. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9205. begin
  9206. next := p;
  9207. SetLength(InstrList, 0);
  9208. InstrMax := -1;
  9209. PotentialModified := False;
  9210. { Make a note of every instruction that modifies the FLAGS
  9211. register }
  9212. while GetNextInstruction(next, next) and (next <> hp1) do
  9213. begin
  9214. if next.typ <> ait_instruction then
  9215. { GetNextInstructionUsingReg should have returned False }
  9216. InternalError(2021051701);
  9217. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9218. begin
  9219. case taicpu(next).opcode of
  9220. A_SETcc,
  9221. A_CMOVcc,
  9222. A_Jcc:
  9223. begin
  9224. if PotentialModified then
  9225. { Not safe because the flags were modified earlier }
  9226. Exit
  9227. else
  9228. { Condition is the same as the initial SETcc, so this is safe
  9229. (don't add to instruction list though) }
  9230. Continue;
  9231. end;
  9232. A_ADD:
  9233. begin
  9234. if (taicpu(next).opsize = S_B) or
  9235. { LEA doesn't support 8-bit operands }
  9236. (taicpu(next).oper[1]^.typ <> top_reg) or
  9237. { Must write to a register }
  9238. (taicpu(next).oper[0]^.typ = top_ref) then
  9239. { Require a constant or a register }
  9240. Exit;
  9241. PotentialModified := True;
  9242. end;
  9243. A_SUB:
  9244. begin
  9245. if (taicpu(next).opsize = S_B) or
  9246. { LEA doesn't support 8-bit operands }
  9247. (taicpu(next).oper[1]^.typ <> top_reg) or
  9248. { Must write to a register }
  9249. (taicpu(next).oper[0]^.typ <> top_const) or
  9250. (taicpu(next).oper[0]^.val = $80000000) then
  9251. { Can't subtract a register with LEA - also
  9252. check that the value isn't -2^31, as this
  9253. can't be negated }
  9254. Exit;
  9255. PotentialModified := True;
  9256. end;
  9257. A_SAL,
  9258. A_SHL:
  9259. begin
  9260. if (taicpu(next).opsize = S_B) or
  9261. { LEA doesn't support 8-bit operands }
  9262. (taicpu(next).oper[1]^.typ <> top_reg) or
  9263. { Must write to a register }
  9264. (taicpu(next).oper[0]^.typ <> top_const) or
  9265. (taicpu(next).oper[0]^.val < 0) or
  9266. (taicpu(next).oper[0]^.val > 3) then
  9267. Exit;
  9268. PotentialModified := True;
  9269. end;
  9270. A_IMUL:
  9271. begin
  9272. if (taicpu(next).ops <> 3) or
  9273. (taicpu(next).oper[1]^.typ <> top_reg) or
  9274. { Must write to a register }
  9275. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9276. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9277. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9278. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9279. Exit
  9280. else
  9281. PotentialModified := True;
  9282. end;
  9283. else
  9284. { Don't know how to change this, so abort }
  9285. Exit;
  9286. end;
  9287. { Contains highest index (so instruction count - 1) }
  9288. Inc(InstrMax);
  9289. if InstrMax > High(InstrList) then
  9290. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9291. InstrList[InstrMax] := taicpu(next);
  9292. end;
  9293. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9294. end;
  9295. if not Assigned(next) or (next <> hp1) then
  9296. { It should be equal to hp1 }
  9297. InternalError(2021051702);
  9298. { Cycle through each instruction and check to see if we can
  9299. change them to versions that don't modify the flags }
  9300. if (InstrMax >= 0) then
  9301. begin
  9302. for Index := 0 to InstrMax do
  9303. case InstrList[Index].opcode of
  9304. A_ADD:
  9305. begin
  9306. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9307. InstrList[Index].opcode := A_LEA;
  9308. reference_reset(NewRef, 1, []);
  9309. NewRef.base := InstrList[Index].oper[1]^.reg;
  9310. if InstrList[Index].oper[0]^.typ = top_reg then
  9311. begin
  9312. NewRef.index := InstrList[Index].oper[0]^.reg;
  9313. NewRef.scalefactor := 1;
  9314. end
  9315. else
  9316. NewRef.offset := InstrList[Index].oper[0]^.val;
  9317. InstrList[Index].loadref(0, NewRef);
  9318. end;
  9319. A_SUB:
  9320. begin
  9321. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9322. InstrList[Index].opcode := A_LEA;
  9323. reference_reset(NewRef, 1, []);
  9324. NewRef.base := InstrList[Index].oper[1]^.reg;
  9325. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9326. InstrList[Index].loadref(0, NewRef);
  9327. end;
  9328. A_SHL,
  9329. A_SAL:
  9330. begin
  9331. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9332. InstrList[Index].opcode := A_LEA;
  9333. reference_reset(NewRef, 1, []);
  9334. NewRef.index := InstrList[Index].oper[1]^.reg;
  9335. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9336. InstrList[Index].loadref(0, NewRef);
  9337. end;
  9338. A_IMUL:
  9339. begin
  9340. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9341. InstrList[Index].opcode := A_LEA;
  9342. reference_reset(NewRef, 1, []);
  9343. NewRef.index := InstrList[Index].oper[1]^.reg;
  9344. case InstrList[Index].oper[0]^.val of
  9345. 2, 4, 8:
  9346. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9347. else {3, 5 and 9}
  9348. begin
  9349. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9350. NewRef.base := InstrList[Index].oper[1]^.reg;
  9351. end;
  9352. end;
  9353. InstrList[Index].loadref(0, NewRef);
  9354. end;
  9355. else
  9356. InternalError(2021051710);
  9357. end;
  9358. end;
  9359. { Mark the FLAGS register as used across this whole block }
  9360. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9361. end;
  9362. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9363. JumpC := taicpu(hp2).condition;
  9364. Unconditional := False;
  9365. if conditions_equal(JumpC, C_E) then
  9366. SetC := inverse_cond(taicpu(p).condition)
  9367. else if conditions_equal(JumpC, C_NE) then
  9368. SetC := taicpu(p).condition
  9369. else
  9370. { We've got something weird here (and inefficent) }
  9371. begin
  9372. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9373. SetC := C_NONE;
  9374. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9375. if condition_in(C_AE, JumpC) then
  9376. Unconditional := True
  9377. else
  9378. { Not sure what to do with this jump - drop out }
  9379. Exit;
  9380. end;
  9381. RemoveInstruction(hp1);
  9382. if Unconditional then
  9383. MakeUnconditional(taicpu(hp2))
  9384. else
  9385. begin
  9386. if SetC = C_NONE then
  9387. InternalError(2018061402);
  9388. taicpu(hp2).SetCondition(SetC);
  9389. end;
  9390. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9391. TmpUsedRegs }
  9392. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9393. begin
  9394. RemoveCurrentp(p, hp2);
  9395. if taicpu(hp2).opcode = A_SETcc then
  9396. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9397. else
  9398. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9399. end
  9400. else
  9401. if taicpu(hp2).opcode = A_SETcc then
  9402. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9403. else
  9404. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9405. Result := True;
  9406. end
  9407. else if
  9408. { Make sure the instructions are adjacent }
  9409. (
  9410. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9411. GetNextInstruction(p, hp1)
  9412. ) and
  9413. MatchInstruction(hp1, A_MOV, [S_B]) and
  9414. { Writing to memory is allowed }
  9415. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9416. begin
  9417. {
  9418. Watch out for sequences such as:
  9419. set(c)b %regb
  9420. movb %regb,(ref)
  9421. movb $0,1(ref)
  9422. movb $0,2(ref)
  9423. movb $0,3(ref)
  9424. Much more efficient to turn it into:
  9425. movl $0,%regl
  9426. set(c)b %regb
  9427. movl %regl,(ref)
  9428. Or:
  9429. set(c)b %regb
  9430. movzbl %regb,%regl
  9431. movl %regl,(ref)
  9432. }
  9433. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9434. GetNextInstruction(hp1, hp2) and
  9435. MatchInstruction(hp2, A_MOV, [S_B]) and
  9436. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9437. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9438. begin
  9439. { Don't do anything else except set Result to True }
  9440. end
  9441. else
  9442. begin
  9443. if taicpu(p).oper[0]^.typ = top_reg then
  9444. begin
  9445. TransferUsedRegs(TmpUsedRegs);
  9446. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9447. end;
  9448. { If it's not a register, it's a memory address }
  9449. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9450. begin
  9451. { Even if the register is still in use, we can minimise the
  9452. pipeline stall by changing the MOV into another SETcc. }
  9453. taicpu(hp1).opcode := A_SETcc;
  9454. taicpu(hp1).condition := taicpu(p).condition;
  9455. if taicpu(hp1).oper[1]^.typ = top_ref then
  9456. begin
  9457. { Swapping the operand pointers like this is probably a
  9458. bit naughty, but it is far faster than using loadoper
  9459. to transfer the reference from oper[1] to oper[0] if
  9460. you take into account the extra procedure calls and
  9461. the memory allocation and deallocation required }
  9462. OperPtr := taicpu(hp1).oper[1];
  9463. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9464. taicpu(hp1).oper[0] := OperPtr;
  9465. end
  9466. else
  9467. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9468. taicpu(hp1).clearop(1);
  9469. taicpu(hp1).ops := 1;
  9470. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9471. end
  9472. else
  9473. begin
  9474. if taicpu(hp1).oper[1]^.typ = top_reg then
  9475. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9476. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9477. RemoveInstruction(hp1);
  9478. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9479. end
  9480. end;
  9481. Result := True;
  9482. end;
  9483. end;
  9484. end;
  9485. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9486. var
  9487. hp1: tai;
  9488. Count: Integer;
  9489. OrigLabel: TAsmLabel;
  9490. begin
  9491. result := False;
  9492. { Sometimes, the optimisations below can permit this }
  9493. RemoveDeadCodeAfterJump(p);
  9494. 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
  9495. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9496. begin
  9497. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9498. { Also a side-effect of optimisations }
  9499. if CollapseZeroDistJump(p, OrigLabel) then
  9500. begin
  9501. Result := True;
  9502. Exit;
  9503. end;
  9504. hp1 := GetLabelWithSym(OrigLabel);
  9505. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9506. begin
  9507. if taicpu(hp1).opcode = A_RET then
  9508. begin
  9509. {
  9510. change
  9511. jmp .L1
  9512. ...
  9513. .L1:
  9514. ret
  9515. into
  9516. ret
  9517. }
  9518. begin
  9519. ConvertJumpToRET(p, hp1);
  9520. result:=true;
  9521. end;
  9522. end
  9523. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9524. not (cs_opt_size in current_settings.optimizerswitches) and
  9525. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9526. begin
  9527. Result := True;
  9528. Exit;
  9529. end;
  9530. end;
  9531. end;
  9532. end;
  9533. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9534. begin
  9535. CanBeCMOV:=assigned(p) and
  9536. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9537. { we can't use cmov ref,reg because
  9538. ref could be nil and cmov still throws an exception
  9539. if ref=nil but the mov isn't done (FK)
  9540. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9541. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9542. }
  9543. (taicpu(p).oper[1]^.typ = top_reg) and
  9544. (
  9545. (taicpu(p).oper[0]^.typ = top_reg) or
  9546. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9547. it is not expected that this can cause a seg. violation }
  9548. (
  9549. (taicpu(p).oper[0]^.typ = top_ref) and
  9550. IsRefSafe(taicpu(p).oper[0]^.ref)
  9551. )
  9552. );
  9553. end;
  9554. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9555. var
  9556. hp1,hp2: tai;
  9557. {$ifndef i8086}
  9558. hp3,hp4,hpmov2, hp5: tai;
  9559. l : Longint;
  9560. condition : TAsmCond;
  9561. {$endif i8086}
  9562. carryadd_opcode : TAsmOp;
  9563. symbol: TAsmSymbol;
  9564. increg, tmpreg: TRegister;
  9565. begin
  9566. result:=false;
  9567. if GetNextInstruction(p,hp1) then
  9568. begin
  9569. if (hp1.typ=ait_label) then
  9570. begin
  9571. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9572. Exit;
  9573. end
  9574. else if (hp1.typ<>ait_instruction) then
  9575. Exit;
  9576. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9577. if (
  9578. (
  9579. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9580. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9581. (Taicpu(hp1).oper[0]^.val=1)
  9582. ) or
  9583. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9584. ) and
  9585. GetNextInstruction(hp1,hp2) and
  9586. SkipAligns(hp2, hp2) and
  9587. (hp2.typ = ait_label) and
  9588. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9589. { jb @@1 cmc
  9590. inc/dec operand --> adc/sbb operand,0
  9591. @@1:
  9592. ... and ...
  9593. jnb @@1
  9594. inc/dec operand --> adc/sbb operand,0
  9595. @@1: }
  9596. begin
  9597. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9598. begin
  9599. case taicpu(hp1).opcode of
  9600. A_INC,
  9601. A_ADD:
  9602. carryadd_opcode:=A_ADC;
  9603. A_DEC,
  9604. A_SUB:
  9605. carryadd_opcode:=A_SBB;
  9606. else
  9607. InternalError(2021011001);
  9608. end;
  9609. Taicpu(p).clearop(0);
  9610. Taicpu(p).ops:=0;
  9611. Taicpu(p).is_jmp:=false;
  9612. Taicpu(p).opcode:=A_CMC;
  9613. Taicpu(p).condition:=C_NONE;
  9614. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9615. Taicpu(hp1).ops:=2;
  9616. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9617. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9618. else
  9619. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9620. Taicpu(hp1).loadconst(0,0);
  9621. Taicpu(hp1).opcode:=carryadd_opcode;
  9622. result:=true;
  9623. exit;
  9624. end
  9625. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9626. begin
  9627. case taicpu(hp1).opcode of
  9628. A_INC,
  9629. A_ADD:
  9630. carryadd_opcode:=A_ADC;
  9631. A_DEC,
  9632. A_SUB:
  9633. carryadd_opcode:=A_SBB;
  9634. else
  9635. InternalError(2021011002);
  9636. end;
  9637. Taicpu(hp1).ops:=2;
  9638. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9639. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9640. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9641. else
  9642. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9643. Taicpu(hp1).loadconst(0,0);
  9644. Taicpu(hp1).opcode:=carryadd_opcode;
  9645. RemoveCurrentP(p, hp1);
  9646. result:=true;
  9647. exit;
  9648. end
  9649. {
  9650. jcc @@1 setcc tmpreg
  9651. inc/dec/add/sub operand -> (movzx tmpreg)
  9652. @@1: add/sub tmpreg,operand
  9653. While this increases code size slightly, it makes the code much faster if the
  9654. jump is unpredictable
  9655. }
  9656. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9657. begin
  9658. { search for an available register which is volatile }
  9659. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9660. if increg <> NR_NO then
  9661. begin
  9662. { We don't need to check if tmpreg is in hp1 or not, because
  9663. it will be marked as in use at p (if not, this is
  9664. indictive of a compiler bug). }
  9665. TAsmLabel(symbol).decrefs;
  9666. Taicpu(p).clearop(0);
  9667. Taicpu(p).ops:=1;
  9668. Taicpu(p).is_jmp:=false;
  9669. Taicpu(p).opcode:=A_SETcc;
  9670. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9671. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9672. Taicpu(p).loadreg(0,increg);
  9673. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9674. begin
  9675. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9676. R_SUBW:
  9677. begin
  9678. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9679. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9680. end;
  9681. R_SUBD:
  9682. begin
  9683. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9684. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9685. end;
  9686. {$ifdef x86_64}
  9687. R_SUBQ:
  9688. begin
  9689. { MOVZX doesn't have a 64-bit variant, because
  9690. the 32-bit version implicitly zeroes the
  9691. upper 32-bits of the destination register }
  9692. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9693. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9694. setsubreg(tmpreg, R_SUBQ);
  9695. end;
  9696. {$endif x86_64}
  9697. else
  9698. Internalerror(2020030601);
  9699. end;
  9700. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9701. asml.InsertAfter(hp2,p);
  9702. end
  9703. else
  9704. tmpreg := increg;
  9705. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9706. begin
  9707. Taicpu(hp1).ops:=2;
  9708. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9709. end;
  9710. Taicpu(hp1).loadreg(0,tmpreg);
  9711. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9712. Result := True;
  9713. { p is no longer a Jcc instruction, so exit }
  9714. Exit;
  9715. end;
  9716. end;
  9717. end;
  9718. { Detect the following:
  9719. jmp<cond> @Lbl1
  9720. jmp @Lbl2
  9721. ...
  9722. @Lbl1:
  9723. ret
  9724. Change to:
  9725. jmp<inv_cond> @Lbl2
  9726. ret
  9727. }
  9728. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9729. begin
  9730. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9731. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9732. MatchInstruction(hp2,A_RET,[S_NO]) then
  9733. begin
  9734. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9735. { Change label address to that of the unconditional jump }
  9736. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9737. TAsmLabel(symbol).DecRefs;
  9738. taicpu(hp1).opcode := A_RET;
  9739. taicpu(hp1).is_jmp := false;
  9740. taicpu(hp1).ops := taicpu(hp2).ops;
  9741. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9742. case taicpu(hp2).ops of
  9743. 0:
  9744. taicpu(hp1).clearop(0);
  9745. 1:
  9746. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9747. else
  9748. internalerror(2016041302);
  9749. end;
  9750. end;
  9751. {$ifndef i8086}
  9752. end
  9753. {
  9754. convert
  9755. j<c> .L1
  9756. mov 1,reg
  9757. jmp .L2
  9758. .L1
  9759. mov 0,reg
  9760. .L2
  9761. into
  9762. mov 0,reg
  9763. set<not(c)> reg
  9764. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9765. would destroy the flag contents
  9766. }
  9767. else if MatchInstruction(hp1,A_MOV,[]) and
  9768. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9769. {$ifdef i386}
  9770. (
  9771. { Under i386, ESI, EDI, EBP and ESP
  9772. don't have an 8-bit representation }
  9773. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9774. ) and
  9775. {$endif i386}
  9776. (taicpu(hp1).oper[0]^.val=1) and
  9777. GetNextInstruction(hp1,hp2) and
  9778. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9779. GetNextInstruction(hp2,hp3) and
  9780. { skip align }
  9781. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9782. (hp3.typ=ait_label) and
  9783. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9784. (tai_label(hp3).labsym.getrefs=1) and
  9785. GetNextInstruction(hp3,hp4) and
  9786. MatchInstruction(hp4,A_MOV,[]) and
  9787. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9788. (taicpu(hp4).oper[0]^.val=0) and
  9789. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9790. GetNextInstruction(hp4,hp5) and
  9791. (hp5.typ=ait_label) and
  9792. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9793. (tai_label(hp5).labsym.getrefs=1) then
  9794. begin
  9795. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9796. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9797. { remove last label }
  9798. RemoveInstruction(hp5);
  9799. { remove second label }
  9800. RemoveInstruction(hp3);
  9801. { if align is present remove it }
  9802. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9803. RemoveInstruction(hp3);
  9804. { remove jmp }
  9805. RemoveInstruction(hp2);
  9806. if taicpu(hp1).opsize=S_B then
  9807. RemoveInstruction(hp1)
  9808. else
  9809. taicpu(hp1).loadconst(0,0);
  9810. taicpu(hp4).opcode:=A_SETcc;
  9811. taicpu(hp4).opsize:=S_B;
  9812. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9813. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9814. taicpu(hp4).opercnt:=1;
  9815. taicpu(hp4).ops:=1;
  9816. taicpu(hp4).freeop(1);
  9817. RemoveCurrentP(p);
  9818. Result:=true;
  9819. exit;
  9820. end
  9821. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9822. begin
  9823. { check for
  9824. jCC xxx
  9825. <several movs>
  9826. xxx:
  9827. Also spot:
  9828. Jcc xxx
  9829. <several movs>
  9830. jmp xxx
  9831. Change to:
  9832. <several cmovs with inverted condition>
  9833. jmp xxx
  9834. }
  9835. l:=0;
  9836. while assigned(hp1) and
  9837. CanBeCMOV(hp1) and
  9838. { stop on labels }
  9839. not(hp1.typ=ait_label) do
  9840. begin
  9841. inc(l);
  9842. hp5 := hp1;
  9843. GetNextInstruction(hp1,hp1);
  9844. end;
  9845. if assigned(hp1) then
  9846. begin
  9847. TransferUsedRegs(TmpUsedRegs);
  9848. if (
  9849. MatchInstruction(hp1, A_JMP, []) and
  9850. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9851. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9852. ) or
  9853. FindLabel(tasmlabel(symbol),hp1) then
  9854. begin
  9855. if (l<=4) and (l>0) then
  9856. begin
  9857. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9858. condition:=inverse_cond(taicpu(p).condition);
  9859. UpdateUsedRegs(tai(p.next));
  9860. GetNextInstruction(p,hp1);
  9861. repeat
  9862. if not Assigned(hp1) then
  9863. InternalError(2018062900);
  9864. taicpu(hp1).opcode:=A_CMOVcc;
  9865. taicpu(hp1).condition:=condition;
  9866. UpdateUsedRegs(tai(hp1.next));
  9867. GetNextInstruction(hp1,hp1);
  9868. until not(CanBeCMOV(hp1));
  9869. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9870. hp2 := hp1;
  9871. repeat
  9872. if not Assigned(hp2) then
  9873. InternalError(2018062910);
  9874. case hp2.typ of
  9875. ait_label:
  9876. { What we expected - break out of the loop (it won't be a dead label at the top of
  9877. a cluster because that was optimised at an earlier stage) }
  9878. Break;
  9879. ait_align:
  9880. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9881. begin
  9882. hp2 := tai(hp2.Next);
  9883. Continue;
  9884. end;
  9885. ait_instruction:
  9886. begin
  9887. if taicpu(hp2).opcode<>A_JMP then
  9888. InternalError(2018062912);
  9889. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9890. Break;
  9891. end
  9892. else
  9893. begin
  9894. { Might be a comment or temporary allocation entry }
  9895. if not (hp2.typ in SkipInstr) then
  9896. InternalError(2018062911);
  9897. hp2 := tai(hp2.Next);
  9898. Continue;
  9899. end;
  9900. end;
  9901. until False;
  9902. { Now we can safely decrement the reference count }
  9903. tasmlabel(symbol).decrefs;
  9904. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9905. { Remove the original jump }
  9906. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9907. if hp2.typ=ait_instruction then
  9908. begin
  9909. p:=hp2;
  9910. Result:=True;
  9911. end
  9912. else
  9913. begin
  9914. UpdateUsedRegs(tai(hp2.next));
  9915. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9916. { Remove the label if this is its final reference }
  9917. if (tasmlabel(symbol).getrefs=0) then
  9918. StripLabelFast(hp1);
  9919. end;
  9920. exit;
  9921. end;
  9922. end
  9923. else
  9924. begin
  9925. { check further for
  9926. jCC xxx
  9927. <several movs 1>
  9928. jmp yyy
  9929. xxx:
  9930. <several movs 2>
  9931. yyy:
  9932. }
  9933. { hp2 points to jmp yyy }
  9934. hp2:=hp1;
  9935. { skip hp1 to xxx (or an align right before it) }
  9936. GetNextInstruction(hp1, hp1);
  9937. if assigned(hp2) and
  9938. assigned(hp1) and
  9939. (l<=3) and
  9940. (hp2.typ=ait_instruction) and
  9941. (taicpu(hp2).is_jmp) and
  9942. (taicpu(hp2).condition=C_None) and
  9943. { real label and jump, no further references to the
  9944. label are allowed }
  9945. (tasmlabel(symbol).getrefs=1) and
  9946. FindLabel(tasmlabel(symbol),hp1) then
  9947. begin
  9948. l:=0;
  9949. { skip hp1 to <several moves 2> }
  9950. if (hp1.typ = ait_align) then
  9951. GetNextInstruction(hp1, hp1);
  9952. GetNextInstruction(hp1, hpmov2);
  9953. hp1 := hpmov2;
  9954. while assigned(hp1) and
  9955. CanBeCMOV(hp1) do
  9956. begin
  9957. inc(l);
  9958. hp5 := hp1;
  9959. GetNextInstruction(hp1, hp1);
  9960. end;
  9961. { hp1 points to yyy (or an align right before it) }
  9962. hp3 := hp1;
  9963. if assigned(hp1) and
  9964. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9965. begin
  9966. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9967. condition:=inverse_cond(taicpu(p).condition);
  9968. UpdateUsedRegs(tai(p.next));
  9969. GetNextInstruction(p,hp1);
  9970. repeat
  9971. taicpu(hp1).opcode:=A_CMOVcc;
  9972. taicpu(hp1).condition:=condition;
  9973. UpdateUsedRegs(tai(hp1.next));
  9974. GetNextInstruction(hp1,hp1);
  9975. until not(assigned(hp1)) or
  9976. not(CanBeCMOV(hp1));
  9977. condition:=inverse_cond(condition);
  9978. if GetLastInstruction(hpmov2,hp1) then
  9979. UpdateUsedRegs(tai(hp1.next));
  9980. hp1 := hpmov2;
  9981. { hp1 is now at <several movs 2> }
  9982. while Assigned(hp1) and CanBeCMOV(hp1) do
  9983. begin
  9984. taicpu(hp1).opcode:=A_CMOVcc;
  9985. taicpu(hp1).condition:=condition;
  9986. UpdateUsedRegs(tai(hp1.next));
  9987. GetNextInstruction(hp1,hp1);
  9988. end;
  9989. hp1 := p;
  9990. { Get first instruction after label }
  9991. UpdateUsedRegs(tai(hp3.next));
  9992. GetNextInstruction(hp3, p);
  9993. if assigned(p) and (hp3.typ = ait_align) then
  9994. GetNextInstruction(p, p);
  9995. { Don't dereference yet, as doing so will cause
  9996. GetNextInstruction to skip the label and
  9997. optional align marker. [Kit] }
  9998. GetNextInstruction(hp2, hp4);
  9999. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10000. { remove jCC }
  10001. RemoveInstruction(hp1);
  10002. { Now we can safely decrement it }
  10003. tasmlabel(symbol).decrefs;
  10004. { Remove label xxx (it will have a ref of zero due to the initial check }
  10005. StripLabelFast(hp4);
  10006. { remove jmp }
  10007. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10008. RemoveInstruction(hp2);
  10009. { As before, now we can safely decrement it }
  10010. tasmlabel(symbol).decrefs;
  10011. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10012. if tasmlabel(symbol).getrefs = 0 then
  10013. StripLabelFast(hp3);
  10014. if Assigned(p) then
  10015. result:=true;
  10016. exit;
  10017. end;
  10018. end;
  10019. end;
  10020. end;
  10021. {$endif i8086}
  10022. end;
  10023. end;
  10024. end;
  10025. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10026. var
  10027. hp1,hp2,hp3: tai;
  10028. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10029. NewSize: TOpSize;
  10030. NewRegSize: TSubRegister;
  10031. Limit: TCgInt;
  10032. SwapOper: POper;
  10033. begin
  10034. result:=false;
  10035. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10036. GetNextInstruction(p,hp1) and
  10037. (hp1.typ = ait_instruction);
  10038. if reg_and_hp1_is_instr and
  10039. (
  10040. (taicpu(hp1).opcode <> A_LEA) or
  10041. { If the LEA instruction can be converted into an arithmetic instruction,
  10042. it may be possible to then fold it. }
  10043. (
  10044. { If the flags register is in use, don't change the instruction
  10045. to an ADD otherwise this will scramble the flags. [Kit] }
  10046. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10047. ConvertLEA(taicpu(hp1))
  10048. )
  10049. ) and
  10050. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10051. GetNextInstruction(hp1,hp2) and
  10052. MatchInstruction(hp2,A_MOV,[]) and
  10053. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10054. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10055. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10056. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10057. {$ifdef i386}
  10058. { not all registers have byte size sub registers on i386 }
  10059. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10060. {$endif i386}
  10061. (((taicpu(hp1).ops=2) and
  10062. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10063. ((taicpu(hp1).ops=1) and
  10064. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10065. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10066. begin
  10067. { change movsX/movzX reg/ref, reg2
  10068. add/sub/or/... reg3/$const, reg2
  10069. mov reg2 reg/ref
  10070. to add/sub/or/... reg3/$const, reg/ref }
  10071. { by example:
  10072. movswl %si,%eax movswl %si,%eax p
  10073. decl %eax addl %edx,%eax hp1
  10074. movw %ax,%si movw %ax,%si hp2
  10075. ->
  10076. movswl %si,%eax movswl %si,%eax p
  10077. decw %eax addw %edx,%eax hp1
  10078. movw %ax,%si movw %ax,%si hp2
  10079. }
  10080. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10081. {
  10082. ->
  10083. movswl %si,%eax movswl %si,%eax p
  10084. decw %si addw %dx,%si hp1
  10085. movw %ax,%si movw %ax,%si hp2
  10086. }
  10087. case taicpu(hp1).ops of
  10088. 1:
  10089. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10090. 2:
  10091. begin
  10092. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10093. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10094. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10095. end;
  10096. else
  10097. internalerror(2008042702);
  10098. end;
  10099. {
  10100. ->
  10101. decw %si addw %dx,%si p
  10102. }
  10103. DebugMsg(SPeepholeOptimization + 'var3',p);
  10104. RemoveCurrentP(p, hp1);
  10105. RemoveInstruction(hp2);
  10106. Result := True;
  10107. Exit;
  10108. end;
  10109. if reg_and_hp1_is_instr and
  10110. (taicpu(hp1).opcode = A_MOV) and
  10111. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10112. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10113. {$ifdef x86_64}
  10114. { check for implicit extension to 64 bit }
  10115. or
  10116. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10117. (taicpu(hp1).opsize=S_Q) and
  10118. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10119. )
  10120. {$endif x86_64}
  10121. )
  10122. then
  10123. begin
  10124. { change
  10125. movx %reg1,%reg2
  10126. mov %reg2,%reg3
  10127. dealloc %reg2
  10128. into
  10129. movx %reg,%reg3
  10130. }
  10131. TransferUsedRegs(TmpUsedRegs);
  10132. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10133. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10134. begin
  10135. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10136. {$ifdef x86_64}
  10137. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10138. (taicpu(hp1).opsize=S_Q) then
  10139. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10140. else
  10141. {$endif x86_64}
  10142. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10143. RemoveInstruction(hp1);
  10144. Result := True;
  10145. Exit;
  10146. end;
  10147. end;
  10148. if reg_and_hp1_is_instr and
  10149. ((taicpu(hp1).opcode=A_MOV) or
  10150. (taicpu(hp1).opcode=A_ADD) or
  10151. (taicpu(hp1).opcode=A_SUB) or
  10152. (taicpu(hp1).opcode=A_CMP) or
  10153. (taicpu(hp1).opcode=A_OR) or
  10154. (taicpu(hp1).opcode=A_XOR) or
  10155. (taicpu(hp1).opcode=A_AND)
  10156. ) and
  10157. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10158. begin
  10159. AndTest := (taicpu(hp1).opcode=A_AND) and
  10160. GetNextInstruction(hp1, hp2) and
  10161. (hp2.typ = ait_instruction) and
  10162. (
  10163. (
  10164. (taicpu(hp2).opcode=A_TEST) and
  10165. (
  10166. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10167. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10168. (
  10169. { If the AND and TEST instructions share a constant, this is also valid }
  10170. (taicpu(hp1).oper[0]^.typ = top_const) and
  10171. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10172. )
  10173. ) and
  10174. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10175. ) or
  10176. (
  10177. (taicpu(hp2).opcode=A_CMP) and
  10178. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10179. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10180. )
  10181. );
  10182. { change
  10183. movx (oper),%reg2
  10184. and $x,%reg2
  10185. test %reg2,%reg2
  10186. dealloc %reg2
  10187. into
  10188. op %reg1,%reg3
  10189. if the second op accesses only the bits stored in reg1
  10190. }
  10191. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10192. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10193. (taicpu(hp1).oper[0]^.typ = top_const) and
  10194. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10195. AndTest then
  10196. begin
  10197. { Check if the AND constant is in range }
  10198. case taicpu(p).opsize of
  10199. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10200. begin
  10201. NewSize := S_B;
  10202. Limit := $FF;
  10203. end;
  10204. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10205. begin
  10206. NewSize := S_W;
  10207. Limit := $FFFF;
  10208. end;
  10209. {$ifdef x86_64}
  10210. S_LQ:
  10211. begin
  10212. NewSize := S_L;
  10213. Limit := $FFFFFFFF;
  10214. end;
  10215. {$endif x86_64}
  10216. else
  10217. InternalError(2021120303);
  10218. end;
  10219. if (
  10220. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10221. { Check for negative operands }
  10222. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10223. ) and
  10224. GetNextInstruction(hp2,hp3) and
  10225. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10226. (taicpu(hp3).condition in [C_E,C_NE]) then
  10227. begin
  10228. TransferUsedRegs(TmpUsedRegs);
  10229. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10230. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10231. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10232. begin
  10233. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10234. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10235. taicpu(hp1).opcode := A_TEST;
  10236. taicpu(hp1).opsize := NewSize;
  10237. RemoveInstruction(hp2);
  10238. RemoveCurrentP(p, hp1);
  10239. Result:=true;
  10240. exit;
  10241. end;
  10242. end;
  10243. end;
  10244. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10245. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10246. (taicpu(hp1).opsize=S_B)) or
  10247. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10248. (taicpu(hp1).opsize=S_W))
  10249. {$ifdef x86_64}
  10250. or ((taicpu(p).opsize=S_LQ) and
  10251. (taicpu(hp1).opsize=S_L))
  10252. {$endif x86_64}
  10253. ) and
  10254. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10255. begin
  10256. { change
  10257. movx %reg1,%reg2
  10258. op %reg2,%reg3
  10259. dealloc %reg2
  10260. into
  10261. op %reg1,%reg3
  10262. if the second op accesses only the bits stored in reg1
  10263. }
  10264. TransferUsedRegs(TmpUsedRegs);
  10265. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10266. if AndTest then
  10267. begin
  10268. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10269. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10270. end
  10271. else
  10272. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10273. if not RegUsed then
  10274. begin
  10275. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10276. if taicpu(p).oper[0]^.typ=top_reg then
  10277. begin
  10278. case taicpu(hp1).opsize of
  10279. S_B:
  10280. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10281. S_W:
  10282. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10283. S_L:
  10284. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10285. else
  10286. Internalerror(2020102301);
  10287. end;
  10288. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10289. end
  10290. else
  10291. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10292. RemoveCurrentP(p);
  10293. if AndTest then
  10294. RemoveInstruction(hp2);
  10295. result:=true;
  10296. exit;
  10297. end;
  10298. end
  10299. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10300. (
  10301. { Bitwise operations only }
  10302. (taicpu(hp1).opcode=A_AND) or
  10303. (taicpu(hp1).opcode=A_TEST) or
  10304. (
  10305. (taicpu(hp1).oper[0]^.typ = top_const) and
  10306. (
  10307. (taicpu(hp1).opcode=A_OR) or
  10308. (taicpu(hp1).opcode=A_XOR)
  10309. )
  10310. )
  10311. ) and
  10312. (
  10313. (taicpu(hp1).oper[0]^.typ = top_const) or
  10314. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10315. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10316. ) then
  10317. begin
  10318. { change
  10319. movx %reg2,%reg2
  10320. op const,%reg2
  10321. into
  10322. op const,%reg2 (smaller version)
  10323. movx %reg2,%reg2
  10324. also change
  10325. movx %reg1,%reg2
  10326. and/test (oper),%reg2
  10327. dealloc %reg2
  10328. into
  10329. and/test (oper),%reg1
  10330. }
  10331. case taicpu(p).opsize of
  10332. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10333. begin
  10334. NewSize := S_B;
  10335. NewRegSize := R_SUBL;
  10336. Limit := $FF;
  10337. end;
  10338. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10339. begin
  10340. NewSize := S_W;
  10341. NewRegSize := R_SUBW;
  10342. Limit := $FFFF;
  10343. end;
  10344. {$ifdef x86_64}
  10345. S_LQ:
  10346. begin
  10347. NewSize := S_L;
  10348. NewRegSize := R_SUBD;
  10349. Limit := $FFFFFFFF;
  10350. end;
  10351. {$endif x86_64}
  10352. else
  10353. Internalerror(2021120302);
  10354. end;
  10355. TransferUsedRegs(TmpUsedRegs);
  10356. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10357. if AndTest then
  10358. begin
  10359. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10360. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10361. end
  10362. else
  10363. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10364. if
  10365. (
  10366. (taicpu(p).opcode = A_MOVZX) and
  10367. (
  10368. (taicpu(hp1).opcode=A_AND) or
  10369. (taicpu(hp1).opcode=A_TEST)
  10370. ) and
  10371. not (
  10372. { If both are references, then the final instruction will have
  10373. both operands as references, which is not allowed }
  10374. (taicpu(p).oper[0]^.typ = top_ref) and
  10375. (taicpu(hp1).oper[0]^.typ = top_ref)
  10376. ) and
  10377. not RegUsed
  10378. ) or
  10379. (
  10380. (
  10381. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10382. not RegUsed
  10383. ) and
  10384. (taicpu(p).oper[0]^.typ = top_reg) and
  10385. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10386. (taicpu(hp1).oper[0]^.typ = top_const) and
  10387. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10388. ) then
  10389. begin
  10390. {$if defined(i386) or defined(i8086)}
  10391. { If the target size is 8-bit, make sure we can actually encode it }
  10392. 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
  10393. Exit;
  10394. {$endif i386 or i8086}
  10395. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10396. taicpu(hp1).opsize := NewSize;
  10397. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10398. if AndTest then
  10399. begin
  10400. RemoveInstruction(hp2);
  10401. if not RegUsed then
  10402. begin
  10403. taicpu(hp1).opcode := A_TEST;
  10404. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10405. begin
  10406. { Make sure the reference is the second operand }
  10407. SwapOper := taicpu(hp1).oper[0];
  10408. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10409. taicpu(hp1).oper[1] := SwapOper;
  10410. end;
  10411. end;
  10412. end;
  10413. case taicpu(hp1).oper[0]^.typ of
  10414. top_reg:
  10415. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10416. top_const:
  10417. { For the AND/TEST case }
  10418. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10419. else
  10420. ;
  10421. end;
  10422. if RegUsed then
  10423. begin
  10424. AsmL.Remove(p);
  10425. AsmL.InsertAfter(p, hp1);
  10426. p := hp1;
  10427. end
  10428. else
  10429. RemoveCurrentP(p, hp1);
  10430. result:=true;
  10431. exit;
  10432. end;
  10433. end;
  10434. end;
  10435. if reg_and_hp1_is_instr and
  10436. (taicpu(p).oper[0]^.typ = top_reg) and
  10437. (
  10438. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10439. ) and
  10440. (taicpu(hp1).oper[0]^.typ = top_const) and
  10441. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10442. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10443. { Minimum shift value allowed is the bit difference between the sizes }
  10444. (taicpu(hp1).oper[0]^.val >=
  10445. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10446. 8 * (
  10447. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10448. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10449. )
  10450. ) then
  10451. begin
  10452. { For:
  10453. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10454. shl/sal ##, %reg1
  10455. Remove the movsx/movzx instruction if the shift overwrites the
  10456. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10457. }
  10458. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10459. RemoveCurrentP(p, hp1);
  10460. Result := True;
  10461. Exit;
  10462. end
  10463. else if reg_and_hp1_is_instr and
  10464. (taicpu(p).oper[0]^.typ = top_reg) and
  10465. (
  10466. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10467. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10468. ) and
  10469. (taicpu(hp1).oper[0]^.typ = top_const) and
  10470. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10471. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10472. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10473. (taicpu(hp1).oper[0]^.val <
  10474. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10475. 8 * (
  10476. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10477. )
  10478. ) then
  10479. begin
  10480. { For:
  10481. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10482. sar ##, %reg1 shr ##, %reg1
  10483. Move the shift to before the movx instruction if the shift value
  10484. is not too large.
  10485. }
  10486. asml.Remove(hp1);
  10487. asml.InsertBefore(hp1, p);
  10488. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10489. case taicpu(p).opsize of
  10490. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10491. taicpu(hp1).opsize := S_B;
  10492. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10493. taicpu(hp1).opsize := S_W;
  10494. {$ifdef x86_64}
  10495. S_LQ:
  10496. taicpu(hp1).opsize := S_L;
  10497. {$endif}
  10498. else
  10499. InternalError(2020112401);
  10500. end;
  10501. if (taicpu(hp1).opcode = A_SHR) then
  10502. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10503. else
  10504. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10505. Result := True;
  10506. end;
  10507. if reg_and_hp1_is_instr and
  10508. (taicpu(p).oper[0]^.typ = top_reg) and
  10509. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10510. (
  10511. (taicpu(hp1).opcode = taicpu(p).opcode)
  10512. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10513. {$ifdef x86_64}
  10514. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10515. {$endif x86_64}
  10516. ) then
  10517. begin
  10518. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10519. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10520. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10521. begin
  10522. {
  10523. For example:
  10524. movzbw %al,%ax
  10525. movzwl %ax,%eax
  10526. Compress into:
  10527. movzbl %al,%eax
  10528. }
  10529. RegUsed := False;
  10530. case taicpu(p).opsize of
  10531. S_BW:
  10532. case taicpu(hp1).opsize of
  10533. S_WL:
  10534. begin
  10535. taicpu(p).opsize := S_BL;
  10536. RegUsed := True;
  10537. end;
  10538. {$ifdef x86_64}
  10539. S_WQ:
  10540. begin
  10541. if taicpu(p).opcode = A_MOVZX then
  10542. begin
  10543. taicpu(p).opsize := S_BL;
  10544. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10545. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10546. end
  10547. else
  10548. taicpu(p).opsize := S_BQ;
  10549. RegUsed := True;
  10550. end;
  10551. {$endif x86_64}
  10552. else
  10553. ;
  10554. end;
  10555. {$ifdef x86_64}
  10556. S_BL:
  10557. case taicpu(hp1).opsize of
  10558. S_LQ:
  10559. begin
  10560. if taicpu(p).opcode = A_MOVZX then
  10561. begin
  10562. taicpu(p).opsize := S_BL;
  10563. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10564. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10565. end
  10566. else
  10567. taicpu(p).opsize := S_BQ;
  10568. RegUsed := True;
  10569. end;
  10570. else
  10571. ;
  10572. end;
  10573. S_WL:
  10574. case taicpu(hp1).opsize of
  10575. S_LQ:
  10576. begin
  10577. if taicpu(p).opcode = A_MOVZX then
  10578. begin
  10579. taicpu(p).opsize := S_WL;
  10580. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10581. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10582. end
  10583. else
  10584. taicpu(p).opsize := S_WQ;
  10585. RegUsed := True;
  10586. end;
  10587. else
  10588. ;
  10589. end;
  10590. {$endif x86_64}
  10591. else
  10592. ;
  10593. end;
  10594. if RegUsed then
  10595. begin
  10596. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10597. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10598. RemoveInstruction(hp1);
  10599. Result := True;
  10600. Exit;
  10601. end;
  10602. end;
  10603. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10604. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10605. GetNextInstruction(hp1, hp2) and
  10606. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10607. (
  10608. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10609. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10610. {$ifdef x86_64}
  10611. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10612. {$endif x86_64}
  10613. ) and
  10614. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10615. (
  10616. (
  10617. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10618. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10619. ) or
  10620. (
  10621. { Only allow the operands in reverse order for TEST instructions }
  10622. (taicpu(hp2).opcode = A_TEST) and
  10623. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10624. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10625. )
  10626. ) then
  10627. begin
  10628. {
  10629. For example:
  10630. movzbl %al,%eax
  10631. movzbl (ref),%edx
  10632. andl %edx,%eax
  10633. (%edx deallocated)
  10634. Change to:
  10635. andb (ref),%al
  10636. movzbl %al,%eax
  10637. Rules are:
  10638. - First two instructions have the same opcode and opsize
  10639. - First instruction's operands are the same super-register
  10640. - Second instruction operates on a different register
  10641. - Third instruction is AND, OR, XOR or TEST
  10642. - Third instruction's operands are the destination registers of the first two instructions
  10643. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10644. - Second instruction's destination register is deallocated afterwards
  10645. }
  10646. TransferUsedRegs(TmpUsedRegs);
  10647. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10648. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10649. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10650. begin
  10651. case taicpu(p).opsize of
  10652. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10653. NewSize := S_B;
  10654. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10655. NewSize := S_W;
  10656. {$ifdef x86_64}
  10657. S_LQ:
  10658. NewSize := S_L;
  10659. {$endif x86_64}
  10660. else
  10661. InternalError(2021120301);
  10662. end;
  10663. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10664. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10665. taicpu(hp2).opsize := NewSize;
  10666. RemoveInstruction(hp1);
  10667. { With TEST, it's best to keep the MOVX instruction at the top }
  10668. if (taicpu(hp2).opcode <> A_TEST) then
  10669. begin
  10670. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10671. asml.Remove(p);
  10672. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10673. asml.InsertAfter(p, hp2);
  10674. p := hp2;
  10675. end
  10676. else
  10677. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10678. Result := True;
  10679. Exit;
  10680. end;
  10681. end;
  10682. end;
  10683. if taicpu(p).opcode=A_MOVZX then
  10684. begin
  10685. { removes superfluous And's after movzx's }
  10686. if reg_and_hp1_is_instr and
  10687. (taicpu(hp1).opcode = A_AND) and
  10688. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10689. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10690. {$ifdef x86_64}
  10691. { check for implicit extension to 64 bit }
  10692. or
  10693. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10694. (taicpu(hp1).opsize=S_Q) and
  10695. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10696. )
  10697. {$endif x86_64}
  10698. )
  10699. then
  10700. begin
  10701. case taicpu(p).opsize Of
  10702. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10703. if (taicpu(hp1).oper[0]^.val = $ff) then
  10704. begin
  10705. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10706. RemoveInstruction(hp1);
  10707. Result:=true;
  10708. exit;
  10709. end;
  10710. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10711. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10712. begin
  10713. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10714. RemoveInstruction(hp1);
  10715. Result:=true;
  10716. exit;
  10717. end;
  10718. {$ifdef x86_64}
  10719. S_LQ:
  10720. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10721. begin
  10722. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10723. RemoveInstruction(hp1);
  10724. Result:=true;
  10725. exit;
  10726. end;
  10727. {$endif x86_64}
  10728. else
  10729. ;
  10730. end;
  10731. { we cannot get rid of the and, but can we get rid of the movz ?}
  10732. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10733. begin
  10734. case taicpu(p).opsize Of
  10735. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10736. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10737. begin
  10738. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10739. RemoveCurrentP(p,hp1);
  10740. Result:=true;
  10741. exit;
  10742. end;
  10743. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10744. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10745. begin
  10746. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10747. RemoveCurrentP(p,hp1);
  10748. Result:=true;
  10749. exit;
  10750. end;
  10751. {$ifdef x86_64}
  10752. S_LQ:
  10753. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10754. begin
  10755. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10756. RemoveCurrentP(p,hp1);
  10757. Result:=true;
  10758. exit;
  10759. end;
  10760. {$endif x86_64}
  10761. else
  10762. ;
  10763. end;
  10764. end;
  10765. end;
  10766. { changes some movzx constructs to faster synonyms (all examples
  10767. are given with eax/ax, but are also valid for other registers)}
  10768. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10769. begin
  10770. case taicpu(p).opsize of
  10771. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10772. (the machine code is equivalent to movzbl %al,%eax), but the
  10773. code generator still generates that assembler instruction and
  10774. it is silently converted. This should probably be checked.
  10775. [Kit] }
  10776. S_BW:
  10777. begin
  10778. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10779. (
  10780. not IsMOVZXAcceptable
  10781. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10782. or (
  10783. (cs_opt_size in current_settings.optimizerswitches) and
  10784. (taicpu(p).oper[1]^.reg = NR_AX)
  10785. )
  10786. ) then
  10787. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10788. begin
  10789. DebugMsg(SPeepholeOptimization + 'var7',p);
  10790. taicpu(p).opcode := A_AND;
  10791. taicpu(p).changeopsize(S_W);
  10792. taicpu(p).loadConst(0,$ff);
  10793. Result := True;
  10794. end
  10795. else if not IsMOVZXAcceptable and
  10796. GetNextInstruction(p, hp1) and
  10797. (tai(hp1).typ = ait_instruction) and
  10798. (taicpu(hp1).opcode = A_AND) and
  10799. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10800. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10801. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10802. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10803. begin
  10804. DebugMsg(SPeepholeOptimization + 'var8',p);
  10805. taicpu(p).opcode := A_MOV;
  10806. taicpu(p).changeopsize(S_W);
  10807. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10808. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10809. Result := True;
  10810. end;
  10811. end;
  10812. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10813. S_BL:
  10814. begin
  10815. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10816. (
  10817. not IsMOVZXAcceptable
  10818. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10819. or (
  10820. (cs_opt_size in current_settings.optimizerswitches) and
  10821. (taicpu(p).oper[1]^.reg = NR_EAX)
  10822. )
  10823. ) then
  10824. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10825. begin
  10826. DebugMsg(SPeepholeOptimization + 'var9',p);
  10827. taicpu(p).opcode := A_AND;
  10828. taicpu(p).changeopsize(S_L);
  10829. taicpu(p).loadConst(0,$ff);
  10830. Result := True;
  10831. end
  10832. else if not IsMOVZXAcceptable and
  10833. GetNextInstruction(p, hp1) and
  10834. (tai(hp1).typ = ait_instruction) and
  10835. (taicpu(hp1).opcode = A_AND) and
  10836. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10837. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10838. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10839. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10840. begin
  10841. DebugMsg(SPeepholeOptimization + 'var10',p);
  10842. taicpu(p).opcode := A_MOV;
  10843. taicpu(p).changeopsize(S_L);
  10844. { do not use R_SUBWHOLE
  10845. as movl %rdx,%eax
  10846. is invalid in assembler PM }
  10847. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10848. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10849. Result := True;
  10850. end;
  10851. end;
  10852. {$endif i8086}
  10853. S_WL:
  10854. if not IsMOVZXAcceptable then
  10855. begin
  10856. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10857. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10858. begin
  10859. DebugMsg(SPeepholeOptimization + 'var11',p);
  10860. taicpu(p).opcode := A_AND;
  10861. taicpu(p).changeopsize(S_L);
  10862. taicpu(p).loadConst(0,$ffff);
  10863. Result := True;
  10864. end
  10865. else if GetNextInstruction(p, hp1) and
  10866. (tai(hp1).typ = ait_instruction) and
  10867. (taicpu(hp1).opcode = A_AND) and
  10868. (taicpu(hp1).oper[0]^.typ = top_const) and
  10869. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10870. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10871. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10872. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10873. begin
  10874. DebugMsg(SPeepholeOptimization + 'var12',p);
  10875. taicpu(p).opcode := A_MOV;
  10876. taicpu(p).changeopsize(S_L);
  10877. { do not use R_SUBWHOLE
  10878. as movl %rdx,%eax
  10879. is invalid in assembler PM }
  10880. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10881. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10882. Result := True;
  10883. end;
  10884. end;
  10885. else
  10886. InternalError(2017050705);
  10887. end;
  10888. end
  10889. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10890. begin
  10891. if GetNextInstruction(p, hp1) and
  10892. (tai(hp1).typ = ait_instruction) and
  10893. (taicpu(hp1).opcode = A_AND) and
  10894. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10895. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10896. begin
  10897. //taicpu(p).opcode := A_MOV;
  10898. case taicpu(p).opsize Of
  10899. S_BL:
  10900. begin
  10901. DebugMsg(SPeepholeOptimization + 'var13',p);
  10902. taicpu(hp1).changeopsize(S_L);
  10903. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10904. end;
  10905. S_WL:
  10906. begin
  10907. DebugMsg(SPeepholeOptimization + 'var14',p);
  10908. taicpu(hp1).changeopsize(S_L);
  10909. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10910. end;
  10911. S_BW:
  10912. begin
  10913. DebugMsg(SPeepholeOptimization + 'var15',p);
  10914. taicpu(hp1).changeopsize(S_W);
  10915. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10916. end;
  10917. else
  10918. Internalerror(2017050704)
  10919. end;
  10920. Result := True;
  10921. end;
  10922. end;
  10923. end;
  10924. end;
  10925. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10926. var
  10927. hp1, hp2 : tai;
  10928. MaskLength : Cardinal;
  10929. MaskedBits : TCgInt;
  10930. ActiveReg : TRegister;
  10931. begin
  10932. Result:=false;
  10933. { There are no optimisations for reference targets }
  10934. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10935. Exit;
  10936. while GetNextInstruction(p, hp1) and
  10937. (hp1.typ = ait_instruction) do
  10938. begin
  10939. if (taicpu(p).oper[0]^.typ = top_const) then
  10940. begin
  10941. case taicpu(hp1).opcode of
  10942. A_AND:
  10943. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10944. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10945. { the second register must contain the first one, so compare their subreg types }
  10946. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10947. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10948. { change
  10949. and const1, reg
  10950. and const2, reg
  10951. to
  10952. and (const1 and const2), reg
  10953. }
  10954. begin
  10955. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10956. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10957. RemoveCurrentP(p, hp1);
  10958. Result:=true;
  10959. exit;
  10960. end;
  10961. A_CMP:
  10962. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10963. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10964. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10965. { Just check that the condition on the next instruction is compatible }
  10966. GetNextInstruction(hp1, hp2) and
  10967. (hp2.typ = ait_instruction) and
  10968. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10969. then
  10970. { change
  10971. and 2^n, reg
  10972. cmp 2^n, reg
  10973. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10974. to
  10975. and 2^n, reg
  10976. test reg, reg
  10977. j(~c) / set(~c) / cmov(~c)
  10978. }
  10979. begin
  10980. { Keep TEST instruction in, rather than remove it, because
  10981. it may trigger other optimisations such as MovAndTest2Test }
  10982. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10983. taicpu(hp1).opcode := A_TEST;
  10984. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10985. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10986. Result := True;
  10987. Exit;
  10988. end;
  10989. A_MOVZX:
  10990. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10991. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10992. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10993. (
  10994. (
  10995. (taicpu(p).opsize=S_W) and
  10996. (taicpu(hp1).opsize=S_BW)
  10997. ) or
  10998. (
  10999. (taicpu(p).opsize=S_L) and
  11000. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11001. )
  11002. {$ifdef x86_64}
  11003. or
  11004. (
  11005. (taicpu(p).opsize=S_Q) and
  11006. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11007. )
  11008. {$endif x86_64}
  11009. ) then
  11010. begin
  11011. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11012. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11013. ) or
  11014. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11015. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11016. then
  11017. begin
  11018. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11019. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11020. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11021. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11022. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11023. }
  11024. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11025. RemoveInstruction(hp1);
  11026. { See if there are other optimisations possible }
  11027. Continue;
  11028. end;
  11029. end;
  11030. A_SHL:
  11031. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11032. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11033. begin
  11034. {$ifopt R+}
  11035. {$define RANGE_WAS_ON}
  11036. {$R-}
  11037. {$endif}
  11038. { get length of potential and mask }
  11039. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11040. { really a mask? }
  11041. {$ifdef RANGE_WAS_ON}
  11042. {$R+}
  11043. {$endif}
  11044. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11045. { unmasked part shifted out? }
  11046. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11047. begin
  11048. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11049. RemoveCurrentP(p, hp1);
  11050. Result:=true;
  11051. exit;
  11052. end;
  11053. end;
  11054. A_SHR:
  11055. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11056. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11057. (taicpu(hp1).oper[0]^.val <= 63) then
  11058. begin
  11059. { Does SHR combined with the AND cover all the bits?
  11060. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11061. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11062. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11063. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11064. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11065. begin
  11066. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11067. RemoveCurrentP(p, hp1);
  11068. Result := True;
  11069. Exit;
  11070. end;
  11071. end;
  11072. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11073. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11074. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11075. begin
  11076. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11077. (
  11078. (
  11079. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11080. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11081. ) or (
  11082. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11083. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11084. {$ifdef x86_64}
  11085. ) or (
  11086. (taicpu(hp1).opsize = S_LQ) and
  11087. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11088. {$endif x86_64}
  11089. )
  11090. ) then
  11091. begin
  11092. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11093. begin
  11094. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11095. RemoveInstruction(hp1);
  11096. { See if there are other optimisations possible }
  11097. Continue;
  11098. end;
  11099. { The super-registers are the same though.
  11100. Note that this change by itself doesn't improve
  11101. code speed, but it opens up other optimisations. }
  11102. {$ifdef x86_64}
  11103. { Convert 64-bit register to 32-bit }
  11104. case taicpu(hp1).opsize of
  11105. S_BQ:
  11106. begin
  11107. taicpu(hp1).opsize := S_BL;
  11108. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11109. end;
  11110. S_WQ:
  11111. begin
  11112. taicpu(hp1).opsize := S_WL;
  11113. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11114. end
  11115. else
  11116. ;
  11117. end;
  11118. {$endif x86_64}
  11119. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11120. taicpu(hp1).opcode := A_MOVZX;
  11121. { See if there are other optimisations possible }
  11122. Continue;
  11123. end;
  11124. end;
  11125. else
  11126. ;
  11127. end;
  11128. end
  11129. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11130. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11131. begin
  11132. {$ifdef x86_64}
  11133. if (taicpu(p).opsize = S_Q) then
  11134. begin
  11135. { Never necessary }
  11136. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11137. RemoveCurrentP(p, hp1);
  11138. Result := True;
  11139. Exit;
  11140. end;
  11141. {$endif x86_64}
  11142. { Forward check to determine necessity of and %reg,%reg }
  11143. TransferUsedRegs(TmpUsedRegs);
  11144. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11145. { Saves on a bunch of dereferences }
  11146. ActiveReg := taicpu(p).oper[1]^.reg;
  11147. case taicpu(hp1).opcode of
  11148. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11149. if (
  11150. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11151. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11152. ) and
  11153. (
  11154. (taicpu(hp1).opcode <> A_MOV) or
  11155. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11156. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11157. ) and
  11158. not (
  11159. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11160. (taicpu(hp1).opcode = A_MOV) and
  11161. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11162. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11163. ) and
  11164. (
  11165. (
  11166. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11167. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11168. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11169. ) or
  11170. (
  11171. {$ifdef x86_64}
  11172. (
  11173. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11174. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11175. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11176. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11177. ) and
  11178. {$endif x86_64}
  11179. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11180. )
  11181. ) then
  11182. begin
  11183. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11184. RemoveCurrentP(p, hp1);
  11185. Result := True;
  11186. Exit;
  11187. end;
  11188. A_ADD,
  11189. A_AND,
  11190. A_BSF,
  11191. A_BSR,
  11192. A_BTC,
  11193. A_BTR,
  11194. A_BTS,
  11195. A_OR,
  11196. A_SUB,
  11197. A_XOR:
  11198. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11199. if (
  11200. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11201. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11202. ) and
  11203. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11204. begin
  11205. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11206. RemoveCurrentP(p, hp1);
  11207. Result := True;
  11208. Exit;
  11209. end;
  11210. A_CMP,
  11211. A_TEST:
  11212. if (
  11213. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11214. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11215. ) and
  11216. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11217. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11218. begin
  11219. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11220. RemoveCurrentP(p, hp1);
  11221. Result := True;
  11222. Exit;
  11223. end;
  11224. A_BSWAP,
  11225. A_NEG,
  11226. A_NOT:
  11227. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11228. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11229. begin
  11230. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11231. RemoveCurrentP(p, hp1);
  11232. Result := True;
  11233. Exit;
  11234. end;
  11235. else
  11236. ;
  11237. end;
  11238. end;
  11239. if (taicpu(hp1).is_jmp) and
  11240. (taicpu(hp1).opcode<>A_JMP) and
  11241. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11242. begin
  11243. { change
  11244. and x, reg
  11245. jxx
  11246. to
  11247. test x, reg
  11248. jxx
  11249. if reg is deallocated before the
  11250. jump, but only if it's a conditional jump (PFV)
  11251. }
  11252. taicpu(p).opcode := A_TEST;
  11253. Exit;
  11254. end;
  11255. Break;
  11256. end;
  11257. { Lone AND tests }
  11258. if (taicpu(p).oper[0]^.typ = top_const) then
  11259. begin
  11260. {
  11261. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11262. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11263. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11264. }
  11265. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11266. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11267. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11268. begin
  11269. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11270. if taicpu(p).opsize = S_L then
  11271. begin
  11272. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11273. Result := True;
  11274. end;
  11275. end;
  11276. end;
  11277. { Backward check to determine necessity of and %reg,%reg }
  11278. if (taicpu(p).oper[0]^.typ = top_reg) and
  11279. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11280. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11281. GetLastInstruction(p, hp2) and
  11282. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11283. { Check size of adjacent instruction to determine if the AND is
  11284. effectively a null operation }
  11285. (
  11286. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11287. { Note: Don't include S_Q }
  11288. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11289. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11290. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11291. ) then
  11292. begin
  11293. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11294. { If GetNextInstruction returned False, hp1 will be nil }
  11295. RemoveCurrentP(p, hp1);
  11296. Result := True;
  11297. Exit;
  11298. end;
  11299. end;
  11300. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11301. var
  11302. hp1: tai; NewRef: TReference;
  11303. { This entire nested function is used in an if-statement below, but we
  11304. want to avoid all the used reg transfers and GetNextInstruction calls
  11305. until we really have to check }
  11306. function MemRegisterNotUsedLater: Boolean; inline;
  11307. var
  11308. hp2: tai;
  11309. begin
  11310. TransferUsedRegs(TmpUsedRegs);
  11311. hp2 := p;
  11312. repeat
  11313. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11314. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11315. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11316. end;
  11317. begin
  11318. Result := False;
  11319. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11320. Exit;
  11321. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11322. begin
  11323. { Change:
  11324. add %reg2,%reg1
  11325. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11326. To:
  11327. mov/s/z #(%reg1,%reg2),%reg1
  11328. }
  11329. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11330. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11331. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11332. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11333. (
  11334. (
  11335. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11336. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11337. { r/esp cannot be an index }
  11338. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11339. ) or (
  11340. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11341. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11342. )
  11343. ) and (
  11344. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11345. (
  11346. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11347. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11348. MemRegisterNotUsedLater
  11349. )
  11350. ) then
  11351. begin
  11352. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11353. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11354. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11355. RemoveCurrentp(p, hp1);
  11356. Result := True;
  11357. Exit;
  11358. end;
  11359. { Change:
  11360. addl/q $x,%reg1
  11361. movl/q %reg1,%reg2
  11362. To:
  11363. leal/q $x(%reg1),%reg2
  11364. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11365. Breaks the dependency chain.
  11366. }
  11367. if MatchOpType(taicpu(p),top_const,top_reg) and
  11368. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11369. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11370. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11371. (
  11372. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11373. not (cs_opt_size in current_settings.optimizerswitches) or
  11374. (
  11375. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11376. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11377. )
  11378. ) then
  11379. begin
  11380. { Change the MOV instruction to a LEA instruction, and update the
  11381. first operand }
  11382. reference_reset(NewRef, 1, []);
  11383. NewRef.base := taicpu(p).oper[1]^.reg;
  11384. NewRef.scalefactor := 1;
  11385. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11386. taicpu(hp1).opcode := A_LEA;
  11387. taicpu(hp1).loadref(0, NewRef);
  11388. TransferUsedRegs(TmpUsedRegs);
  11389. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11390. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11391. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11392. begin
  11393. { Move what is now the LEA instruction to before the SUB instruction }
  11394. Asml.Remove(hp1);
  11395. Asml.InsertBefore(hp1, p);
  11396. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11397. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11398. p := hp1;
  11399. end
  11400. else
  11401. begin
  11402. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11403. RemoveCurrentP(p, hp1);
  11404. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11405. end;
  11406. Result := True;
  11407. end;
  11408. end;
  11409. end;
  11410. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11411. var
  11412. SubReg: TSubRegister;
  11413. begin
  11414. Result:=false;
  11415. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11416. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11417. with taicpu(p).oper[0]^.ref^ do
  11418. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11419. begin
  11420. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11421. begin
  11422. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11423. taicpu(p).opcode := A_ADD;
  11424. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11425. Result := True;
  11426. end
  11427. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11428. begin
  11429. if (base <> NR_NO) then
  11430. begin
  11431. if (scalefactor <= 1) then
  11432. begin
  11433. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11434. taicpu(p).opcode := A_ADD;
  11435. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11436. Result := True;
  11437. end;
  11438. end
  11439. else
  11440. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11441. if (scalefactor in [2, 4, 8]) then
  11442. begin
  11443. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11444. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11445. taicpu(p).opcode := A_SHL;
  11446. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11447. Result := True;
  11448. end;
  11449. end;
  11450. end;
  11451. end;
  11452. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11453. var
  11454. hp1: tai; NewRef: TReference;
  11455. begin
  11456. { Change:
  11457. subl/q $x,%reg1
  11458. movl/q %reg1,%reg2
  11459. To:
  11460. leal/q $-x(%reg1),%reg2
  11461. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11462. Breaks the dependency chain and potentially permits the removal of
  11463. a CMP instruction if one follows.
  11464. }
  11465. Result := False;
  11466. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11467. MatchOpType(taicpu(p),top_const,top_reg) and
  11468. GetNextInstruction(p, hp1) and
  11469. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11470. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11471. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11472. (
  11473. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11474. not (cs_opt_size in current_settings.optimizerswitches) or
  11475. (
  11476. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11477. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11478. )
  11479. ) then
  11480. begin
  11481. { Change the MOV instruction to a LEA instruction, and update the
  11482. first operand }
  11483. reference_reset(NewRef, 1, []);
  11484. NewRef.base := taicpu(p).oper[1]^.reg;
  11485. NewRef.scalefactor := 1;
  11486. NewRef.offset := -taicpu(p).oper[0]^.val;
  11487. taicpu(hp1).opcode := A_LEA;
  11488. taicpu(hp1).loadref(0, NewRef);
  11489. TransferUsedRegs(TmpUsedRegs);
  11490. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11491. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11492. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11493. begin
  11494. { Move what is now the LEA instruction to before the SUB instruction }
  11495. Asml.Remove(hp1);
  11496. Asml.InsertBefore(hp1, p);
  11497. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11498. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11499. p := hp1;
  11500. end
  11501. else
  11502. begin
  11503. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11504. RemoveCurrentP(p, hp1);
  11505. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11506. end;
  11507. Result := True;
  11508. end;
  11509. end;
  11510. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11511. begin
  11512. { we can skip all instructions not messing with the stack pointer }
  11513. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11514. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11515. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11516. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11517. ({(taicpu(hp1).ops=0) or }
  11518. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11519. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11520. ) and }
  11521. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11522. )
  11523. ) do
  11524. GetNextInstruction(hp1,hp1);
  11525. Result:=assigned(hp1);
  11526. end;
  11527. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11528. var
  11529. hp1, hp2, hp3, hp4, hp5: tai;
  11530. begin
  11531. Result:=false;
  11532. hp5:=nil;
  11533. { replace
  11534. leal(q) x(<stackpointer>),<stackpointer>
  11535. call procname
  11536. leal(q) -x(<stackpointer>),<stackpointer>
  11537. ret
  11538. by
  11539. jmp procname
  11540. but do it only on level 4 because it destroys stack back traces
  11541. }
  11542. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11543. MatchOpType(taicpu(p),top_ref,top_reg) and
  11544. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11545. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11546. { the -8 or -24 are not required, but bail out early if possible,
  11547. higher values are unlikely }
  11548. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11549. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11550. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11551. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11552. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11553. GetNextInstruction(p, hp1) and
  11554. { Take a copy of hp1 }
  11555. SetAndTest(hp1, hp4) and
  11556. { trick to skip label }
  11557. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11558. SkipSimpleInstructions(hp1) and
  11559. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11560. GetNextInstruction(hp1, hp2) and
  11561. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11562. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11563. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11564. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11565. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11566. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11567. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11568. { Segment register will be NR_NO }
  11569. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11570. GetNextInstruction(hp2, hp3) and
  11571. { trick to skip label }
  11572. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11573. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11574. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11575. SetAndTest(hp3,hp5) and
  11576. GetNextInstruction(hp3,hp3) and
  11577. MatchInstruction(hp3,A_RET,[S_NO])
  11578. )
  11579. ) and
  11580. (taicpu(hp3).ops=0) then
  11581. begin
  11582. taicpu(hp1).opcode := A_JMP;
  11583. taicpu(hp1).is_jmp := true;
  11584. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11585. RemoveCurrentP(p, hp4);
  11586. RemoveInstruction(hp2);
  11587. RemoveInstruction(hp3);
  11588. if Assigned(hp5) then
  11589. begin
  11590. AsmL.Remove(hp5);
  11591. ASmL.InsertBefore(hp5,hp1)
  11592. end;
  11593. Result:=true;
  11594. end;
  11595. end;
  11596. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11597. {$ifdef x86_64}
  11598. var
  11599. hp1, hp2, hp3, hp4, hp5: tai;
  11600. {$endif x86_64}
  11601. begin
  11602. Result:=false;
  11603. {$ifdef x86_64}
  11604. hp5:=nil;
  11605. { replace
  11606. push %rax
  11607. call procname
  11608. pop %rcx
  11609. ret
  11610. by
  11611. jmp procname
  11612. but do it only on level 4 because it destroys stack back traces
  11613. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11614. for all supported calling conventions
  11615. }
  11616. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11617. MatchOpType(taicpu(p),top_reg) and
  11618. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11619. GetNextInstruction(p, hp1) and
  11620. { Take a copy of hp1 }
  11621. SetAndTest(hp1, hp4) and
  11622. { trick to skip label }
  11623. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11624. SkipSimpleInstructions(hp1) and
  11625. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11626. GetNextInstruction(hp1, hp2) and
  11627. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11628. MatchOpType(taicpu(hp2),top_reg) and
  11629. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11630. GetNextInstruction(hp2, hp3) and
  11631. { trick to skip label }
  11632. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11633. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11634. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11635. SetAndTest(hp3,hp5) and
  11636. GetNextInstruction(hp3,hp3) and
  11637. MatchInstruction(hp3,A_RET,[S_NO])
  11638. )
  11639. ) and
  11640. (taicpu(hp3).ops=0) then
  11641. begin
  11642. taicpu(hp1).opcode := A_JMP;
  11643. taicpu(hp1).is_jmp := true;
  11644. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11645. RemoveCurrentP(p, hp4);
  11646. RemoveInstruction(hp2);
  11647. RemoveInstruction(hp3);
  11648. if Assigned(hp5) then
  11649. begin
  11650. AsmL.Remove(hp5);
  11651. ASmL.InsertBefore(hp5,hp1)
  11652. end;
  11653. Result:=true;
  11654. end;
  11655. {$endif x86_64}
  11656. end;
  11657. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11658. var
  11659. Value, RegName: string;
  11660. begin
  11661. Result:=false;
  11662. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11663. begin
  11664. case taicpu(p).oper[0]^.val of
  11665. 0:
  11666. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11667. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11668. begin
  11669. { change "mov $0,%reg" into "xor %reg,%reg" }
  11670. taicpu(p).opcode := A_XOR;
  11671. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11672. Result := True;
  11673. {$ifdef x86_64}
  11674. end
  11675. else if (taicpu(p).opsize = S_Q) then
  11676. begin
  11677. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11678. { The actual optimization }
  11679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11680. taicpu(p).changeopsize(S_L);
  11681. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11682. Result := True;
  11683. end;
  11684. $1..$FFFFFFFF:
  11685. begin
  11686. { Code size reduction by J. Gareth "Kit" Moreton }
  11687. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11688. case taicpu(p).opsize of
  11689. S_Q:
  11690. begin
  11691. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11692. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11693. { The actual optimization }
  11694. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11695. taicpu(p).changeopsize(S_L);
  11696. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11697. Result := True;
  11698. end;
  11699. else
  11700. { Do nothing };
  11701. end;
  11702. {$endif x86_64}
  11703. end;
  11704. -1:
  11705. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11706. if (cs_opt_size in current_settings.optimizerswitches) and
  11707. (taicpu(p).opsize <> S_B) and
  11708. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11709. begin
  11710. { change "mov $-1,%reg" into "or $-1,%reg" }
  11711. { NOTES:
  11712. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11713. - This operation creates a false dependency on the register, so only do it when optimising for size
  11714. - 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
  11715. }
  11716. taicpu(p).opcode := A_OR;
  11717. Result := True;
  11718. end;
  11719. else
  11720. { Do nothing };
  11721. end;
  11722. end;
  11723. end;
  11724. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11725. var
  11726. hp1: tai;
  11727. begin
  11728. { Detect:
  11729. andw x, %ax (0 <= x < $8000)
  11730. ...
  11731. movzwl %ax,%eax
  11732. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11733. }
  11734. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11735. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11736. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11737. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11738. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11739. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11740. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11741. begin
  11742. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11743. taicpu(hp1).opcode := A_CWDE;
  11744. taicpu(hp1).clearop(0);
  11745. taicpu(hp1).clearop(1);
  11746. taicpu(hp1).ops := 0;
  11747. { A change was made, but not with p, so move forward 1 }
  11748. p := tai(p.Next);
  11749. Result := True;
  11750. end;
  11751. end;
  11752. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11753. begin
  11754. Result := False;
  11755. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11756. Exit;
  11757. { Convert:
  11758. movswl %ax,%eax -> cwtl
  11759. movslq %eax,%rax -> cdqe
  11760. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11761. refer to the same opcode and depends only on the assembler's
  11762. current operand-size attribute. [Kit]
  11763. }
  11764. with taicpu(p) do
  11765. case opsize of
  11766. S_WL:
  11767. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11768. begin
  11769. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11770. opcode := A_CWDE;
  11771. clearop(0);
  11772. clearop(1);
  11773. ops := 0;
  11774. Result := True;
  11775. end;
  11776. {$ifdef x86_64}
  11777. S_LQ:
  11778. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11779. begin
  11780. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11781. opcode := A_CDQE;
  11782. clearop(0);
  11783. clearop(1);
  11784. ops := 0;
  11785. Result := True;
  11786. end;
  11787. {$endif x86_64}
  11788. else
  11789. ;
  11790. end;
  11791. end;
  11792. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11793. var
  11794. hp1: tai;
  11795. begin
  11796. { Detect:
  11797. shr x, %ax (x > 0)
  11798. ...
  11799. movzwl %ax,%eax
  11800. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11801. }
  11802. Result := False;
  11803. if MatchOpType(taicpu(p), top_const, top_reg) and
  11804. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11805. (taicpu(p).oper[0]^.val > 0) and
  11806. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11807. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11808. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11809. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11810. begin
  11811. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11812. taicpu(hp1).opcode := A_CWDE;
  11813. taicpu(hp1).clearop(0);
  11814. taicpu(hp1).clearop(1);
  11815. taicpu(hp1).ops := 0;
  11816. { A change was made, but not with p, so move forward 1 }
  11817. p := tai(p.Next);
  11818. Result := True;
  11819. end;
  11820. end;
  11821. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11822. var
  11823. hp1, hp2: tai;
  11824. Opposite, SecondOpposite: TAsmOp;
  11825. NewCond: TAsmCond;
  11826. begin
  11827. Result := False;
  11828. { Change:
  11829. add/sub 128,(dest)
  11830. To:
  11831. sub/add -128,(dest)
  11832. This generaally takes fewer bytes to encode because -128 can be stored
  11833. in a signed byte, whereas +128 cannot.
  11834. }
  11835. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11836. begin
  11837. if taicpu(p).opcode = A_ADD then
  11838. Opposite := A_SUB
  11839. else
  11840. Opposite := A_ADD;
  11841. { Be careful if the flags are in use, because the CF flag inverts
  11842. when changing from ADD to SUB and vice versa }
  11843. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11844. GetNextInstruction(p, hp1) then
  11845. begin
  11846. TransferUsedRegs(TmpUsedRegs);
  11847. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11848. hp2 := hp1;
  11849. { Scan ahead to check if everything's safe }
  11850. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11851. begin
  11852. if (hp1.typ <> ait_instruction) then
  11853. { Probably unsafe since the flags are still in use }
  11854. Exit;
  11855. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11856. { Stop searching at an unconditional jump }
  11857. Break;
  11858. if not
  11859. (
  11860. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11861. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11862. ) and
  11863. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11864. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11865. Exit;
  11866. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11867. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11868. { Move to the next instruction }
  11869. GetNextInstruction(hp1, hp1);
  11870. end;
  11871. while Assigned(hp2) and (hp2 <> hp1) do
  11872. begin
  11873. NewCond := C_None;
  11874. case taicpu(hp2).condition of
  11875. C_A, C_NBE:
  11876. NewCond := C_BE;
  11877. C_B, C_C, C_NAE:
  11878. NewCond := C_AE;
  11879. C_AE, C_NB, C_NC:
  11880. NewCond := C_B;
  11881. C_BE, C_NA:
  11882. NewCond := C_A;
  11883. else
  11884. { No change needed };
  11885. end;
  11886. if NewCond <> C_None then
  11887. begin
  11888. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11889. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11890. taicpu(hp2).condition := NewCond;
  11891. end
  11892. else
  11893. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11894. begin
  11895. { Because of the flipping of the carry bit, to ensure
  11896. the operation remains equivalent, ADC becomes SBB
  11897. and vice versa, and the constant is not-inverted.
  11898. If multiple ADCs or SBBs appear in a row, each one
  11899. changed causes the carry bit to invert, so they all
  11900. need to be flipped }
  11901. if taicpu(hp2).opcode = A_ADC then
  11902. SecondOpposite := A_SBB
  11903. else
  11904. SecondOpposite := A_ADC;
  11905. if taicpu(hp2).oper[0]^.typ <> top_const then
  11906. { Should have broken out of this optimisation already }
  11907. InternalError(2021112901);
  11908. 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]^) + ' -> ' +
  11909. 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);
  11910. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11911. taicpu(hp2).opcode := SecondOpposite;
  11912. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11913. end;
  11914. { Move to the next instruction }
  11915. GetNextInstruction(hp2, hp2);
  11916. end;
  11917. if (hp2 <> hp1) then
  11918. InternalError(2021111501);
  11919. end;
  11920. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11921. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11922. taicpu(p).opcode := Opposite;
  11923. taicpu(p).oper[0]^.val := -128;
  11924. { No further optimisations can be made on this instruction, so move
  11925. onto the next one to save time }
  11926. p := tai(p.Next);
  11927. UpdateUsedRegs(p);
  11928. Result := True;
  11929. Exit;
  11930. end;
  11931. { Detect:
  11932. add/sub %reg2,(dest)
  11933. add/sub x, (dest)
  11934. (dest can be a register or a reference)
  11935. Swap the instructions to minimise a pipeline stall. This reverses the
  11936. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11937. optimisations could be made.
  11938. }
  11939. if (taicpu(p).oper[0]^.typ = top_reg) and
  11940. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11941. (
  11942. (
  11943. (taicpu(p).oper[1]^.typ = top_reg) and
  11944. { We can try searching further ahead if we're writing to a register }
  11945. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11946. ) or
  11947. (
  11948. (taicpu(p).oper[1]^.typ = top_ref) and
  11949. GetNextInstruction(p, hp1)
  11950. )
  11951. ) and
  11952. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11953. (taicpu(hp1).oper[0]^.typ = top_const) and
  11954. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11955. begin
  11956. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11957. TransferUsedRegs(TmpUsedRegs);
  11958. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11959. hp2 := p;
  11960. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11961. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11962. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11963. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11964. begin
  11965. asml.remove(hp1);
  11966. asml.InsertBefore(hp1, p);
  11967. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11968. Result := True;
  11969. end;
  11970. end;
  11971. end;
  11972. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11973. begin
  11974. Result:=false;
  11975. { change "cmp $0, %reg" to "test %reg, %reg" }
  11976. if MatchOpType(taicpu(p),top_const,top_reg) and
  11977. (taicpu(p).oper[0]^.val = 0) then
  11978. begin
  11979. taicpu(p).opcode := A_TEST;
  11980. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11981. Result:=true;
  11982. end;
  11983. end;
  11984. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11985. var
  11986. IsTestConstX : Boolean;
  11987. hp1,hp2 : tai;
  11988. begin
  11989. Result:=false;
  11990. { removes the line marked with (x) from the sequence
  11991. and/or/xor/add/sub/... $x, %y
  11992. test/or %y, %y | test $-1, %y (x)
  11993. j(n)z _Label
  11994. as the first instruction already adjusts the ZF
  11995. %y operand may also be a reference }
  11996. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11997. MatchOperand(taicpu(p).oper[0]^,-1);
  11998. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11999. GetLastInstruction(p, hp1) and
  12000. (tai(hp1).typ = ait_instruction) and
  12001. GetNextInstruction(p,hp2) and
  12002. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  12003. case taicpu(hp1).opcode Of
  12004. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  12005. { These two instructions set the zero flag if the result is zero }
  12006. A_POPCNT, A_LZCNT:
  12007. begin
  12008. if (
  12009. { With POPCNT, an input of zero will set the zero flag
  12010. because the population count of zero is zero }
  12011. (taicpu(hp1).opcode = A_POPCNT) and
  12012. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  12013. (
  12014. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  12015. { Faster than going through the second half of the 'or'
  12016. condition below }
  12017. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  12018. )
  12019. ) or (
  12020. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  12021. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12022. { and in case of carry for A(E)/B(E)/C/NC }
  12023. (
  12024. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  12025. (
  12026. (taicpu(hp1).opcode <> A_ADD) and
  12027. (taicpu(hp1).opcode <> A_SUB) and
  12028. (taicpu(hp1).opcode <> A_LZCNT)
  12029. )
  12030. )
  12031. ) then
  12032. begin
  12033. RemoveCurrentP(p, hp2);
  12034. Result:=true;
  12035. Exit;
  12036. end;
  12037. end;
  12038. A_SHL, A_SAL, A_SHR, A_SAR:
  12039. begin
  12040. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  12041. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  12042. { therefore, it's only safe to do this optimization for }
  12043. { shifts by a (nonzero) constant }
  12044. (taicpu(hp1).oper[0]^.typ = top_const) and
  12045. (taicpu(hp1).oper[0]^.val <> 0) and
  12046. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12047. { and in case of carry for A(E)/B(E)/C/NC }
  12048. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12049. begin
  12050. RemoveCurrentP(p, hp2);
  12051. Result:=true;
  12052. Exit;
  12053. end;
  12054. end;
  12055. A_DEC, A_INC, A_NEG:
  12056. begin
  12057. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  12058. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12059. { and in case of carry for A(E)/B(E)/C/NC }
  12060. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12061. begin
  12062. RemoveCurrentP(p, hp2);
  12063. Result:=true;
  12064. Exit;
  12065. end;
  12066. end
  12067. else
  12068. ;
  12069. end; { case }
  12070. { change "test $-1,%reg" into "test %reg,%reg" }
  12071. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  12072. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  12073. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  12074. if MatchInstruction(p, A_OR, []) and
  12075. { Can only match if they're both registers }
  12076. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  12077. begin
  12078. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  12079. taicpu(p).opcode := A_TEST;
  12080. { No need to set Result to True, as we've done all the optimisations we can }
  12081. end;
  12082. end;
  12083. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  12084. var
  12085. hp1,hp3 : tai;
  12086. {$ifndef x86_64}
  12087. hp2 : taicpu;
  12088. {$endif x86_64}
  12089. begin
  12090. Result:=false;
  12091. hp3:=nil;
  12092. {$ifndef x86_64}
  12093. { don't do this on modern CPUs, this really hurts them due to
  12094. broken call/ret pairing }
  12095. if (current_settings.optimizecputype < cpu_Pentium2) and
  12096. not(cs_create_pic in current_settings.moduleswitches) and
  12097. GetNextInstruction(p, hp1) and
  12098. MatchInstruction(hp1,A_JMP,[S_NO]) and
  12099. MatchOpType(taicpu(hp1),top_ref) and
  12100. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12101. begin
  12102. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  12103. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  12104. InsertLLItem(p.previous, p, hp2);
  12105. taicpu(p).opcode := A_JMP;
  12106. taicpu(p).is_jmp := true;
  12107. RemoveInstruction(hp1);
  12108. Result:=true;
  12109. end
  12110. else
  12111. {$endif x86_64}
  12112. { replace
  12113. call procname
  12114. ret
  12115. by
  12116. jmp procname
  12117. but do it only on level 4 because it destroys stack back traces
  12118. else if the subroutine is marked as no return, remove the ret
  12119. }
  12120. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12121. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12122. GetNextInstruction(p, hp1) and
  12123. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12124. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12125. SetAndTest(hp1,hp3) and
  12126. GetNextInstruction(hp1,hp1) and
  12127. MatchInstruction(hp1,A_RET,[S_NO])
  12128. )
  12129. ) and
  12130. (taicpu(hp1).ops=0) then
  12131. begin
  12132. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12133. { we might destroy stack alignment here if we do not do a call }
  12134. (target_info.stackalign<=sizeof(SizeUInt)) then
  12135. begin
  12136. taicpu(p).opcode := A_JMP;
  12137. taicpu(p).is_jmp := true;
  12138. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12139. end
  12140. else
  12141. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12142. RemoveInstruction(hp1);
  12143. if Assigned(hp3) then
  12144. begin
  12145. AsmL.Remove(hp3);
  12146. AsmL.InsertBefore(hp3,p)
  12147. end;
  12148. Result:=true;
  12149. end;
  12150. end;
  12151. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12152. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12153. begin
  12154. case OpSize of
  12155. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12156. Result := (Val <= $FF) and (Val >= -128);
  12157. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12158. Result := (Val <= $FFFF) and (Val >= -32768);
  12159. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12160. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12161. else
  12162. Result := True;
  12163. end;
  12164. end;
  12165. var
  12166. hp1, hp2 : tai;
  12167. SizeChange: Boolean;
  12168. PreMessage: string;
  12169. begin
  12170. Result := False;
  12171. if (taicpu(p).oper[0]^.typ = top_reg) and
  12172. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12173. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12174. begin
  12175. { Change (using movzbl %al,%eax as an example):
  12176. movzbl %al, %eax movzbl %al, %eax
  12177. cmpl x, %eax testl %eax,%eax
  12178. To:
  12179. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12180. movzbl %al, %eax movzbl %al, %eax
  12181. Smaller instruction and minimises pipeline stall as the CPU
  12182. doesn't have to wait for the register to get zero-extended. [Kit]
  12183. Also allow if the smaller of the two registers is being checked,
  12184. as this still removes the false dependency.
  12185. }
  12186. if
  12187. (
  12188. (
  12189. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12190. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12191. ) or (
  12192. { If MatchOperand returns True, they must both be registers }
  12193. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12194. )
  12195. ) and
  12196. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12197. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12198. begin
  12199. 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);
  12200. asml.Remove(hp1);
  12201. asml.InsertBefore(hp1, p);
  12202. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12203. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12204. begin
  12205. taicpu(hp1).opcode := A_TEST;
  12206. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12207. end;
  12208. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12209. case taicpu(p).opsize of
  12210. S_BW, S_BL:
  12211. begin
  12212. SizeChange := taicpu(hp1).opsize <> S_B;
  12213. taicpu(hp1).changeopsize(S_B);
  12214. end;
  12215. S_WL:
  12216. begin
  12217. SizeChange := taicpu(hp1).opsize <> S_W;
  12218. taicpu(hp1).changeopsize(S_W);
  12219. end
  12220. else
  12221. InternalError(2020112701);
  12222. end;
  12223. UpdateUsedRegs(tai(p.Next));
  12224. { Check if the register is used aferwards - if not, we can
  12225. remove the movzx instruction completely }
  12226. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12227. begin
  12228. { Hp1 is a better position than p for debugging purposes }
  12229. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12230. RemoveCurrentp(p, hp1);
  12231. Result := True;
  12232. end;
  12233. if SizeChange then
  12234. DebugMsg(SPeepholeOptimization + PreMessage +
  12235. 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)
  12236. else
  12237. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12238. Exit;
  12239. end;
  12240. { Change (using movzwl %ax,%eax as an example):
  12241. movzwl %ax, %eax
  12242. movb %al, (dest) (Register is smaller than read register in movz)
  12243. To:
  12244. movb %al, (dest) (Move one back to avoid a false dependency)
  12245. movzwl %ax, %eax
  12246. }
  12247. if (taicpu(hp1).opcode = A_MOV) and
  12248. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12249. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12250. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12251. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12252. begin
  12253. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12254. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12255. asml.Remove(hp1);
  12256. asml.InsertBefore(hp1, p);
  12257. if taicpu(hp1).oper[1]^.typ = top_reg then
  12258. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12259. { Check if the register is used aferwards - if not, we can
  12260. remove the movzx instruction completely }
  12261. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12262. begin
  12263. { Hp1 is a better position than p for debugging purposes }
  12264. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12265. RemoveCurrentp(p, hp1);
  12266. Result := True;
  12267. end;
  12268. Exit;
  12269. end;
  12270. end;
  12271. end;
  12272. {$ifdef x86_64}
  12273. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12274. var
  12275. PreMessage, RegName: string;
  12276. begin
  12277. { Code size reduction by J. Gareth "Kit" Moreton }
  12278. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12279. as this removes the REX prefix }
  12280. Result := False;
  12281. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12282. Exit;
  12283. if taicpu(p).oper[0]^.typ <> top_reg then
  12284. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12285. InternalError(2018011500);
  12286. case taicpu(p).opsize of
  12287. S_Q:
  12288. begin
  12289. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12290. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12291. { The actual optimization }
  12292. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12293. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12294. taicpu(p).changeopsize(S_L);
  12295. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12296. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12297. end;
  12298. else
  12299. ;
  12300. end;
  12301. end;
  12302. {$endif}
  12303. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12304. var
  12305. XReg: TRegister;
  12306. begin
  12307. Result := False;
  12308. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12309. Smaller encoding and slightly faster on some platforms (also works for
  12310. ZMM-sized registers) }
  12311. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12312. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12313. begin
  12314. XReg := taicpu(p).oper[0]^.reg;
  12315. if (taicpu(p).oper[1]^.reg = XReg) then
  12316. begin
  12317. taicpu(p).changeopsize(S_XMM);
  12318. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12319. if (cs_opt_size in current_settings.optimizerswitches) then
  12320. begin
  12321. { Change input registers to %xmm0 to reduce size. Note that
  12322. there's a risk of a false dependency doing this, so only
  12323. optimise for size here }
  12324. XReg := NR_XMM0;
  12325. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12326. end
  12327. else
  12328. begin
  12329. setsubreg(XReg, R_SUBMMX);
  12330. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12331. end;
  12332. taicpu(p).oper[0]^.reg := XReg;
  12333. taicpu(p).oper[1]^.reg := XReg;
  12334. Result := True;
  12335. end;
  12336. end;
  12337. end;
  12338. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12339. var
  12340. OperIdx: Integer;
  12341. begin
  12342. for OperIdx := 0 to p.ops - 1 do
  12343. if p.oper[OperIdx]^.typ = top_ref then
  12344. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12345. end;
  12346. end.