aoptx86.pas 609 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer 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 GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p : tai) : boolean; static;
  102. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  103. conversion was successful }
  104. function ConvertLEA(const p : taicpu): Boolean;
  105. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  106. procedure DebugMsg(const s : string; p : tai);inline;
  107. class function IsExitCode(p : tai) : boolean; static;
  108. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  109. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  110. procedure RemoveLastDeallocForFuncRes(p : tai);
  111. function DoSubAddOpt(var p : tai) : Boolean;
  112. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  113. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  114. function PrePeepholeOptSxx(var p : tai) : boolean;
  115. function PrePeepholeOptIMUL(var p : tai) : boolean;
  116. function PrePeepholeOptAND(var p : tai) : boolean;
  117. function OptPass1Test(var p: tai): boolean;
  118. function OptPass1Add(var p: tai): boolean;
  119. function OptPass1AND(var p : tai) : boolean;
  120. function OptPass1_V_MOVAP(var p : tai) : boolean;
  121. function OptPass1VOP(var p : tai) : boolean;
  122. function OptPass1MOV(var p : tai) : boolean;
  123. function OptPass1Movx(var p : tai) : boolean;
  124. function OptPass1MOVXX(var p : tai) : boolean;
  125. function OptPass1OP(var p : tai) : boolean;
  126. function OptPass1LEA(var p : tai) : boolean;
  127. function OptPass1Sub(var p : tai) : boolean;
  128. function OptPass1SHLSAL(var p : tai) : boolean;
  129. function OptPass1SHR(var p : tai) : boolean;
  130. function OptPass1FSTP(var p : tai) : boolean;
  131. function OptPass1FLD(var p : tai) : boolean;
  132. function OptPass1Cmp(var p : tai) : boolean;
  133. function OptPass1PXor(var p : tai) : boolean;
  134. function OptPass1VPXor(var p: tai): boolean;
  135. function OptPass1Imul(var p : tai) : boolean;
  136. function OptPass1Jcc(var p : tai) : boolean;
  137. function OptPass1SHXX(var p: tai): boolean;
  138. function OptPass1VMOVDQ(var p: tai): Boolean;
  139. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  140. function OptPass2Movx(var p : tai): Boolean;
  141. function OptPass2MOV(var p : tai) : boolean;
  142. function OptPass2Imul(var p : tai) : boolean;
  143. function OptPass2Jmp(var p : tai) : boolean;
  144. function OptPass2Jcc(var p : tai) : boolean;
  145. function OptPass2Lea(var p: tai): Boolean;
  146. function OptPass2SUB(var p: tai): Boolean;
  147. function OptPass2ADD(var p : tai): Boolean;
  148. function OptPass2SETcc(var p : tai) : boolean;
  149. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  150. function PostPeepholeOptMov(var p : tai) : Boolean;
  151. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  152. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  153. function PostPeepholeOptXor(var p : tai) : Boolean;
  154. {$endif x86_64}
  155. function PostPeepholeOptAnd(var p : tai) : boolean;
  156. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  157. function PostPeepholeOptCmp(var p : tai) : Boolean;
  158. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  159. function PostPeepholeOptCall(var p : tai) : Boolean;
  160. function PostPeepholeOptLea(var p : tai) : Boolean;
  161. function PostPeepholeOptPush(var p: tai): Boolean;
  162. function PostPeepholeOptShr(var p : tai) : boolean;
  163. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  164. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  165. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  166. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  167. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  168. { Processor-dependent reference optimisation }
  169. class procedure OptimizeRefs(var p: taicpu); static;
  170. end;
  171. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  172. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  173. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  174. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  175. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  176. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  177. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  178. {$if max_operands>2}
  179. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  180. {$endif max_operands>2}
  181. function RefsEqual(const r1, r2: treference): boolean;
  182. { Note that Result is set to True if the references COULD overlap but the
  183. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  184. might still overlap because %reg2 could be equal to %reg1-4 }
  185. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  186. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  187. { returns true, if ref is a reference using only the registers passed as base and index
  188. and having an offset }
  189. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  190. implementation
  191. uses
  192. cutils,verbose,
  193. systems,
  194. globals,
  195. cpuinfo,
  196. procinfo,
  197. paramgr,
  198. aasmbase,
  199. aoptbase,aoptutils,
  200. symconst,symsym,
  201. cgx86,
  202. itcpugas;
  203. {$ifdef DEBUG_AOPTCPU}
  204. const
  205. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  206. {$else DEBUG_AOPTCPU}
  207. { Empty strings help the optimizer to remove string concatenations that won't
  208. ever appear to the user on release builds. [Kit] }
  209. const
  210. SPeepholeOptimization = '';
  211. {$endif DEBUG_AOPTCPU}
  212. LIST_STEP_SIZE = 4;
  213. type
  214. TJumpTrackingItem = class(TLinkedListItem)
  215. private
  216. FSymbol: TAsmSymbol;
  217. FRefs: LongInt;
  218. public
  219. constructor Create(ASymbol: TAsmSymbol);
  220. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  221. property Symbol: TAsmSymbol read FSymbol;
  222. property Refs: LongInt read FRefs;
  223. end;
  224. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  225. begin
  226. inherited Create;
  227. FSymbol := ASymbol;
  228. FRefs := 0;
  229. end;
  230. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  231. begin
  232. Inc(FRefs);
  233. end;
  234. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  235. begin
  236. result :=
  237. (instr.typ = ait_instruction) and
  238. (taicpu(instr).opcode = op) and
  239. ((opsize = []) or (taicpu(instr).opsize in opsize));
  240. end;
  241. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  242. begin
  243. result :=
  244. (instr.typ = ait_instruction) and
  245. ((taicpu(instr).opcode = op1) or
  246. (taicpu(instr).opcode = op2)
  247. ) and
  248. ((opsize = []) or (taicpu(instr).opsize in opsize));
  249. end;
  250. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  251. begin
  252. result :=
  253. (instr.typ = ait_instruction) and
  254. ((taicpu(instr).opcode = op1) or
  255. (taicpu(instr).opcode = op2) or
  256. (taicpu(instr).opcode = op3)
  257. ) and
  258. ((opsize = []) or (taicpu(instr).opsize in opsize));
  259. end;
  260. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  261. const opsize : topsizes) : boolean;
  262. var
  263. op : TAsmOp;
  264. begin
  265. result:=false;
  266. if (instr.typ <> ait_instruction) or
  267. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  268. exit;
  269. for op in ops do
  270. begin
  271. if taicpu(instr).opcode = op then
  272. begin
  273. result:=true;
  274. exit;
  275. end;
  276. end;
  277. end;
  278. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  279. begin
  280. result := (oper.typ = top_reg) and (oper.reg = reg);
  281. end;
  282. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  283. begin
  284. result := (oper.typ = top_const) and (oper.val = a);
  285. end;
  286. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  287. begin
  288. result := oper1.typ = oper2.typ;
  289. if result then
  290. case oper1.typ of
  291. top_const:
  292. Result:=oper1.val = oper2.val;
  293. top_reg:
  294. Result:=oper1.reg = oper2.reg;
  295. top_ref:
  296. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  297. else
  298. internalerror(2013102801);
  299. end
  300. end;
  301. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  302. begin
  303. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  304. if result then
  305. case oper1.typ of
  306. top_const:
  307. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  308. top_reg:
  309. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  310. top_ref:
  311. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  312. else
  313. internalerror(2020052401);
  314. end
  315. end;
  316. function RefsEqual(const r1, r2: treference): boolean;
  317. begin
  318. RefsEqual :=
  319. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  320. (r1.relsymbol = r2.relsymbol) and
  321. (r1.segment = r2.segment) and (r1.base = r2.base) and
  322. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  323. (r1.offset = r2.offset) and
  324. (r1.volatility + r2.volatility = []);
  325. end;
  326. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  327. begin
  328. if (r1.symbol<>r2.symbol) then
  329. { If the index registers are different, there's a chance one could
  330. be set so it equals the other symbol }
  331. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  332. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  333. (r1.relsymbol = r2.relsymbol) and
  334. (r1.segment = r2.segment) and (r1.base = r2.base) and
  335. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  336. (r1.volatility + r2.volatility = []) then
  337. { In this case, it all depends on the offsets }
  338. Exit(abs(r1.offset - r2.offset) < Range);
  339. { There's a chance things MIGHT overlap, so take no chances }
  340. Result := True;
  341. end;
  342. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  343. begin
  344. Result:=(ref.offset=0) and
  345. (ref.scalefactor in [0,1]) and
  346. (ref.segment=NR_NO) and
  347. (ref.symbol=nil) and
  348. (ref.relsymbol=nil) and
  349. ((base=NR_INVALID) or
  350. (ref.base=base)) and
  351. ((index=NR_INVALID) or
  352. (ref.index=index)) and
  353. (ref.volatility=[]);
  354. end;
  355. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  356. begin
  357. Result:=(ref.scalefactor in [0,1]) and
  358. (ref.segment=NR_NO) and
  359. (ref.symbol=nil) and
  360. (ref.relsymbol=nil) and
  361. ((base=NR_INVALID) or
  362. (ref.base=base)) and
  363. ((index=NR_INVALID) or
  364. (ref.index=index)) and
  365. (ref.volatility=[]);
  366. end;
  367. function InstrReadsFlags(p: tai): boolean;
  368. begin
  369. InstrReadsFlags := true;
  370. case p.typ of
  371. ait_instruction:
  372. if InsProp[taicpu(p).opcode].Ch*
  373. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  374. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  375. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  376. exit;
  377. ait_label:
  378. exit;
  379. else
  380. ;
  381. end;
  382. InstrReadsFlags := false;
  383. end;
  384. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  385. begin
  386. Next:=Current;
  387. repeat
  388. Result:=GetNextInstruction(Next,Next);
  389. until not (Result) or
  390. not(cs_opt_level3 in current_settings.optimizerswitches) or
  391. (Next.typ<>ait_instruction) or
  392. RegInInstruction(reg,Next) or
  393. is_calljmp(taicpu(Next).opcode);
  394. end;
  395. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  396. var
  397. GetNextResult: Boolean;
  398. begin
  399. Result:=0;
  400. Next:=Current;
  401. repeat
  402. GetNextResult := GetNextInstruction(Next,Next);
  403. if GetNextResult then
  404. Inc(Result)
  405. else
  406. { Must return zero upon hitting the end of the linked list without a match }
  407. Result := 0;
  408. until not (GetNextResult) or
  409. not(cs_opt_level3 in current_settings.optimizerswitches) or
  410. (Next.typ<>ait_instruction) or
  411. RegInInstruction(reg,Next) or
  412. is_calljmp(taicpu(Next).opcode);
  413. end;
  414. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  415. procedure TrackJump(Symbol: TAsmSymbol);
  416. var
  417. Search: TJumpTrackingItem;
  418. begin
  419. { See if an entry already exists in our jump tracking list
  420. (faster to search backwards due to the higher chance of
  421. matching destinations) }
  422. Search := TJumpTrackingItem(JumpTracking.Last);
  423. while Assigned(Search) do
  424. begin
  425. if Search.Symbol = Symbol then
  426. begin
  427. { Found it - remove it so it can be pushed to the front }
  428. JumpTracking.Remove(Search);
  429. Break;
  430. end;
  431. Search := TJumpTrackingItem(Search.Previous);
  432. end;
  433. if not Assigned(Search) then
  434. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  435. JumpTracking.Concat(Search);
  436. Search.IncRefs;
  437. end;
  438. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  439. var
  440. Search: TJumpTrackingItem;
  441. begin
  442. Result := False;
  443. { See if this label appears in the tracking list }
  444. Search := TJumpTrackingItem(JumpTracking.Last);
  445. while Assigned(Search) do
  446. begin
  447. if Search.Symbol = Symbol then
  448. begin
  449. { Found it - let's see what we can discover }
  450. if Search.Symbol.getrefs = Search.Refs then
  451. begin
  452. { Success - all the references are accounted for }
  453. JumpTracking.Remove(Search);
  454. Search.Free;
  455. { It is logically impossible for CrossJump to be false here
  456. because we must have run into a conditional jump for
  457. this label at some point }
  458. if not CrossJump then
  459. InternalError(2022041710);
  460. if JumpTracking.First = nil then
  461. { Tracking list is now empty - no more cross jumps }
  462. CrossJump := False;
  463. Result := True;
  464. Exit;
  465. end;
  466. { If the references don't match, it's possible to enter
  467. this label through other means, so drop out }
  468. Exit;
  469. end;
  470. Search := TJumpTrackingItem(Search.Previous);
  471. end;
  472. end;
  473. var
  474. Next_Label: tai;
  475. begin
  476. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  477. Next := Current;
  478. repeat
  479. Result := GetNextInstruction(Next,Next);
  480. if not Result then
  481. Break;
  482. if Next.typ = ait_align then
  483. Result := SkipAligns(Next, Next);
  484. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  485. if is_calljmpuncondret(taicpu(Next).opcode) then
  486. begin
  487. if (taicpu(Next).opcode = A_JMP) and
  488. { Remove dead code now to save time }
  489. RemoveDeadCodeAfterJump(taicpu(Next)) then
  490. { A jump was removed, but not the current instruction, and
  491. Result doesn't necessarily translate into an optimisation
  492. routine's Result, so use the "Force New Iteration" flag so
  493. mark a new pass }
  494. Include(OptsToCheck, aoc_ForceNewIteration);
  495. if not Assigned(JumpTracking) then
  496. begin
  497. { Cross-label optimisations often causes other optimisations
  498. to perform worse because they're not given the chance to
  499. optimise locally. In this case, don't do the cross-label
  500. optimisations yet, but flag them as a potential possibility
  501. for the next iteration of Pass 1 }
  502. if not NotFirstIteration then
  503. Include(OptsToCheck, aoc_ForceNewIteration);
  504. end
  505. else if IsJumpToLabel(taicpu(Next)) and
  506. GetNextInstruction(Next, Next_Label) and
  507. SkipAligns(Next_Label, Next_Label) then
  508. begin
  509. { If we have JMP .lbl, and the label after it has all of its
  510. references tracked, then this is probably an if-else style of
  511. block and we can keep tracking. If the label for this jump
  512. then appears later and is fully tracked, then it's the end
  513. of the if-else blocks and the code paths converge (thus
  514. marking the end of the cross-jump) }
  515. if (Next_Label.typ = ait_label) then
  516. begin
  517. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  518. begin
  519. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  520. Next := Next_Label;
  521. { CrossJump gets set to false by LabelAccountedFor if the
  522. list is completely emptied (as it indicates that all
  523. code paths have converged). We could avoid this nuance
  524. by moving the TrackJump call to before the
  525. LabelAccountedFor call, but this is slower in situations
  526. where LabelAccountedFor would return False due to the
  527. creation of a new object that is not used and destroyed
  528. soon after. }
  529. CrossJump := True;
  530. Continue;
  531. end;
  532. end
  533. else if (Next_Label.typ <> ait_marker) then
  534. { We just did a RemoveDeadCodeAfterJump, so either we find
  535. a label, the end of the procedure or some kind of marker}
  536. InternalError(2022041720);
  537. end;
  538. Result := False;
  539. Exit;
  540. end
  541. else
  542. begin
  543. if not Assigned(JumpTracking) then
  544. begin
  545. { Cross-label optimisations often causes other optimisations
  546. to perform worse because they're not given the chance to
  547. optimise locally. In this case, don't do the cross-label
  548. optimisations yet, but flag them as a potential possibility
  549. for the next iteration of Pass 1 }
  550. if not NotFirstIteration then
  551. Include(OptsToCheck, aoc_ForceNewIteration);
  552. end
  553. else if IsJumpToLabel(taicpu(Next)) then
  554. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  555. else
  556. { Conditional jumps should always be a jump to label }
  557. InternalError(2022041701);
  558. CrossJump := True;
  559. Continue;
  560. end;
  561. if Next.typ = ait_label then
  562. begin
  563. if not Assigned(JumpTracking) then
  564. begin
  565. { Cross-label optimisations often causes other optimisations
  566. to perform worse because they're not given the chance to
  567. optimise locally. In this case, don't do the cross-label
  568. optimisations yet, but flag them as a potential possibility
  569. for the next iteration of Pass 1 }
  570. if not NotFirstIteration then
  571. Include(OptsToCheck, aoc_ForceNewIteration);
  572. end
  573. else if LabelAccountedFor(tai_label(Next).labsym) then
  574. Continue;
  575. { If we reach here, we're at a label that hasn't been seen before
  576. (or JumpTracking was nil) }
  577. Break;
  578. end;
  579. until not Result or
  580. not (cs_opt_level3 in current_settings.optimizerswitches) or
  581. not (Next.typ in [ait_label, ait_instruction]) or
  582. RegInInstruction(reg,Next);
  583. end;
  584. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  585. begin
  586. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  587. begin
  588. Result:=GetNextInstruction(Current,Next);
  589. exit;
  590. end;
  591. Next:=tai(Current.Next);
  592. Result:=false;
  593. while assigned(Next) do
  594. begin
  595. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  596. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  597. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  598. exit
  599. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  600. begin
  601. Result:=true;
  602. exit;
  603. end;
  604. Next:=tai(Next.Next);
  605. end;
  606. end;
  607. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  608. begin
  609. Result:=RegReadByInstruction(reg,hp);
  610. end;
  611. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  612. var
  613. p: taicpu;
  614. opcount: longint;
  615. begin
  616. RegReadByInstruction := false;
  617. if hp.typ <> ait_instruction then
  618. exit;
  619. p := taicpu(hp);
  620. case p.opcode of
  621. A_CALL:
  622. regreadbyinstruction := true;
  623. A_IMUL:
  624. case p.ops of
  625. 1:
  626. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  627. (
  628. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  629. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  630. );
  631. 2,3:
  632. regReadByInstruction :=
  633. reginop(reg,p.oper[0]^) or
  634. reginop(reg,p.oper[1]^);
  635. else
  636. InternalError(2019112801);
  637. end;
  638. A_MUL:
  639. begin
  640. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  641. (
  642. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  643. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  644. );
  645. end;
  646. A_IDIV,A_DIV:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. (getregtype(reg)=R_INTREGISTER) and
  651. (
  652. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  653. )
  654. );
  655. end;
  656. else
  657. begin
  658. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  659. begin
  660. RegReadByInstruction := false;
  661. exit;
  662. end;
  663. for opcount := 0 to p.ops-1 do
  664. if (p.oper[opCount]^.typ = top_ref) and
  665. RegInRef(reg,p.oper[opcount]^.ref^) then
  666. begin
  667. RegReadByInstruction := true;
  668. exit
  669. end;
  670. { special handling for SSE MOVSD }
  671. if (p.opcode=A_MOVSD) and (p.ops>0) then
  672. begin
  673. if p.ops<>2 then
  674. internalerror(2017042702);
  675. regReadByInstruction := reginop(reg,p.oper[0]^) or
  676. (
  677. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  678. );
  679. exit;
  680. end;
  681. with insprop[p.opcode] do
  682. begin
  683. case getregtype(reg) of
  684. R_INTREGISTER:
  685. begin
  686. case getsupreg(reg) of
  687. RS_EAX:
  688. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  689. begin
  690. RegReadByInstruction := true;
  691. exit
  692. end;
  693. RS_ECX:
  694. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  695. begin
  696. RegReadByInstruction := true;
  697. exit
  698. end;
  699. RS_EDX:
  700. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  701. begin
  702. RegReadByInstruction := true;
  703. exit
  704. end;
  705. RS_EBX:
  706. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  707. begin
  708. RegReadByInstruction := true;
  709. exit
  710. end;
  711. RS_ESP:
  712. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  713. begin
  714. RegReadByInstruction := true;
  715. exit
  716. end;
  717. RS_EBP:
  718. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  719. begin
  720. RegReadByInstruction := true;
  721. exit
  722. end;
  723. RS_ESI:
  724. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  725. begin
  726. RegReadByInstruction := true;
  727. exit
  728. end;
  729. RS_EDI:
  730. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  731. begin
  732. RegReadByInstruction := true;
  733. exit
  734. end;
  735. end;
  736. end;
  737. R_MMREGISTER:
  738. begin
  739. case getsupreg(reg) of
  740. RS_XMM0:
  741. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  742. begin
  743. RegReadByInstruction := true;
  744. exit
  745. end;
  746. end;
  747. end;
  748. else
  749. ;
  750. end;
  751. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  752. begin
  753. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  754. begin
  755. case p.condition of
  756. C_A,C_NBE, { CF=0 and ZF=0 }
  757. C_BE,C_NA: { CF=1 or ZF=1 }
  758. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  759. C_AE,C_NB,C_NC, { CF=0 }
  760. C_B,C_NAE,C_C: { CF=1 }
  761. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  762. C_NE,C_NZ, { ZF=0 }
  763. C_E,C_Z: { ZF=1 }
  764. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  765. C_G,C_NLE, { ZF=0 and SF=OF }
  766. C_LE,C_NG: { ZF=1 or SF<>OF }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  768. C_GE,C_NL, { SF=OF }
  769. C_L,C_NGE: { SF<>OF }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  771. C_NO, { OF=0 }
  772. C_O: { OF=1 }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  774. C_NP,C_PO, { PF=0 }
  775. C_P,C_PE: { PF=1 }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  777. C_NS, { SF=0 }
  778. C_S: { SF=1 }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  780. else
  781. internalerror(2017042701);
  782. end;
  783. if RegReadByInstruction then
  784. exit;
  785. end;
  786. case getsubreg(reg) of
  787. R_SUBW,R_SUBD,R_SUBQ:
  788. RegReadByInstruction :=
  789. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  790. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  791. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  792. R_SUBFLAGCARRY:
  793. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  794. R_SUBFLAGPARITY:
  795. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  796. R_SUBFLAGAUXILIARY:
  797. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  798. R_SUBFLAGZERO:
  799. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  800. R_SUBFLAGSIGN:
  801. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGOVERFLOW:
  803. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGINTERRUPT:
  805. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGDIRECTION:
  807. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. else
  809. internalerror(2017042601);
  810. end;
  811. exit;
  812. end;
  813. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  814. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  815. (p.oper[0]^.reg=p.oper[1]^.reg) then
  816. exit;
  817. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  818. begin
  819. RegReadByInstruction := true;
  820. exit
  821. end;
  822. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  823. begin
  824. RegReadByInstruction := true;
  825. exit
  826. end;
  827. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  828. begin
  829. RegReadByInstruction := true;
  830. exit
  831. end;
  832. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  833. begin
  834. RegReadByInstruction := true;
  835. exit
  836. end;
  837. end;
  838. end;
  839. end;
  840. end;
  841. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  842. begin
  843. result:=false;
  844. if p1.typ<>ait_instruction then
  845. exit;
  846. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  847. exit(true);
  848. if (getregtype(reg)=R_INTREGISTER) and
  849. { change information for xmm movsd are not correct }
  850. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  851. begin
  852. case getsupreg(reg) of
  853. { RS_EAX = RS_RAX on x86-64 }
  854. RS_EAX:
  855. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. RS_ECX:
  857. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  858. RS_EDX:
  859. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  860. RS_EBX:
  861. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  862. RS_ESP:
  863. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_EBP:
  865. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_ESI:
  867. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EDI:
  869. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. else
  871. ;
  872. end;
  873. if result then
  874. exit;
  875. end
  876. else if getregtype(reg)=R_MMREGISTER then
  877. begin
  878. case getsupreg(reg) of
  879. RS_XMM0:
  880. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. else
  882. ;
  883. end;
  884. if result then
  885. exit;
  886. end
  887. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  888. begin
  889. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  890. exit(true);
  891. case getsubreg(reg) of
  892. R_SUBFLAGCARRY:
  893. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  894. R_SUBFLAGPARITY:
  895. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  896. R_SUBFLAGAUXILIARY:
  897. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  898. R_SUBFLAGZERO:
  899. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  900. R_SUBFLAGSIGN:
  901. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGOVERFLOW:
  903. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGINTERRUPT:
  905. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGDIRECTION:
  907. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBW,R_SUBD,R_SUBQ:
  909. { Everything except the direction bits }
  910. Result:=
  911. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  912. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  913. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  914. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  915. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  916. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  917. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  918. else
  919. ;
  920. end;
  921. if result then
  922. exit;
  923. end
  924. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  925. exit(true);
  926. Result:=inherited RegInInstruction(Reg, p1);
  927. end;
  928. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  929. const
  930. WriteOps: array[0..3] of set of TInsChange =
  931. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  932. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  933. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  934. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  935. var
  936. OperIdx: Integer;
  937. begin
  938. Result := False;
  939. if p1.typ <> ait_instruction then
  940. exit;
  941. with insprop[taicpu(p1).opcode] do
  942. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  943. begin
  944. case getsubreg(reg) of
  945. R_SUBW,R_SUBD,R_SUBQ:
  946. Result :=
  947. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  948. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  949. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  950. R_SUBFLAGCARRY:
  951. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  952. R_SUBFLAGPARITY:
  953. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  954. R_SUBFLAGAUXILIARY:
  955. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  956. R_SUBFLAGZERO:
  957. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGSIGN:
  959. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGOVERFLOW:
  961. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGINTERRUPT:
  963. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGDIRECTION:
  965. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. else
  967. internalerror(2017042602);
  968. end;
  969. exit;
  970. end;
  971. case taicpu(p1).opcode of
  972. A_CALL:
  973. { We could potentially set Result to False if the register in
  974. question is non-volatile for the subroutine's calling convention,
  975. but this would require detecting the calling convention in use and
  976. also assuming that the routine doesn't contain malformed assembly
  977. language, for example... so it could only be done under -O4 as it
  978. would be considered a side-effect. [Kit] }
  979. Result := True;
  980. A_MOVSD:
  981. { special handling for SSE MOVSD }
  982. if (taicpu(p1).ops>0) then
  983. begin
  984. if taicpu(p1).ops<>2 then
  985. internalerror(2017042703);
  986. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  987. end;
  988. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  989. so fix it here (FK)
  990. }
  991. A_VMOVSS,
  992. A_VMOVSD:
  993. begin
  994. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  995. exit;
  996. end;
  997. A_IMUL:
  998. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  999. else
  1000. ;
  1001. end;
  1002. if Result then
  1003. exit;
  1004. with insprop[taicpu(p1).opcode] do
  1005. begin
  1006. if getregtype(reg)=R_INTREGISTER then
  1007. begin
  1008. case getsupreg(reg) of
  1009. RS_EAX:
  1010. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1011. begin
  1012. Result := True;
  1013. exit
  1014. end;
  1015. RS_ECX:
  1016. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1017. begin
  1018. Result := True;
  1019. exit
  1020. end;
  1021. RS_EDX:
  1022. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1023. begin
  1024. Result := True;
  1025. exit
  1026. end;
  1027. RS_EBX:
  1028. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1029. begin
  1030. Result := True;
  1031. exit
  1032. end;
  1033. RS_ESP:
  1034. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1035. begin
  1036. Result := True;
  1037. exit
  1038. end;
  1039. RS_EBP:
  1040. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1041. begin
  1042. Result := True;
  1043. exit
  1044. end;
  1045. RS_ESI:
  1046. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1047. begin
  1048. Result := True;
  1049. exit
  1050. end;
  1051. RS_EDI:
  1052. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1053. begin
  1054. Result := True;
  1055. exit
  1056. end;
  1057. end;
  1058. end;
  1059. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1060. if (WriteOps[OperIdx]*Ch<>[]) and
  1061. { The register doesn't get modified inside a reference }
  1062. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1063. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1064. begin
  1065. Result := true;
  1066. exit
  1067. end;
  1068. end;
  1069. end;
  1070. {$ifdef DEBUG_AOPTCPU}
  1071. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1072. begin
  1073. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1074. end;
  1075. function debug_tostr(i: tcgint): string; inline;
  1076. begin
  1077. Result := tostr(i);
  1078. end;
  1079. function debug_regname(r: TRegister): string; inline;
  1080. begin
  1081. Result := '%' + std_regname(r);
  1082. end;
  1083. { Debug output function - creates a string representation of an operator }
  1084. function debug_operstr(oper: TOper): string;
  1085. begin
  1086. case oper.typ of
  1087. top_const:
  1088. Result := '$' + debug_tostr(oper.val);
  1089. top_reg:
  1090. Result := debug_regname(oper.reg);
  1091. top_ref:
  1092. begin
  1093. if oper.ref^.offset <> 0 then
  1094. Result := debug_tostr(oper.ref^.offset) + '('
  1095. else
  1096. Result := '(';
  1097. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1098. begin
  1099. Result := Result + debug_regname(oper.ref^.base);
  1100. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1101. Result := Result + ',' + debug_regname(oper.ref^.index);
  1102. end
  1103. else
  1104. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1105. Result := Result + debug_regname(oper.ref^.index);
  1106. if (oper.ref^.scalefactor > 1) then
  1107. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1108. else
  1109. Result := Result + ')';
  1110. end;
  1111. else
  1112. Result := '[UNKNOWN]';
  1113. end;
  1114. end;
  1115. function debug_op2str(opcode: tasmop): string; inline;
  1116. begin
  1117. Result := std_op2str[opcode];
  1118. end;
  1119. function debug_opsize2str(opsize: topsize): string; inline;
  1120. begin
  1121. Result := gas_opsize2str[opsize];
  1122. end;
  1123. {$else DEBUG_AOPTCPU}
  1124. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1125. begin
  1126. end;
  1127. function debug_tostr(i: tcgint): string; inline;
  1128. begin
  1129. Result := '';
  1130. end;
  1131. function debug_regname(r: TRegister): string; inline;
  1132. begin
  1133. Result := '';
  1134. end;
  1135. function debug_operstr(oper: TOper): string; inline;
  1136. begin
  1137. Result := '';
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := '';
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := '';
  1146. end;
  1147. {$endif DEBUG_AOPTCPU}
  1148. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1149. begin
  1150. {$ifdef x86_64}
  1151. { Always fine on x86-64 }
  1152. Result := True;
  1153. {$else x86_64}
  1154. Result :=
  1155. {$ifdef i8086}
  1156. (current_settings.cputype >= cpu_386) and
  1157. {$endif i8086}
  1158. (
  1159. { Always accept if optimising for size }
  1160. (cs_opt_size in current_settings.optimizerswitches) or
  1161. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1162. (current_settings.optimizecputype >= cpu_Pentium2)
  1163. );
  1164. {$endif x86_64}
  1165. end;
  1166. { Attempts to allocate a volatile integer register for use between p and hp,
  1167. using AUsedRegs for the current register usage information. Returns NR_NO
  1168. if no free register could be found }
  1169. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1170. var
  1171. RegSet: TCPURegisterSet;
  1172. CurrentSuperReg: Integer;
  1173. CurrentReg: TRegister;
  1174. Currentp: tai;
  1175. Breakout: Boolean;
  1176. begin
  1177. Result := NR_NO;
  1178. RegSet :=
  1179. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1180. current_procinfo.saved_regs_int;
  1181. for CurrentSuperReg in RegSet do
  1182. begin
  1183. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1184. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1185. {$if defined(i386) or defined(i8086)}
  1186. { If the target size is 8-bit, make sure we can actually encode it }
  1187. and (
  1188. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1189. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1190. )
  1191. {$endif i386 or i8086}
  1192. then
  1193. begin
  1194. Currentp := p;
  1195. Breakout := False;
  1196. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1197. begin
  1198. case Currentp.typ of
  1199. ait_instruction:
  1200. begin
  1201. if RegInInstruction(CurrentReg, Currentp) then
  1202. begin
  1203. Breakout := True;
  1204. Break;
  1205. end;
  1206. { Cannot allocate across an unconditional jump }
  1207. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1208. Exit;
  1209. end;
  1210. ait_marker:
  1211. { Don't try anything more if a marker is hit }
  1212. Exit;
  1213. ait_regalloc:
  1214. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1215. begin
  1216. Breakout := True;
  1217. Break;
  1218. end;
  1219. else
  1220. ;
  1221. end;
  1222. end;
  1223. if Breakout then
  1224. { Try the next register }
  1225. Continue;
  1226. { We have a free register available }
  1227. Result := CurrentReg;
  1228. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1229. Exit;
  1230. end;
  1231. end;
  1232. end;
  1233. { Attempts to allocate a volatile MM register for use between p and hp,
  1234. using AUsedRegs for the current register usage information. Returns NR_NO
  1235. if no free register could be found }
  1236. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1237. var
  1238. RegSet: TCPURegisterSet;
  1239. CurrentSuperReg: Integer;
  1240. CurrentReg: TRegister;
  1241. Currentp: tai;
  1242. Breakout: Boolean;
  1243. begin
  1244. Result := NR_NO;
  1245. RegSet :=
  1246. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1247. current_procinfo.saved_regs_mm;
  1248. for CurrentSuperReg in RegSet do
  1249. begin
  1250. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1251. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1252. begin
  1253. Currentp := p;
  1254. Breakout := False;
  1255. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1256. begin
  1257. case Currentp.typ of
  1258. ait_instruction:
  1259. begin
  1260. if RegInInstruction(CurrentReg, Currentp) then
  1261. begin
  1262. Breakout := True;
  1263. Break;
  1264. end;
  1265. { Cannot allocate across an unconditional jump }
  1266. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1267. Exit;
  1268. end;
  1269. ait_marker:
  1270. { Don't try anything more if a marker is hit }
  1271. Exit;
  1272. ait_regalloc:
  1273. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1274. begin
  1275. Breakout := True;
  1276. Break;
  1277. end;
  1278. else
  1279. ;
  1280. end;
  1281. end;
  1282. if Breakout then
  1283. { Try the next register }
  1284. Continue;
  1285. { We have a free register available }
  1286. Result := CurrentReg;
  1287. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1288. Exit;
  1289. end;
  1290. end;
  1291. end;
  1292. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1293. begin
  1294. if not SuperRegistersEqual(reg1,reg2) then
  1295. exit(false);
  1296. if getregtype(reg1)<>R_INTREGISTER then
  1297. exit(true); {because SuperRegisterEqual is true}
  1298. case getsubreg(reg1) of
  1299. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1300. higher, it preserves the high bits, so the new value depends on
  1301. reg2's previous value. In other words, it is equivalent to doing:
  1302. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1303. R_SUBL:
  1304. exit(getsubreg(reg2)=R_SUBL);
  1305. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1306. higher, it actually does a:
  1307. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)=R_SUBH);
  1310. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1311. bits of reg2:
  1312. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1313. R_SUBW:
  1314. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1315. { a write to R_SUBD always overwrites every other subregister,
  1316. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1317. R_SUBD,
  1318. R_SUBQ:
  1319. exit(true);
  1320. else
  1321. internalerror(2017042801);
  1322. end;
  1323. end;
  1324. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1325. begin
  1326. if not SuperRegistersEqual(reg1,reg2) then
  1327. exit(false);
  1328. if getregtype(reg1)<>R_INTREGISTER then
  1329. exit(true); {because SuperRegisterEqual is true}
  1330. case getsubreg(reg1) of
  1331. R_SUBL:
  1332. exit(getsubreg(reg2)<>R_SUBH);
  1333. R_SUBH:
  1334. exit(getsubreg(reg2)<>R_SUBL);
  1335. R_SUBW,
  1336. R_SUBD,
  1337. R_SUBQ:
  1338. exit(true);
  1339. else
  1340. internalerror(2017042802);
  1341. end;
  1342. end;
  1343. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1344. var
  1345. hp1 : tai;
  1346. l : TCGInt;
  1347. begin
  1348. result:=false;
  1349. { changes the code sequence
  1350. shr/sar const1, x
  1351. shl const2, x
  1352. to
  1353. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1354. if GetNextInstruction(p, hp1) and
  1355. MatchInstruction(hp1,A_SHL,[]) and
  1356. (taicpu(p).oper[0]^.typ = top_const) and
  1357. (taicpu(hp1).oper[0]^.typ = top_const) and
  1358. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1359. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1360. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1361. begin
  1362. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1363. not(cs_opt_size in current_settings.optimizerswitches) then
  1364. begin
  1365. { shr/sar const1, %reg
  1366. shl const2, %reg
  1367. with const1 > const2 }
  1368. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1369. taicpu(hp1).opcode := A_AND;
  1370. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1371. case taicpu(p).opsize Of
  1372. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1373. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1374. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1375. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1376. else
  1377. Internalerror(2017050703)
  1378. end;
  1379. end
  1380. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1381. not(cs_opt_size in current_settings.optimizerswitches) then
  1382. begin
  1383. { shr/sar const1, %reg
  1384. shl const2, %reg
  1385. with const1 < const2 }
  1386. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1387. taicpu(p).opcode := A_AND;
  1388. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1389. case taicpu(p).opsize Of
  1390. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1391. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1392. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1393. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1394. else
  1395. Internalerror(2017050702)
  1396. end;
  1397. end
  1398. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1399. begin
  1400. { shr/sar const1, %reg
  1401. shl const2, %reg
  1402. with const1 = const2 }
  1403. taicpu(p).opcode := A_AND;
  1404. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1405. case taicpu(p).opsize Of
  1406. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1407. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1408. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1409. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1410. else
  1411. Internalerror(2017050701)
  1412. end;
  1413. RemoveInstruction(hp1);
  1414. end;
  1415. end;
  1416. end;
  1417. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1418. var
  1419. opsize : topsize;
  1420. hp1, hp2 : tai;
  1421. tmpref : treference;
  1422. ShiftValue : Cardinal;
  1423. BaseValue : TCGInt;
  1424. begin
  1425. result:=false;
  1426. opsize:=taicpu(p).opsize;
  1427. { changes certain "imul const, %reg"'s to lea sequences }
  1428. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1429. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1430. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1431. if (taicpu(p).oper[0]^.val = 1) then
  1432. if (taicpu(p).ops = 2) then
  1433. { remove "imul $1, reg" }
  1434. begin
  1435. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1436. Result := RemoveCurrentP(p);
  1437. end
  1438. else
  1439. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1440. begin
  1441. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1442. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1443. asml.InsertAfter(hp1, p);
  1444. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1445. RemoveCurrentP(p, hp1);
  1446. Result := True;
  1447. end
  1448. else if ((taicpu(p).ops <= 2) or
  1449. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1450. not(cs_opt_size in current_settings.optimizerswitches) and
  1451. (not(GetNextInstruction(p, hp1)) or
  1452. not((tai(hp1).typ = ait_instruction) and
  1453. ((taicpu(hp1).opcode=A_Jcc) and
  1454. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1455. begin
  1456. {
  1457. imul X, reg1, reg2 to
  1458. lea (reg1,reg1,Y), reg2
  1459. shl ZZ,reg2
  1460. imul XX, reg1 to
  1461. lea (reg1,reg1,YY), reg1
  1462. shl ZZ,reg2
  1463. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1464. it does not exist as a separate optimization target in FPC though.
  1465. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1466. at most two zeros
  1467. }
  1468. reference_reset(tmpref,1,[]);
  1469. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1470. begin
  1471. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1472. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1473. TmpRef.base := taicpu(p).oper[1]^.reg;
  1474. TmpRef.index := taicpu(p).oper[1]^.reg;
  1475. if not(BaseValue in [3,5,9]) then
  1476. Internalerror(2018110101);
  1477. TmpRef.ScaleFactor := BaseValue-1;
  1478. if (taicpu(p).ops = 2) then
  1479. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1480. else
  1481. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1482. AsmL.InsertAfter(hp1,p);
  1483. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1484. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1485. RemoveCurrentP(p, hp1);
  1486. if ShiftValue>0 then
  1487. begin
  1488. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1489. AsmL.InsertAfter(hp2,hp1);
  1490. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1491. end;
  1492. Result := True;
  1493. end;
  1494. end;
  1495. end;
  1496. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1497. begin
  1498. Result := False;
  1499. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1500. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1501. begin
  1502. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1503. taicpu(p).opcode := A_MOV;
  1504. Result := True;
  1505. end;
  1506. end;
  1507. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1508. var
  1509. p: taicpu absolute hp; { Implicit typecast }
  1510. i: Integer;
  1511. begin
  1512. Result := False;
  1513. if not assigned(hp) or
  1514. (hp.typ <> ait_instruction) then
  1515. Exit;
  1516. Prefetch(insprop[p.opcode]);
  1517. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1518. with insprop[p.opcode] do
  1519. begin
  1520. case getsubreg(reg) of
  1521. R_SUBW,R_SUBD,R_SUBQ:
  1522. Result:=
  1523. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1524. uncommon flags are checked first }
  1525. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1526. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1527. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1528. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1529. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1531. R_SUBFLAGCARRY:
  1532. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1533. R_SUBFLAGPARITY:
  1534. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1535. R_SUBFLAGAUXILIARY:
  1536. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1537. R_SUBFLAGZERO:
  1538. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1539. R_SUBFLAGSIGN:
  1540. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1541. R_SUBFLAGOVERFLOW:
  1542. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1543. R_SUBFLAGINTERRUPT:
  1544. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1545. R_SUBFLAGDIRECTION:
  1546. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1547. else
  1548. internalerror(2017050501);
  1549. end;
  1550. exit;
  1551. end;
  1552. { Handle special cases first }
  1553. case p.opcode of
  1554. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1555. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1556. begin
  1557. Result :=
  1558. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1559. (p.oper[1]^.typ = top_reg) and
  1560. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1561. (
  1562. (p.oper[0]^.typ = top_const) or
  1563. (
  1564. (p.oper[0]^.typ = top_reg) and
  1565. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1566. ) or (
  1567. (p.oper[0]^.typ = top_ref) and
  1568. not RegInRef(reg,p.oper[0]^.ref^)
  1569. )
  1570. );
  1571. end;
  1572. A_MUL, A_IMUL:
  1573. Result :=
  1574. (
  1575. (p.ops=3) and { IMUL only }
  1576. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1577. (
  1578. (
  1579. (p.oper[1]^.typ=top_reg) and
  1580. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1581. ) or (
  1582. (p.oper[1]^.typ=top_ref) and
  1583. not RegInRef(reg,p.oper[1]^.ref^)
  1584. )
  1585. )
  1586. ) or (
  1587. (
  1588. (p.ops=1) and
  1589. (
  1590. (
  1591. (
  1592. (p.oper[0]^.typ=top_reg) and
  1593. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1594. )
  1595. ) or (
  1596. (p.oper[0]^.typ=top_ref) and
  1597. not RegInRef(reg,p.oper[0]^.ref^)
  1598. )
  1599. ) and (
  1600. (
  1601. (p.opsize=S_B) and
  1602. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1603. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1604. ) or (
  1605. (p.opsize=S_W) and
  1606. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1607. ) or (
  1608. (p.opsize=S_L) and
  1609. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1610. {$ifdef x86_64}
  1611. ) or (
  1612. (p.opsize=S_Q) and
  1613. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1614. {$endif x86_64}
  1615. )
  1616. )
  1617. )
  1618. );
  1619. A_CBW:
  1620. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1621. {$ifndef x86_64}
  1622. A_LDS:
  1623. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1624. A_LES:
  1625. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1626. {$endif not x86_64}
  1627. A_LFS:
  1628. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1629. A_LGS:
  1630. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1631. A_LSS:
  1632. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1633. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1634. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1635. A_LODSB:
  1636. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1637. A_LODSW:
  1638. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1639. {$ifdef x86_64}
  1640. A_LODSQ:
  1641. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1642. {$endif x86_64}
  1643. A_LODSD:
  1644. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1645. A_FSTSW, A_FNSTSW:
  1646. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1647. else
  1648. begin
  1649. with insprop[p.opcode] do
  1650. begin
  1651. if (
  1652. { xor %reg,%reg etc. is classed as a new value }
  1653. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1654. MatchOpType(p, top_reg, top_reg) and
  1655. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1656. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1657. ) then
  1658. begin
  1659. Result := True;
  1660. Exit;
  1661. end;
  1662. { Make sure the entire register is overwritten }
  1663. if (getregtype(reg) = R_INTREGISTER) then
  1664. begin
  1665. if (p.ops > 0) then
  1666. begin
  1667. if RegInOp(reg, p.oper[0]^) then
  1668. begin
  1669. if (p.oper[0]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[0]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[0]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp1]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 1) then
  1697. begin
  1698. if RegInOp(reg, p.oper[1]^) then
  1699. begin
  1700. if (p.oper[1]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[1]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[1]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp2]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 2) then
  1728. begin
  1729. if RegInOp(reg, p.oper[2]^) then
  1730. begin
  1731. if (p.oper[2]^.typ = top_ref) then
  1732. begin
  1733. if RegInRef(reg, p.oper[2]^.ref^) then
  1734. begin
  1735. Result := False;
  1736. Exit;
  1737. end;
  1738. end
  1739. else if (p.oper[2]^.typ = top_reg) then
  1740. begin
  1741. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1742. begin
  1743. Result := False;
  1744. Exit;
  1745. end
  1746. else if ([Ch_WOp3]*Ch<>[]) then
  1747. begin
  1748. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1749. Result := True
  1750. else
  1751. begin
  1752. Result := False;
  1753. Exit;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1759. begin
  1760. if (p.oper[3]^.typ = top_ref) then
  1761. begin
  1762. if RegInRef(reg, p.oper[3]^.ref^) then
  1763. begin
  1764. Result := False;
  1765. Exit;
  1766. end;
  1767. end
  1768. else if (p.oper[3]^.typ = top_reg) then
  1769. begin
  1770. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1771. begin
  1772. Result := False;
  1773. Exit;
  1774. end
  1775. else if ([Ch_WOp4]*Ch<>[]) then
  1776. begin
  1777. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1778. Result := True
  1779. else
  1780. begin
  1781. Result := False;
  1782. Exit;
  1783. end;
  1784. end;
  1785. end;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1791. case getsupreg(reg) of
  1792. RS_EAX:
  1793. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1794. begin
  1795. Result := True;
  1796. Exit;
  1797. end;
  1798. RS_ECX:
  1799. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1800. begin
  1801. Result := True;
  1802. Exit;
  1803. end;
  1804. RS_EDX:
  1805. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1806. begin
  1807. Result := True;
  1808. Exit;
  1809. end;
  1810. RS_EBX:
  1811. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1812. begin
  1813. Result := True;
  1814. Exit;
  1815. end;
  1816. RS_ESP:
  1817. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1818. begin
  1819. Result := True;
  1820. Exit;
  1821. end;
  1822. RS_EBP:
  1823. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1824. begin
  1825. Result := True;
  1826. Exit;
  1827. end;
  1828. RS_ESI:
  1829. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1830. begin
  1831. Result := True;
  1832. Exit;
  1833. end;
  1834. RS_EDI:
  1835. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1836. begin
  1837. Result := True;
  1838. Exit;
  1839. end;
  1840. else
  1841. ;
  1842. end;
  1843. end;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1849. var
  1850. hp2,hp3 : tai;
  1851. begin
  1852. { some x86-64 issue a NOP before the real exit code }
  1853. if MatchInstruction(p,A_NOP,[]) then
  1854. GetNextInstruction(p,p);
  1855. result:=assigned(p) and (p.typ=ait_instruction) and
  1856. ((taicpu(p).opcode = A_RET) or
  1857. ((taicpu(p).opcode=A_LEAVE) and
  1858. GetNextInstruction(p,hp2) and
  1859. MatchInstruction(hp2,A_RET,[S_NO])
  1860. ) or
  1861. (((taicpu(p).opcode=A_LEA) and
  1862. MatchOpType(taicpu(p),top_ref,top_reg) and
  1863. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1864. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1865. ) and
  1866. GetNextInstruction(p,hp2) and
  1867. MatchInstruction(hp2,A_RET,[S_NO])
  1868. ) or
  1869. ((((taicpu(p).opcode=A_MOV) and
  1870. MatchOpType(taicpu(p),top_reg,top_reg) and
  1871. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1872. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1873. ((taicpu(p).opcode=A_LEA) and
  1874. MatchOpType(taicpu(p),top_ref,top_reg) and
  1875. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1876. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1877. )
  1878. ) and
  1879. GetNextInstruction(p,hp2) and
  1880. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1881. MatchOpType(taicpu(hp2),top_reg) and
  1882. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1883. GetNextInstruction(hp2,hp3) and
  1884. MatchInstruction(hp3,A_RET,[S_NO])
  1885. )
  1886. );
  1887. end;
  1888. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1889. begin
  1890. isFoldableArithOp := False;
  1891. case hp1.opcode of
  1892. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1893. isFoldableArithOp :=
  1894. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1895. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1896. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1897. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1898. (taicpu(hp1).oper[1]^.reg = reg);
  1899. A_INC,A_DEC,A_NEG,A_NOT:
  1900. isFoldableArithOp :=
  1901. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1902. (taicpu(hp1).oper[0]^.reg = reg);
  1903. else
  1904. ;
  1905. end;
  1906. end;
  1907. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1908. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1909. var
  1910. hp2: tai;
  1911. begin
  1912. hp2 := p;
  1913. repeat
  1914. hp2 := tai(hp2.previous);
  1915. if assigned(hp2) and
  1916. (hp2.typ = ait_regalloc) and
  1917. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1918. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1919. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1920. begin
  1921. RemoveInstruction(hp2);
  1922. break;
  1923. end;
  1924. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1925. end;
  1926. begin
  1927. case current_procinfo.procdef.returndef.typ of
  1928. arraydef,recorddef,pointerdef,
  1929. stringdef,enumdef,procdef,objectdef,errordef,
  1930. filedef,setdef,procvardef,
  1931. classrefdef,forwarddef:
  1932. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1933. orddef:
  1934. if current_procinfo.procdef.returndef.size <> 0 then
  1935. begin
  1936. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1937. { for int64/qword }
  1938. if current_procinfo.procdef.returndef.size = 8 then
  1939. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1940. end;
  1941. else
  1942. ;
  1943. end;
  1944. end;
  1945. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1946. var
  1947. hp1,hp2 : tai;
  1948. begin
  1949. result:=false;
  1950. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1951. begin
  1952. { vmova* reg1,reg1
  1953. =>
  1954. <nop> }
  1955. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1956. begin
  1957. RemoveCurrentP(p);
  1958. result:=true;
  1959. exit;
  1960. end
  1961. else if GetNextInstruction(p,hp1) then
  1962. begin
  1963. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1964. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1965. begin
  1966. { vmova* reg1,reg2
  1967. vmova* reg2,reg3
  1968. dealloc reg2
  1969. =>
  1970. vmova* reg1,reg3 }
  1971. TransferUsedRegs(TmpUsedRegs);
  1972. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1973. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1974. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1975. begin
  1976. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1977. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1978. RemoveInstruction(hp1);
  1979. result:=true;
  1980. exit;
  1981. end
  1982. { special case:
  1983. vmova* reg1,<op>
  1984. vmova* <op>,reg1
  1985. =>
  1986. vmova* reg1,<op> }
  1987. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1988. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1989. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1990. ) then
  1991. begin
  1992. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1993. RemoveInstruction(hp1);
  1994. result:=true;
  1995. exit;
  1996. end
  1997. end
  1998. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1999. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2000. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2001. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2002. ) and
  2003. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2004. begin
  2005. { vmova* reg1,reg2
  2006. vmovs* reg2,<op>
  2007. dealloc reg2
  2008. =>
  2009. vmovs* reg1,reg3 }
  2010. TransferUsedRegs(TmpUsedRegs);
  2011. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2012. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2013. begin
  2014. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2015. taicpu(p).opcode:=taicpu(hp1).opcode;
  2016. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2017. RemoveInstruction(hp1);
  2018. result:=true;
  2019. exit;
  2020. end
  2021. end;
  2022. end;
  2023. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2024. begin
  2025. if MatchInstruction(hp1,[A_VFMADDPD,
  2026. A_VFMADD132PD,
  2027. A_VFMADD132PS,
  2028. A_VFMADD132SD,
  2029. A_VFMADD132SS,
  2030. A_VFMADD213PD,
  2031. A_VFMADD213PS,
  2032. A_VFMADD213SD,
  2033. A_VFMADD213SS,
  2034. A_VFMADD231PD,
  2035. A_VFMADD231PS,
  2036. A_VFMADD231SD,
  2037. A_VFMADD231SS,
  2038. A_VFMADDSUB132PD,
  2039. A_VFMADDSUB132PS,
  2040. A_VFMADDSUB213PD,
  2041. A_VFMADDSUB213PS,
  2042. A_VFMADDSUB231PD,
  2043. A_VFMADDSUB231PS,
  2044. A_VFMSUB132PD,
  2045. A_VFMSUB132PS,
  2046. A_VFMSUB132SD,
  2047. A_VFMSUB132SS,
  2048. A_VFMSUB213PD,
  2049. A_VFMSUB213PS,
  2050. A_VFMSUB213SD,
  2051. A_VFMSUB213SS,
  2052. A_VFMSUB231PD,
  2053. A_VFMSUB231PS,
  2054. A_VFMSUB231SD,
  2055. A_VFMSUB231SS,
  2056. A_VFMSUBADD132PD,
  2057. A_VFMSUBADD132PS,
  2058. A_VFMSUBADD213PD,
  2059. A_VFMSUBADD213PS,
  2060. A_VFMSUBADD231PD,
  2061. A_VFMSUBADD231PS,
  2062. A_VFNMADD132PD,
  2063. A_VFNMADD132PS,
  2064. A_VFNMADD132SD,
  2065. A_VFNMADD132SS,
  2066. A_VFNMADD213PD,
  2067. A_VFNMADD213PS,
  2068. A_VFNMADD213SD,
  2069. A_VFNMADD213SS,
  2070. A_VFNMADD231PD,
  2071. A_VFNMADD231PS,
  2072. A_VFNMADD231SD,
  2073. A_VFNMADD231SS,
  2074. A_VFNMSUB132PD,
  2075. A_VFNMSUB132PS,
  2076. A_VFNMSUB132SD,
  2077. A_VFNMSUB132SS,
  2078. A_VFNMSUB213PD,
  2079. A_VFNMSUB213PS,
  2080. A_VFNMSUB213SD,
  2081. A_VFNMSUB213SS,
  2082. A_VFNMSUB231PD,
  2083. A_VFNMSUB231PS,
  2084. A_VFNMSUB231SD,
  2085. A_VFNMSUB231SS],[S_NO]) and
  2086. { we mix single and double opperations here because we assume that the compiler
  2087. generates vmovapd only after double operations and vmovaps only after single operations }
  2088. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2089. GetNextInstruction(hp1,hp2) and
  2090. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2091. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2099. RemoveCurrentP(p);
  2100. RemoveInstruction(hp2);
  2101. end;
  2102. end
  2103. else if (hp1.typ = ait_instruction) and
  2104. GetNextInstruction(hp1, hp2) and
  2105. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2106. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2107. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2108. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2109. (((taicpu(p).opcode=A_MOVAPS) and
  2110. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2111. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2112. ((taicpu(p).opcode=A_MOVAPD) and
  2113. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2114. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2115. ) then
  2116. { change
  2117. movapX reg,reg2
  2118. addsX/subsX/... reg3, reg2
  2119. movapX reg2,reg
  2120. to
  2121. addsX/subsX/... reg3,reg
  2122. }
  2123. begin
  2124. TransferUsedRegs(TmpUsedRegs);
  2125. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2126. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2127. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2128. begin
  2129. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2130. debug_op2str(taicpu(p).opcode)+' '+
  2131. debug_op2str(taicpu(hp1).opcode)+' '+
  2132. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2133. { we cannot eliminate the first move if
  2134. the operations uses the same register for source and dest }
  2135. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2136. { Remember that hp1 is not necessarily the immediate
  2137. next instruction }
  2138. RemoveCurrentP(p);
  2139. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2140. RemoveInstruction(hp2);
  2141. result:=true;
  2142. end;
  2143. end
  2144. else if (hp1.typ = ait_instruction) and
  2145. (((taicpu(p).opcode=A_VMOVAPD) and
  2146. (taicpu(hp1).opcode=A_VCOMISD)) or
  2147. ((taicpu(p).opcode=A_VMOVAPS) and
  2148. ((taicpu(hp1).opcode=A_VCOMISS))
  2149. )
  2150. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2151. { change
  2152. movapX reg,reg1
  2153. vcomisX reg1,reg1
  2154. to
  2155. vcomisX reg,reg
  2156. }
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2160. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2163. debug_op2str(taicpu(p).opcode)+' '+
  2164. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2165. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2166. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2167. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2168. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2169. RemoveCurrentP(p);
  2170. result:=true;
  2171. exit;
  2172. end;
  2173. end
  2174. end;
  2175. end;
  2176. end;
  2177. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2178. var
  2179. hp1 : tai;
  2180. begin
  2181. result:=false;
  2182. { replace
  2183. V<Op>X %mreg1,%mreg2,%mreg3
  2184. VMovX %mreg3,%mreg4
  2185. dealloc %mreg3
  2186. by
  2187. V<Op>X %mreg1,%mreg2,%mreg4
  2188. ?
  2189. }
  2190. if GetNextInstruction(p,hp1) and
  2191. { we mix single and double operations here because we assume that the compiler
  2192. generates vmovapd only after double operations and vmovaps only after single operations }
  2193. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2194. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2195. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2196. begin
  2197. TransferUsedRegs(TmpUsedRegs);
  2198. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2199. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2200. begin
  2201. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2202. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2203. RemoveInstruction(hp1);
  2204. result:=true;
  2205. end;
  2206. end;
  2207. end;
  2208. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2209. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2210. begin
  2211. Result := False;
  2212. { For safety reasons, only check for exact register matches }
  2213. { Check base register }
  2214. if (ref.base = AOldReg) then
  2215. begin
  2216. ref.base := ANewReg;
  2217. Result := True;
  2218. end;
  2219. { Check index register }
  2220. if (ref.index = AOldReg) then
  2221. begin
  2222. ref.index := ANewReg;
  2223. Result := True;
  2224. end;
  2225. end;
  2226. { Replaces all references to AOldReg in an operand to ANewReg }
  2227. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2228. var
  2229. OldSupReg, NewSupReg: TSuperRegister;
  2230. OldSubReg, NewSubReg: TSubRegister;
  2231. OldRegType: TRegisterType;
  2232. ThisOper: POper;
  2233. begin
  2234. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2235. Result := False;
  2236. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2237. InternalError(2020011801);
  2238. OldSupReg := getsupreg(AOldReg);
  2239. OldSubReg := getsubreg(AOldReg);
  2240. OldRegType := getregtype(AOldReg);
  2241. NewSupReg := getsupreg(ANewReg);
  2242. NewSubReg := getsubreg(ANewReg);
  2243. if OldRegType <> getregtype(ANewReg) then
  2244. InternalError(2020011802);
  2245. if OldSubReg <> NewSubReg then
  2246. InternalError(2020011803);
  2247. case ThisOper^.typ of
  2248. top_reg:
  2249. if (
  2250. (ThisOper^.reg = AOldReg) or
  2251. (
  2252. (OldRegType = R_INTREGISTER) and
  2253. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2254. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2255. (
  2256. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2257. {$ifndef x86_64}
  2258. and (
  2259. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2260. don't have an 8-bit representation }
  2261. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2262. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2263. )
  2264. {$endif x86_64}
  2265. )
  2266. )
  2267. ) then
  2268. begin
  2269. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2270. Result := True;
  2271. end;
  2272. top_ref:
  2273. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2274. Result := True;
  2275. else
  2276. ;
  2277. end;
  2278. end;
  2279. { Replaces all references to AOldReg in an instruction to ANewReg }
  2280. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2281. const
  2282. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2283. var
  2284. OperIdx: Integer;
  2285. begin
  2286. Result := False;
  2287. for OperIdx := 0 to p.ops - 1 do
  2288. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2289. begin
  2290. { The shift and rotate instructions can only use CL }
  2291. if not (
  2292. (OperIdx = 0) and
  2293. { This second condition just helps to avoid unnecessarily
  2294. calling MatchInstruction for 10 different opcodes }
  2295. (p.oper[0]^.reg = NR_CL) and
  2296. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2297. ) then
  2298. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2299. end
  2300. else if p.oper[OperIdx]^.typ = top_ref then
  2301. { It's okay to replace registers in references that get written to }
  2302. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2303. end;
  2304. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2305. begin
  2306. with ref^ do
  2307. Result :=
  2308. (index = NR_NO) and
  2309. (
  2310. {$ifdef x86_64}
  2311. (
  2312. (base = NR_RIP) and
  2313. (refaddr in [addr_pic, addr_pic_no_got])
  2314. ) or
  2315. {$endif x86_64}
  2316. (base = NR_STACK_POINTER_REG) or
  2317. (base = current_procinfo.framepointer)
  2318. );
  2319. end;
  2320. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2321. var
  2322. l: asizeint;
  2323. begin
  2324. Result := False;
  2325. { Should have been checked previously }
  2326. if p.opcode <> A_LEA then
  2327. InternalError(2020072501);
  2328. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2329. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2330. not(cs_opt_size in current_settings.optimizerswitches) then
  2331. exit;
  2332. with p.oper[0]^.ref^ do
  2333. begin
  2334. if (base <> p.oper[1]^.reg) or
  2335. (index <> NR_NO) or
  2336. assigned(symbol) then
  2337. exit;
  2338. l:=offset;
  2339. if (l=1) and UseIncDec then
  2340. begin
  2341. p.opcode:=A_INC;
  2342. p.loadreg(0,p.oper[1]^.reg);
  2343. p.ops:=1;
  2344. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2345. end
  2346. else if (l=-1) and UseIncDec then
  2347. begin
  2348. p.opcode:=A_DEC;
  2349. p.loadreg(0,p.oper[1]^.reg);
  2350. p.ops:=1;
  2351. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2352. end
  2353. else
  2354. begin
  2355. if (l<0) and (l<>-2147483648) then
  2356. begin
  2357. p.opcode:=A_SUB;
  2358. p.loadConst(0,-l);
  2359. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2360. end
  2361. else
  2362. begin
  2363. p.opcode:=A_ADD;
  2364. p.loadConst(0,l);
  2365. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2366. end;
  2367. end;
  2368. end;
  2369. Result := True;
  2370. end;
  2371. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2372. var
  2373. CurrentReg, ReplaceReg: TRegister;
  2374. begin
  2375. Result := False;
  2376. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2377. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2378. case hp.opcode of
  2379. A_FSTSW, A_FNSTSW,
  2380. A_IN, A_INS, A_OUT, A_OUTS,
  2381. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2382. { These routines have explicit operands, but they are restricted in
  2383. what they can be (e.g. IN and OUT can only read from AL, AX or
  2384. EAX. }
  2385. Exit;
  2386. A_IMUL:
  2387. begin
  2388. { The 1-operand version writes to implicit registers
  2389. The 2-operand version reads from the first operator, and reads
  2390. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2391. the 3-operand version reads from a register that it doesn't write to
  2392. }
  2393. case hp.ops of
  2394. 1:
  2395. if (
  2396. (
  2397. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2398. ) or
  2399. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2400. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2401. begin
  2402. Result := True;
  2403. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2404. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2405. end;
  2406. 2:
  2407. { Only modify the first parameter }
  2408. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2409. begin
  2410. Result := True;
  2411. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2412. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2413. end;
  2414. 3:
  2415. { Only modify the second parameter }
  2416. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2417. begin
  2418. Result := True;
  2419. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2420. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2421. end;
  2422. else
  2423. InternalError(2020012901);
  2424. end;
  2425. end;
  2426. else
  2427. if (hp.ops > 0) and
  2428. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2429. begin
  2430. Result := True;
  2431. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2432. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2433. end;
  2434. end;
  2435. end;
  2436. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2437. var
  2438. hp1, hp2, hp3: tai;
  2439. DoOptimisation, TempBool: Boolean;
  2440. {$ifdef x86_64}
  2441. NewConst: TCGInt;
  2442. {$endif x86_64}
  2443. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2444. begin
  2445. if taicpu(hp1).opcode = signed_movop then
  2446. begin
  2447. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2448. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2449. end
  2450. else
  2451. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2452. end;
  2453. function TryConstMerge(var p1, p2: tai): Boolean;
  2454. var
  2455. ThisRef: TReference;
  2456. begin
  2457. Result := False;
  2458. ThisRef := taicpu(p2).oper[1]^.ref^;
  2459. { Only permit writes to the stack, since we can guarantee alignment with that }
  2460. if (ThisRef.index = NR_NO) and
  2461. (
  2462. (ThisRef.base = NR_STACK_POINTER_REG) or
  2463. (ThisRef.base = current_procinfo.framepointer)
  2464. ) then
  2465. begin
  2466. case taicpu(p).opsize of
  2467. S_B:
  2468. begin
  2469. { Word writes must be on a 2-byte boundary }
  2470. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2471. begin
  2472. { Reduce offset of second reference to see if it is sequential with the first }
  2473. Dec(ThisRef.offset, 1);
  2474. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2475. begin
  2476. { Make sure the constants aren't represented as a
  2477. negative number, as these won't merge properly }
  2478. taicpu(p1).opsize := S_W;
  2479. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2480. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2481. RemoveInstruction(p2);
  2482. Result := True;
  2483. end;
  2484. end;
  2485. end;
  2486. S_W:
  2487. begin
  2488. { Longword writes must be on a 4-byte boundary }
  2489. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2490. begin
  2491. { Reduce offset of second reference to see if it is sequential with the first }
  2492. Dec(ThisRef.offset, 2);
  2493. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2494. begin
  2495. { Make sure the constants aren't represented as a
  2496. negative number, as these won't merge properly }
  2497. taicpu(p1).opsize := S_L;
  2498. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2499. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2500. RemoveInstruction(p2);
  2501. Result := True;
  2502. end;
  2503. end;
  2504. end;
  2505. {$ifdef x86_64}
  2506. S_L:
  2507. begin
  2508. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2509. see if the constants can be encoded this way. }
  2510. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2511. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2512. { Quadword writes must be on an 8-byte boundary }
  2513. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2514. begin
  2515. { Reduce offset of second reference to see if it is sequential with the first }
  2516. Dec(ThisRef.offset, 4);
  2517. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2518. begin
  2519. { Make sure the constants aren't represented as a
  2520. negative number, as these won't merge properly }
  2521. taicpu(p1).opsize := S_Q;
  2522. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2523. taicpu(p1).oper[0]^.val := NewConst;
  2524. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2525. RemoveInstruction(p2);
  2526. Result := True;
  2527. end;
  2528. end;
  2529. end;
  2530. {$endif x86_64}
  2531. else
  2532. ;
  2533. end;
  2534. end;
  2535. end;
  2536. var
  2537. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2538. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2539. NewSize: topsize; NewOffset: asizeint;
  2540. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2541. SourceRef, TargetRef: TReference;
  2542. MovAligned, MovUnaligned: TAsmOp;
  2543. ThisRef: TReference;
  2544. JumpTracking: TLinkedList;
  2545. begin
  2546. Result:=false;
  2547. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2548. { remove mov reg1,reg1? }
  2549. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2550. then
  2551. begin
  2552. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2553. { take care of the register (de)allocs following p }
  2554. RemoveCurrentP(p, hp1);
  2555. Result:=true;
  2556. exit;
  2557. end;
  2558. { All the next optimisations require a next instruction }
  2559. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2560. Exit;
  2561. { Prevent compiler warnings }
  2562. p_TargetReg := NR_NO;
  2563. if taicpu(p).oper[1]^.typ = top_reg then
  2564. begin
  2565. { Saves on a large number of dereferences }
  2566. p_TargetReg := taicpu(p).oper[1]^.reg;
  2567. { Look for:
  2568. mov %reg1,%reg2
  2569. ??? %reg2,r/m
  2570. Change to:
  2571. mov %reg1,%reg2
  2572. ??? %reg1,r/m
  2573. }
  2574. if taicpu(p).oper[0]^.typ = top_reg then
  2575. begin
  2576. if RegReadByInstruction(p_TargetReg, hp1) and
  2577. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2578. begin
  2579. { A change has occurred, just not in p }
  2580. Result := True;
  2581. TransferUsedRegs(TmpUsedRegs);
  2582. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2583. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2584. { Just in case something didn't get modified (e.g. an
  2585. implicit register) }
  2586. not RegReadByInstruction(p_TargetReg, hp1) then
  2587. begin
  2588. { We can remove the original MOV }
  2589. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2590. RemoveCurrentp(p, hp1);
  2591. { UsedRegs got updated by RemoveCurrentp }
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. { If we know a MOV instruction has become a null operation, we might as well
  2596. get rid of it now to save time. }
  2597. if (taicpu(hp1).opcode = A_MOV) and
  2598. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2599. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2600. { Just being a register is enough to confirm it's a null operation }
  2601. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2602. begin
  2603. Result := True;
  2604. { Speed-up to reduce a pipeline stall... if we had something like...
  2605. movl %eax,%edx
  2606. movw %dx,%ax
  2607. ... the second instruction would change to movw %ax,%ax, but
  2608. given that it is now %ax that's active rather than %eax,
  2609. penalties might occur due to a partial register write, so instead,
  2610. change it to a MOVZX instruction when optimising for speed.
  2611. }
  2612. if not (cs_opt_size in current_settings.optimizerswitches) and
  2613. IsMOVZXAcceptable and
  2614. (taicpu(hp1).opsize < taicpu(p).opsize)
  2615. {$ifdef x86_64}
  2616. { operations already implicitly set the upper 64 bits to zero }
  2617. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2618. {$endif x86_64}
  2619. then
  2620. begin
  2621. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2622. case taicpu(p).opsize of
  2623. S_W:
  2624. if taicpu(hp1).opsize = S_B then
  2625. taicpu(hp1).opsize := S_BL
  2626. else
  2627. InternalError(2020012911);
  2628. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2629. case taicpu(hp1).opsize of
  2630. S_B:
  2631. taicpu(hp1).opsize := S_BL;
  2632. S_W:
  2633. taicpu(hp1).opsize := S_WL;
  2634. else
  2635. InternalError(2020012912);
  2636. end;
  2637. else
  2638. InternalError(2020012910);
  2639. end;
  2640. taicpu(hp1).opcode := A_MOVZX;
  2641. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2642. end
  2643. else
  2644. begin
  2645. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2646. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2647. RemoveInstruction(hp1);
  2648. { The instruction after what was hp1 is now the immediate next instruction,
  2649. so we can continue to make optimisations if it's present }
  2650. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2651. Exit;
  2652. hp1 := hp2;
  2653. end;
  2654. end;
  2655. end;
  2656. end;
  2657. end;
  2658. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2659. overwrites the original destination register. e.g.
  2660. movl ###,%reg2d
  2661. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2662. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2663. }
  2664. if (taicpu(p).oper[1]^.typ = top_reg) and
  2665. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2666. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2667. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2668. begin
  2669. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2670. begin
  2671. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2672. case taicpu(p).oper[0]^.typ of
  2673. top_const:
  2674. { We have something like:
  2675. movb $x, %regb
  2676. movzbl %regb,%regd
  2677. Change to:
  2678. movl $x, %regd
  2679. }
  2680. begin
  2681. case taicpu(hp1).opsize of
  2682. S_BW:
  2683. begin
  2684. convert_mov_value(A_MOVSX, $FF);
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2686. taicpu(p).opsize := S_W;
  2687. end;
  2688. S_BL:
  2689. begin
  2690. convert_mov_value(A_MOVSX, $FF);
  2691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2692. taicpu(p).opsize := S_L;
  2693. end;
  2694. S_WL:
  2695. begin
  2696. convert_mov_value(A_MOVSX, $FFFF);
  2697. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2698. taicpu(p).opsize := S_L;
  2699. end;
  2700. {$ifdef x86_64}
  2701. S_BQ:
  2702. begin
  2703. convert_mov_value(A_MOVSX, $FF);
  2704. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2705. taicpu(p).opsize := S_Q;
  2706. end;
  2707. S_WQ:
  2708. begin
  2709. convert_mov_value(A_MOVSX, $FFFF);
  2710. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2711. taicpu(p).opsize := S_Q;
  2712. end;
  2713. S_LQ:
  2714. begin
  2715. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2716. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2717. taicpu(p).opsize := S_Q;
  2718. end;
  2719. {$endif x86_64}
  2720. else
  2721. { If hp1 was a MOV instruction, it should have been
  2722. optimised already }
  2723. InternalError(2020021001);
  2724. end;
  2725. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2726. RemoveInstruction(hp1);
  2727. Result := True;
  2728. Exit;
  2729. end;
  2730. top_ref:
  2731. begin
  2732. { We have something like:
  2733. movb mem, %regb
  2734. movzbl %regb,%regd
  2735. Change to:
  2736. movzbl mem, %regd
  2737. }
  2738. ThisRef := taicpu(p).oper[0]^.ref^;
  2739. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2740. begin
  2741. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2742. taicpu(hp1).loadref(0, ThisRef);
  2743. { Make sure any registers in the references are properly tracked }
  2744. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2745. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2746. if (ThisRef.index <> NR_NO) then
  2747. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2748. RemoveCurrentP(p, hp1);
  2749. Result := True;
  2750. Exit;
  2751. end;
  2752. end;
  2753. else
  2754. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2755. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2756. Exit;
  2757. end;
  2758. end
  2759. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2760. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2761. optimised }
  2762. else
  2763. begin
  2764. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2765. RemoveCurrentP(p, hp1);
  2766. Result := True;
  2767. Exit;
  2768. end;
  2769. end;
  2770. if (taicpu(hp1).opcode = A_AND) and
  2771. (taicpu(p).oper[1]^.typ = top_reg) and
  2772. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2773. begin
  2774. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2775. begin
  2776. case taicpu(p).opsize of
  2777. S_L:
  2778. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2779. begin
  2780. { Optimize out:
  2781. mov x, %reg
  2782. and ffffffffh, %reg
  2783. }
  2784. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2785. RemoveInstruction(hp1);
  2786. Result:=true;
  2787. exit;
  2788. end;
  2789. S_Q: { TODO: Confirm if this is even possible }
  2790. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2791. begin
  2792. { Optimize out:
  2793. mov x, %reg
  2794. and ffffffffffffffffh, %reg
  2795. }
  2796. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2797. RemoveInstruction(hp1);
  2798. Result:=true;
  2799. exit;
  2800. end;
  2801. else
  2802. ;
  2803. end;
  2804. if (
  2805. (taicpu(p).oper[0]^.typ=top_reg) or
  2806. (
  2807. (taicpu(p).oper[0]^.typ=top_ref) and
  2808. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2809. )
  2810. ) and
  2811. GetNextInstruction(hp1,hp2) and
  2812. MatchInstruction(hp2,A_TEST,[]) and
  2813. (
  2814. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2815. (
  2816. { If the register being tested is smaller than the one
  2817. that received a bitwise AND, permit it if the constant
  2818. fits into the smaller size }
  2819. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2820. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2821. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2822. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2823. (
  2824. (
  2825. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2826. (taicpu(hp1).oper[0]^.val <= $FF)
  2827. ) or
  2828. (
  2829. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2830. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2831. {$ifdef x86_64}
  2832. ) or
  2833. (
  2834. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2835. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2836. {$endif x86_64}
  2837. )
  2838. )
  2839. )
  2840. ) and
  2841. (
  2842. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2843. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2844. ) and
  2845. GetNextInstruction(hp2,hp3) and
  2846. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2847. (taicpu(hp3).condition in [C_E,C_NE]) then
  2848. begin
  2849. TransferUsedRegs(TmpUsedRegs);
  2850. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2852. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2853. begin
  2854. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2855. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2856. taicpu(hp1).opcode:=A_TEST;
  2857. { Shrink the TEST instruction down to the smallest possible size }
  2858. case taicpu(hp1).oper[0]^.val of
  2859. 0..255:
  2860. if (taicpu(hp1).opsize <> S_B)
  2861. {$ifndef x86_64}
  2862. and (
  2863. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2864. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2865. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2866. )
  2867. {$endif x86_64}
  2868. then
  2869. begin
  2870. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2871. { Only print debug message if the TEST instruction
  2872. is a different size before and after }
  2873. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2874. taicpu(hp1).opsize := S_B;
  2875. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2876. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2877. end;
  2878. 256..65535:
  2879. if (taicpu(hp1).opsize <> S_W) then
  2880. begin
  2881. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2882. { Only print debug message if the TEST instruction
  2883. is a different size before and after }
  2884. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2885. taicpu(hp1).opsize := S_W;
  2886. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2887. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2888. end;
  2889. {$ifdef x86_64}
  2890. 65536..$7FFFFFFF:
  2891. if (taicpu(hp1).opsize <> S_L) then
  2892. begin
  2893. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2894. { Only print debug message if the TEST instruction
  2895. is a different size before and after }
  2896. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2897. taicpu(hp1).opsize := S_L;
  2898. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2899. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2900. end;
  2901. {$endif x86_64}
  2902. else
  2903. ;
  2904. end;
  2905. RemoveInstruction(hp2);
  2906. RemoveCurrentP(p, hp1);
  2907. Result:=true;
  2908. exit;
  2909. end;
  2910. end;
  2911. end
  2912. else if IsMOVZXAcceptable and
  2913. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2914. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2915. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2916. then
  2917. begin
  2918. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2919. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2920. case taicpu(p).opsize of
  2921. S_B:
  2922. if (taicpu(hp1).oper[0]^.val = $ff) then
  2923. begin
  2924. { Convert:
  2925. movb x, %regl movb x, %regl
  2926. andw ffh, %regw andl ffh, %regd
  2927. To:
  2928. movzbw x, %regd movzbl x, %regd
  2929. (Identical registers, just different sizes)
  2930. }
  2931. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2932. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2933. case taicpu(hp1).opsize of
  2934. S_W: NewSize := S_BW;
  2935. S_L: NewSize := S_BL;
  2936. {$ifdef x86_64}
  2937. S_Q: NewSize := S_BQ;
  2938. {$endif x86_64}
  2939. else
  2940. InternalError(2018011510);
  2941. end;
  2942. end
  2943. else
  2944. NewSize := S_NO;
  2945. S_W:
  2946. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2947. begin
  2948. { Convert:
  2949. movw x, %regw
  2950. andl ffffh, %regd
  2951. To:
  2952. movzwl x, %regd
  2953. (Identical registers, just different sizes)
  2954. }
  2955. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2956. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2957. case taicpu(hp1).opsize of
  2958. S_L: NewSize := S_WL;
  2959. {$ifdef x86_64}
  2960. S_Q: NewSize := S_WQ;
  2961. {$endif x86_64}
  2962. else
  2963. InternalError(2018011511);
  2964. end;
  2965. end
  2966. else
  2967. NewSize := S_NO;
  2968. else
  2969. NewSize := S_NO;
  2970. end;
  2971. if NewSize <> S_NO then
  2972. begin
  2973. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2974. { The actual optimization }
  2975. taicpu(p).opcode := A_MOVZX;
  2976. taicpu(p).changeopsize(NewSize);
  2977. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2978. { Safeguard if "and" is followed by a conditional command }
  2979. TransferUsedRegs(TmpUsedRegs);
  2980. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2981. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2982. begin
  2983. { At this point, the "and" command is effectively equivalent to
  2984. "test %reg,%reg". This will be handled separately by the
  2985. Peephole Optimizer. [Kit] }
  2986. DebugMsg(SPeepholeOptimization + PreMessage +
  2987. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2988. end
  2989. else
  2990. begin
  2991. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2992. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2993. RemoveInstruction(hp1);
  2994. end;
  2995. Result := True;
  2996. Exit;
  2997. end;
  2998. end;
  2999. end;
  3000. if (taicpu(hp1).opcode = A_OR) and
  3001. (taicpu(p).oper[1]^.typ = top_reg) and
  3002. MatchOperand(taicpu(p).oper[0]^, 0) and
  3003. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3004. begin
  3005. { mov 0, %reg
  3006. or ###,%reg
  3007. Change to (only if the flags are not used):
  3008. mov ###,%reg
  3009. }
  3010. TransferUsedRegs(TmpUsedRegs);
  3011. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3012. DoOptimisation := True;
  3013. { Even if the flags are used, we might be able to do the optimisation
  3014. if the conditions are predictable }
  3015. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3016. begin
  3017. { Only perform if ### = %reg (the same register) or equal to 0,
  3018. so %reg is guaranteed to still have a value of zero }
  3019. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3020. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3021. begin
  3022. hp2 := hp1;
  3023. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3024. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3025. GetNextInstruction(hp2, hp3) do
  3026. begin
  3027. { Don't continue modifying if the flags state is getting changed }
  3028. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3029. Break;
  3030. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3031. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3032. begin
  3033. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3034. begin
  3035. { Condition is always true }
  3036. case taicpu(hp3).opcode of
  3037. A_Jcc:
  3038. begin
  3039. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3040. { Check for jump shortcuts before we destroy the condition }
  3041. DoJumpOptimizations(hp3, TempBool);
  3042. MakeUnconditional(taicpu(hp3));
  3043. Result := True;
  3044. end;
  3045. A_CMOVcc:
  3046. begin
  3047. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3048. taicpu(hp3).opcode := A_MOV;
  3049. taicpu(hp3).condition := C_None;
  3050. Result := True;
  3051. end;
  3052. A_SETcc:
  3053. begin
  3054. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3055. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3056. taicpu(hp3).opcode := A_MOV;
  3057. taicpu(hp3).ops := 2;
  3058. taicpu(hp3).condition := C_None;
  3059. taicpu(hp3).opsize := S_B;
  3060. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3061. taicpu(hp3).loadconst(0, 1);
  3062. Result := True;
  3063. end;
  3064. else
  3065. InternalError(2021090701);
  3066. end;
  3067. end
  3068. 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
  3069. begin
  3070. { Condition is always false }
  3071. case taicpu(hp3).opcode of
  3072. A_Jcc:
  3073. begin
  3074. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3075. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3076. RemoveInstruction(hp3);
  3077. Result := True;
  3078. { Since hp3 was deleted, hp2 must not be updated }
  3079. Continue;
  3080. end;
  3081. A_CMOVcc:
  3082. begin
  3083. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3084. RemoveInstruction(hp3);
  3085. Result := True;
  3086. { Since hp3 was deleted, hp2 must not be updated }
  3087. Continue;
  3088. end;
  3089. A_SETcc:
  3090. begin
  3091. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3092. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3093. taicpu(hp3).opcode := A_MOV;
  3094. taicpu(hp3).ops := 2;
  3095. taicpu(hp3).condition := C_None;
  3096. taicpu(hp3).opsize := S_B;
  3097. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3098. taicpu(hp3).loadconst(0, 0);
  3099. Result := True;
  3100. end;
  3101. else
  3102. InternalError(2021090702);
  3103. end;
  3104. end
  3105. else
  3106. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3107. DoOptimisation := False;
  3108. end;
  3109. hp2 := hp3;
  3110. end;
  3111. { Flags are still in use - don't optimise }
  3112. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3113. DoOptimisation := False;
  3114. end
  3115. else
  3116. DoOptimisation := False;
  3117. end;
  3118. if DoOptimisation then
  3119. begin
  3120. {$ifdef x86_64}
  3121. { OR only supports 32-bit sign-extended constants for 64-bit
  3122. instructions, so compensate for this if the constant is
  3123. encoded as a value greater than or equal to 2^31 }
  3124. if (taicpu(hp1).opsize = S_Q) and
  3125. (taicpu(hp1).oper[0]^.typ = top_const) and
  3126. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3127. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3128. {$endif x86_64}
  3129. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3130. taicpu(hp1).opcode := A_MOV;
  3131. RemoveCurrentP(p, hp1);
  3132. Result := True;
  3133. Exit;
  3134. end;
  3135. end;
  3136. { Next instruction is also a MOV ? }
  3137. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3138. begin
  3139. if MatchOpType(taicpu(p), top_const, top_ref) and
  3140. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3141. TryConstMerge(p, hp1) then
  3142. begin
  3143. Result := True;
  3144. { In case we have four byte writes in a row, check for 2 more
  3145. right now so we don't have to wait for another iteration of
  3146. pass 1
  3147. }
  3148. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3149. case taicpu(p).opsize of
  3150. S_W:
  3151. begin
  3152. if GetNextInstruction(p, hp1) and
  3153. MatchInstruction(hp1, A_MOV, [S_B]) and
  3154. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3155. GetNextInstruction(hp1, hp2) and
  3156. MatchInstruction(hp2, A_MOV, [S_B]) and
  3157. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3158. { Try to merge the two bytes }
  3159. TryConstMerge(hp1, hp2) then
  3160. { Now try to merge the two words (hp2 will get deleted) }
  3161. TryConstMerge(p, hp1);
  3162. end;
  3163. S_L:
  3164. begin
  3165. { Though this only really benefits x86_64 and not i386, it
  3166. gets a potential optimisation done faster and hence
  3167. reduces the number of times OptPass1MOV is entered }
  3168. if GetNextInstruction(p, hp1) and
  3169. MatchInstruction(hp1, A_MOV, [S_W]) and
  3170. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3171. GetNextInstruction(hp1, hp2) and
  3172. MatchInstruction(hp2, A_MOV, [S_W]) and
  3173. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3174. { Try to merge the two words }
  3175. TryConstMerge(hp1, hp2) then
  3176. { This will always fail on i386, so don't bother
  3177. calling it unless we're doing x86_64 }
  3178. {$ifdef x86_64}
  3179. { Now try to merge the two longwords (hp2 will get deleted) }
  3180. TryConstMerge(p, hp1)
  3181. {$endif x86_64}
  3182. ;
  3183. end;
  3184. else
  3185. ;
  3186. end;
  3187. Exit;
  3188. end;
  3189. if (taicpu(p).oper[1]^.typ = top_reg) and
  3190. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3191. begin
  3192. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3193. TransferUsedRegs(TmpUsedRegs);
  3194. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3195. { we have
  3196. mov x, %treg
  3197. mov %treg, y
  3198. }
  3199. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3200. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3201. { we've got
  3202. mov x, %treg
  3203. mov %treg, y
  3204. with %treg is not used after }
  3205. case taicpu(p).oper[0]^.typ Of
  3206. { top_reg is covered by DeepMOVOpt }
  3207. top_const:
  3208. begin
  3209. { change
  3210. mov const, %treg
  3211. mov %treg, y
  3212. to
  3213. mov const, y
  3214. }
  3215. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3216. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3217. begin
  3218. if taicpu(hp1).oper[1]^.typ=top_reg then
  3219. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3220. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3221. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3222. RemoveInstruction(hp1);
  3223. Result:=true;
  3224. Exit;
  3225. end;
  3226. end;
  3227. top_ref:
  3228. case taicpu(hp1).oper[1]^.typ of
  3229. top_reg:
  3230. begin
  3231. { change
  3232. mov mem, %treg
  3233. mov %treg, %reg
  3234. to
  3235. mov mem, %reg"
  3236. }
  3237. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3238. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3239. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3240. RemoveInstruction(hp1);
  3241. Result:=true;
  3242. Exit;
  3243. end;
  3244. top_ref:
  3245. begin
  3246. {$ifdef x86_64}
  3247. { Look for the following to simplify:
  3248. mov x(mem1), %reg
  3249. mov %reg, y(mem2)
  3250. mov x+8(mem1), %reg
  3251. mov %reg, y+8(mem2)
  3252. Change to:
  3253. movdqu x(mem1), %xmmreg
  3254. movdqu %xmmreg, y(mem2)
  3255. ...but only as long as the memory blocks don't overlap
  3256. }
  3257. SourceRef := taicpu(p).oper[0]^.ref^;
  3258. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3259. if (taicpu(p).opsize = S_Q) and
  3260. GetNextInstruction(hp1, hp2) and
  3261. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3262. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3263. begin
  3264. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3265. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3266. Inc(SourceRef.offset, 8);
  3267. if UseAVX then
  3268. begin
  3269. MovAligned := A_VMOVDQA;
  3270. MovUnaligned := A_VMOVDQU;
  3271. end
  3272. else
  3273. begin
  3274. MovAligned := A_MOVDQA;
  3275. MovUnaligned := A_MOVDQU;
  3276. end;
  3277. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3278. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3279. begin
  3280. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3281. Inc(TargetRef.offset, 8);
  3282. if GetNextInstruction(hp2, hp3) and
  3283. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3284. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3285. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3286. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3287. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3288. begin
  3289. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3290. if NewMMReg <> NR_NO then
  3291. begin
  3292. { Remember that the offsets are 8 ahead }
  3293. if ((SourceRef.offset mod 16) = 8) and
  3294. (
  3295. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3296. (SourceRef.base = current_procinfo.framepointer) or
  3297. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3298. ) then
  3299. taicpu(p).opcode := MovAligned
  3300. else
  3301. taicpu(p).opcode := MovUnaligned;
  3302. taicpu(p).opsize := S_XMM;
  3303. taicpu(p).oper[1]^.reg := NewMMReg;
  3304. if ((TargetRef.offset mod 16) = 8) and
  3305. (
  3306. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3307. (TargetRef.base = current_procinfo.framepointer) or
  3308. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3309. ) then
  3310. taicpu(hp1).opcode := MovAligned
  3311. else
  3312. taicpu(hp1).opcode := MovUnaligned;
  3313. taicpu(hp1).opsize := S_XMM;
  3314. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3315. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3316. RemoveInstruction(hp2);
  3317. RemoveInstruction(hp3);
  3318. Result := True;
  3319. Exit;
  3320. end;
  3321. end;
  3322. end
  3323. else
  3324. begin
  3325. { See if the next references are 8 less rather than 8 greater }
  3326. Dec(SourceRef.offset, 16); { -8 the other way }
  3327. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3328. begin
  3329. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3330. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3331. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3332. GetNextInstruction(hp2, hp3) and
  3333. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3334. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3335. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3336. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3337. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3338. begin
  3339. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3340. if NewMMReg <> NR_NO then
  3341. begin
  3342. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3343. if ((SourceRef.offset mod 16) = 0) and
  3344. (
  3345. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3346. (SourceRef.base = current_procinfo.framepointer) or
  3347. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3348. ) then
  3349. taicpu(hp2).opcode := MovAligned
  3350. else
  3351. taicpu(hp2).opcode := MovUnaligned;
  3352. taicpu(hp2).opsize := S_XMM;
  3353. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3354. if ((TargetRef.offset mod 16) = 0) and
  3355. (
  3356. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3357. (TargetRef.base = current_procinfo.framepointer) or
  3358. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3359. ) then
  3360. taicpu(hp3).opcode := MovAligned
  3361. else
  3362. taicpu(hp3).opcode := MovUnaligned;
  3363. taicpu(hp3).opsize := S_XMM;
  3364. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3365. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3366. RemoveInstruction(hp1);
  3367. RemoveCurrentP(p, hp2);
  3368. Result := True;
  3369. Exit;
  3370. end;
  3371. end;
  3372. end;
  3373. end;
  3374. end;
  3375. {$endif x86_64}
  3376. end;
  3377. else
  3378. { The write target should be a reg or a ref }
  3379. InternalError(2021091601);
  3380. end;
  3381. else
  3382. ;
  3383. end
  3384. else
  3385. { %treg is used afterwards, but all eventualities
  3386. other than the first MOV instruction being a constant
  3387. are covered by DeepMOVOpt, so only check for that }
  3388. if (taicpu(p).oper[0]^.typ = top_const) and
  3389. (
  3390. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3391. not (cs_opt_size in current_settings.optimizerswitches) or
  3392. (taicpu(hp1).opsize = S_B)
  3393. ) and
  3394. (
  3395. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3396. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3397. ) then
  3398. begin
  3399. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3400. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3401. end;
  3402. end;
  3403. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3404. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3405. { mov reg1, mem1 or mov mem1, reg1
  3406. mov mem2, reg2 mov reg2, mem2}
  3407. begin
  3408. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3409. { mov reg1, mem1 or mov mem1, reg1
  3410. mov mem2, reg1 mov reg2, mem1}
  3411. begin
  3412. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3413. { Removes the second statement from
  3414. mov reg1, mem1/reg2
  3415. mov mem1/reg2, reg1 }
  3416. begin
  3417. if taicpu(p).oper[0]^.typ=top_reg then
  3418. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3419. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3420. RemoveInstruction(hp1);
  3421. Result:=true;
  3422. exit;
  3423. end
  3424. else
  3425. begin
  3426. TransferUsedRegs(TmpUsedRegs);
  3427. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3428. if (taicpu(p).oper[1]^.typ = top_ref) and
  3429. { mov reg1, mem1
  3430. mov mem2, reg1 }
  3431. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3432. GetNextInstruction(hp1, hp2) and
  3433. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3434. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3435. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3436. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3437. { change to
  3438. mov reg1, mem1 mov reg1, mem1
  3439. mov mem2, reg1 cmp reg1, mem2
  3440. cmp mem1, reg1
  3441. }
  3442. begin
  3443. RemoveInstruction(hp2);
  3444. taicpu(hp1).opcode := A_CMP;
  3445. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3446. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3447. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3448. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3449. end;
  3450. end;
  3451. end
  3452. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3453. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3454. begin
  3455. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3456. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3457. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3458. end
  3459. else
  3460. begin
  3461. TransferUsedRegs(TmpUsedRegs);
  3462. if GetNextInstruction(hp1, hp2) and
  3463. MatchOpType(taicpu(p),top_ref,top_reg) and
  3464. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3465. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3466. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3467. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3468. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3469. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3470. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3471. { mov mem1, %reg1
  3472. mov %reg1, mem2
  3473. mov mem2, reg2
  3474. to:
  3475. mov mem1, reg2
  3476. mov reg2, mem2}
  3477. begin
  3478. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3479. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3480. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3481. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3482. RemoveInstruction(hp2);
  3483. Result := True;
  3484. end
  3485. {$ifdef i386}
  3486. { this is enabled for i386 only, as the rules to create the reg sets below
  3487. are too complicated for x86-64, so this makes this code too error prone
  3488. on x86-64
  3489. }
  3490. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3491. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3492. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3493. { mov mem1, reg1 mov mem1, reg1
  3494. mov reg1, mem2 mov reg1, mem2
  3495. mov mem2, reg2 mov mem2, reg1
  3496. to: to:
  3497. mov mem1, reg1 mov mem1, reg1
  3498. mov mem1, reg2 mov reg1, mem2
  3499. mov reg1, mem2
  3500. or (if mem1 depends on reg1
  3501. and/or if mem2 depends on reg2)
  3502. to:
  3503. mov mem1, reg1
  3504. mov reg1, mem2
  3505. mov reg1, reg2
  3506. }
  3507. begin
  3508. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3509. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3510. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3511. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3512. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3513. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3514. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3515. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3516. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3517. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3518. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3519. end
  3520. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3521. begin
  3522. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3523. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3524. end
  3525. else
  3526. begin
  3527. RemoveInstruction(hp2);
  3528. end
  3529. {$endif i386}
  3530. ;
  3531. end;
  3532. end
  3533. { movl [mem1],reg1
  3534. movl [mem1],reg2
  3535. to
  3536. movl [mem1],reg1
  3537. movl reg1,reg2
  3538. }
  3539. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3540. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3541. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3542. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3543. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3544. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3545. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3546. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3547. begin
  3548. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3549. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3550. end;
  3551. { movl const1,[mem1]
  3552. movl [mem1],reg1
  3553. to
  3554. movl const1,reg1
  3555. movl reg1,[mem1]
  3556. }
  3557. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3558. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3559. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3560. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3561. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3562. begin
  3563. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3564. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3565. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3566. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3567. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3568. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3569. Result:=true;
  3570. exit;
  3571. end;
  3572. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3573. { Change:
  3574. movl %reg1,%reg2
  3575. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3576. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3577. To:
  3578. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3579. movl x(%reg1),%reg1
  3580. movl %reg1,%regX
  3581. }
  3582. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3583. begin
  3584. p_SourceReg := taicpu(p).oper[0]^.reg;
  3585. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3586. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3587. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3588. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3589. GetNextInstruction(hp1, hp2) and
  3590. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3591. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3592. begin
  3593. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3594. if RegInRef(p_TargetReg, SourceRef) and
  3595. { If %reg1 also appears in the second reference, then it will
  3596. not refer to the same memory block as the first reference }
  3597. not RegInRef(p_SourceReg, SourceRef) then
  3598. begin
  3599. { Check to see if the references match if %reg2 is changed to %reg1 }
  3600. if SourceRef.base = p_TargetReg then
  3601. SourceRef.base := p_SourceReg;
  3602. if SourceRef.index = p_TargetReg then
  3603. SourceRef.index := p_SourceReg;
  3604. { RefsEqual also checks to ensure both references are non-volatile }
  3605. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3606. begin
  3607. taicpu(hp2).loadreg(0, p_SourceReg);
  3608. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3609. Result := True;
  3610. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3611. begin
  3612. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3613. RemoveCurrentP(p, hp1);
  3614. Exit;
  3615. end
  3616. else
  3617. begin
  3618. { Check to see if %reg2 is no longer in use }
  3619. TransferUsedRegs(TmpUsedRegs);
  3620. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3621. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3622. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3623. begin
  3624. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3625. RemoveCurrentP(p, hp1);
  3626. Exit;
  3627. end;
  3628. end;
  3629. { If we reach this point, p and hp1 weren't actually modified,
  3630. so we can do a bit more work on this pass }
  3631. end;
  3632. end;
  3633. end;
  3634. end;
  3635. end;
  3636. { search further than the next instruction for a mov (as long as it's not a jump) }
  3637. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3638. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3639. (taicpu(p).oper[1]^.typ = top_reg) and
  3640. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3641. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3642. begin
  3643. { we work with hp2 here, so hp1 can be still used later on when
  3644. checking for GetNextInstruction_p }
  3645. hp3 := hp1;
  3646. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3647. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3648. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3649. TransferUsedRegs(TmpUsedRegs);
  3650. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3651. if NotFirstIteration then
  3652. JumpTracking := TLinkedList.Create
  3653. else
  3654. JumpTracking := nil;
  3655. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3656. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3657. (hp2.typ=ait_instruction) do
  3658. begin
  3659. case taicpu(hp2).opcode of
  3660. A_POP:
  3661. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3662. begin
  3663. if not CrossJump and
  3664. not RegUsedBetween(p_TargetReg, p, hp2) then
  3665. begin
  3666. { We can remove the original MOV since the register
  3667. wasn't used between it and its popping from the stack }
  3668. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3669. RemoveCurrentp(p, hp1);
  3670. Result := True;
  3671. JumpTracking.Free;
  3672. Exit;
  3673. end;
  3674. { Can't go any further }
  3675. Break;
  3676. end;
  3677. A_MOV:
  3678. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3679. ((taicpu(p).oper[0]^.typ=top_const) or
  3680. ((taicpu(p).oper[0]^.typ=top_reg) and
  3681. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3682. )
  3683. ) then
  3684. begin
  3685. { we have
  3686. mov x, %treg
  3687. mov %treg, y
  3688. }
  3689. { We don't need to call UpdateUsedRegs for every instruction between
  3690. p and hp2 because the register we're concerned about will not
  3691. become deallocated (otherwise GetNextInstructionUsingReg would
  3692. have stopped at an earlier instruction). [Kit] }
  3693. TempRegUsed :=
  3694. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3695. RegReadByInstruction(p_TargetReg, hp3) or
  3696. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3697. case taicpu(p).oper[0]^.typ Of
  3698. top_reg:
  3699. begin
  3700. { change
  3701. mov %reg, %treg
  3702. mov %treg, y
  3703. to
  3704. mov %reg, y
  3705. }
  3706. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3707. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3708. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3709. begin
  3710. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3711. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3712. if TempRegUsed then
  3713. begin
  3714. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3715. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3716. { Set the start of the next GetNextInstructionUsingRegCond search
  3717. to start at the entry right before hp2 (which is about to be removed) }
  3718. hp3 := tai(hp2.Previous);
  3719. RemoveInstruction(hp2);
  3720. { See if there's more we can optimise }
  3721. Continue;
  3722. end
  3723. else
  3724. begin
  3725. RemoveInstruction(hp2);
  3726. { We can remove the original MOV too }
  3727. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3728. RemoveCurrentP(p, hp1);
  3729. Result:=true;
  3730. JumpTracking.Free;
  3731. Exit;
  3732. end;
  3733. end
  3734. else
  3735. begin
  3736. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3737. taicpu(hp2).loadReg(0, p_SourceReg);
  3738. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3739. { Check to see if the register also appears in the reference }
  3740. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3741. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3742. { Don't remove the first instruction if the temporary register is in use }
  3743. if not TempRegUsed and
  3744. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3745. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3746. begin
  3747. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3748. RemoveCurrentP(p, hp1);
  3749. Result:=true;
  3750. JumpTracking.Free;
  3751. Exit;
  3752. end;
  3753. { No need to set Result to True here. If there's another instruction later
  3754. on that can be optimised, it will be detected when the main Pass 1 loop
  3755. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3756. end;
  3757. end;
  3758. top_const:
  3759. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3760. begin
  3761. { change
  3762. mov const, %treg
  3763. mov %treg, y
  3764. to
  3765. mov const, y
  3766. }
  3767. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3768. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3769. begin
  3770. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3771. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3772. if TempRegUsed then
  3773. begin
  3774. { Don't remove the first instruction if the temporary register is in use }
  3775. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3776. { No need to set Result to True. If there's another instruction later on
  3777. that can be optimised, it will be detected when the main Pass 1 loop
  3778. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3779. end
  3780. else
  3781. begin
  3782. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3783. RemoveCurrentP(p, hp1);
  3784. Result:=true;
  3785. Exit;
  3786. end;
  3787. end;
  3788. end;
  3789. else
  3790. Internalerror(2019103001);
  3791. end;
  3792. end
  3793. else
  3794. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3795. begin
  3796. if not CrossJump and
  3797. not RegUsedBetween(p_TargetReg, p, hp2) and
  3798. not RegReadByInstruction(p_TargetReg, hp2) then
  3799. begin
  3800. { Register is not used before it is overwritten }
  3801. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3802. RemoveCurrentp(p, hp1);
  3803. Result := True;
  3804. Exit;
  3805. end;
  3806. if (taicpu(p).oper[0]^.typ = top_const) and
  3807. (taicpu(hp2).oper[0]^.typ = top_const) then
  3808. begin
  3809. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3810. begin
  3811. { Same value - register hasn't changed }
  3812. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3813. RemoveInstruction(hp2);
  3814. Result := True;
  3815. { See if there's more we can optimise }
  3816. Continue;
  3817. end;
  3818. end;
  3819. end;
  3820. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3821. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3822. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3823. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3824. begin
  3825. {
  3826. Change from:
  3827. mov ###, %reg
  3828. ...
  3829. movs/z %reg,%reg (Same register, just different sizes)
  3830. To:
  3831. movs/z ###, %reg (Longer version)
  3832. ...
  3833. (remove)
  3834. }
  3835. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3836. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3837. { Keep the first instruction as mov if ### is a constant }
  3838. if taicpu(p).oper[0]^.typ = top_const then
  3839. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3840. else
  3841. begin
  3842. taicpu(p).opcode := taicpu(hp2).opcode;
  3843. taicpu(p).opsize := taicpu(hp2).opsize;
  3844. end;
  3845. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3846. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3847. RemoveInstruction(hp2);
  3848. Result := True;
  3849. JumpTracking.Free;
  3850. Exit;
  3851. end;
  3852. else
  3853. { Move down to the MatchOpType if-block below };
  3854. end;
  3855. { Also catches MOV/S/Z instructions that aren't modified }
  3856. if taicpu(p).oper[0]^.typ = top_reg then
  3857. begin
  3858. p_SourceReg := taicpu(p).oper[0]^.reg;
  3859. if
  3860. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3861. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3862. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3863. begin
  3864. Result := True;
  3865. { Just in case something didn't get modified (e.g. an
  3866. implicit register). Also, if it does read from this
  3867. register, then there's no longer an advantage to
  3868. changing the register on subsequent instructions.}
  3869. if not RegReadByInstruction(p_TargetReg, hp2) then
  3870. begin
  3871. { If a conditional jump was crossed, do not delete
  3872. the original MOV no matter what }
  3873. if not CrossJump and
  3874. { RegEndOfLife returns True if the register is
  3875. deallocated before the next instruction or has
  3876. been loaded with a new value }
  3877. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3878. begin
  3879. { We can remove the original MOV }
  3880. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3881. RemoveCurrentp(p, hp1);
  3882. JumpTracking.Free;
  3883. Result := True;
  3884. Exit;
  3885. end;
  3886. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3887. begin
  3888. { See if there's more we can optimise }
  3889. hp3 := hp2;
  3890. Continue;
  3891. end;
  3892. end;
  3893. end;
  3894. end;
  3895. { Break out of the while loop under normal circumstances }
  3896. Break;
  3897. end;
  3898. JumpTracking.Free;
  3899. end;
  3900. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3901. (taicpu(p).oper[1]^.typ = top_reg) and
  3902. (taicpu(p).opsize = S_L) and
  3903. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3904. (hp2.typ = ait_instruction) and
  3905. (taicpu(hp2).opcode = A_AND) and
  3906. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3907. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3908. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3909. ) then
  3910. begin
  3911. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3912. begin
  3913. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3914. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3915. begin
  3916. { Optimize out:
  3917. mov x, %reg
  3918. and ffffffffh, %reg
  3919. }
  3920. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3921. RemoveInstruction(hp2);
  3922. Result:=true;
  3923. exit;
  3924. end;
  3925. end;
  3926. end;
  3927. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3928. x >= RetOffset) as it doesn't do anything (it writes either to a
  3929. parameter or to the temporary storage room for the function
  3930. result)
  3931. }
  3932. if IsExitCode(hp1) and
  3933. (taicpu(p).oper[1]^.typ = top_ref) and
  3934. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3935. (
  3936. (
  3937. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3938. not (
  3939. assigned(current_procinfo.procdef.funcretsym) and
  3940. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3941. )
  3942. ) or
  3943. { Also discard writes to the stack that are below the base pointer,
  3944. as this is temporary storage rather than a function result on the
  3945. stack, say. }
  3946. (
  3947. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3948. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3949. )
  3950. ) then
  3951. begin
  3952. RemoveCurrentp(p, hp1);
  3953. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3954. RemoveLastDeallocForFuncRes(p);
  3955. Result:=true;
  3956. exit;
  3957. end;
  3958. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3959. begin
  3960. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3961. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3962. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3963. begin
  3964. { change
  3965. mov reg1, mem1
  3966. test/cmp x, mem1
  3967. to
  3968. mov reg1, mem1
  3969. test/cmp x, reg1
  3970. }
  3971. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3972. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3973. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3974. Result := True;
  3975. Exit;
  3976. end;
  3977. if DoMovCmpMemOpt(p, hp1, True) then
  3978. begin
  3979. Result := True;
  3980. Exit;
  3981. end;
  3982. end;
  3983. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3984. { If the flags register is in use, don't change the instruction to an
  3985. ADD otherwise this will scramble the flags. [Kit] }
  3986. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3987. begin
  3988. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3989. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3990. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3991. ) or
  3992. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3993. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3994. )
  3995. ) then
  3996. { mov reg1,ref
  3997. lea reg2,[reg1,reg2]
  3998. to
  3999. add reg2,ref}
  4000. begin
  4001. TransferUsedRegs(TmpUsedRegs);
  4002. { reg1 may not be used afterwards }
  4003. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4004. begin
  4005. Taicpu(hp1).opcode:=A_ADD;
  4006. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4007. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4008. RemoveCurrentp(p, hp1);
  4009. result:=true;
  4010. exit;
  4011. end;
  4012. end;
  4013. { If the LEA instruction can be converted into an arithmetic instruction,
  4014. it may be possible to then fold it in the next optimisation, otherwise
  4015. there's nothing more that can be optimised here. }
  4016. if not ConvertLEA(taicpu(hp1)) then
  4017. Exit;
  4018. end;
  4019. if (taicpu(p).oper[1]^.typ = top_reg) and
  4020. (hp1.typ = ait_instruction) and
  4021. GetNextInstruction(hp1, hp2) and
  4022. MatchInstruction(hp2,A_MOV,[]) and
  4023. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4024. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4025. (
  4026. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4027. {$ifdef x86_64}
  4028. or
  4029. (
  4030. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4031. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4032. )
  4033. {$endif x86_64}
  4034. ) then
  4035. begin
  4036. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4037. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4038. { change movsX/movzX reg/ref, reg2
  4039. add/sub/or/... reg3/$const, reg2
  4040. mov reg2 reg/ref
  4041. dealloc reg2
  4042. to
  4043. add/sub/or/... reg3/$const, reg/ref }
  4044. begin
  4045. TransferUsedRegs(TmpUsedRegs);
  4046. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4047. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4048. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4049. begin
  4050. { by example:
  4051. movswl %si,%eax movswl %si,%eax p
  4052. decl %eax addl %edx,%eax hp1
  4053. movw %ax,%si movw %ax,%si hp2
  4054. ->
  4055. movswl %si,%eax movswl %si,%eax p
  4056. decw %eax addw %edx,%eax hp1
  4057. movw %ax,%si movw %ax,%si hp2
  4058. }
  4059. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4060. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4061. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4062. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4063. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4064. {
  4065. ->
  4066. movswl %si,%eax movswl %si,%eax p
  4067. decw %si addw %dx,%si hp1
  4068. movw %ax,%si movw %ax,%si hp2
  4069. }
  4070. case taicpu(hp1).ops of
  4071. 1:
  4072. begin
  4073. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4074. if taicpu(hp1).oper[0]^.typ=top_reg then
  4075. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4076. end;
  4077. 2:
  4078. begin
  4079. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4080. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4081. (taicpu(hp1).opcode<>A_SHL) and
  4082. (taicpu(hp1).opcode<>A_SHR) and
  4083. (taicpu(hp1).opcode<>A_SAR) then
  4084. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4085. end;
  4086. else
  4087. internalerror(2008042701);
  4088. end;
  4089. {
  4090. ->
  4091. decw %si addw %dx,%si p
  4092. }
  4093. RemoveInstruction(hp2);
  4094. RemoveCurrentP(p, hp1);
  4095. Result:=True;
  4096. Exit;
  4097. end;
  4098. end;
  4099. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4100. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4101. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4102. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4103. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4104. )
  4105. {$ifdef i386}
  4106. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4107. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4108. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4109. {$endif i386}
  4110. then
  4111. { change movsX/movzX reg/ref, reg2
  4112. add/sub/or/... regX/$const, reg2
  4113. mov reg2, reg3
  4114. dealloc reg2
  4115. to
  4116. movsX/movzX reg/ref, reg3
  4117. add/sub/or/... reg3/$const, reg3
  4118. }
  4119. begin
  4120. TransferUsedRegs(TmpUsedRegs);
  4121. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4122. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4123. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4124. begin
  4125. { by example:
  4126. movswl %si,%eax movswl %si,%eax p
  4127. decl %eax addl %edx,%eax hp1
  4128. movw %ax,%si movw %ax,%si hp2
  4129. ->
  4130. movswl %si,%eax movswl %si,%eax p
  4131. decw %eax addw %edx,%eax hp1
  4132. movw %ax,%si movw %ax,%si hp2
  4133. }
  4134. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4135. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4136. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4137. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4138. { limit size of constants as well to avoid assembler errors, but
  4139. check opsize to avoid overflow when left shifting the 1 }
  4140. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4141. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4142. {$ifdef x86_64}
  4143. { Be careful of, for example:
  4144. movl %reg1,%reg2
  4145. addl %reg3,%reg2
  4146. movq %reg2,%reg4
  4147. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4148. }
  4149. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4150. begin
  4151. taicpu(hp2).changeopsize(S_L);
  4152. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4153. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4154. end;
  4155. {$endif x86_64}
  4156. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4157. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4158. if taicpu(p).oper[0]^.typ=top_reg then
  4159. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4160. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4161. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4162. {
  4163. ->
  4164. movswl %si,%eax movswl %si,%eax p
  4165. decw %si addw %dx,%si hp1
  4166. movw %ax,%si movw %ax,%si hp2
  4167. }
  4168. case taicpu(hp1).ops of
  4169. 1:
  4170. begin
  4171. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4172. if taicpu(hp1).oper[0]^.typ=top_reg then
  4173. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4174. end;
  4175. 2:
  4176. begin
  4177. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4178. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4179. (taicpu(hp1).opcode<>A_SHL) and
  4180. (taicpu(hp1).opcode<>A_SHR) and
  4181. (taicpu(hp1).opcode<>A_SAR) then
  4182. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4183. end;
  4184. else
  4185. internalerror(2018111801);
  4186. end;
  4187. {
  4188. ->
  4189. decw %si addw %dx,%si p
  4190. }
  4191. RemoveInstruction(hp2);
  4192. end;
  4193. end;
  4194. end;
  4195. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4196. GetNextInstruction(hp1, hp2) and
  4197. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4198. MatchOperand(Taicpu(p).oper[0]^,0) and
  4199. (Taicpu(p).oper[1]^.typ = top_reg) and
  4200. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4201. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4202. { mov reg1,0
  4203. bts reg1,operand1 --> mov reg1,operand2
  4204. or reg1,operand2 bts reg1,operand1}
  4205. begin
  4206. Taicpu(hp2).opcode:=A_MOV;
  4207. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4208. asml.remove(hp1);
  4209. insertllitem(hp2,hp2.next,hp1);
  4210. RemoveCurrentp(p, hp1);
  4211. Result:=true;
  4212. exit;
  4213. end;
  4214. {
  4215. mov ref,reg0
  4216. <op> reg0,reg1
  4217. dealloc reg0
  4218. to
  4219. <op> ref,reg1
  4220. }
  4221. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4222. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4223. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4224. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4225. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4226. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4227. begin
  4228. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4229. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4230. RemoveCurrentp(p, hp1);
  4231. Result:=true;
  4232. exit;
  4233. end;
  4234. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4235. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4236. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4237. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4238. begin
  4239. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4240. {$ifdef x86_64}
  4241. { Convert:
  4242. movq x(ref),%reg64
  4243. shrq y,%reg64
  4244. To:
  4245. movl x+4(ref),%reg32
  4246. shrl y-32,%reg32 (Remove if y = 32)
  4247. }
  4248. if (taicpu(p).opsize = S_Q) and
  4249. (taicpu(hp1).opcode = A_SHR) and
  4250. (taicpu(hp1).oper[0]^.val >= 32) then
  4251. begin
  4252. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4253. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4254. { Convert to 32-bit }
  4255. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4256. taicpu(p).opsize := S_L;
  4257. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4258. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4259. if (taicpu(hp1).oper[0]^.val = 32) then
  4260. begin
  4261. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4262. RemoveInstruction(hp1);
  4263. end
  4264. else
  4265. begin
  4266. { This will potentially open up more arithmetic operations since
  4267. the peephole optimizer now has a big hint that only the lower
  4268. 32 bits are currently in use (and opcodes are smaller in size) }
  4269. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4270. taicpu(hp1).opsize := S_L;
  4271. Dec(taicpu(hp1).oper[0]^.val, 32);
  4272. DebugMsg(SPeepholeOptimization + PreMessage +
  4273. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4274. end;
  4275. Result := True;
  4276. Exit;
  4277. end;
  4278. {$endif x86_64}
  4279. { Convert:
  4280. movl x(ref),%reg
  4281. shrl $24,%reg
  4282. To:
  4283. movzbl x+3(ref),%reg
  4284. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4285. Also accept sar instead of shr, but convert to movsx instead of movzx
  4286. }
  4287. if taicpu(hp1).opcode = A_SHR then
  4288. MovUnaligned := A_MOVZX
  4289. else
  4290. MovUnaligned := A_MOVSX;
  4291. NewSize := S_NO;
  4292. NewOffset := 0;
  4293. case taicpu(p).opsize of
  4294. S_B:
  4295. { No valid combinations };
  4296. S_W:
  4297. if (taicpu(hp1).oper[0]^.val = 8) then
  4298. begin
  4299. NewSize := S_BW;
  4300. NewOffset := 1;
  4301. end;
  4302. S_L:
  4303. case taicpu(hp1).oper[0]^.val of
  4304. 16:
  4305. begin
  4306. NewSize := S_WL;
  4307. NewOffset := 2;
  4308. end;
  4309. 24:
  4310. begin
  4311. NewSize := S_BL;
  4312. NewOffset := 3;
  4313. end;
  4314. else
  4315. ;
  4316. end;
  4317. {$ifdef x86_64}
  4318. S_Q:
  4319. case taicpu(hp1).oper[0]^.val of
  4320. 32:
  4321. begin
  4322. if taicpu(hp1).opcode = A_SAR then
  4323. begin
  4324. { 32-bit to 64-bit is a distinct instruction }
  4325. MovUnaligned := A_MOVSXD;
  4326. NewSize := S_LQ;
  4327. NewOffset := 4;
  4328. end
  4329. else
  4330. { Should have been handled by MovShr2Mov above }
  4331. InternalError(2022081811);
  4332. end;
  4333. 48:
  4334. begin
  4335. NewSize := S_WQ;
  4336. NewOffset := 6;
  4337. end;
  4338. 56:
  4339. begin
  4340. NewSize := S_BQ;
  4341. NewOffset := 7;
  4342. end;
  4343. else
  4344. ;
  4345. end;
  4346. {$endif x86_64}
  4347. else
  4348. InternalError(2022081810);
  4349. end;
  4350. if (NewSize <> S_NO) and
  4351. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4352. begin
  4353. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4354. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4355. debug_op2str(MovUnaligned);
  4356. {$ifdef x86_64}
  4357. if MovUnaligned <> A_MOVSXD then
  4358. { Don't add size suffix for MOVSXD }
  4359. {$endif x86_64}
  4360. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4361. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4362. taicpu(p).opcode := MovUnaligned;
  4363. taicpu(p).opsize := NewSize;
  4364. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4365. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4366. RemoveInstruction(hp1);
  4367. Result := True;
  4368. Exit;
  4369. end;
  4370. end;
  4371. { Backward optimisation. If we have:
  4372. func. %reg1,%reg2
  4373. mov %reg2,%reg3
  4374. (dealloc %reg2)
  4375. Change to:
  4376. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4377. }
  4378. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4379. begin
  4380. p_SourceReg := taicpu(p).oper[0]^.reg;
  4381. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4382. TransferUsedRegs(TmpUsedRegs);
  4383. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4384. GetLastInstruction(p, hp2) and
  4385. (hp2.typ = ait_instruction) and
  4386. { Have to make sure it's an instruction that only reads from
  4387. operand 1 and only writes (not reads or modifies) from operand 2;
  4388. in essence, a one-operand pure function such as BSR or POPCNT }
  4389. (taicpu(hp2).ops = 2) and
  4390. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4391. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4392. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4393. begin
  4394. case taicpu(hp2).opcode of
  4395. A_FSTSW, A_FNSTSW,
  4396. A_IN, A_INS, A_OUT, A_OUTS,
  4397. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4398. { These routines have explicit operands, but they are restricted in
  4399. what they can be (e.g. IN and OUT can only read from AL, AX or
  4400. EAX. }
  4401. ;
  4402. else
  4403. begin
  4404. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4405. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4406. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4407. RemoveCurrentp(p, hp1);
  4408. Result := True;
  4409. Exit;
  4410. end;
  4411. end;
  4412. end;
  4413. end;
  4414. end;
  4415. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4416. var
  4417. hp1 : tai;
  4418. begin
  4419. Result:=false;
  4420. if taicpu(p).ops <> 2 then
  4421. exit;
  4422. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4423. GetNextInstruction(p,hp1) then
  4424. begin
  4425. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4426. (taicpu(hp1).ops = 2) then
  4427. begin
  4428. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4429. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4430. { movXX reg1, mem1 or movXX mem1, reg1
  4431. movXX mem2, reg2 movXX reg2, mem2}
  4432. begin
  4433. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4434. { movXX reg1, mem1 or movXX mem1, reg1
  4435. movXX mem2, reg1 movXX reg2, mem1}
  4436. begin
  4437. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4438. begin
  4439. { Removes the second statement from
  4440. movXX reg1, mem1/reg2
  4441. movXX mem1/reg2, reg1
  4442. }
  4443. if taicpu(p).oper[0]^.typ=top_reg then
  4444. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4445. { Removes the second statement from
  4446. movXX mem1/reg1, reg2
  4447. movXX reg2, mem1/reg1
  4448. }
  4449. if (taicpu(p).oper[1]^.typ=top_reg) and
  4450. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4451. begin
  4452. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4453. RemoveInstruction(hp1);
  4454. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4455. Result:=true;
  4456. exit;
  4457. end
  4458. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4459. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4460. begin
  4461. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4462. RemoveInstruction(hp1);
  4463. Result:=true;
  4464. exit;
  4465. end;
  4466. end
  4467. end;
  4468. end;
  4469. end;
  4470. end;
  4471. end;
  4472. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4473. var
  4474. hp1 : tai;
  4475. begin
  4476. result:=false;
  4477. { replace
  4478. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4479. MovX %mreg2,%mreg1
  4480. dealloc %mreg2
  4481. by
  4482. <Op>X %mreg2,%mreg1
  4483. ?
  4484. }
  4485. if GetNextInstruction(p,hp1) and
  4486. { we mix single and double opperations here because we assume that the compiler
  4487. generates vmovapd only after double operations and vmovaps only after single operations }
  4488. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4489. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4490. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4491. (taicpu(p).oper[0]^.typ=top_reg) then
  4492. begin
  4493. TransferUsedRegs(TmpUsedRegs);
  4494. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4495. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4496. begin
  4497. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4498. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4499. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4500. RemoveInstruction(hp1);
  4501. result:=true;
  4502. end;
  4503. end;
  4504. end;
  4505. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4506. var
  4507. hp1, p_label, p_dist, hp1_dist: tai;
  4508. JumpLabel, JumpLabel_dist: TAsmLabel;
  4509. FirstValue, SecondValue: TCGInt;
  4510. begin
  4511. Result := False;
  4512. if (taicpu(p).oper[0]^.typ = top_const) and
  4513. (taicpu(p).oper[0]^.val <> -1) then
  4514. begin
  4515. { Convert unsigned maximum constants to -1 to aid optimisation }
  4516. case taicpu(p).opsize of
  4517. S_B:
  4518. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4519. begin
  4520. taicpu(p).oper[0]^.val := -1;
  4521. Result := True;
  4522. Exit;
  4523. end;
  4524. S_W:
  4525. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4526. begin
  4527. taicpu(p).oper[0]^.val := -1;
  4528. Result := True;
  4529. Exit;
  4530. end;
  4531. S_L:
  4532. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4533. begin
  4534. taicpu(p).oper[0]^.val := -1;
  4535. Result := True;
  4536. Exit;
  4537. end;
  4538. {$ifdef x86_64}
  4539. S_Q:
  4540. { Storing anything greater than $7FFFFFFF is not possible so do
  4541. nothing };
  4542. {$endif x86_64}
  4543. else
  4544. InternalError(2021121001);
  4545. end;
  4546. end;
  4547. if GetNextInstruction(p, hp1) and
  4548. TrySwapMovCmp(p, hp1) then
  4549. begin
  4550. Result := True;
  4551. Exit;
  4552. end;
  4553. { Search for:
  4554. test $x,(reg/ref)
  4555. jne @lbl1
  4556. test $y,(reg/ref) (same register or reference)
  4557. jne @lbl1
  4558. Change to:
  4559. test $(x or y),(reg/ref)
  4560. jne @lbl1
  4561. (Note, this doesn't work with je instead of jne)
  4562. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4563. Also search for:
  4564. test $x,(reg/ref)
  4565. je @lbl1
  4566. test $y,(reg/ref)
  4567. je/jne @lbl2
  4568. If (x or y) = x, then the second jump is deterministic
  4569. }
  4570. if (
  4571. (
  4572. (taicpu(p).oper[0]^.typ = top_const) or
  4573. (
  4574. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4575. (taicpu(p).oper[0]^.typ = top_reg) and
  4576. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4577. )
  4578. ) and
  4579. MatchInstruction(hp1, A_JCC, [])
  4580. ) then
  4581. begin
  4582. if (taicpu(p).oper[0]^.typ = top_reg) and
  4583. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4584. FirstValue := -1
  4585. else
  4586. FirstValue := taicpu(p).oper[0]^.val;
  4587. { If we have several test/jne's in a row, it might be the case that
  4588. the second label doesn't go to the same location, but the one
  4589. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4590. so accommodate for this with a while loop.
  4591. }
  4592. hp1_dist := hp1;
  4593. if GetNextInstruction(hp1, p_dist) and
  4594. (p_dist.typ = ait_instruction) and
  4595. (
  4596. (
  4597. (taicpu(p_dist).opcode = A_TEST) and
  4598. (
  4599. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4600. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4601. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4602. )
  4603. ) or
  4604. (
  4605. { cmp 0,%reg = test %reg,%reg }
  4606. (taicpu(p_dist).opcode = A_CMP) and
  4607. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4608. )
  4609. ) and
  4610. { Make sure the destination operands are actually the same }
  4611. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4612. GetNextInstruction(p_dist, hp1_dist) and
  4613. MatchInstruction(hp1_dist, A_JCC, []) then
  4614. begin
  4615. if
  4616. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4617. (
  4618. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4619. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4620. ) then
  4621. SecondValue := -1
  4622. else
  4623. SecondValue := taicpu(p_dist).oper[0]^.val;
  4624. { If both of the TEST constants are identical, delete the second
  4625. TEST that is unnecessary. }
  4626. if (FirstValue = SecondValue) then
  4627. begin
  4628. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4629. RemoveInstruction(p_dist);
  4630. { Don't let the flags register become deallocated and reallocated between the jumps }
  4631. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4632. Result := True;
  4633. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4634. begin
  4635. { Since the second jump's condition is a subset of the first, we
  4636. know it will never branch because the first jump dominates it.
  4637. Get it out of the way now rather than wait for the jump
  4638. optimisations for a speed boost. }
  4639. if IsJumpToLabel(taicpu(hp1_dist)) then
  4640. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4641. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4642. RemoveInstruction(hp1_dist);
  4643. end
  4644. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4645. begin
  4646. { If the inverse of the first condition is a subset of the second,
  4647. the second one will definitely branch if the first one doesn't }
  4648. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4649. MakeUnconditional(taicpu(hp1_dist));
  4650. RemoveDeadCodeAfterJump(hp1_dist);
  4651. end;
  4652. Exit;
  4653. end;
  4654. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4655. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4656. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4657. then the second jump will never branch, so it can also be
  4658. removed regardless of where it goes }
  4659. (
  4660. (FirstValue = -1) or
  4661. (SecondValue = -1) or
  4662. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4663. ) then
  4664. begin
  4665. { Same jump location... can be a register since nothing's changed }
  4666. { If any of the entries are equivalent to test %reg,%reg, then the
  4667. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4668. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4669. if IsJumpToLabel(taicpu(hp1_dist)) then
  4670. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4671. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4672. RemoveInstruction(hp1_dist);
  4673. { Only remove the second test if no jumps or other conditional instructions follow }
  4674. TransferUsedRegs(TmpUsedRegs);
  4675. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4676. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4677. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4678. RemoveInstruction(p_dist);
  4679. Result := True;
  4680. Exit;
  4681. end;
  4682. end;
  4683. end;
  4684. { Search for:
  4685. test %reg,%reg
  4686. j(c1) @lbl1
  4687. ...
  4688. @lbl:
  4689. test %reg,%reg (same register)
  4690. j(c2) @lbl2
  4691. If c2 is a subset of c1, change to:
  4692. test %reg,%reg
  4693. j(c1) @lbl2
  4694. (@lbl1 may become a dead label as a result)
  4695. }
  4696. if (taicpu(p).oper[1]^.typ = top_reg) and
  4697. (taicpu(p).oper[0]^.typ = top_reg) and
  4698. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4699. MatchInstruction(hp1, A_JCC, []) and
  4700. IsJumpToLabel(taicpu(hp1)) then
  4701. begin
  4702. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4703. p_label := nil;
  4704. if Assigned(JumpLabel) then
  4705. p_label := getlabelwithsym(JumpLabel);
  4706. if Assigned(p_label) and
  4707. GetNextInstruction(p_label, p_dist) and
  4708. MatchInstruction(p_dist, A_TEST, []) and
  4709. { It's fine if the second test uses smaller sub-registers }
  4710. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4711. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4712. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4713. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4714. GetNextInstruction(p_dist, hp1_dist) and
  4715. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4716. begin
  4717. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4718. if JumpLabel = JumpLabel_dist then
  4719. { This is an infinite loop }
  4720. Exit;
  4721. { Best optimisation when the first condition is a subset (or equal) of the second }
  4722. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4723. begin
  4724. { Any registers used here will already be allocated }
  4725. if Assigned(JumpLabel) then
  4726. JumpLabel.DecRefs;
  4727. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4728. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4729. Result := True;
  4730. Exit;
  4731. end;
  4732. end;
  4733. end;
  4734. end;
  4735. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4736. var
  4737. hp1, hp2: tai;
  4738. ActiveReg: TRegister;
  4739. OldOffset: asizeint;
  4740. ThisConst: TCGInt;
  4741. function RegDeallocated: Boolean;
  4742. begin
  4743. TransferUsedRegs(TmpUsedRegs);
  4744. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4745. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4746. end;
  4747. begin
  4748. result:=false;
  4749. hp1 := nil;
  4750. { replace
  4751. addX const,%reg1
  4752. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4753. dealloc %reg1
  4754. by
  4755. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4756. }
  4757. if MatchOpType(taicpu(p),top_const,top_reg) then
  4758. begin
  4759. ActiveReg := taicpu(p).oper[1]^.reg;
  4760. { Ensures the entire register was updated }
  4761. if (taicpu(p).opsize >= S_L) and
  4762. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4763. MatchInstruction(hp1,A_LEA,[]) and
  4764. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4765. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4766. (
  4767. { Cover the case where the register in the reference is also the destination register }
  4768. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4769. (
  4770. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4771. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4772. RegDeallocated
  4773. )
  4774. ) then
  4775. begin
  4776. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4777. {$push}
  4778. {$R-}{$Q-}
  4779. { Explicitly disable overflow checking for these offset calculation
  4780. as those do not matter for the final result }
  4781. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4782. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4783. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4784. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4785. {$pop}
  4786. {$ifdef x86_64}
  4787. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4788. begin
  4789. { Overflow; abort }
  4790. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4791. end
  4792. else
  4793. {$endif x86_64}
  4794. begin
  4795. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4796. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4797. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4798. RemoveCurrentP(p, hp1)
  4799. else
  4800. RemoveCurrentP(p);
  4801. result:=true;
  4802. Exit;
  4803. end;
  4804. end;
  4805. if (
  4806. { Save calling GetNextInstructionUsingReg again }
  4807. Assigned(hp1) or
  4808. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4809. ) and
  4810. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4811. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4812. begin
  4813. if taicpu(hp1).oper[0]^.typ = top_const then
  4814. begin
  4815. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4816. if taicpu(hp1).opcode = A_ADD then
  4817. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4818. else
  4819. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4820. Result := True;
  4821. { Handle any overflows }
  4822. case taicpu(p).opsize of
  4823. S_B:
  4824. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4825. S_W:
  4826. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4827. S_L:
  4828. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4829. {$ifdef x86_64}
  4830. S_Q:
  4831. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4832. { Overflow; abort }
  4833. Result := False
  4834. else
  4835. taicpu(p).oper[0]^.val := ThisConst;
  4836. {$endif x86_64}
  4837. else
  4838. InternalError(2021102610);
  4839. end;
  4840. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4841. if Result then
  4842. begin
  4843. if (taicpu(p).oper[0]^.val < 0) and
  4844. (
  4845. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4846. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4847. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4848. ) then
  4849. begin
  4850. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4851. taicpu(p).opcode := A_SUB;
  4852. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4853. end
  4854. else
  4855. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4856. RemoveInstruction(hp1);
  4857. end;
  4858. end
  4859. else
  4860. begin
  4861. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4862. TransferUsedRegs(TmpUsedRegs);
  4863. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4864. hp2 := p;
  4865. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4866. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4867. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4868. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4869. begin
  4870. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4871. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4872. Asml.Remove(p);
  4873. Asml.InsertAfter(p, hp1);
  4874. p := hp1;
  4875. Result := True;
  4876. end;
  4877. end;
  4878. end;
  4879. end;
  4880. end;
  4881. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4882. var
  4883. hp1: tai;
  4884. ref: Integer;
  4885. saveref: treference;
  4886. Multiple: TCGInt;
  4887. Adjacent: Boolean;
  4888. begin
  4889. Result:=false;
  4890. { play save and throw an error if LEA uses a seg register prefix,
  4891. this is most likely an error somewhere else }
  4892. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4893. internalerror(2022022001);
  4894. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4895. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4896. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4897. (
  4898. { do not mess with leas accessing the stack pointer
  4899. unless it's a null operation }
  4900. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4901. (
  4902. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4903. (taicpu(p).oper[0]^.ref^.offset = 0)
  4904. )
  4905. ) and
  4906. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4907. begin
  4908. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4909. begin
  4910. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4911. begin
  4912. taicpu(p).opcode := A_MOV;
  4913. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4914. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4915. end
  4916. else
  4917. begin
  4918. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4919. RemoveCurrentP(p);
  4920. end;
  4921. Result:=true;
  4922. exit;
  4923. end
  4924. else if (
  4925. { continue to use lea to adjust the stack pointer,
  4926. it is the recommended way, but only if not optimizing for size }
  4927. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4928. (cs_opt_size in current_settings.optimizerswitches)
  4929. ) and
  4930. { If the flags register is in use, don't change the instruction
  4931. to an ADD otherwise this will scramble the flags. [Kit] }
  4932. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4933. ConvertLEA(taicpu(p)) then
  4934. begin
  4935. Result:=true;
  4936. exit;
  4937. end;
  4938. end;
  4939. { Don't optimise if the stack or frame pointer is the destination register }
  4940. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4941. Exit;
  4942. if GetNextInstruction(p,hp1) and
  4943. (hp1.typ=ait_instruction) then
  4944. begin
  4945. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4946. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4947. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4948. begin
  4949. TransferUsedRegs(TmpUsedRegs);
  4950. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4951. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4952. begin
  4953. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4954. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4955. RemoveInstruction(hp1);
  4956. result:=true;
  4957. exit;
  4958. end;
  4959. end;
  4960. { changes
  4961. lea <ref1>, reg1
  4962. <op> ...,<ref. with reg1>,...
  4963. to
  4964. <op> ...,<ref1>,... }
  4965. { find a reference which uses reg1 }
  4966. 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
  4967. ref:=0
  4968. 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
  4969. ref:=1
  4970. else
  4971. ref:=-1;
  4972. if (ref<>-1) and
  4973. { reg1 must be either the base or the index }
  4974. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4975. begin
  4976. { reg1 can be removed from the reference }
  4977. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4978. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4979. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4980. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4981. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4982. else
  4983. Internalerror(2019111201);
  4984. { check if the can insert all data of the lea into the second instruction }
  4985. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4986. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4987. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4988. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4989. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4990. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4991. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4992. {$ifdef x86_64}
  4993. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4994. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4995. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4996. )
  4997. {$endif x86_64}
  4998. then
  4999. begin
  5000. { reg1 might not used by the second instruction after it is remove from the reference }
  5001. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5002. begin
  5003. TransferUsedRegs(TmpUsedRegs);
  5004. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5005. { reg1 is not updated so it might not be used afterwards }
  5006. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5007. begin
  5008. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5009. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5010. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5011. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5012. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5013. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5014. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5015. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5016. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5017. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5018. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5019. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5020. RemoveCurrentP(p, hp1);
  5021. result:=true;
  5022. exit;
  5023. end
  5024. end;
  5025. end;
  5026. { recover }
  5027. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5028. end;
  5029. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5030. if Adjacent or
  5031. { Check further ahead (up to 2 instructions ahead for -O2) }
  5032. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5033. begin
  5034. { Check common LEA/LEA conditions }
  5035. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5036. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5037. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5038. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5039. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5040. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5041. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5042. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5043. (
  5044. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5045. calling it (since it calls GetNextInstruction) }
  5046. Adjacent or
  5047. (
  5048. (
  5049. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5050. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5051. ) and (
  5052. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5053. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5054. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5055. )
  5056. )
  5057. ) then
  5058. begin
  5059. { changes
  5060. lea (regX,scale), reg1
  5061. lea offset(reg1,reg1), reg1
  5062. to
  5063. lea offset(regX,scale*2), reg1
  5064. and
  5065. lea (regX,scale1), reg1
  5066. lea offset(reg1,scale2), reg1
  5067. to
  5068. lea offset(regX,scale1*scale2), reg1
  5069. ... so long as the final scale does not exceed 8
  5070. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5071. }
  5072. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5073. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5074. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5075. (
  5076. (
  5077. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5078. ) or (
  5079. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5080. (
  5081. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5082. (
  5083. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5084. Adjacent or
  5085. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5086. )
  5087. )
  5088. )
  5089. ) and (
  5090. (
  5091. { lea (reg1,scale2), reg1 variant }
  5092. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5093. (
  5094. (
  5095. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5096. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5097. ) or (
  5098. { lea (regX,regX), reg1 variant }
  5099. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5100. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5101. )
  5102. )
  5103. ) or (
  5104. { lea (reg1,reg1), reg1 variant }
  5105. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5106. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5107. )
  5108. ) then
  5109. begin
  5110. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5111. { Make everything homogeneous to make calculations easier }
  5112. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5113. begin
  5114. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5115. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5116. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5117. else
  5118. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5119. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5120. end;
  5121. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5122. begin
  5123. { Just to prevent miscalculations }
  5124. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5125. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5126. else
  5127. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5128. end
  5129. else
  5130. begin
  5131. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5132. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5133. end;
  5134. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5135. RemoveCurrentP(p);
  5136. result:=true;
  5137. exit;
  5138. end
  5139. { changes
  5140. lea offset1(regX), reg1
  5141. lea offset2(reg1), reg1
  5142. to
  5143. lea offset1+offset2(regX), reg1 }
  5144. else if
  5145. (
  5146. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5147. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5148. ) or (
  5149. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5150. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5151. (
  5152. (
  5153. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5154. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5155. ) or (
  5156. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5157. (
  5158. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5159. (
  5160. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5161. (
  5162. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5163. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5164. )
  5165. )
  5166. )
  5167. )
  5168. )
  5169. ) then
  5170. begin
  5171. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5172. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5173. begin
  5174. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5175. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5176. { if the register is used as index and base, we have to increase for base as well
  5177. and adapt base }
  5178. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5179. begin
  5180. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5181. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5182. end;
  5183. end
  5184. else
  5185. begin
  5186. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5187. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5188. end;
  5189. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5190. begin
  5191. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5192. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5193. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5194. end;
  5195. RemoveCurrentP(p);
  5196. result:=true;
  5197. exit;
  5198. end;
  5199. end;
  5200. { Change:
  5201. leal/q $x(%reg1),%reg2
  5202. ...
  5203. shll/q $y,%reg2
  5204. To:
  5205. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5206. }
  5207. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5208. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5209. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5210. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5211. (taicpu(hp1).oper[0]^.val <= 3) then
  5212. begin
  5213. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5214. TransferUsedRegs(TmpUsedRegs);
  5215. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5216. if
  5217. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5218. (this works even if scalefactor is zero) }
  5219. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5220. { Ensure offset doesn't go out of bounds }
  5221. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5222. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5223. (
  5224. (
  5225. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5226. (
  5227. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5228. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5229. (
  5230. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5231. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5232. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5233. )
  5234. )
  5235. ) or (
  5236. (
  5237. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5238. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5239. ) and
  5240. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5241. )
  5242. ) then
  5243. begin
  5244. repeat
  5245. with taicpu(p).oper[0]^.ref^ do
  5246. begin
  5247. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5248. if index = base then
  5249. begin
  5250. if Multiple > 4 then
  5251. { Optimisation will no longer work because resultant
  5252. scale factor will exceed 8 }
  5253. Break;
  5254. base := NR_NO;
  5255. scalefactor := 2;
  5256. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5257. end
  5258. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5259. begin
  5260. { Scale factor only works on the index register }
  5261. index := base;
  5262. base := NR_NO;
  5263. end;
  5264. { For safety }
  5265. if scalefactor <= 1 then
  5266. begin
  5267. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5268. scalefactor := Multiple;
  5269. end
  5270. else
  5271. begin
  5272. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5273. scalefactor := scalefactor * Multiple;
  5274. end;
  5275. offset := offset * Multiple;
  5276. end;
  5277. RemoveInstruction(hp1);
  5278. Result := True;
  5279. Exit;
  5280. { This repeat..until loop exists for the benefit of Break }
  5281. until True;
  5282. end;
  5283. end;
  5284. end;
  5285. end;
  5286. end;
  5287. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5288. var
  5289. hp1 : tai;
  5290. begin
  5291. DoSubAddOpt := False;
  5292. if taicpu(p).oper[0]^.typ <> top_const then
  5293. { Should have been confirmed before calling }
  5294. InternalError(2021102601);
  5295. if GetLastInstruction(p, hp1) and
  5296. (hp1.typ = ait_instruction) and
  5297. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5298. case taicpu(hp1).opcode Of
  5299. A_DEC:
  5300. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5301. begin
  5302. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5303. RemoveInstruction(hp1);
  5304. end;
  5305. A_SUB:
  5306. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5307. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5308. begin
  5309. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5310. RemoveInstruction(hp1);
  5311. end;
  5312. A_ADD:
  5313. begin
  5314. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5315. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5316. begin
  5317. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5318. RemoveInstruction(hp1);
  5319. if (taicpu(p).oper[0]^.val = 0) then
  5320. begin
  5321. hp1 := tai(p.next);
  5322. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5323. if not GetLastInstruction(hp1, p) then
  5324. p := hp1;
  5325. DoSubAddOpt := True;
  5326. end
  5327. end;
  5328. end;
  5329. else
  5330. ;
  5331. end;
  5332. end;
  5333. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5334. begin
  5335. Result := False;
  5336. if UpdateTmpUsedRegs then
  5337. TransferUsedRegs(TmpUsedRegs);
  5338. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5339. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5340. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5341. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5342. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5343. (
  5344. (
  5345. (taicpu(hp1).opcode = A_TEST)
  5346. ) or (
  5347. (taicpu(hp1).opcode = A_CMP) and
  5348. { A sanity check more than anything }
  5349. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5350. )
  5351. ) then
  5352. begin
  5353. { change
  5354. mov mem, %reg
  5355. cmp/test x, %reg / test %reg,%reg
  5356. (reg deallocated)
  5357. to
  5358. cmp/test x, mem / cmp 0, mem
  5359. }
  5360. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5361. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5362. begin
  5363. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5364. if (taicpu(hp1).opcode = A_TEST) and
  5365. (
  5366. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5367. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5368. ) then
  5369. begin
  5370. taicpu(hp1).opcode := A_CMP;
  5371. taicpu(hp1).loadconst(0, 0);
  5372. end;
  5373. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5374. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5375. RemoveCurrentP(p, hp1);
  5376. Result := True;
  5377. Exit;
  5378. end;
  5379. end;
  5380. end;
  5381. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5382. var
  5383. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5384. ThisReg, SecondReg: TRegister;
  5385. JumpLoc: TAsmLabel;
  5386. NewSize: TOpSize;
  5387. begin
  5388. Result := False;
  5389. {
  5390. Convert:
  5391. j<c> .L1
  5392. .L2:
  5393. mov 1,reg
  5394. jmp .L3 (or ret, although it might not be a RET yet)
  5395. .L1:
  5396. mov 0,reg
  5397. jmp .L3 (or ret)
  5398. ( As long as .L3 <> .L1 or .L2)
  5399. To:
  5400. mov 0,reg
  5401. set<not(c)> reg
  5402. jmp .L3 (or ret)
  5403. .L2:
  5404. mov 1,reg
  5405. jmp .L3 (or ret)
  5406. .L1:
  5407. mov 0,reg
  5408. jmp .L3 (or ret)
  5409. }
  5410. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5411. Exit;
  5412. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5413. if GetNextInstruction(hp_label, hp2) and
  5414. MatchInstruction(hp2,A_MOV,[]) and
  5415. (taicpu(hp2).oper[0]^.typ = top_const) and
  5416. (
  5417. (
  5418. (taicpu(hp2).oper[1]^.typ = top_reg)
  5419. {$ifdef i386}
  5420. { Under i386, ESI, EDI, EBP and ESP
  5421. don't have an 8-bit representation }
  5422. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5423. {$endif i386}
  5424. ) or (
  5425. {$ifdef i386}
  5426. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5427. {$endif i386}
  5428. (taicpu(hp2).opsize = S_B)
  5429. )
  5430. ) and
  5431. GetNextInstruction(hp2, hp3) and
  5432. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5433. (
  5434. (taicpu(hp3).opcode=A_RET) or
  5435. (
  5436. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5437. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5438. )
  5439. ) and
  5440. GetNextInstruction(hp3, hp4) and
  5441. SkipAligns(hp4, hp4) and
  5442. (hp4.typ=ait_label) and
  5443. (tai_label(hp4).labsym=JumpLoc) and
  5444. (
  5445. not (cs_opt_size in current_settings.optimizerswitches) or
  5446. { If the initial jump is the label's only reference, then it will
  5447. become a dead label if the other conditions are met and hence
  5448. remove at least 2 instructions, including a jump }
  5449. (JumpLoc.getrefs = 1)
  5450. ) and
  5451. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5452. that will be optimised out }
  5453. GetNextInstruction(hp4, hp5) and
  5454. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5455. (taicpu(hp5).oper[0]^.typ = top_const) and
  5456. (
  5457. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5458. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5459. ) and
  5460. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5461. GetNextInstruction(hp5,hp6) and
  5462. (
  5463. (hp6.typ<>ait_label) or
  5464. SkipLabels(hp6, hp6)
  5465. ) and
  5466. (hp6.typ=ait_instruction) then
  5467. begin
  5468. { First, let's look at the two jumps that are hp3 and hp6 }
  5469. if not
  5470. (
  5471. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5472. (
  5473. (taicpu(hp6).opcode=A_RET) or
  5474. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5475. )
  5476. ) then
  5477. { If condition is False, then the JMP/RET instructions matched conventionally }
  5478. begin
  5479. { See if one of the jumps can be instantly converted into a RET }
  5480. if (taicpu(hp3).opcode=A_JMP) then
  5481. begin
  5482. { Reuse hp5 }
  5483. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5484. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5485. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5486. Exit;
  5487. if MatchInstruction(hp5, A_RET, []) then
  5488. begin
  5489. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5490. ConvertJumpToRET(hp3, hp5);
  5491. Result := True;
  5492. end
  5493. else
  5494. Exit;
  5495. end;
  5496. if (taicpu(hp6).opcode=A_JMP) then
  5497. begin
  5498. { Reuse hp5 }
  5499. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5500. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5501. Exit;
  5502. if MatchInstruction(hp5, A_RET, []) then
  5503. begin
  5504. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5505. ConvertJumpToRET(hp6, hp5);
  5506. Result := True;
  5507. end
  5508. else
  5509. Exit;
  5510. end;
  5511. if not
  5512. (
  5513. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5514. (
  5515. (taicpu(hp6).opcode=A_RET) or
  5516. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5517. )
  5518. ) then
  5519. { Still doesn't match }
  5520. Exit;
  5521. end;
  5522. if (taicpu(hp2).oper[0]^.val = 1) then
  5523. begin
  5524. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5525. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5526. end
  5527. else
  5528. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5529. if taicpu(hp2).opsize=S_B then
  5530. begin
  5531. if taicpu(hp2).oper[1]^.typ = top_reg then
  5532. begin
  5533. SecondReg := taicpu(hp2).oper[1]^.reg;
  5534. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5535. end
  5536. else
  5537. begin
  5538. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5539. SecondReg := NR_NO;
  5540. end;
  5541. hp_pos := p;
  5542. hp_allocstart := hp4;
  5543. end
  5544. else
  5545. begin
  5546. { Will be a register because the size can't be S_B otherwise }
  5547. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5548. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5549. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5550. if (cs_opt_size in current_settings.optimizerswitches) then
  5551. begin
  5552. { Favour using MOVZX when optimising for size }
  5553. case taicpu(hp2).opsize of
  5554. S_W:
  5555. NewSize := S_BW;
  5556. S_L:
  5557. NewSize := S_BL;
  5558. {$ifdef x86_64}
  5559. S_Q:
  5560. begin
  5561. NewSize := S_BL;
  5562. { Will implicitly zero-extend to 64-bit }
  5563. setsubreg(SecondReg, R_SUBD);
  5564. end;
  5565. {$endif x86_64}
  5566. else
  5567. InternalError(2022101301);
  5568. end;
  5569. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5570. { Inserting it right before p will guarantee that the flags are also tracked }
  5571. Asml.InsertBefore(hp5, p);
  5572. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5573. hp_pos := hp5;
  5574. hp_allocstart := hp4;
  5575. end
  5576. else
  5577. begin
  5578. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5579. { Inserting it right before p will guarantee that the flags are also tracked }
  5580. Asml.InsertBefore(hp5, p);
  5581. hp_pos := p;
  5582. hp_allocstart := hp5;
  5583. end;
  5584. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5585. end;
  5586. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5587. taicpu(hp4).condition := taicpu(p).condition;
  5588. asml.InsertBefore(hp4, hp_pos);
  5589. if taicpu(hp3).is_jmp then
  5590. begin
  5591. JumpLoc.decrefs;
  5592. MakeUnconditional(taicpu(p));
  5593. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5594. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5595. end
  5596. else
  5597. ConvertJumpToRET(p, hp3);
  5598. if SecondReg <> NR_NO then
  5599. { Ensure the destination register is allocated over this region }
  5600. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5601. if (JumpLoc.getrefs = 0) then
  5602. RemoveDeadCodeAfterJump(hp3);
  5603. Result:=true;
  5604. exit;
  5605. end;
  5606. end;
  5607. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5608. var
  5609. hp1, hp2: tai;
  5610. ActiveReg: TRegister;
  5611. OldOffset: asizeint;
  5612. ThisConst: TCGInt;
  5613. function RegDeallocated: Boolean;
  5614. begin
  5615. TransferUsedRegs(TmpUsedRegs);
  5616. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5617. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5618. end;
  5619. begin
  5620. Result:=false;
  5621. hp1 := nil;
  5622. { replace
  5623. subX const,%reg1
  5624. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5625. dealloc %reg1
  5626. by
  5627. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5628. }
  5629. if MatchOpType(taicpu(p),top_const,top_reg) then
  5630. begin
  5631. ActiveReg := taicpu(p).oper[1]^.reg;
  5632. { Ensures the entire register was updated }
  5633. if (taicpu(p).opsize >= S_L) and
  5634. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5635. MatchInstruction(hp1,A_LEA,[]) and
  5636. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5637. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5638. (
  5639. { Cover the case where the register in the reference is also the destination register }
  5640. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5641. (
  5642. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5643. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5644. RegDeallocated
  5645. )
  5646. ) then
  5647. begin
  5648. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5649. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5650. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5651. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5652. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5653. {$ifdef x86_64}
  5654. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5655. begin
  5656. { Overflow; abort }
  5657. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5658. end
  5659. else
  5660. {$endif x86_64}
  5661. begin
  5662. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5663. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5664. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5665. RemoveCurrentP(p, hp1)
  5666. else
  5667. RemoveCurrentP(p);
  5668. result:=true;
  5669. Exit;
  5670. end;
  5671. end;
  5672. if (
  5673. { Save calling GetNextInstructionUsingReg again }
  5674. Assigned(hp1) or
  5675. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5676. ) and
  5677. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5678. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5679. begin
  5680. if taicpu(hp1).oper[0]^.typ = top_const then
  5681. begin
  5682. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5683. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5684. Result := True;
  5685. { Handle any overflows }
  5686. case taicpu(p).opsize of
  5687. S_B:
  5688. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5689. S_W:
  5690. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5691. S_L:
  5692. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5693. {$ifdef x86_64}
  5694. S_Q:
  5695. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5696. { Overflow; abort }
  5697. Result := False
  5698. else
  5699. taicpu(p).oper[0]^.val := ThisConst;
  5700. {$endif x86_64}
  5701. else
  5702. InternalError(2021102611);
  5703. end;
  5704. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5705. if Result then
  5706. begin
  5707. if (taicpu(p).oper[0]^.val < 0) and
  5708. (
  5709. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5710. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5711. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5712. ) then
  5713. begin
  5714. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5715. taicpu(p).opcode := A_SUB;
  5716. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5717. end
  5718. else
  5719. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5720. RemoveInstruction(hp1);
  5721. end;
  5722. end
  5723. else
  5724. begin
  5725. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5726. TransferUsedRegs(TmpUsedRegs);
  5727. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5728. hp2 := p;
  5729. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5730. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5731. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5732. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5733. begin
  5734. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5735. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5736. Asml.Remove(p);
  5737. Asml.InsertAfter(p, hp1);
  5738. p := hp1;
  5739. Result := True;
  5740. Exit;
  5741. end;
  5742. end;
  5743. end;
  5744. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5745. { * change "sub/add const1, reg" or "dec reg" followed by
  5746. "sub const2, reg" to one "sub ..., reg" }
  5747. {$ifdef i386}
  5748. if (taicpu(p).oper[0]^.val = 2) and
  5749. (ActiveReg = NR_ESP) and
  5750. { Don't do the sub/push optimization if the sub }
  5751. { comes from setting up the stack frame (JM) }
  5752. (not(GetLastInstruction(p,hp1)) or
  5753. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5754. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5755. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5756. begin
  5757. hp1 := tai(p.next);
  5758. while Assigned(hp1) and
  5759. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5760. not RegReadByInstruction(NR_ESP,hp1) and
  5761. not RegModifiedByInstruction(NR_ESP,hp1) do
  5762. hp1 := tai(hp1.next);
  5763. if Assigned(hp1) and
  5764. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5765. begin
  5766. taicpu(hp1).changeopsize(S_L);
  5767. if taicpu(hp1).oper[0]^.typ=top_reg then
  5768. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5769. hp1 := tai(p.next);
  5770. RemoveCurrentp(p, hp1);
  5771. Result:=true;
  5772. exit;
  5773. end;
  5774. end;
  5775. {$endif i386}
  5776. if DoSubAddOpt(p) then
  5777. Result:=true;
  5778. end;
  5779. end;
  5780. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5781. var
  5782. TmpBool1,TmpBool2 : Boolean;
  5783. tmpref : treference;
  5784. hp1,hp2: tai;
  5785. mask: tcgint;
  5786. begin
  5787. Result:=false;
  5788. { All these optimisations work on "shl/sal const,%reg" }
  5789. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5790. Exit;
  5791. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5792. (taicpu(p).oper[0]^.val <= 3) then
  5793. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5794. begin
  5795. { should we check the next instruction? }
  5796. TmpBool1 := True;
  5797. { have we found an add/sub which could be
  5798. integrated in the lea? }
  5799. TmpBool2 := False;
  5800. reference_reset(tmpref,2,[]);
  5801. TmpRef.index := taicpu(p).oper[1]^.reg;
  5802. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5803. while TmpBool1 and
  5804. GetNextInstruction(p, hp1) and
  5805. (tai(hp1).typ = ait_instruction) and
  5806. ((((taicpu(hp1).opcode = A_ADD) or
  5807. (taicpu(hp1).opcode = A_SUB)) and
  5808. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5809. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5810. (((taicpu(hp1).opcode = A_INC) or
  5811. (taicpu(hp1).opcode = A_DEC)) and
  5812. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5813. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5814. ((taicpu(hp1).opcode = A_LEA) and
  5815. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5816. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5817. (not GetNextInstruction(hp1,hp2) or
  5818. not instrReadsFlags(hp2)) Do
  5819. begin
  5820. TmpBool1 := False;
  5821. if taicpu(hp1).opcode=A_LEA then
  5822. begin
  5823. if (TmpRef.base = NR_NO) and
  5824. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5825. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5826. { Segment register isn't a concern here }
  5827. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5828. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5829. begin
  5830. TmpBool1 := True;
  5831. TmpBool2 := True;
  5832. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5833. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5834. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5835. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5836. RemoveInstruction(hp1);
  5837. end
  5838. end
  5839. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5840. begin
  5841. TmpBool1 := True;
  5842. TmpBool2 := True;
  5843. case taicpu(hp1).opcode of
  5844. A_ADD:
  5845. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5846. A_SUB:
  5847. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5848. else
  5849. internalerror(2019050536);
  5850. end;
  5851. RemoveInstruction(hp1);
  5852. end
  5853. else
  5854. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5855. (((taicpu(hp1).opcode = A_ADD) and
  5856. (TmpRef.base = NR_NO)) or
  5857. (taicpu(hp1).opcode = A_INC) or
  5858. (taicpu(hp1).opcode = A_DEC)) then
  5859. begin
  5860. TmpBool1 := True;
  5861. TmpBool2 := True;
  5862. case taicpu(hp1).opcode of
  5863. A_ADD:
  5864. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5865. A_INC:
  5866. inc(TmpRef.offset);
  5867. A_DEC:
  5868. dec(TmpRef.offset);
  5869. else
  5870. internalerror(2019050535);
  5871. end;
  5872. RemoveInstruction(hp1);
  5873. end;
  5874. end;
  5875. if TmpBool2
  5876. {$ifndef x86_64}
  5877. or
  5878. ((current_settings.optimizecputype < cpu_Pentium2) and
  5879. (taicpu(p).oper[0]^.val <= 3) and
  5880. not(cs_opt_size in current_settings.optimizerswitches))
  5881. {$endif x86_64}
  5882. then
  5883. begin
  5884. if not(TmpBool2) and
  5885. (taicpu(p).oper[0]^.val=1) then
  5886. begin
  5887. taicpu(p).opcode := A_ADD;
  5888. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5889. end
  5890. else
  5891. begin
  5892. taicpu(p).opcode := A_LEA;
  5893. taicpu(p).loadref(0, TmpRef);
  5894. end;
  5895. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5896. Result := True;
  5897. end;
  5898. end
  5899. {$ifndef x86_64}
  5900. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5901. begin
  5902. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5903. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5904. (unlike shl, which is only Tairable in the U pipe) }
  5905. if taicpu(p).oper[0]^.val=1 then
  5906. begin
  5907. taicpu(p).opcode := A_ADD;
  5908. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5909. Result := True;
  5910. end
  5911. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5912. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5913. else if (taicpu(p).opsize = S_L) and
  5914. (taicpu(p).oper[0]^.val<= 3) then
  5915. begin
  5916. reference_reset(tmpref,2,[]);
  5917. TmpRef.index := taicpu(p).oper[1]^.reg;
  5918. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5919. taicpu(p).opcode := A_LEA;
  5920. taicpu(p).loadref(0, TmpRef);
  5921. Result := True;
  5922. end;
  5923. end
  5924. {$endif x86_64}
  5925. else if
  5926. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5927. (
  5928. (
  5929. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5930. SetAndTest(hp1, hp2)
  5931. {$ifdef x86_64}
  5932. ) or
  5933. (
  5934. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5935. GetNextInstruction(hp1, hp2) and
  5936. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5937. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5938. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5939. {$endif x86_64}
  5940. )
  5941. ) and
  5942. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5943. begin
  5944. { Change:
  5945. shl x, %reg1
  5946. mov -(1<<x), %reg2
  5947. and %reg2, %reg1
  5948. Or:
  5949. shl x, %reg1
  5950. and -(1<<x), %reg1
  5951. To just:
  5952. shl x, %reg1
  5953. Since the and operation only zeroes bits that are already zero from the shl operation
  5954. }
  5955. case taicpu(p).oper[0]^.val of
  5956. 8:
  5957. mask:=$FFFFFFFFFFFFFF00;
  5958. 16:
  5959. mask:=$FFFFFFFFFFFF0000;
  5960. 32:
  5961. mask:=$FFFFFFFF00000000;
  5962. 63:
  5963. { Constant pre-calculated to prevent overflow errors with Int64 }
  5964. mask:=$8000000000000000;
  5965. else
  5966. begin
  5967. if taicpu(p).oper[0]^.val >= 64 then
  5968. { Shouldn't happen realistically, since the register
  5969. is guaranteed to be set to zero at this point }
  5970. mask := 0
  5971. else
  5972. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5973. end;
  5974. end;
  5975. if taicpu(hp1).oper[0]^.val = mask then
  5976. begin
  5977. { Everything checks out, perform the optimisation, as long as
  5978. the FLAGS register isn't being used}
  5979. TransferUsedRegs(TmpUsedRegs);
  5980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5981. {$ifdef x86_64}
  5982. if (hp1 <> hp2) then
  5983. begin
  5984. { "shl/mov/and" version }
  5985. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5986. { Don't do the optimisation if the FLAGS register is in use }
  5987. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5988. begin
  5989. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5990. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5991. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5992. begin
  5993. RemoveInstruction(hp1);
  5994. Result := True;
  5995. end;
  5996. { Only set Result to True if the 'mov' instruction was removed }
  5997. RemoveInstruction(hp2);
  5998. end;
  5999. end
  6000. else
  6001. {$endif x86_64}
  6002. begin
  6003. { "shl/and" version }
  6004. { Don't do the optimisation if the FLAGS register is in use }
  6005. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6006. begin
  6007. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6008. RemoveInstruction(hp1);
  6009. Result := True;
  6010. end;
  6011. end;
  6012. Exit;
  6013. end
  6014. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6015. begin
  6016. { Even if the mask doesn't allow for its removal, we might be
  6017. able to optimise the mask for the "shl/and" version, which
  6018. may permit other peephole optimisations }
  6019. {$ifdef DEBUG_AOPTCPU}
  6020. mask := taicpu(hp1).oper[0]^.val and mask;
  6021. if taicpu(hp1).oper[0]^.val <> mask then
  6022. begin
  6023. DebugMsg(
  6024. SPeepholeOptimization +
  6025. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6026. ' to $' + debug_tostr(mask) +
  6027. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6028. taicpu(hp1).oper[0]^.val := mask;
  6029. end;
  6030. {$else DEBUG_AOPTCPU}
  6031. { If debugging is off, just set the operand even if it's the same }
  6032. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6033. {$endif DEBUG_AOPTCPU}
  6034. end;
  6035. end;
  6036. {
  6037. change
  6038. shl/sal const,reg
  6039. <op> ...(...,reg,1),...
  6040. into
  6041. <op> ...(...,reg,1 shl const),...
  6042. if const in 1..3
  6043. }
  6044. if MatchOpType(taicpu(p), top_const, top_reg) and
  6045. (taicpu(p).oper[0]^.val in [1..3]) and
  6046. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6047. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6048. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6049. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6050. MatchOpType(taicpu(hp1),top_ref))
  6051. ) and
  6052. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6053. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6054. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6055. begin
  6056. TransferUsedRegs(TmpUsedRegs);
  6057. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6058. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6059. begin
  6060. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6061. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6062. RemoveCurrentP(p);
  6063. Result:=true;
  6064. end;
  6065. end;
  6066. end;
  6067. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6068. begin
  6069. case shr_size of
  6070. S_B:
  6071. { No valid combinations }
  6072. Result := False;
  6073. S_W:
  6074. Result := (Shift >= 8) and (movz_size = S_BW);
  6075. S_L:
  6076. Result :=
  6077. (Shift >= 24) { Any opsize is valid for this shift } or
  6078. ((Shift >= 16) and (movz_size = S_WL));
  6079. {$ifdef x86_64}
  6080. S_Q:
  6081. Result :=
  6082. (Shift >= 56) { Any opsize is valid for this shift } or
  6083. ((Shift >= 48) and (movz_size = S_WL));
  6084. {$endif x86_64}
  6085. else
  6086. InternalError(2022081510);
  6087. end;
  6088. end;
  6089. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6090. var
  6091. hp1, hp2: tai;
  6092. Shift: TCGInt;
  6093. LimitSize: Topsize;
  6094. DoNotMerge: Boolean;
  6095. begin
  6096. Result := False;
  6097. { All these optimisations work on "shr const,%reg" }
  6098. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6099. Exit;
  6100. DoNotMerge := False;
  6101. Shift := taicpu(p).oper[0]^.val;
  6102. LimitSize := taicpu(p).opsize;
  6103. hp1 := p;
  6104. repeat
  6105. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6106. Exit;
  6107. case taicpu(hp1).opcode of
  6108. A_TEST, A_CMP, A_Jcc:
  6109. { Skip over conditional jumps and relevant comparisons }
  6110. Continue;
  6111. A_MOVZX:
  6112. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6113. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6114. begin
  6115. { Since the original register is being read as is, subsequent
  6116. SHRs must not be merged at this point }
  6117. DoNotMerge := True;
  6118. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6119. begin
  6120. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6121. begin
  6122. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6123. taicpu(hp1).opcode := A_MOV;
  6124. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6125. case taicpu(hp1).opsize of
  6126. S_BW:
  6127. taicpu(hp1).opsize := S_W;
  6128. S_BL, S_WL:
  6129. taicpu(hp1).opsize := S_L;
  6130. else
  6131. InternalError(2022081503);
  6132. end;
  6133. { p itself hasn't changed, so no need to set Result to True }
  6134. Include(OptsToCheck, aoc_ForceNewIteration);
  6135. { See if there's anything afterwards that can be
  6136. optimised, since the input register hasn't changed }
  6137. Continue;
  6138. end;
  6139. { NOTE: If the MOVZX instruction reads and writes the same
  6140. register, defer this to the post-peephole optimisation stage }
  6141. Exit;
  6142. end;
  6143. end;
  6144. A_SHL, A_SAL, A_SHR:
  6145. if (taicpu(hp1).opsize <= LimitSize) and
  6146. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6147. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6148. begin
  6149. { Make sure the sizes don't exceed the register size limit
  6150. (measured by the shift value falling below the limit) }
  6151. if taicpu(hp1).opsize < LimitSize then
  6152. LimitSize := taicpu(hp1).opsize;
  6153. if taicpu(hp1).opcode = A_SHR then
  6154. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6155. else
  6156. begin
  6157. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6158. DoNotMerge := True;
  6159. end;
  6160. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6161. Exit;
  6162. { Since we've established that the combined shift is within
  6163. limits, we can actually combine the adjacent SHR
  6164. instructions even if they're different sizes }
  6165. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6166. begin
  6167. hp2 := tai(hp1.Previous);
  6168. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6169. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6170. RemoveInstruction(hp1);
  6171. hp1 := hp2;
  6172. { Though p has changed, only the constant has, and its
  6173. effects can still be detected on the next iteration of
  6174. the repeat..until loop }
  6175. Include(OptsToCheck, aoc_ForceNewIteration);
  6176. end;
  6177. { Move onto the next instruction }
  6178. Continue;
  6179. end;
  6180. else
  6181. ;
  6182. end;
  6183. Break;
  6184. until False;
  6185. end;
  6186. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6187. var
  6188. CurrentRef: TReference;
  6189. FullReg: TRegister;
  6190. hp1, hp2: tai;
  6191. begin
  6192. Result := False;
  6193. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6194. Exit;
  6195. { We assume you've checked if the operand is actually a reference by
  6196. this point. If it isn't, you'll most likely get an access violation }
  6197. CurrentRef := first_mov.oper[1]^.ref^;
  6198. { Memory must be aligned }
  6199. if (CurrentRef.offset mod 4) <> 0 then
  6200. Exit;
  6201. Inc(CurrentRef.offset);
  6202. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6203. if MatchOperand(second_mov.oper[0]^, 0) and
  6204. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6205. GetNextInstruction(second_mov, hp1) and
  6206. (hp1.typ = ait_instruction) and
  6207. (taicpu(hp1).opcode = A_MOV) and
  6208. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6209. (taicpu(hp1).oper[0]^.val = 0) then
  6210. begin
  6211. Inc(CurrentRef.offset);
  6212. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6213. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6214. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6215. begin
  6216. case taicpu(hp1).opsize of
  6217. S_B:
  6218. if GetNextInstruction(hp1, hp2) and
  6219. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6220. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6221. (taicpu(hp2).oper[0]^.val = 0) then
  6222. begin
  6223. Inc(CurrentRef.offset);
  6224. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6225. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6226. (taicpu(hp2).opsize = S_B) then
  6227. begin
  6228. RemoveInstruction(hp1);
  6229. RemoveInstruction(hp2);
  6230. first_mov.opsize := S_L;
  6231. if first_mov.oper[0]^.typ = top_reg then
  6232. begin
  6233. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6234. { Reuse second_mov as a MOVZX instruction }
  6235. second_mov.opcode := A_MOVZX;
  6236. second_mov.opsize := S_BL;
  6237. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6238. second_mov.loadreg(1, FullReg);
  6239. first_mov.oper[0]^.reg := FullReg;
  6240. asml.Remove(second_mov);
  6241. asml.InsertBefore(second_mov, first_mov);
  6242. end
  6243. else
  6244. { It's a value }
  6245. begin
  6246. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6247. RemoveInstruction(second_mov);
  6248. end;
  6249. Result := True;
  6250. Exit;
  6251. end;
  6252. end;
  6253. S_W:
  6254. begin
  6255. RemoveInstruction(hp1);
  6256. first_mov.opsize := S_L;
  6257. if first_mov.oper[0]^.typ = top_reg then
  6258. begin
  6259. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6260. { Reuse second_mov as a MOVZX instruction }
  6261. second_mov.opcode := A_MOVZX;
  6262. second_mov.opsize := S_BL;
  6263. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6264. second_mov.loadreg(1, FullReg);
  6265. first_mov.oper[0]^.reg := FullReg;
  6266. asml.Remove(second_mov);
  6267. asml.InsertBefore(second_mov, first_mov);
  6268. end
  6269. else
  6270. { It's a value }
  6271. begin
  6272. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6273. RemoveInstruction(second_mov);
  6274. end;
  6275. Result := True;
  6276. Exit;
  6277. end;
  6278. else
  6279. ;
  6280. end;
  6281. end;
  6282. end;
  6283. end;
  6284. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6285. { returns true if a "continue" should be done after this optimization }
  6286. var
  6287. hp1, hp2: tai;
  6288. begin
  6289. Result := false;
  6290. if MatchOpType(taicpu(p),top_ref) and
  6291. GetNextInstruction(p, hp1) and
  6292. (hp1.typ = ait_instruction) and
  6293. (((taicpu(hp1).opcode = A_FLD) and
  6294. (taicpu(p).opcode = A_FSTP)) or
  6295. ((taicpu(p).opcode = A_FISTP) and
  6296. (taicpu(hp1).opcode = A_FILD))) and
  6297. MatchOpType(taicpu(hp1),top_ref) and
  6298. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6299. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6300. begin
  6301. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6302. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6303. GetNextInstruction(hp1, hp2) and
  6304. (((hp2.typ = ait_instruction) and
  6305. IsExitCode(hp2) and
  6306. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6307. not(assigned(current_procinfo.procdef.funcretsym) and
  6308. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6309. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6310. { fstp <temp>
  6311. fld <temp>
  6312. <dealloc> <temp>
  6313. }
  6314. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6315. (tai_tempalloc(hp2).allocation=false) and
  6316. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6317. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6318. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6319. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6320. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6321. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6322. )
  6323. )
  6324. ) then
  6325. begin
  6326. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6327. RemoveInstruction(hp1);
  6328. RemoveCurrentP(p, hp2);
  6329. { first case: exit code }
  6330. if hp2.typ = ait_instruction then
  6331. RemoveLastDeallocForFuncRes(p);
  6332. Result := true;
  6333. end
  6334. else
  6335. { we can do this only in fast math mode as fstp is rounding ...
  6336. ... still disabled as it breaks the compiler and/or rtl }
  6337. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6338. { ... or if another fstp equal to the first one follows }
  6339. (GetNextInstruction(hp1,hp2) and
  6340. (hp2.typ = ait_instruction) and
  6341. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6342. (taicpu(p).opsize=taicpu(hp2).opsize))
  6343. ) and
  6344. { fst can't store an extended/comp value }
  6345. (taicpu(p).opsize <> S_FX) and
  6346. (taicpu(p).opsize <> S_IQ) then
  6347. begin
  6348. if (taicpu(p).opcode = A_FSTP) then
  6349. taicpu(p).opcode := A_FST
  6350. else
  6351. taicpu(p).opcode := A_FIST;
  6352. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6353. RemoveInstruction(hp1);
  6354. end;
  6355. end;
  6356. end;
  6357. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6358. var
  6359. hp1, hp2: tai;
  6360. begin
  6361. result:=false;
  6362. if MatchOpType(taicpu(p),top_reg) and
  6363. GetNextInstruction(p, hp1) and
  6364. (hp1.typ = Ait_Instruction) and
  6365. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6366. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6367. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6368. { change to
  6369. fld reg fxxx reg,st
  6370. fxxxp st, st1 (hp1)
  6371. Remark: non commutative operations must be reversed!
  6372. }
  6373. begin
  6374. case taicpu(hp1).opcode Of
  6375. A_FMULP,A_FADDP,
  6376. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6377. begin
  6378. case taicpu(hp1).opcode Of
  6379. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6380. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6381. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6382. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6383. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6384. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6385. else
  6386. internalerror(2019050534);
  6387. end;
  6388. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6389. taicpu(hp1).oper[1]^.reg := NR_ST;
  6390. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6391. RemoveCurrentP(p, hp1);
  6392. Result:=true;
  6393. exit;
  6394. end;
  6395. else
  6396. ;
  6397. end;
  6398. end
  6399. else
  6400. if MatchOpType(taicpu(p),top_ref) and
  6401. GetNextInstruction(p, hp2) and
  6402. (hp2.typ = Ait_Instruction) and
  6403. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6404. (taicpu(p).opsize in [S_FS, S_FL]) and
  6405. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6406. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6407. if GetLastInstruction(p, hp1) and
  6408. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6409. MatchOpType(taicpu(hp1),top_ref) and
  6410. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6411. if ((taicpu(hp2).opcode = A_FMULP) or
  6412. (taicpu(hp2).opcode = A_FADDP)) then
  6413. { change to
  6414. fld/fst mem1 (hp1) fld/fst mem1
  6415. fld mem1 (p) fadd/
  6416. faddp/ fmul st, st
  6417. fmulp st, st1 (hp2) }
  6418. begin
  6419. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6420. RemoveCurrentP(p, hp1);
  6421. if (taicpu(hp2).opcode = A_FADDP) then
  6422. taicpu(hp2).opcode := A_FADD
  6423. else
  6424. taicpu(hp2).opcode := A_FMUL;
  6425. taicpu(hp2).oper[1]^.reg := NR_ST;
  6426. end
  6427. else
  6428. { change to
  6429. fld/fst mem1 (hp1) fld/fst mem1
  6430. fld mem1 (p) fld st
  6431. }
  6432. begin
  6433. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6434. taicpu(p).changeopsize(S_FL);
  6435. taicpu(p).loadreg(0,NR_ST);
  6436. end
  6437. else
  6438. begin
  6439. case taicpu(hp2).opcode Of
  6440. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6441. { change to
  6442. fld/fst mem1 (hp1) fld/fst mem1
  6443. fld mem2 (p) fxxx mem2
  6444. fxxxp st, st1 (hp2) }
  6445. begin
  6446. case taicpu(hp2).opcode Of
  6447. A_FADDP: taicpu(p).opcode := A_FADD;
  6448. A_FMULP: taicpu(p).opcode := A_FMUL;
  6449. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6450. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6451. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6452. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6453. else
  6454. internalerror(2019050533);
  6455. end;
  6456. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6457. RemoveInstruction(hp2);
  6458. end
  6459. else
  6460. ;
  6461. end
  6462. end
  6463. end;
  6464. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6465. begin
  6466. Result := condition_in(cond1, cond2) or
  6467. { Not strictly subsets due to the actual flags checked, but because we're
  6468. comparing integers, E is a subset of AE and GE and their aliases }
  6469. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6470. end;
  6471. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6472. var
  6473. v: TCGInt;
  6474. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6475. FirstMatch: Boolean;
  6476. NewReg: TRegister;
  6477. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6478. begin
  6479. Result:=false;
  6480. { All these optimisations need a next instruction }
  6481. if not GetNextInstruction(p, hp1) then
  6482. Exit;
  6483. { Search for:
  6484. cmp ###,###
  6485. j(c1) @lbl1
  6486. ...
  6487. @lbl:
  6488. cmp ###,### (same comparison as above)
  6489. j(c2) @lbl2
  6490. If c1 is a subset of c2, change to:
  6491. cmp ###,###
  6492. j(c1) @lbl2
  6493. (@lbl1 may become a dead label as a result)
  6494. }
  6495. { Also handle cases where there are multiple jumps in a row }
  6496. p_jump := hp1;
  6497. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6498. begin
  6499. if IsJumpToLabel(taicpu(p_jump)) then
  6500. begin
  6501. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6502. p_label := nil;
  6503. if Assigned(JumpLabel) then
  6504. p_label := getlabelwithsym(JumpLabel);
  6505. if Assigned(p_label) and
  6506. GetNextInstruction(p_label, p_dist) and
  6507. MatchInstruction(p_dist, A_CMP, []) and
  6508. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6509. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6510. GetNextInstruction(p_dist, hp1_dist) and
  6511. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6512. begin
  6513. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6514. if JumpLabel = JumpLabel_dist then
  6515. { This is an infinite loop }
  6516. Exit;
  6517. { Best optimisation when the first condition is a subset (or equal) of the second }
  6518. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6519. begin
  6520. { Any registers used here will already be allocated }
  6521. if Assigned(JumpLabel) then
  6522. JumpLabel.DecRefs;
  6523. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6524. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6525. Result := True;
  6526. { Don't exit yet. Since p and p_jump haven't actually been
  6527. removed, we can check for more on this iteration }
  6528. end
  6529. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6530. GetNextInstruction(hp1_dist, hp1_label) and
  6531. SkipAligns(hp1_label, hp1_label) and
  6532. (hp1_label.typ = ait_label) then
  6533. begin
  6534. JumpLabel_far := tai_label(hp1_label).labsym;
  6535. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6536. { This is an infinite loop }
  6537. Exit;
  6538. if Assigned(JumpLabel_far) then
  6539. begin
  6540. { In this situation, if the first jump branches, the second one will never,
  6541. branch so change the destination label to after the second jump }
  6542. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6543. if Assigned(JumpLabel) then
  6544. JumpLabel.DecRefs;
  6545. JumpLabel_far.IncRefs;
  6546. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6547. Result := True;
  6548. { Don't exit yet. Since p and p_jump haven't actually been
  6549. removed, we can check for more on this iteration }
  6550. Continue;
  6551. end;
  6552. end;
  6553. end;
  6554. end;
  6555. { Search for:
  6556. cmp ###,###
  6557. j(c1) @lbl1
  6558. cmp ###,### (same as first)
  6559. Remove second cmp
  6560. }
  6561. if GetNextInstruction(p_jump, hp2) and
  6562. (
  6563. (
  6564. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6565. (
  6566. (
  6567. MatchOpType(taicpu(p), top_const, top_reg) and
  6568. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6569. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6570. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6571. ) or (
  6572. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6573. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6574. )
  6575. )
  6576. ) or (
  6577. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6578. MatchOperand(taicpu(p).oper[0]^, 0) and
  6579. (taicpu(p).oper[1]^.typ = top_reg) and
  6580. MatchInstruction(hp2, A_TEST, []) and
  6581. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6582. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6583. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6584. )
  6585. ) then
  6586. begin
  6587. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6588. RemoveInstruction(hp2);
  6589. Result := True;
  6590. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6591. end;
  6592. GetNextInstruction(p_jump, p_jump);
  6593. end;
  6594. {
  6595. Try to optimise the following:
  6596. cmp $x,### ($x and $y can be registers or constants)
  6597. je @lbl1 (only reference)
  6598. cmp $y,### (### are identical)
  6599. @Lbl:
  6600. sete %reg1
  6601. Change to:
  6602. cmp $x,###
  6603. sete %reg2 (allocate new %reg2)
  6604. cmp $y,###
  6605. sete %reg1
  6606. orb %reg2,%reg1
  6607. (dealloc %reg2)
  6608. This adds an instruction (so don't perform under -Os), but it removes
  6609. a conditional branch.
  6610. }
  6611. if not (cs_opt_size in current_settings.optimizerswitches) and
  6612. (
  6613. (hp1 = p_jump) or
  6614. GetNextInstruction(p, hp1)
  6615. ) and
  6616. MatchInstruction(hp1, A_Jcc, []) and
  6617. IsJumpToLabel(taicpu(hp1)) and
  6618. (taicpu(hp1).condition in [C_E, C_Z]) and
  6619. GetNextInstruction(hp1, hp2) and
  6620. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6621. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6622. { The first operand of CMP instructions can only be a register or
  6623. immediate anyway, so no need to check }
  6624. GetNextInstruction(hp2, p_label) and
  6625. (
  6626. (p_label.typ = ait_label) or
  6627. (
  6628. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6629. to potentially cut down on the iterations of Pass 1 }
  6630. MatchInstruction(p_label, A_Jcc, []) and
  6631. IsJumpToLabel(taicpu(p_label)) and
  6632. { Use p_dist to hold the jump briefly }
  6633. SetAndTest(p_label, p_dist) and
  6634. GetNextInstruction(p_dist, p_label) and
  6635. (p_label.typ = ait_label) and
  6636. (tai_label(p_label).labsym.getrefs >= 2) and
  6637. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6638. { We might as well collapse the jump now }
  6639. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6640. )
  6641. ) and
  6642. (tai_label(p_label).labsym.getrefs = 1) and
  6643. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6644. GetNextInstruction(p_label, p_dist) and
  6645. MatchInstruction(p_dist, A_SETcc, []) and
  6646. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6647. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6648. { Get the instruction after the SETcc instruction so we can
  6649. allocate a new register over the entire range }
  6650. GetNextInstruction(p_dist, hp1_dist) then
  6651. begin
  6652. TransferUsedRegs(TmpUsedRegs);
  6653. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6654. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6655. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6656. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6657. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6658. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6659. begin
  6660. { Register can appear in p if it's not used afterwards, so only
  6661. allocate between hp1 and hp1_dist }
  6662. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6663. if NewReg <> NR_NO then
  6664. begin
  6665. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6666. { Change the jump instruction into a SETcc instruction }
  6667. taicpu(hp1).opcode := A_SETcc;
  6668. taicpu(hp1).opsize := S_B;
  6669. taicpu(hp1).loadreg(0, NewReg);
  6670. { This is now a dead label }
  6671. tai_label(p_label).labsym.decrefs;
  6672. { Prefer adding before the next instruction so the FLAGS
  6673. register is deallocated first }
  6674. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6675. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6676. AsmL.InsertBefore(
  6677. hp2,
  6678. hp1_dist
  6679. );
  6680. { Make sure the new register is in use over the new instruction
  6681. (long-winded, but things work best when the FLAGS register
  6682. is not allocated here) }
  6683. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6684. Result := True;
  6685. { Don't exit yet, as p wasn't changed and hp1, while
  6686. modified, is still intact and might be optimised by the
  6687. SETcc optimisation below }
  6688. end;
  6689. end;
  6690. end;
  6691. if taicpu(p).oper[0]^.typ = top_const then
  6692. begin
  6693. if (taicpu(p).oper[0]^.val = 0) and
  6694. (taicpu(p).oper[1]^.typ = top_reg) and
  6695. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6696. begin
  6697. hp2 := p;
  6698. FirstMatch := True;
  6699. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6700. anything meaningful once it's converted to "test %reg,%reg";
  6701. additionally, some jumps will always (or never) branch, so
  6702. evaluate every jump immediately following the
  6703. comparison, optimising the conditions if possible.
  6704. Similarly with SETcc... those that are always set to 0 or 1
  6705. are changed to MOV instructions }
  6706. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6707. (
  6708. GetNextInstruction(hp2, hp1) and
  6709. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6710. ) do
  6711. begin
  6712. FirstMatch := False;
  6713. case taicpu(hp1).condition of
  6714. C_B, C_C, C_NAE, C_O:
  6715. { For B/NAE:
  6716. Will never branch since an unsigned integer can never be below zero
  6717. For C/O:
  6718. Result cannot overflow because 0 is being subtracted
  6719. }
  6720. begin
  6721. if taicpu(hp1).opcode = A_Jcc then
  6722. begin
  6723. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6724. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6725. RemoveInstruction(hp1);
  6726. { Since hp1 was deleted, hp2 must not be updated }
  6727. Continue;
  6728. end
  6729. else
  6730. begin
  6731. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6732. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6733. taicpu(hp1).opcode := A_MOV;
  6734. taicpu(hp1).ops := 2;
  6735. taicpu(hp1).condition := C_None;
  6736. taicpu(hp1).opsize := S_B;
  6737. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6738. taicpu(hp1).loadconst(0, 0);
  6739. end;
  6740. end;
  6741. C_BE, C_NA:
  6742. begin
  6743. { Will only branch if equal to zero }
  6744. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6745. taicpu(hp1).condition := C_E;
  6746. end;
  6747. C_A, C_NBE:
  6748. begin
  6749. { Will only branch if not equal to zero }
  6750. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6751. taicpu(hp1).condition := C_NE;
  6752. end;
  6753. C_AE, C_NB, C_NC, C_NO:
  6754. begin
  6755. { Will always branch }
  6756. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6757. if taicpu(hp1).opcode = A_Jcc then
  6758. begin
  6759. MakeUnconditional(taicpu(hp1));
  6760. { Any jumps/set that follow will now be dead code }
  6761. RemoveDeadCodeAfterJump(taicpu(hp1));
  6762. Break;
  6763. end
  6764. else
  6765. begin
  6766. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6767. taicpu(hp1).opcode := A_MOV;
  6768. taicpu(hp1).ops := 2;
  6769. taicpu(hp1).condition := C_None;
  6770. taicpu(hp1).opsize := S_B;
  6771. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6772. taicpu(hp1).loadconst(0, 1);
  6773. end;
  6774. end;
  6775. C_None:
  6776. InternalError(2020012201);
  6777. C_P, C_PE, C_NP, C_PO:
  6778. { We can't handle parity checks and they should never be generated
  6779. after a general-purpose CMP (it's used in some floating-point
  6780. comparisons that don't use CMP) }
  6781. InternalError(2020012202);
  6782. else
  6783. { Zero/Equality, Sign, their complements and all of the
  6784. signed comparisons do not need to be converted };
  6785. end;
  6786. hp2 := hp1;
  6787. end;
  6788. { Convert the instruction to a TEST }
  6789. taicpu(p).opcode := A_TEST;
  6790. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6791. Result := True;
  6792. Exit;
  6793. end
  6794. else if (taicpu(p).oper[0]^.val = 1) and
  6795. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6796. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6797. begin
  6798. { Convert; To:
  6799. cmp $1,r/m cmp $0,r/m
  6800. jl @lbl jle @lbl
  6801. }
  6802. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6803. taicpu(p).oper[0]^.val := 0;
  6804. taicpu(hp1).condition := C_LE;
  6805. { If the instruction is now "cmp $0,%reg", convert it to a
  6806. TEST (and effectively do the work of the "cmp $0,%reg" in
  6807. the block above)
  6808. If it's a reference, we can get away with not setting
  6809. Result to True because he haven't evaluated the jump
  6810. in this pass yet.
  6811. }
  6812. if (taicpu(p).oper[1]^.typ = top_reg) then
  6813. begin
  6814. taicpu(p).opcode := A_TEST;
  6815. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6816. Result := True;
  6817. end;
  6818. Exit;
  6819. end
  6820. else if (taicpu(p).oper[1]^.typ = top_reg)
  6821. {$ifdef x86_64}
  6822. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6823. {$endif x86_64}
  6824. then
  6825. begin
  6826. { cmp register,$8000 neg register
  6827. je target --> jo target
  6828. .... only if register is deallocated before jump.}
  6829. case Taicpu(p).opsize of
  6830. S_B: v:=$80;
  6831. S_W: v:=$8000;
  6832. S_L: v:=qword($80000000);
  6833. else
  6834. internalerror(2013112905);
  6835. end;
  6836. if (taicpu(p).oper[0]^.val=v) and
  6837. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6838. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6839. begin
  6840. TransferUsedRegs(TmpUsedRegs);
  6841. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6842. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6843. begin
  6844. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6845. Taicpu(p).opcode:=A_NEG;
  6846. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6847. Taicpu(p).clearop(1);
  6848. Taicpu(p).ops:=1;
  6849. if Taicpu(hp1).condition=C_E then
  6850. Taicpu(hp1).condition:=C_O
  6851. else
  6852. Taicpu(hp1).condition:=C_NO;
  6853. Result:=true;
  6854. exit;
  6855. end;
  6856. end;
  6857. end;
  6858. end;
  6859. if TrySwapMovCmp(p, hp1) then
  6860. begin
  6861. Result := True;
  6862. Exit;
  6863. end;
  6864. end;
  6865. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6866. var
  6867. hp1: tai;
  6868. begin
  6869. {
  6870. remove the second (v)pxor from
  6871. pxor reg,reg
  6872. ...
  6873. pxor reg,reg
  6874. }
  6875. Result:=false;
  6876. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6877. MatchOpType(taicpu(p),top_reg,top_reg) and
  6878. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6879. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6880. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6881. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6882. begin
  6883. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6884. RemoveInstruction(hp1);
  6885. Result:=true;
  6886. Exit;
  6887. end
  6888. {
  6889. replace
  6890. pxor reg1,reg1
  6891. movapd/s reg1,reg2
  6892. dealloc reg1
  6893. by
  6894. pxor reg2,reg2
  6895. }
  6896. else if GetNextInstruction(p,hp1) and
  6897. { we mix single and double opperations here because we assume that the compiler
  6898. generates vmovapd only after double operations and vmovaps only after single operations }
  6899. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6900. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6901. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6902. (taicpu(p).oper[0]^.typ=top_reg) then
  6903. begin
  6904. TransferUsedRegs(TmpUsedRegs);
  6905. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6906. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6907. begin
  6908. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6909. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6910. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6911. RemoveInstruction(hp1);
  6912. result:=true;
  6913. end;
  6914. end;
  6915. end;
  6916. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6917. var
  6918. hp1: tai;
  6919. begin
  6920. {
  6921. remove the second (v)pxor from
  6922. (v)pxor reg,reg
  6923. ...
  6924. (v)pxor reg,reg
  6925. }
  6926. Result:=false;
  6927. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6928. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6929. begin
  6930. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6931. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6932. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6933. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6934. begin
  6935. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6936. RemoveInstruction(hp1);
  6937. Result:=true;
  6938. Exit;
  6939. end;
  6940. {$ifdef x86_64}
  6941. {
  6942. replace
  6943. vpxor reg1,reg1,reg1
  6944. vmov reg,mem
  6945. by
  6946. movq $0,mem
  6947. }
  6948. if GetNextInstruction(p,hp1) and
  6949. MatchInstruction(hp1,A_VMOVSD,[]) and
  6950. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6951. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6952. begin
  6953. TransferUsedRegs(TmpUsedRegs);
  6954. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6955. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6956. begin
  6957. taicpu(hp1).loadconst(0,0);
  6958. taicpu(hp1).opcode:=A_MOV;
  6959. taicpu(hp1).opsize:=S_Q;
  6960. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6961. RemoveCurrentP(p);
  6962. result:=true;
  6963. Exit;
  6964. end;
  6965. end;
  6966. {$endif x86_64}
  6967. end
  6968. {
  6969. replace
  6970. vpxor reg1,reg1,reg2
  6971. by
  6972. vpxor reg2,reg2,reg2
  6973. to avoid unncessary data dependencies
  6974. }
  6975. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6976. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6977. begin
  6978. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6979. { avoid unncessary data dependency }
  6980. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6981. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6982. result:=true;
  6983. exit;
  6984. end;
  6985. Result:=OptPass1VOP(p);
  6986. end;
  6987. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6988. var
  6989. hp1 : tai;
  6990. begin
  6991. result:=false;
  6992. { replace
  6993. IMul const,%mreg1,%mreg2
  6994. Mov %reg2,%mreg3
  6995. dealloc %mreg3
  6996. by
  6997. Imul const,%mreg1,%mreg23
  6998. }
  6999. if (taicpu(p).ops=3) and
  7000. GetNextInstruction(p,hp1) and
  7001. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7002. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7003. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7004. begin
  7005. TransferUsedRegs(TmpUsedRegs);
  7006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7007. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7008. begin
  7009. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7010. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7011. RemoveInstruction(hp1);
  7012. result:=true;
  7013. end;
  7014. end;
  7015. end;
  7016. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7017. var
  7018. hp1 : tai;
  7019. begin
  7020. result:=false;
  7021. { replace
  7022. IMul %reg0,%reg1,%reg2
  7023. Mov %reg2,%reg3
  7024. dealloc %reg2
  7025. by
  7026. Imul %reg0,%reg1,%reg3
  7027. }
  7028. if GetNextInstruction(p,hp1) and
  7029. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7030. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7031. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7032. begin
  7033. TransferUsedRegs(TmpUsedRegs);
  7034. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7035. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7036. begin
  7037. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7038. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7039. RemoveInstruction(hp1);
  7040. result:=true;
  7041. end;
  7042. end;
  7043. end;
  7044. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7045. var
  7046. hp1: tai;
  7047. begin
  7048. Result:=false;
  7049. { get rid of
  7050. (v)cvtss2sd reg0,<reg1,>reg2
  7051. (v)cvtss2sd reg2,<reg2,>reg0
  7052. }
  7053. if GetNextInstruction(p,hp1) and
  7054. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7055. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7056. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7057. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7058. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7059. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7060. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7061. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7062. )
  7063. ) then
  7064. begin
  7065. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7066. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7067. begin
  7068. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7069. RemoveCurrentP(p);
  7070. RemoveInstruction(hp1);
  7071. end
  7072. else
  7073. begin
  7074. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7075. if taicpu(hp1).opcode=A_CVTSD2SS then
  7076. begin
  7077. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7078. taicpu(p).opcode:=A_MOVAPS;
  7079. end
  7080. else
  7081. begin
  7082. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7083. taicpu(p).opcode:=A_VMOVAPS;
  7084. end;
  7085. taicpu(p).ops:=2;
  7086. RemoveInstruction(hp1);
  7087. end;
  7088. Result:=true;
  7089. Exit;
  7090. end;
  7091. end;
  7092. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7093. var
  7094. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7095. ThisReg: TRegister;
  7096. begin
  7097. Result := False;
  7098. if not GetNextInstruction(p,hp1) then
  7099. Exit;
  7100. {
  7101. convert
  7102. j<c> .L1
  7103. mov 1,reg
  7104. jmp .L2
  7105. .L1
  7106. mov 0,reg
  7107. .L2
  7108. into
  7109. mov 0,reg
  7110. set<not(c)> reg
  7111. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7112. would destroy the flag contents
  7113. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7114. executed at the same time as a previous comparison.
  7115. set<not(c)> reg
  7116. movzx reg, reg
  7117. }
  7118. if MatchInstruction(hp1,A_MOV,[]) and
  7119. (taicpu(hp1).oper[0]^.typ = top_const) and
  7120. (
  7121. (
  7122. (taicpu(hp1).oper[1]^.typ = top_reg)
  7123. {$ifdef i386}
  7124. { Under i386, ESI, EDI, EBP and ESP
  7125. don't have an 8-bit representation }
  7126. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7127. {$endif i386}
  7128. ) or (
  7129. {$ifdef i386}
  7130. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7131. {$endif i386}
  7132. (taicpu(hp1).opsize = S_B)
  7133. )
  7134. ) and
  7135. GetNextInstruction(hp1,hp2) and
  7136. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7137. GetNextInstruction(hp2,hp3) and
  7138. SkipAligns(hp3, hp3) and
  7139. (hp3.typ=ait_label) and
  7140. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7141. GetNextInstruction(hp3,hp4) and
  7142. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7143. (taicpu(hp4).oper[0]^.typ = top_const) and
  7144. (
  7145. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7146. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7147. ) and
  7148. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7149. GetNextInstruction(hp4,hp5) and
  7150. SkipAligns(hp5, hp5) and
  7151. (hp5.typ=ait_label) and
  7152. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7153. begin
  7154. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7155. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7156. tai_label(hp3).labsym.DecRefs;
  7157. { If this isn't the only reference to the middle label, we can
  7158. still make a saving - only that the first jump and everything
  7159. that follows will remain. }
  7160. if (tai_label(hp3).labsym.getrefs = 0) then
  7161. begin
  7162. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7163. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7164. else
  7165. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7166. { remove jump, first label and second MOV (also catching any aligns) }
  7167. repeat
  7168. if not GetNextInstruction(hp2, hp3) then
  7169. InternalError(2021040810);
  7170. RemoveInstruction(hp2);
  7171. hp2 := hp3;
  7172. until hp2 = hp5;
  7173. { Don't decrement reference count before the removal loop
  7174. above, otherwise GetNextInstruction won't stop on the
  7175. the label }
  7176. tai_label(hp5).labsym.DecRefs;
  7177. end
  7178. else
  7179. begin
  7180. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7181. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7182. else
  7183. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7184. end;
  7185. taicpu(p).opcode:=A_SETcc;
  7186. taicpu(p).opsize:=S_B;
  7187. taicpu(p).is_jmp:=False;
  7188. if taicpu(hp1).opsize=S_B then
  7189. begin
  7190. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7191. if taicpu(hp1).oper[1]^.typ = top_reg then
  7192. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7193. RemoveInstruction(hp1);
  7194. end
  7195. else
  7196. begin
  7197. { Will be a register because the size can't be S_B otherwise }
  7198. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7199. taicpu(p).loadreg(0, ThisReg);
  7200. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7201. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7202. begin
  7203. case taicpu(hp1).opsize of
  7204. S_W:
  7205. taicpu(hp1).opsize := S_BW;
  7206. S_L:
  7207. taicpu(hp1).opsize := S_BL;
  7208. {$ifdef x86_64}
  7209. S_Q:
  7210. begin
  7211. taicpu(hp1).opsize := S_BL;
  7212. { Change the destination register to 32-bit }
  7213. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7214. end;
  7215. {$endif x86_64}
  7216. else
  7217. InternalError(2021040820);
  7218. end;
  7219. taicpu(hp1).opcode := A_MOVZX;
  7220. taicpu(hp1).loadreg(0, ThisReg);
  7221. end
  7222. else
  7223. begin
  7224. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7225. { hp1 is already a MOV instruction with the correct register }
  7226. taicpu(hp1).loadconst(0, 0);
  7227. { Inserting it right before p will guarantee that the flags are also tracked }
  7228. asml.Remove(hp1);
  7229. asml.InsertBefore(hp1, p);
  7230. end;
  7231. end;
  7232. Result:=true;
  7233. exit;
  7234. end
  7235. else if (hp1.typ = ait_label) then
  7236. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7237. end;
  7238. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7239. var
  7240. hp1, hp2, hp3: tai;
  7241. SourceRef, TargetRef: TReference;
  7242. CurrentReg: TRegister;
  7243. begin
  7244. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7245. if not UseAVX then
  7246. InternalError(2021100501);
  7247. Result := False;
  7248. { Look for the following to simplify:
  7249. vmovdqa/u x(mem1), %xmmreg
  7250. vmovdqa/u %xmmreg, y(mem2)
  7251. vmovdqa/u x+16(mem1), %xmmreg
  7252. vmovdqa/u %xmmreg, y+16(mem2)
  7253. Change to:
  7254. vmovdqa/u x(mem1), %ymmreg
  7255. vmovdqa/u %ymmreg, y(mem2)
  7256. vpxor %ymmreg, %ymmreg, %ymmreg
  7257. ( The VPXOR instruction is to zero the upper half, thus removing the
  7258. need to call the potentially expensive VZEROUPPER instruction. Other
  7259. peephole optimisations can remove VPXOR if it's unnecessary )
  7260. }
  7261. TransferUsedRegs(TmpUsedRegs);
  7262. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7263. { NOTE: In the optimisations below, if the references dictate that an
  7264. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7265. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7266. if (taicpu(p).opsize = S_XMM) and
  7267. MatchOpType(taicpu(p), top_ref, top_reg) and
  7268. GetNextInstruction(p, hp1) and
  7269. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7270. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7271. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7272. begin
  7273. SourceRef := taicpu(p).oper[0]^.ref^;
  7274. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7275. if GetNextInstruction(hp1, hp2) and
  7276. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7277. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7278. begin
  7279. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7280. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7281. Inc(SourceRef.offset, 16);
  7282. { Reuse the register in the first block move }
  7283. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7284. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7285. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7286. begin
  7287. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7288. Inc(TargetRef.offset, 16);
  7289. if GetNextInstruction(hp2, hp3) and
  7290. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7291. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7292. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7293. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7294. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7295. begin
  7296. { Update the register tracking to the new size }
  7297. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7298. { Remember that the offsets are 16 ahead }
  7299. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7300. if not (
  7301. ((SourceRef.offset mod 32) = 16) and
  7302. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7303. ) then
  7304. taicpu(p).opcode := A_VMOVDQU;
  7305. taicpu(p).opsize := S_YMM;
  7306. taicpu(p).oper[1]^.reg := CurrentReg;
  7307. if not (
  7308. ((TargetRef.offset mod 32) = 16) and
  7309. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7310. ) then
  7311. taicpu(hp1).opcode := A_VMOVDQU;
  7312. taicpu(hp1).opsize := S_YMM;
  7313. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7314. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7315. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7316. if (pi_uses_ymm in current_procinfo.flags) then
  7317. RemoveInstruction(hp2)
  7318. else
  7319. begin
  7320. taicpu(hp2).opcode := A_VPXOR;
  7321. taicpu(hp2).opsize := S_YMM;
  7322. taicpu(hp2).loadreg(0, CurrentReg);
  7323. taicpu(hp2).loadreg(1, CurrentReg);
  7324. taicpu(hp2).loadreg(2, CurrentReg);
  7325. taicpu(hp2).ops := 3;
  7326. end;
  7327. RemoveInstruction(hp3);
  7328. Result := True;
  7329. Exit;
  7330. end;
  7331. end
  7332. else
  7333. begin
  7334. { See if the next references are 16 less rather than 16 greater }
  7335. Dec(SourceRef.offset, 32); { -16 the other way }
  7336. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7337. begin
  7338. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7339. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7340. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7341. GetNextInstruction(hp2, hp3) and
  7342. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7343. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7344. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7345. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7346. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7347. begin
  7348. { Update the register tracking to the new size }
  7349. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7350. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7351. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7352. if not(
  7353. ((SourceRef.offset mod 32) = 0) and
  7354. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7355. ) then
  7356. taicpu(hp2).opcode := A_VMOVDQU;
  7357. taicpu(hp2).opsize := S_YMM;
  7358. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7359. if not (
  7360. ((TargetRef.offset mod 32) = 0) and
  7361. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7362. ) then
  7363. taicpu(hp3).opcode := A_VMOVDQU;
  7364. taicpu(hp3).opsize := S_YMM;
  7365. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7366. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7367. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7368. if (pi_uses_ymm in current_procinfo.flags) then
  7369. RemoveInstruction(hp1)
  7370. else
  7371. begin
  7372. taicpu(hp1).opcode := A_VPXOR;
  7373. taicpu(hp1).opsize := S_YMM;
  7374. taicpu(hp1).loadreg(0, CurrentReg);
  7375. taicpu(hp1).loadreg(1, CurrentReg);
  7376. taicpu(hp1).loadreg(2, CurrentReg);
  7377. taicpu(hp1).ops := 3;
  7378. Asml.Remove(hp1);
  7379. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7380. end;
  7381. RemoveCurrentP(p, hp2);
  7382. Result := True;
  7383. Exit;
  7384. end;
  7385. end;
  7386. end;
  7387. end;
  7388. end;
  7389. end;
  7390. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7391. var
  7392. hp2, hp3, first_assignment: tai;
  7393. IncCount, OperIdx: Integer;
  7394. OrigLabel: TAsmLabel;
  7395. begin
  7396. Count := 0;
  7397. Result := False;
  7398. first_assignment := nil;
  7399. if (LoopCount >= 20) then
  7400. begin
  7401. { Guard against infinite loops }
  7402. Exit;
  7403. end;
  7404. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7405. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7406. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7407. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7408. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7409. Exit;
  7410. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7411. {
  7412. change
  7413. jmp .L1
  7414. ...
  7415. .L1:
  7416. mov ##, ## ( multiple movs possible )
  7417. jmp/ret
  7418. into
  7419. mov ##, ##
  7420. jmp/ret
  7421. }
  7422. if not Assigned(hp1) then
  7423. begin
  7424. hp1 := GetLabelWithSym(OrigLabel);
  7425. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7426. Exit;
  7427. end;
  7428. hp2 := hp1;
  7429. while Assigned(hp2) do
  7430. begin
  7431. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7432. SkipLabels(hp2,hp2);
  7433. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7434. Break;
  7435. case taicpu(hp2).opcode of
  7436. A_MOVSS:
  7437. begin
  7438. if taicpu(hp2).ops = 0 then
  7439. { Wrong MOVSS }
  7440. Break;
  7441. Inc(Count);
  7442. if Count >= 5 then
  7443. { Too many to be worthwhile }
  7444. Break;
  7445. GetNextInstruction(hp2, hp2);
  7446. Continue;
  7447. end;
  7448. A_MOV,
  7449. A_MOVD,
  7450. A_MOVQ,
  7451. A_MOVSX,
  7452. {$ifdef x86_64}
  7453. A_MOVSXD,
  7454. {$endif x86_64}
  7455. A_MOVZX,
  7456. A_MOVAPS,
  7457. A_MOVUPS,
  7458. A_MOVSD,
  7459. A_MOVAPD,
  7460. A_MOVUPD,
  7461. A_MOVDQA,
  7462. A_MOVDQU,
  7463. A_VMOVSS,
  7464. A_VMOVAPS,
  7465. A_VMOVUPS,
  7466. A_VMOVSD,
  7467. A_VMOVAPD,
  7468. A_VMOVUPD,
  7469. A_VMOVDQA,
  7470. A_VMOVDQU:
  7471. begin
  7472. Inc(Count);
  7473. if Count >= 5 then
  7474. { Too many to be worthwhile }
  7475. Break;
  7476. GetNextInstruction(hp2, hp2);
  7477. Continue;
  7478. end;
  7479. A_JMP:
  7480. begin
  7481. { Guard against infinite loops }
  7482. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7483. Exit;
  7484. { Analyse this jump first in case it also duplicates assignments }
  7485. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7486. begin
  7487. { Something did change! }
  7488. Result := True;
  7489. Inc(Count, IncCount);
  7490. if Count >= 5 then
  7491. begin
  7492. { Too many to be worthwhile }
  7493. Exit;
  7494. end;
  7495. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7496. Break;
  7497. end;
  7498. Result := True;
  7499. Break;
  7500. end;
  7501. A_RET:
  7502. begin
  7503. Result := True;
  7504. Break;
  7505. end;
  7506. else
  7507. Break;
  7508. end;
  7509. end;
  7510. if Result then
  7511. begin
  7512. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7513. if Count = 0 then
  7514. begin
  7515. Result := False;
  7516. Exit;
  7517. end;
  7518. hp3 := p;
  7519. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7520. while True do
  7521. begin
  7522. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7523. SkipLabels(hp1,hp1);
  7524. if (hp1.typ <> ait_instruction) then
  7525. InternalError(2021040720);
  7526. case taicpu(hp1).opcode of
  7527. A_JMP:
  7528. begin
  7529. { Change the original jump to the new destination }
  7530. OrigLabel.decrefs;
  7531. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7532. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7533. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7534. if not Assigned(first_assignment) then
  7535. InternalError(2021040810)
  7536. else
  7537. p := first_assignment;
  7538. Exit;
  7539. end;
  7540. A_RET:
  7541. begin
  7542. { Now change the jump into a RET instruction }
  7543. ConvertJumpToRET(p, hp1);
  7544. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7545. if not Assigned(first_assignment) then
  7546. InternalError(2021040811)
  7547. else
  7548. p := first_assignment;
  7549. Exit;
  7550. end;
  7551. else
  7552. begin
  7553. { Duplicate the MOV instruction }
  7554. hp3:=tai(hp1.getcopy);
  7555. if first_assignment = nil then
  7556. first_assignment := hp3;
  7557. asml.InsertBefore(hp3, p);
  7558. { Make sure the compiler knows about any final registers written here }
  7559. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7560. with taicpu(hp3).oper[OperIdx]^ do
  7561. begin
  7562. case typ of
  7563. top_ref:
  7564. begin
  7565. if (ref^.base <> NR_NO) and
  7566. (getsupreg(ref^.base) <> RS_ESP) and
  7567. (getsupreg(ref^.base) <> RS_EBP)
  7568. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7569. then
  7570. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7571. if (ref^.index <> NR_NO) and
  7572. (getsupreg(ref^.index) <> RS_ESP) and
  7573. (getsupreg(ref^.index) <> RS_EBP)
  7574. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7575. (ref^.index <> ref^.base) then
  7576. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7577. end;
  7578. top_reg:
  7579. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7580. else
  7581. ;
  7582. end;
  7583. end;
  7584. end;
  7585. end;
  7586. if not GetNextInstruction(hp1, hp1) then
  7587. { Should have dropped out earlier }
  7588. InternalError(2021040710);
  7589. end;
  7590. end;
  7591. end;
  7592. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7593. var
  7594. hp2: tai;
  7595. X: Integer;
  7596. const
  7597. WriteOp: array[0..3] of set of TInsChange = (
  7598. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7599. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7600. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7601. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7602. RegWriteFlags: array[0..7] of set of TInsChange = (
  7603. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7604. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7605. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7606. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7607. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7608. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7609. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7610. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7611. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7612. begin
  7613. { If we have something like:
  7614. cmp ###,%reg1
  7615. mov 0,%reg2
  7616. And no modified registers are shared, move the instruction to before
  7617. the comparison as this means it can be optimised without worrying
  7618. about the FLAGS register. (CMP/MOV is generated by
  7619. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7620. As long as the second instruction doesn't use the flags or one of the
  7621. registers used by CMP or TEST (also check any references that use the
  7622. registers), then it can be moved prior to the comparison.
  7623. }
  7624. Result := False;
  7625. if (hp1.typ <> ait_instruction) or
  7626. taicpu(hp1).is_jmp or
  7627. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7628. Exit;
  7629. { NOP is a pipeline fence, likely marking the beginning of the function
  7630. epilogue, so drop out. Similarly, drop out if POP or RET are
  7631. encountered }
  7632. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7633. Exit;
  7634. if (taicpu(hp1).opcode = A_MOVSS) and
  7635. (taicpu(hp1).ops = 0) then
  7636. { Wrong MOVSS }
  7637. Exit;
  7638. { Check for writes to specific registers first }
  7639. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7640. for X := 0 to 7 do
  7641. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7642. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7643. Exit;
  7644. for X := 0 to taicpu(hp1).ops - 1 do
  7645. begin
  7646. { Check to see if this operand writes to something }
  7647. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7648. { And matches something in the CMP/TEST instruction }
  7649. (
  7650. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7651. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7652. (
  7653. { If it's a register, make sure the register written to doesn't
  7654. appear in the cmp instruction as part of a reference }
  7655. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7656. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7657. )
  7658. ) then
  7659. Exit;
  7660. end;
  7661. { The instruction can be safely moved }
  7662. asml.Remove(hp1);
  7663. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7664. can be optimised into "xor %reg,%reg" later }
  7665. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7666. asml.InsertBefore(hp1, hp2)
  7667. else
  7668. { Note, if p.Previous is nil (even if it should logically never be the
  7669. case), FindRegAllocBackward immediately exits with False and so we
  7670. safely land here (we can't just pass p because FindRegAllocBackward
  7671. immediately exits on an instruction). [Kit] }
  7672. asml.InsertBefore(hp1, p);
  7673. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7674. for X := 0 to taicpu(hp1).ops - 1 do
  7675. case taicpu(hp1).oper[X]^.typ of
  7676. top_reg:
  7677. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7678. top_ref:
  7679. begin
  7680. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7681. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7682. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7683. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7684. end;
  7685. else
  7686. ;
  7687. end;
  7688. if taicpu(hp1).opcode = A_LEA then
  7689. { The flags will be overwritten by the CMP/TEST instruction }
  7690. ConvertLEA(taicpu(hp1));
  7691. Result := True;
  7692. end;
  7693. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7694. function IsXCHGAcceptable: Boolean; inline;
  7695. begin
  7696. { Always accept if optimising for size }
  7697. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7698. (
  7699. {$ifdef x86_64}
  7700. { XCHG takes 3 cycles on AMD Athlon64 }
  7701. (current_settings.optimizecputype >= cpu_core_i)
  7702. {$else x86_64}
  7703. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7704. than 3, so it becomes a saving compared to three MOVs with two of
  7705. them able to execute simultaneously. [Kit] }
  7706. (current_settings.optimizecputype >= cpu_PentiumM)
  7707. {$endif x86_64}
  7708. );
  7709. end;
  7710. var
  7711. NewRef: TReference;
  7712. hp1, hp2, hp3, hp4: Tai;
  7713. {$ifndef x86_64}
  7714. OperIdx: Integer;
  7715. {$endif x86_64}
  7716. NewInstr : Taicpu;
  7717. NewAligh : Tai_align;
  7718. DestLabel: TAsmLabel;
  7719. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7720. var
  7721. NextInstr: tai;
  7722. begin
  7723. Result := False;
  7724. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7725. if not GetNextInstruction(InputInstr, NextInstr) or
  7726. (
  7727. { The FLAGS register isn't always tracked properly, so do not
  7728. perform this optimisation if a conditional statement follows }
  7729. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7730. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7731. ) then
  7732. begin
  7733. reference_reset(NewRef, 1, []);
  7734. NewRef.base := taicpu(p).oper[0]^.reg;
  7735. NewRef.scalefactor := 1;
  7736. if taicpu(InputInstr).opcode = A_ADD then
  7737. begin
  7738. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7739. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7740. end
  7741. else
  7742. begin
  7743. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7744. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7745. end;
  7746. taicpu(p).opcode := A_LEA;
  7747. taicpu(p).loadref(0, NewRef);
  7748. RemoveInstruction(InputInstr);
  7749. Result := True;
  7750. end;
  7751. end;
  7752. begin
  7753. Result:=false;
  7754. { This optimisation adds an instruction, so only do it for speed }
  7755. if not (cs_opt_size in current_settings.optimizerswitches) and
  7756. MatchOpType(taicpu(p), top_const, top_reg) and
  7757. (taicpu(p).oper[0]^.val = 0) then
  7758. begin
  7759. { To avoid compiler warning }
  7760. DestLabel := nil;
  7761. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7762. InternalError(2021040750);
  7763. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7764. Exit;
  7765. case hp1.typ of
  7766. ait_label:
  7767. begin
  7768. { Change:
  7769. mov $0,%reg mov $0,%reg
  7770. @Lbl1: @Lbl1:
  7771. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7772. je @Lbl2 jne @Lbl2
  7773. To: To:
  7774. mov $0,%reg mov $0,%reg
  7775. jmp @Lbl2 jmp @Lbl3
  7776. (align) (align)
  7777. @Lbl1: @Lbl1:
  7778. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7779. je @Lbl2 je @Lbl2
  7780. @Lbl3: <-- Only if label exists
  7781. (Not if it's optimised for size)
  7782. }
  7783. if not GetNextInstruction(hp1, hp2) then
  7784. Exit;
  7785. if not (cs_opt_size in current_settings.optimizerswitches) and
  7786. (hp2.typ = ait_instruction) and
  7787. (
  7788. { Register sizes must exactly match }
  7789. (
  7790. (taicpu(hp2).opcode = A_CMP) and
  7791. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7792. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7793. ) or (
  7794. (taicpu(hp2).opcode = A_TEST) and
  7795. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7796. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7797. )
  7798. ) and GetNextInstruction(hp2, hp3) and
  7799. (hp3.typ = ait_instruction) and
  7800. (taicpu(hp3).opcode = A_JCC) and
  7801. (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
  7802. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7803. begin
  7804. { Check condition of jump }
  7805. { Always true? }
  7806. if condition_in(C_E, taicpu(hp3).condition) then
  7807. begin
  7808. { Copy label symbol and obtain matching label entry for the
  7809. conditional jump, as this will be our destination}
  7810. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7811. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7812. Result := True;
  7813. end
  7814. { Always false? }
  7815. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7816. begin
  7817. { This is only worth it if there's a jump to take }
  7818. case hp2.typ of
  7819. ait_instruction:
  7820. begin
  7821. if taicpu(hp2).opcode = A_JMP then
  7822. begin
  7823. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7824. { An unconditional jump follows the conditional jump which will always be false,
  7825. so use this jump's destination for the new jump }
  7826. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7827. Result := True;
  7828. end
  7829. else if taicpu(hp2).opcode = A_JCC then
  7830. begin
  7831. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7832. if condition_in(C_E, taicpu(hp2).condition) then
  7833. begin
  7834. { A second conditional jump follows the conditional jump which will always be false,
  7835. while the second jump is always True, so use this jump's destination for the new jump }
  7836. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7837. Result := True;
  7838. end;
  7839. { Don't risk it if the jump isn't always true (Result remains False) }
  7840. end;
  7841. end;
  7842. else
  7843. { If anything else don't optimise };
  7844. end;
  7845. end;
  7846. if Result then
  7847. begin
  7848. { Just so we have something to insert as a paremeter}
  7849. reference_reset(NewRef, 1, []);
  7850. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7851. { Now actually load the correct parameter (this also
  7852. increases the reference count) }
  7853. NewInstr.loadsymbol(0, DestLabel, 0);
  7854. { Get instruction before original label (may not be p under -O3) }
  7855. if not GetLastInstruction(hp1, hp2) then
  7856. { Shouldn't fail here }
  7857. InternalError(2021040701);
  7858. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  7859. AsmL.InsertAfter(NewInstr, hp2);
  7860. { Add new alignment field }
  7861. (* AsmL.InsertAfter(
  7862. cai_align.create_max(
  7863. current_settings.alignment.jumpalign,
  7864. current_settings.alignment.jumpalignskipmax
  7865. ),
  7866. NewInstr
  7867. ); *)
  7868. end;
  7869. Exit;
  7870. end;
  7871. end;
  7872. else
  7873. ;
  7874. end;
  7875. end;
  7876. if not GetNextInstruction(p, hp1) then
  7877. Exit;
  7878. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7879. and DoMovCmpMemOpt(p, hp1, True) then
  7880. begin
  7881. Result := True;
  7882. Exit;
  7883. end
  7884. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7885. begin
  7886. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7887. further, but we can't just put this jump optimisation in pass 1
  7888. because it tends to perform worse when conditional jumps are
  7889. nearby (e.g. when converting CMOV instructions). [Kit] }
  7890. if OptPass2JMP(hp1) then
  7891. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7892. Result := OptPass1MOV(p)
  7893. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7894. returned True and the instruction is still a MOV, thus checking
  7895. the optimisations below }
  7896. { If OptPass2JMP returned False, no optimisations were done to
  7897. the jump and there are no further optimisations that can be done
  7898. to the MOV instruction on this pass }
  7899. end
  7900. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7901. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7902. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7903. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7904. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7905. begin
  7906. { Change:
  7907. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7908. addl/q $x,%reg2 subl/q $x,%reg2
  7909. To:
  7910. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7911. }
  7912. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7913. { be lazy, checking separately for sub would be slightly better }
  7914. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7915. begin
  7916. TransferUsedRegs(TmpUsedRegs);
  7917. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7918. if TryMovArith2Lea(hp1) then
  7919. begin
  7920. Result := True;
  7921. Exit;
  7922. end
  7923. end
  7924. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7925. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7926. { Same as above, but also adds or subtracts to %reg2 in between.
  7927. It's still valid as long as the flags aren't in use }
  7928. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7929. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7930. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7931. { be lazy, checking separately for sub would be slightly better }
  7932. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7933. begin
  7934. TransferUsedRegs(TmpUsedRegs);
  7935. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7936. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7937. if TryMovArith2Lea(hp2) then
  7938. begin
  7939. Result := True;
  7940. Exit;
  7941. end;
  7942. end;
  7943. end
  7944. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7945. {$ifdef x86_64}
  7946. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7947. {$else x86_64}
  7948. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7949. {$endif x86_64}
  7950. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7951. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7952. { mov reg1, reg2 mov reg1, reg2
  7953. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7954. begin
  7955. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7956. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7957. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7958. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7959. TransferUsedRegs(TmpUsedRegs);
  7960. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7961. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7962. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7963. then
  7964. begin
  7965. RemoveCurrentP(p, hp1);
  7966. Result:=true;
  7967. end;
  7968. exit;
  7969. end
  7970. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7971. IsXCHGAcceptable and
  7972. { XCHG doesn't support 8-byte registers }
  7973. (taicpu(p).opsize <> S_B) and
  7974. MatchInstruction(hp1, A_MOV, []) and
  7975. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7976. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7977. GetNextInstruction(hp1, hp2) and
  7978. MatchInstruction(hp2, A_MOV, []) and
  7979. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7980. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7981. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7982. begin
  7983. { mov %reg1,%reg2
  7984. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7985. mov %reg2,%reg3
  7986. (%reg2 not used afterwards)
  7987. Note that xchg takes 3 cycles to execute, and generally mov's take
  7988. only one cycle apiece, but the first two mov's can be executed in
  7989. parallel, only taking 2 cycles overall. Older processors should
  7990. therefore only optimise for size. [Kit]
  7991. }
  7992. TransferUsedRegs(TmpUsedRegs);
  7993. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7994. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7995. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7996. begin
  7997. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7998. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7999. taicpu(hp1).opcode := A_XCHG;
  8000. RemoveCurrentP(p, hp1);
  8001. RemoveInstruction(hp2);
  8002. Result := True;
  8003. Exit;
  8004. end;
  8005. end
  8006. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8007. MatchInstruction(hp1, A_SAR, []) then
  8008. begin
  8009. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8010. begin
  8011. { the use of %edx also covers the opsize being S_L }
  8012. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8013. begin
  8014. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8015. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8016. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8017. begin
  8018. { Change:
  8019. movl %eax,%edx
  8020. sarl $31,%edx
  8021. To:
  8022. cltd
  8023. }
  8024. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8025. RemoveInstruction(hp1);
  8026. taicpu(p).opcode := A_CDQ;
  8027. taicpu(p).opsize := S_NO;
  8028. taicpu(p).clearop(1);
  8029. taicpu(p).clearop(0);
  8030. taicpu(p).ops:=0;
  8031. Result := True;
  8032. end
  8033. else if (cs_opt_size in current_settings.optimizerswitches) and
  8034. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8035. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8036. begin
  8037. { Change:
  8038. movl %edx,%eax
  8039. sarl $31,%edx
  8040. To:
  8041. movl %edx,%eax
  8042. cltd
  8043. Note that this creates a dependency between the two instructions,
  8044. so only perform if optimising for size.
  8045. }
  8046. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8047. taicpu(hp1).opcode := A_CDQ;
  8048. taicpu(hp1).opsize := S_NO;
  8049. taicpu(hp1).clearop(1);
  8050. taicpu(hp1).clearop(0);
  8051. taicpu(hp1).ops:=0;
  8052. end;
  8053. {$ifndef x86_64}
  8054. end
  8055. { Don't bother if CMOV is supported, because a more optimal
  8056. sequence would have been generated for the Abs() intrinsic }
  8057. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8058. { the use of %eax also covers the opsize being S_L }
  8059. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8060. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8061. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8062. GetNextInstruction(hp1, hp2) and
  8063. MatchInstruction(hp2, A_XOR, [S_L]) and
  8064. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8065. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8066. GetNextInstruction(hp2, hp3) and
  8067. MatchInstruction(hp3, A_SUB, [S_L]) and
  8068. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8069. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8070. begin
  8071. { Change:
  8072. movl %eax,%edx
  8073. sarl $31,%eax
  8074. xorl %eax,%edx
  8075. subl %eax,%edx
  8076. (Instruction that uses %edx)
  8077. (%eax deallocated)
  8078. (%edx deallocated)
  8079. To:
  8080. cltd
  8081. xorl %edx,%eax <-- Note the registers have swapped
  8082. subl %edx,%eax
  8083. (Instruction that uses %eax) <-- %eax rather than %edx
  8084. }
  8085. TransferUsedRegs(TmpUsedRegs);
  8086. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8087. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8088. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8089. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8090. begin
  8091. if GetNextInstruction(hp3, hp4) and
  8092. not RegModifiedByInstruction(NR_EDX, hp4) and
  8093. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8094. begin
  8095. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8096. taicpu(p).opcode := A_CDQ;
  8097. taicpu(p).clearop(1);
  8098. taicpu(p).clearop(0);
  8099. taicpu(p).ops:=0;
  8100. RemoveInstruction(hp1);
  8101. taicpu(hp2).loadreg(0, NR_EDX);
  8102. taicpu(hp2).loadreg(1, NR_EAX);
  8103. taicpu(hp3).loadreg(0, NR_EDX);
  8104. taicpu(hp3).loadreg(1, NR_EAX);
  8105. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8106. { Convert references in the following instruction (hp4) from %edx to %eax }
  8107. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8108. with taicpu(hp4).oper[OperIdx]^ do
  8109. case typ of
  8110. top_reg:
  8111. if getsupreg(reg) = RS_EDX then
  8112. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8113. top_ref:
  8114. begin
  8115. if getsupreg(reg) = RS_EDX then
  8116. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8117. if getsupreg(reg) = RS_EDX then
  8118. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8119. end;
  8120. else
  8121. ;
  8122. end;
  8123. end;
  8124. end;
  8125. {$else x86_64}
  8126. end;
  8127. end
  8128. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8129. { the use of %rdx also covers the opsize being S_Q }
  8130. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8131. begin
  8132. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8133. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8134. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8135. begin
  8136. { Change:
  8137. movq %rax,%rdx
  8138. sarq $63,%rdx
  8139. To:
  8140. cqto
  8141. }
  8142. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8143. RemoveInstruction(hp1);
  8144. taicpu(p).opcode := A_CQO;
  8145. taicpu(p).opsize := S_NO;
  8146. taicpu(p).clearop(1);
  8147. taicpu(p).clearop(0);
  8148. taicpu(p).ops:=0;
  8149. Result := True;
  8150. end
  8151. else if (cs_opt_size in current_settings.optimizerswitches) and
  8152. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8153. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8154. begin
  8155. { Change:
  8156. movq %rdx,%rax
  8157. sarq $63,%rdx
  8158. To:
  8159. movq %rdx,%rax
  8160. cqto
  8161. Note that this creates a dependency between the two instructions,
  8162. so only perform if optimising for size.
  8163. }
  8164. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8165. taicpu(hp1).opcode := A_CQO;
  8166. taicpu(hp1).opsize := S_NO;
  8167. taicpu(hp1).clearop(1);
  8168. taicpu(hp1).clearop(0);
  8169. taicpu(hp1).ops:=0;
  8170. {$endif x86_64}
  8171. end;
  8172. end;
  8173. end
  8174. else if MatchInstruction(hp1, A_MOV, []) and
  8175. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8176. { Though "GetNextInstruction" could be factored out, along with
  8177. the instructions that depend on hp2, it is an expensive call that
  8178. should be delayed for as long as possible, hence we do cheaper
  8179. checks first that are likely to be False. [Kit] }
  8180. begin
  8181. if (
  8182. (
  8183. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8184. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8185. (
  8186. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8187. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8188. )
  8189. ) or
  8190. (
  8191. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8192. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8193. (
  8194. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8195. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8196. )
  8197. )
  8198. ) and
  8199. GetNextInstruction(hp1, hp2) and
  8200. MatchInstruction(hp2, A_SAR, []) and
  8201. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8202. begin
  8203. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8204. begin
  8205. { Change:
  8206. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8207. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8208. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8209. To:
  8210. movl r/m,%eax <- Note the change in register
  8211. cltd
  8212. }
  8213. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8214. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8215. taicpu(p).loadreg(1, NR_EAX);
  8216. taicpu(hp1).opcode := A_CDQ;
  8217. taicpu(hp1).clearop(1);
  8218. taicpu(hp1).clearop(0);
  8219. taicpu(hp1).ops:=0;
  8220. RemoveInstruction(hp2);
  8221. (*
  8222. {$ifdef x86_64}
  8223. end
  8224. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8225. { This code sequence does not get generated - however it might become useful
  8226. if and when 128-bit signed integer types make an appearance, so the code
  8227. is kept here for when it is eventually needed. [Kit] }
  8228. (
  8229. (
  8230. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8231. (
  8232. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8233. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8234. )
  8235. ) or
  8236. (
  8237. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8238. (
  8239. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8240. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8241. )
  8242. )
  8243. ) and
  8244. GetNextInstruction(hp1, hp2) and
  8245. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8246. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8247. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8248. begin
  8249. { Change:
  8250. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8251. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8252. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8253. To:
  8254. movq r/m,%rax <- Note the change in register
  8255. cqto
  8256. }
  8257. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8258. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8259. taicpu(p).loadreg(1, NR_RAX);
  8260. taicpu(hp1).opcode := A_CQO;
  8261. taicpu(hp1).clearop(1);
  8262. taicpu(hp1).clearop(0);
  8263. taicpu(hp1).ops:=0;
  8264. RemoveInstruction(hp2);
  8265. {$endif x86_64}
  8266. *)
  8267. end;
  8268. end;
  8269. {$ifdef x86_64}
  8270. end
  8271. else if (taicpu(p).opsize = S_L) and
  8272. (taicpu(p).oper[1]^.typ = top_reg) and
  8273. (
  8274. MatchInstruction(hp1, A_MOV,[]) and
  8275. (taicpu(hp1).opsize = S_L) and
  8276. (taicpu(hp1).oper[1]^.typ = top_reg)
  8277. ) and (
  8278. GetNextInstruction(hp1, hp2) and
  8279. (tai(hp2).typ=ait_instruction) and
  8280. (taicpu(hp2).opsize = S_Q) and
  8281. (
  8282. (
  8283. MatchInstruction(hp2, A_ADD,[]) and
  8284. (taicpu(hp2).opsize = S_Q) and
  8285. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8286. (
  8287. (
  8288. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8289. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8290. ) or (
  8291. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8292. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8293. )
  8294. )
  8295. ) or (
  8296. MatchInstruction(hp2, A_LEA,[]) and
  8297. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8298. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8299. (
  8300. (
  8301. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8302. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8303. ) or (
  8304. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8305. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8306. )
  8307. ) and (
  8308. (
  8309. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8310. ) or (
  8311. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8312. )
  8313. )
  8314. )
  8315. )
  8316. ) and (
  8317. GetNextInstruction(hp2, hp3) and
  8318. MatchInstruction(hp3, A_SHR,[]) and
  8319. (taicpu(hp3).opsize = S_Q) and
  8320. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8321. (taicpu(hp3).oper[0]^.val = 1) and
  8322. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8323. ) then
  8324. begin
  8325. { Change movl x, reg1d movl x, reg1d
  8326. movl y, reg2d movl y, reg2d
  8327. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8328. shrq $1, reg1q shrq $1, reg1q
  8329. ( reg1d and reg2d can be switched around in the first two instructions )
  8330. To movl x, reg1d
  8331. addl y, reg1d
  8332. rcrl $1, reg1d
  8333. This corresponds to the common expression (x + y) shr 1, where
  8334. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8335. smaller code, but won't account for x + y causing an overflow). [Kit]
  8336. }
  8337. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8338. { Change first MOV command to have the same register as the final output }
  8339. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8340. else
  8341. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8342. { Change second MOV command to an ADD command. This is easier than
  8343. converting the existing command because it means we don't have to
  8344. touch 'y', which might be a complicated reference, and also the
  8345. fact that the third command might either be ADD or LEA. [Kit] }
  8346. taicpu(hp1).opcode := A_ADD;
  8347. { Delete old ADD/LEA instruction }
  8348. RemoveInstruction(hp2);
  8349. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8350. taicpu(hp3).opcode := A_RCR;
  8351. taicpu(hp3).changeopsize(S_L);
  8352. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8353. {$endif x86_64}
  8354. end;
  8355. end;
  8356. {$push}
  8357. {$q-}{$r-}
  8358. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8359. var
  8360. ThisReg: TRegister;
  8361. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8362. TargetSubReg: TSubRegister;
  8363. hp1, hp2: tai;
  8364. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8365. { Store list of found instructions so we don't have to call
  8366. GetNextInstructionUsingReg multiple times }
  8367. InstrList: array of taicpu;
  8368. InstrMax, Index: Integer;
  8369. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8370. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8371. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8372. WorkingValue: TCgInt;
  8373. PreMessage: string;
  8374. { Data flow analysis }
  8375. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8376. BitwiseOnly, OrXorUsed,
  8377. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8378. function CheckOverflowConditions: Boolean;
  8379. begin
  8380. Result := True;
  8381. if (TestValSignedMax > SignedUpperLimit) then
  8382. UpperSignedOverflow := True;
  8383. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8384. LowerSignedOverflow := True;
  8385. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8386. LowerUnsignedOverflow := True;
  8387. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8388. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8389. begin
  8390. { Absolute overflow }
  8391. Result := False;
  8392. Exit;
  8393. end;
  8394. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8395. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8396. ShiftDownOverflow := True;
  8397. if (TestValMin < 0) or (TestValMax < 0) then
  8398. begin
  8399. LowerUnsignedOverflow := True;
  8400. UpperUnsignedOverflow := True;
  8401. end;
  8402. end;
  8403. function AdjustInitialLoadAndSize: Boolean;
  8404. begin
  8405. Result := False;
  8406. if not p_removed then
  8407. begin
  8408. if TargetSize = MinSize then
  8409. begin
  8410. { Convert the input MOVZX to a MOV }
  8411. if (taicpu(p).oper[0]^.typ = top_reg) and
  8412. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8413. begin
  8414. { Or remove it completely! }
  8415. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8416. RemoveCurrentP(p);
  8417. p_removed := True;
  8418. end
  8419. else
  8420. begin
  8421. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8422. taicpu(p).opcode := A_MOV;
  8423. taicpu(p).oper[1]^.reg := ThisReg;
  8424. taicpu(p).opsize := TargetSize;
  8425. end;
  8426. Result := True;
  8427. end
  8428. else if TargetSize <> MaxSize then
  8429. begin
  8430. case MaxSize of
  8431. S_L:
  8432. if TargetSize = S_W then
  8433. begin
  8434. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8435. taicpu(p).opsize := S_BW;
  8436. taicpu(p).oper[1]^.reg := ThisReg;
  8437. Result := True;
  8438. end
  8439. else
  8440. InternalError(2020112341);
  8441. S_W:
  8442. if TargetSize = S_L then
  8443. begin
  8444. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8445. taicpu(p).opsize := S_BL;
  8446. taicpu(p).oper[1]^.reg := ThisReg;
  8447. Result := True;
  8448. end
  8449. else
  8450. InternalError(2020112342);
  8451. else
  8452. ;
  8453. end;
  8454. end
  8455. else if not hp1_removed and not RegInUse then
  8456. begin
  8457. { If we have something like:
  8458. movzbl (oper),%regd
  8459. add x, %regd
  8460. movzbl %regb, %regd
  8461. We can reduce the register size to the input of the final
  8462. movzbl instruction. Overflows won't have any effect.
  8463. }
  8464. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8465. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8466. begin
  8467. TargetSize := S_B;
  8468. setsubreg(ThisReg, R_SUBL);
  8469. Result := True;
  8470. end
  8471. else if (taicpu(p).opsize = S_WL) and
  8472. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8473. begin
  8474. TargetSize := S_W;
  8475. setsubreg(ThisReg, R_SUBW);
  8476. Result := True;
  8477. end;
  8478. if Result then
  8479. begin
  8480. { Convert the input MOVZX to a MOV }
  8481. if (taicpu(p).oper[0]^.typ = top_reg) and
  8482. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8483. begin
  8484. { Or remove it completely! }
  8485. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8486. RemoveCurrentP(p);
  8487. p_removed := True;
  8488. end
  8489. else
  8490. begin
  8491. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8492. taicpu(p).opcode := A_MOV;
  8493. taicpu(p).oper[1]^.reg := ThisReg;
  8494. taicpu(p).opsize := TargetSize;
  8495. end;
  8496. end;
  8497. end;
  8498. end;
  8499. end;
  8500. procedure AdjustFinalLoad;
  8501. begin
  8502. if not LowerUnsignedOverflow then
  8503. begin
  8504. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8505. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8506. begin
  8507. { Convert the output MOVZX to a MOV }
  8508. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8509. begin
  8510. { Or remove it completely! }
  8511. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8512. { Be careful; if p = hp1 and p was also removed, p
  8513. will become a dangling pointer }
  8514. if p = hp1 then
  8515. begin
  8516. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8517. p_removed := True;
  8518. end
  8519. else
  8520. RemoveInstruction(hp1);
  8521. hp1_removed := True;
  8522. end
  8523. else
  8524. begin
  8525. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8526. taicpu(hp1).opcode := A_MOV;
  8527. taicpu(hp1).oper[0]^.reg := ThisReg;
  8528. taicpu(hp1).opsize := TargetSize;
  8529. end;
  8530. end
  8531. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8532. begin
  8533. { Need to change the size of the output }
  8534. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8535. taicpu(hp1).oper[0]^.reg := ThisReg;
  8536. taicpu(hp1).opsize := S_BL;
  8537. end;
  8538. end;
  8539. end;
  8540. function CompressInstructions: Boolean;
  8541. var
  8542. LocalIndex: Integer;
  8543. begin
  8544. Result := False;
  8545. { The objective here is to try to find a combination that
  8546. removes one of the MOV/Z instructions. }
  8547. if (
  8548. (taicpu(p).oper[0]^.typ <> top_reg) or
  8549. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8550. ) and
  8551. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8552. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8553. begin
  8554. { Make a preference to remove the second MOVZX instruction }
  8555. case taicpu(hp1).opsize of
  8556. S_BL, S_WL:
  8557. begin
  8558. TargetSize := S_L;
  8559. TargetSubReg := R_SUBD;
  8560. end;
  8561. S_BW:
  8562. begin
  8563. TargetSize := S_W;
  8564. TargetSubReg := R_SUBW;
  8565. end;
  8566. else
  8567. InternalError(2020112302);
  8568. end;
  8569. end
  8570. else
  8571. begin
  8572. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8573. begin
  8574. { Exceeded lower bound but not upper bound }
  8575. TargetSize := MaxSize;
  8576. end
  8577. else if not LowerUnsignedOverflow then
  8578. begin
  8579. { Size didn't exceed lower bound }
  8580. TargetSize := MinSize;
  8581. end
  8582. else
  8583. Exit;
  8584. end;
  8585. case TargetSize of
  8586. S_B:
  8587. TargetSubReg := R_SUBL;
  8588. S_W:
  8589. TargetSubReg := R_SUBW;
  8590. S_L:
  8591. TargetSubReg := R_SUBD;
  8592. else
  8593. InternalError(2020112350);
  8594. end;
  8595. { Update the register to its new size }
  8596. setsubreg(ThisReg, TargetSubReg);
  8597. RegInUse := False;
  8598. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8599. begin
  8600. { Check to see if the active register is used afterwards;
  8601. if not, we can change it and make a saving. }
  8602. TransferUsedRegs(TmpUsedRegs);
  8603. { The target register may be marked as in use to cross
  8604. a jump to a distant label, so exclude it }
  8605. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8606. hp2 := p;
  8607. repeat
  8608. { Explicitly check for the excluded register (don't include the first
  8609. instruction as it may be reading from here }
  8610. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8611. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8612. begin
  8613. RegInUse := True;
  8614. Break;
  8615. end;
  8616. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8617. if not GetNextInstruction(hp2, hp2) then
  8618. InternalError(2020112340);
  8619. until (hp2 = hp1);
  8620. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8621. { We might still be able to get away with this }
  8622. RegInUse := not
  8623. (
  8624. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8625. (hp2.typ = ait_instruction) and
  8626. (
  8627. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8628. instruction that doesn't actually contain ThisReg }
  8629. (cs_opt_level3 in current_settings.optimizerswitches) or
  8630. RegInInstruction(ThisReg, hp2)
  8631. ) and
  8632. RegLoadedWithNewValue(ThisReg, hp2)
  8633. );
  8634. if not RegInUse then
  8635. begin
  8636. { Force the register size to the same as this instruction so it can be removed}
  8637. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8638. begin
  8639. TargetSize := S_L;
  8640. TargetSubReg := R_SUBD;
  8641. end
  8642. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8643. begin
  8644. TargetSize := S_W;
  8645. TargetSubReg := R_SUBW;
  8646. end;
  8647. ThisReg := taicpu(hp1).oper[1]^.reg;
  8648. setsubreg(ThisReg, TargetSubReg);
  8649. RegChanged := True;
  8650. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8651. TransferUsedRegs(TmpUsedRegs);
  8652. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8653. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8654. if p = hp1 then
  8655. begin
  8656. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8657. p_removed := True;
  8658. end
  8659. else
  8660. RemoveInstruction(hp1);
  8661. hp1_removed := True;
  8662. { Instruction will become "mov %reg,%reg" }
  8663. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8664. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8665. begin
  8666. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8667. RemoveCurrentP(p);
  8668. p_removed := True;
  8669. end
  8670. else
  8671. taicpu(p).oper[1]^.reg := ThisReg;
  8672. Result := True;
  8673. end
  8674. else
  8675. begin
  8676. if TargetSize <> MaxSize then
  8677. begin
  8678. { Since the register is in use, we have to force it to
  8679. MaxSize otherwise part of it may become undefined later on }
  8680. TargetSize := MaxSize;
  8681. case TargetSize of
  8682. S_B:
  8683. TargetSubReg := R_SUBL;
  8684. S_W:
  8685. TargetSubReg := R_SUBW;
  8686. S_L:
  8687. TargetSubReg := R_SUBD;
  8688. else
  8689. InternalError(2020112351);
  8690. end;
  8691. setsubreg(ThisReg, TargetSubReg);
  8692. end;
  8693. AdjustFinalLoad;
  8694. end;
  8695. end
  8696. else
  8697. AdjustFinalLoad;
  8698. Result := AdjustInitialLoadAndSize or Result;
  8699. { Now go through every instruction we found and change the
  8700. size. If TargetSize = MaxSize, then almost no changes are
  8701. needed and Result can remain False if it hasn't been set
  8702. yet.
  8703. If RegChanged is True, then the register requires changing
  8704. and so the point about TargetSize = MaxSize doesn't apply. }
  8705. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8706. begin
  8707. for LocalIndex := 0 to InstrMax do
  8708. begin
  8709. { If p_removed is true, then the original MOV/Z was removed
  8710. and removing the AND instruction may not be safe if it
  8711. appears first }
  8712. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8713. InternalError(2020112310);
  8714. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8715. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8716. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8717. InstrList[LocalIndex].opsize := TargetSize;
  8718. end;
  8719. Result := True;
  8720. end;
  8721. end;
  8722. begin
  8723. Result := False;
  8724. p_removed := False;
  8725. hp1_removed := False;
  8726. ThisReg := taicpu(p).oper[1]^.reg;
  8727. { Check for:
  8728. movs/z ###,%ecx (or %cx or %rcx)
  8729. ...
  8730. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8731. (dealloc %ecx)
  8732. Change to:
  8733. mov ###,%cl (if ### = %cl, then remove completely)
  8734. ...
  8735. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8736. }
  8737. if (getsupreg(ThisReg) = RS_ECX) and
  8738. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8739. (hp1.typ = ait_instruction) and
  8740. (
  8741. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8742. instruction that doesn't actually contain ECX }
  8743. (cs_opt_level3 in current_settings.optimizerswitches) or
  8744. RegInInstruction(NR_ECX, hp1) or
  8745. (
  8746. { It's common for the shift/rotate's read/write register to be
  8747. initialised in between, so under -O2 and under, search ahead
  8748. one more instruction
  8749. }
  8750. GetNextInstruction(hp1, hp1) and
  8751. (hp1.typ = ait_instruction) and
  8752. RegInInstruction(NR_ECX, hp1)
  8753. )
  8754. ) and
  8755. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8756. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8757. begin
  8758. TransferUsedRegs(TmpUsedRegs);
  8759. hp2 := p;
  8760. repeat
  8761. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8762. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8763. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8764. begin
  8765. case taicpu(p).opsize of
  8766. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8767. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8768. begin
  8769. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8770. RemoveCurrentP(p);
  8771. end
  8772. else
  8773. begin
  8774. taicpu(p).opcode := A_MOV;
  8775. taicpu(p).opsize := S_B;
  8776. taicpu(p).oper[1]^.reg := NR_CL;
  8777. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8778. end;
  8779. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8780. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8781. begin
  8782. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8783. RemoveCurrentP(p);
  8784. end
  8785. else
  8786. begin
  8787. taicpu(p).opcode := A_MOV;
  8788. taicpu(p).opsize := S_W;
  8789. taicpu(p).oper[1]^.reg := NR_CX;
  8790. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8791. end;
  8792. {$ifdef x86_64}
  8793. S_LQ:
  8794. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8795. begin
  8796. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8797. RemoveCurrentP(p);
  8798. end
  8799. else
  8800. begin
  8801. taicpu(p).opcode := A_MOV;
  8802. taicpu(p).opsize := S_L;
  8803. taicpu(p).oper[1]^.reg := NR_ECX;
  8804. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8805. end;
  8806. {$endif x86_64}
  8807. else
  8808. InternalError(2021120401);
  8809. end;
  8810. Result := True;
  8811. Exit;
  8812. end;
  8813. end;
  8814. { This is anything but quick! }
  8815. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8816. Exit;
  8817. SetLength(InstrList, 0);
  8818. InstrMax := -1;
  8819. case taicpu(p).opsize of
  8820. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8821. begin
  8822. {$if defined(i386) or defined(i8086)}
  8823. { If the target size is 8-bit, make sure we can actually encode it }
  8824. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8825. Exit;
  8826. {$endif i386 or i8086}
  8827. LowerLimit := $FF;
  8828. SignedLowerLimit := $7F;
  8829. SignedLowerLimitBottom := -128;
  8830. MinSize := S_B;
  8831. if taicpu(p).opsize = S_BW then
  8832. begin
  8833. MaxSize := S_W;
  8834. UpperLimit := $FFFF;
  8835. SignedUpperLimit := $7FFF;
  8836. SignedUpperLimitBottom := -32768;
  8837. end
  8838. else
  8839. begin
  8840. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8841. MaxSize := S_L;
  8842. UpperLimit := $FFFFFFFF;
  8843. SignedUpperLimit := $7FFFFFFF;
  8844. SignedUpperLimitBottom := -2147483648;
  8845. end;
  8846. end;
  8847. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8848. begin
  8849. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8850. LowerLimit := $FFFF;
  8851. SignedLowerLimit := $7FFF;
  8852. SignedLowerLimitBottom := -32768;
  8853. UpperLimit := $FFFFFFFF;
  8854. SignedUpperLimit := $7FFFFFFF;
  8855. SignedUpperLimitBottom := -2147483648;
  8856. MinSize := S_W;
  8857. MaxSize := S_L;
  8858. end;
  8859. {$ifdef x86_64}
  8860. S_LQ:
  8861. begin
  8862. { Both the lower and upper limits are set to 32-bit. If a limit
  8863. is breached, then optimisation is impossible }
  8864. LowerLimit := $FFFFFFFF;
  8865. SignedLowerLimit := $7FFFFFFF;
  8866. SignedLowerLimitBottom := -2147483648;
  8867. UpperLimit := $FFFFFFFF;
  8868. SignedUpperLimit := $7FFFFFFF;
  8869. SignedUpperLimitBottom := -2147483648;
  8870. MinSize := S_L;
  8871. MaxSize := S_L;
  8872. end;
  8873. {$endif x86_64}
  8874. else
  8875. InternalError(2020112301);
  8876. end;
  8877. TestValMin := 0;
  8878. TestValMax := LowerLimit;
  8879. TestValSignedMax := SignedLowerLimit;
  8880. TryShiftDownLimit := LowerLimit;
  8881. TryShiftDown := S_NO;
  8882. ShiftDownOverflow := False;
  8883. RegChanged := False;
  8884. BitwiseOnly := True;
  8885. OrXorUsed := False;
  8886. UpperSignedOverflow := False;
  8887. LowerSignedOverflow := False;
  8888. UpperUnsignedOverflow := False;
  8889. LowerUnsignedOverflow := False;
  8890. hp1 := p;
  8891. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8892. (hp1.typ = ait_instruction) and
  8893. (
  8894. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8895. instruction that doesn't actually contain ThisReg }
  8896. (cs_opt_level3 in current_settings.optimizerswitches) or
  8897. { This allows this Movx optimisation to work through the SETcc instructions
  8898. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8899. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8900. skip over these SETcc instructions). }
  8901. (taicpu(hp1).opcode = A_SETcc) or
  8902. RegInInstruction(ThisReg, hp1)
  8903. ) do
  8904. begin
  8905. case taicpu(hp1).opcode of
  8906. A_INC,A_DEC:
  8907. begin
  8908. { Has to be an exact match on the register }
  8909. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8910. Break;
  8911. if taicpu(hp1).opcode = A_INC then
  8912. begin
  8913. Inc(TestValMin);
  8914. Inc(TestValMax);
  8915. Inc(TestValSignedMax);
  8916. end
  8917. else
  8918. begin
  8919. Dec(TestValMin);
  8920. Dec(TestValMax);
  8921. Dec(TestValSignedMax);
  8922. end;
  8923. end;
  8924. A_TEST, A_CMP:
  8925. begin
  8926. if (
  8927. { Too high a risk of non-linear behaviour that breaks DFA
  8928. here, unless it's cmp $0,%reg, which is equivalent to
  8929. test %reg,%reg }
  8930. OrXorUsed and
  8931. (taicpu(hp1).opcode = A_CMP) and
  8932. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8933. ) or
  8934. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8935. { Has to be an exact match on the register }
  8936. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8937. (
  8938. { Permit "test %reg,%reg" }
  8939. (taicpu(hp1).opcode = A_TEST) and
  8940. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8941. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8942. ) or
  8943. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8944. { Make sure the comparison value is not smaller than the
  8945. smallest allowed signed value for the minimum size (e.g.
  8946. -128 for 8-bit) }
  8947. not (
  8948. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8949. { Is it in the negative range? }
  8950. (
  8951. (taicpu(hp1).oper[0]^.val < 0) and
  8952. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8953. )
  8954. ) then
  8955. Break;
  8956. { Check to see if the active register is used afterwards }
  8957. TransferUsedRegs(TmpUsedRegs);
  8958. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8959. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8960. begin
  8961. { Make sure the comparison or any previous instructions
  8962. hasn't pushed the test values outside of the range of
  8963. MinSize }
  8964. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8965. begin
  8966. { Exceeded lower bound but not upper bound }
  8967. Exit;
  8968. end
  8969. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8970. begin
  8971. { Size didn't exceed lower bound }
  8972. TargetSize := MinSize;
  8973. end
  8974. else
  8975. Break;
  8976. case TargetSize of
  8977. S_B:
  8978. TargetSubReg := R_SUBL;
  8979. S_W:
  8980. TargetSubReg := R_SUBW;
  8981. S_L:
  8982. TargetSubReg := R_SUBD;
  8983. else
  8984. InternalError(2021051002);
  8985. end;
  8986. if TargetSize <> MaxSize then
  8987. begin
  8988. { Update the register to its new size }
  8989. setsubreg(ThisReg, TargetSubReg);
  8990. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8991. taicpu(hp1).oper[1]^.reg := ThisReg;
  8992. taicpu(hp1).opsize := TargetSize;
  8993. { Convert the input MOVZX to a MOV if necessary }
  8994. AdjustInitialLoadAndSize;
  8995. if (InstrMax >= 0) then
  8996. begin
  8997. for Index := 0 to InstrMax do
  8998. begin
  8999. { If p_removed is true, then the original MOV/Z was removed
  9000. and removing the AND instruction may not be safe if it
  9001. appears first }
  9002. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9003. InternalError(2020112311);
  9004. if InstrList[Index].oper[0]^.typ = top_reg then
  9005. InstrList[Index].oper[0]^.reg := ThisReg;
  9006. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9007. InstrList[Index].opsize := MinSize;
  9008. end;
  9009. end;
  9010. Result := True;
  9011. end;
  9012. Exit;
  9013. end;
  9014. end;
  9015. A_SETcc:
  9016. begin
  9017. { This allows this Movx optimisation to work through the SETcc instructions
  9018. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9019. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9020. skip over these SETcc instructions). }
  9021. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9022. { Of course, break out if the current register is used }
  9023. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9024. Break
  9025. else
  9026. { We must use Continue so the instruction doesn't get added
  9027. to InstrList }
  9028. Continue;
  9029. end;
  9030. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9031. begin
  9032. if
  9033. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9034. { Has to be an exact match on the register }
  9035. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9036. (
  9037. (
  9038. (taicpu(hp1).oper[0]^.typ = top_const) and
  9039. (
  9040. (
  9041. (taicpu(hp1).opcode = A_SHL) and
  9042. (
  9043. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9044. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9045. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9046. )
  9047. ) or (
  9048. (taicpu(hp1).opcode <> A_SHL) and
  9049. (
  9050. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9051. { Is it in the negative range? }
  9052. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9053. )
  9054. )
  9055. )
  9056. ) or (
  9057. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9058. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9059. )
  9060. ) then
  9061. Break;
  9062. { Only process OR and XOR if there are only bitwise operations,
  9063. since otherwise they can too easily fool the data flow
  9064. analysis (they can cause non-linear behaviour) }
  9065. case taicpu(hp1).opcode of
  9066. A_ADD:
  9067. begin
  9068. if OrXorUsed then
  9069. { Too high a risk of non-linear behaviour that breaks DFA here }
  9070. Break
  9071. else
  9072. BitwiseOnly := False;
  9073. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9074. begin
  9075. TestValMin := TestValMin * 2;
  9076. TestValMax := TestValMax * 2;
  9077. TestValSignedMax := TestValSignedMax * 2;
  9078. end
  9079. else
  9080. begin
  9081. WorkingValue := taicpu(hp1).oper[0]^.val;
  9082. TestValMin := TestValMin + WorkingValue;
  9083. TestValMax := TestValMax + WorkingValue;
  9084. TestValSignedMax := TestValSignedMax + WorkingValue;
  9085. end;
  9086. end;
  9087. A_SUB:
  9088. begin
  9089. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9090. begin
  9091. TestValMin := 0;
  9092. TestValMax := 0;
  9093. TestValSignedMax := 0;
  9094. end
  9095. else
  9096. begin
  9097. if OrXorUsed then
  9098. { Too high a risk of non-linear behaviour that breaks DFA here }
  9099. Break
  9100. else
  9101. BitwiseOnly := False;
  9102. WorkingValue := taicpu(hp1).oper[0]^.val;
  9103. TestValMin := TestValMin - WorkingValue;
  9104. TestValMax := TestValMax - WorkingValue;
  9105. TestValSignedMax := TestValSignedMax - WorkingValue;
  9106. end;
  9107. end;
  9108. A_AND:
  9109. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9110. begin
  9111. { we might be able to go smaller if AND appears first }
  9112. if InstrMax = -1 then
  9113. case MinSize of
  9114. S_B:
  9115. ;
  9116. S_W:
  9117. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9118. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9119. begin
  9120. TryShiftDown := S_B;
  9121. TryShiftDownLimit := $FF;
  9122. end;
  9123. S_L:
  9124. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9125. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9126. begin
  9127. TryShiftDown := S_B;
  9128. TryShiftDownLimit := $FF;
  9129. end
  9130. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9131. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9132. begin
  9133. TryShiftDown := S_W;
  9134. TryShiftDownLimit := $FFFF;
  9135. end;
  9136. else
  9137. InternalError(2020112320);
  9138. end;
  9139. WorkingValue := taicpu(hp1).oper[0]^.val;
  9140. TestValMin := TestValMin and WorkingValue;
  9141. TestValMax := TestValMax and WorkingValue;
  9142. TestValSignedMax := TestValSignedMax and WorkingValue;
  9143. end;
  9144. A_OR:
  9145. begin
  9146. if not BitwiseOnly then
  9147. Break;
  9148. OrXorUsed := True;
  9149. WorkingValue := taicpu(hp1).oper[0]^.val;
  9150. TestValMin := TestValMin or WorkingValue;
  9151. TestValMax := TestValMax or WorkingValue;
  9152. TestValSignedMax := TestValSignedMax or WorkingValue;
  9153. end;
  9154. A_XOR:
  9155. begin
  9156. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9157. begin
  9158. TestValMin := 0;
  9159. TestValMax := 0;
  9160. TestValSignedMax := 0;
  9161. end
  9162. else
  9163. begin
  9164. if not BitwiseOnly then
  9165. Break;
  9166. OrXorUsed := True;
  9167. WorkingValue := taicpu(hp1).oper[0]^.val;
  9168. TestValMin := TestValMin xor WorkingValue;
  9169. TestValMax := TestValMax xor WorkingValue;
  9170. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9171. end;
  9172. end;
  9173. A_SHL:
  9174. begin
  9175. BitwiseOnly := False;
  9176. WorkingValue := taicpu(hp1).oper[0]^.val;
  9177. TestValMin := TestValMin shl WorkingValue;
  9178. TestValMax := TestValMax shl WorkingValue;
  9179. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9180. end;
  9181. A_SHR,
  9182. { The first instruction was MOVZX, so the value won't be negative }
  9183. A_SAR:
  9184. begin
  9185. if InstrMax <> -1 then
  9186. BitwiseOnly := False
  9187. else
  9188. { we might be able to go smaller if SHR appears first }
  9189. case MinSize of
  9190. S_B:
  9191. ;
  9192. S_W:
  9193. if (taicpu(hp1).oper[0]^.val >= 8) then
  9194. begin
  9195. TryShiftDown := S_B;
  9196. TryShiftDownLimit := $FF;
  9197. TryShiftDownSignedLimit := $7F;
  9198. TryShiftDownSignedLimitLower := -128;
  9199. end;
  9200. S_L:
  9201. if (taicpu(hp1).oper[0]^.val >= 24) then
  9202. begin
  9203. TryShiftDown := S_B;
  9204. TryShiftDownLimit := $FF;
  9205. TryShiftDownSignedLimit := $7F;
  9206. TryShiftDownSignedLimitLower := -128;
  9207. end
  9208. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9209. begin
  9210. TryShiftDown := S_W;
  9211. TryShiftDownLimit := $FFFF;
  9212. TryShiftDownSignedLimit := $7FFF;
  9213. TryShiftDownSignedLimitLower := -32768;
  9214. end;
  9215. else
  9216. InternalError(2020112321);
  9217. end;
  9218. WorkingValue := taicpu(hp1).oper[0]^.val;
  9219. if taicpu(hp1).opcode = A_SAR then
  9220. begin
  9221. TestValMin := SarInt64(TestValMin, WorkingValue);
  9222. TestValMax := SarInt64(TestValMax, WorkingValue);
  9223. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9224. end
  9225. else
  9226. begin
  9227. TestValMin := TestValMin shr WorkingValue;
  9228. TestValMax := TestValMax shr WorkingValue;
  9229. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9230. end;
  9231. end;
  9232. else
  9233. InternalError(2020112303);
  9234. end;
  9235. end;
  9236. (*
  9237. A_IMUL:
  9238. case taicpu(hp1).ops of
  9239. 2:
  9240. begin
  9241. if not MatchOpType(hp1, top_reg, top_reg) or
  9242. { Has to be an exact match on the register }
  9243. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9244. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9245. Break;
  9246. TestValMin := TestValMin * TestValMin;
  9247. TestValMax := TestValMax * TestValMax;
  9248. TestValSignedMax := TestValSignedMax * TestValMax;
  9249. end;
  9250. 3:
  9251. begin
  9252. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9253. { Has to be an exact match on the register }
  9254. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9255. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9256. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9257. { Is it in the negative range? }
  9258. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9259. Break;
  9260. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9261. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9262. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9263. end;
  9264. else
  9265. Break;
  9266. end;
  9267. A_IDIV:
  9268. case taicpu(hp1).ops of
  9269. 3:
  9270. begin
  9271. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9272. { Has to be an exact match on the register }
  9273. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9274. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9275. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9276. { Is it in the negative range? }
  9277. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9278. Break;
  9279. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9280. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9281. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9282. end;
  9283. else
  9284. Break;
  9285. end;
  9286. *)
  9287. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9288. begin
  9289. { If there are no instructions in between, then we might be able to make a saving }
  9290. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9291. Break;
  9292. { We have something like:
  9293. movzbw %dl,%dx
  9294. ...
  9295. movswl %dx,%edx
  9296. Change the latter to a zero-extension then enter the
  9297. A_MOVZX case branch.
  9298. }
  9299. {$ifdef x86_64}
  9300. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9301. begin
  9302. { this becomes a zero extension from 32-bit to 64-bit, but
  9303. the upper 32 bits are already zero, so just delete the
  9304. instruction }
  9305. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9306. RemoveInstruction(hp1);
  9307. Result := True;
  9308. Exit;
  9309. end
  9310. else
  9311. {$endif x86_64}
  9312. begin
  9313. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9314. taicpu(hp1).opcode := A_MOVZX;
  9315. {$ifdef x86_64}
  9316. case taicpu(hp1).opsize of
  9317. S_BQ:
  9318. begin
  9319. taicpu(hp1).opsize := S_BL;
  9320. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9321. end;
  9322. S_WQ:
  9323. begin
  9324. taicpu(hp1).opsize := S_WL;
  9325. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9326. end;
  9327. S_LQ:
  9328. begin
  9329. taicpu(hp1).opcode := A_MOV;
  9330. taicpu(hp1).opsize := S_L;
  9331. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9332. { In this instance, we need to break out because the
  9333. instruction is no longer MOVZX or MOVSXD }
  9334. Result := True;
  9335. Exit;
  9336. end;
  9337. else
  9338. ;
  9339. end;
  9340. {$endif x86_64}
  9341. Result := CompressInstructions;
  9342. Exit;
  9343. end;
  9344. end;
  9345. A_MOVZX:
  9346. begin
  9347. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9348. Break;
  9349. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9350. begin
  9351. if (InstrMax = -1) and
  9352. { Will return false if the second parameter isn't ThisReg
  9353. (can happen on -O2 and under) }
  9354. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9355. begin
  9356. { The two MOVZX instructions are adjacent, so remove the first one }
  9357. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9358. RemoveCurrentP(p);
  9359. Result := True;
  9360. Exit;
  9361. end;
  9362. Break;
  9363. end;
  9364. Result := CompressInstructions;
  9365. Exit;
  9366. end;
  9367. else
  9368. { This includes ADC, SBB and IDIV }
  9369. Break;
  9370. end;
  9371. if not CheckOverflowConditions then
  9372. Break;
  9373. { Contains highest index (so instruction count - 1) }
  9374. Inc(InstrMax);
  9375. if InstrMax > High(InstrList) then
  9376. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9377. InstrList[InstrMax] := taicpu(hp1);
  9378. end;
  9379. end;
  9380. {$pop}
  9381. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9382. var
  9383. hp1 : tai;
  9384. begin
  9385. Result:=false;
  9386. if (taicpu(p).ops >= 2) and
  9387. ((taicpu(p).oper[0]^.typ = top_const) or
  9388. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9389. (taicpu(p).oper[1]^.typ = top_reg) and
  9390. ((taicpu(p).ops = 2) or
  9391. ((taicpu(p).oper[2]^.typ = top_reg) and
  9392. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9393. GetLastInstruction(p,hp1) and
  9394. MatchInstruction(hp1,A_MOV,[]) and
  9395. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9396. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9397. begin
  9398. TransferUsedRegs(TmpUsedRegs);
  9399. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9400. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9401. { change
  9402. mov reg1,reg2
  9403. imul y,reg2 to imul y,reg1,reg2 }
  9404. begin
  9405. taicpu(p).ops := 3;
  9406. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9407. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9408. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9409. RemoveInstruction(hp1);
  9410. result:=true;
  9411. end;
  9412. end;
  9413. end;
  9414. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9415. var
  9416. ThisLabel: TAsmLabel;
  9417. begin
  9418. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9419. ThisLabel.decrefs;
  9420. taicpu(p).condition := C_None;
  9421. taicpu(p).opcode := A_RET;
  9422. taicpu(p).is_jmp := false;
  9423. taicpu(p).ops := taicpu(ret_p).ops;
  9424. case taicpu(ret_p).ops of
  9425. 0:
  9426. taicpu(p).clearop(0);
  9427. 1:
  9428. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9429. else
  9430. internalerror(2016041301);
  9431. end;
  9432. { If the original label is now dead, it might turn out that the label
  9433. immediately follows p. As a result, everything beyond it, which will
  9434. be just some final register configuration and a RET instruction, is
  9435. now dead code. [Kit] }
  9436. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9437. running RemoveDeadCodeAfterJump for each RET instruction, because
  9438. this optimisation rarely happens and most RETs appear at the end of
  9439. routines where there is nothing that can be stripped. [Kit] }
  9440. if not ThisLabel.is_used then
  9441. RemoveDeadCodeAfterJump(p);
  9442. end;
  9443. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9444. var
  9445. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9446. Unconditional, PotentialModified: Boolean;
  9447. OperPtr: POper;
  9448. NewRef: TReference;
  9449. InstrList: array of taicpu;
  9450. InstrMax, Index: Integer;
  9451. const
  9452. {$ifdef DEBUG_AOPTCPU}
  9453. SNoFlags: shortstring = ' so the flags aren''t modified';
  9454. {$else DEBUG_AOPTCPU}
  9455. SNoFlags = '';
  9456. {$endif DEBUG_AOPTCPU}
  9457. begin
  9458. Result:=false;
  9459. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9460. begin
  9461. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9462. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9463. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9464. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9465. GetNextInstruction(hp1, hp2) and
  9466. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9467. { Change from: To:
  9468. set(C) %reg j(~C) label
  9469. test %reg,%reg/cmp $0,%reg
  9470. je label
  9471. set(C) %reg j(C) label
  9472. test %reg,%reg/cmp $0,%reg
  9473. jne label
  9474. (Also do something similar with sete/setne instead of je/jne)
  9475. }
  9476. begin
  9477. { Before we do anything else, we need to check the instructions
  9478. in between SETcc and TEST to make sure they don't modify the
  9479. FLAGS register - if -O2 or under, there won't be any
  9480. instructions between SET and TEST }
  9481. TransferUsedRegs(TmpUsedRegs);
  9482. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9483. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9484. begin
  9485. next := p;
  9486. SetLength(InstrList, 0);
  9487. InstrMax := -1;
  9488. PotentialModified := False;
  9489. { Make a note of every instruction that modifies the FLAGS
  9490. register }
  9491. while GetNextInstruction(next, next) and (next <> hp1) do
  9492. begin
  9493. if next.typ <> ait_instruction then
  9494. { GetNextInstructionUsingReg should have returned False }
  9495. InternalError(2021051701);
  9496. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9497. begin
  9498. case taicpu(next).opcode of
  9499. A_SETcc,
  9500. A_CMOVcc,
  9501. A_Jcc:
  9502. begin
  9503. if PotentialModified then
  9504. { Not safe because the flags were modified earlier }
  9505. Exit
  9506. else
  9507. { Condition is the same as the initial SETcc, so this is safe
  9508. (don't add to instruction list though) }
  9509. Continue;
  9510. end;
  9511. A_ADD:
  9512. begin
  9513. if (taicpu(next).opsize = S_B) or
  9514. { LEA doesn't support 8-bit operands }
  9515. (taicpu(next).oper[1]^.typ <> top_reg) or
  9516. { Must write to a register }
  9517. (taicpu(next).oper[0]^.typ = top_ref) then
  9518. { Require a constant or a register }
  9519. Exit;
  9520. PotentialModified := True;
  9521. end;
  9522. A_SUB:
  9523. begin
  9524. if (taicpu(next).opsize = S_B) or
  9525. { LEA doesn't support 8-bit operands }
  9526. (taicpu(next).oper[1]^.typ <> top_reg) or
  9527. { Must write to a register }
  9528. (taicpu(next).oper[0]^.typ <> top_const) or
  9529. (taicpu(next).oper[0]^.val = $80000000) then
  9530. { Can't subtract a register with LEA - also
  9531. check that the value isn't -2^31, as this
  9532. can't be negated }
  9533. Exit;
  9534. PotentialModified := True;
  9535. end;
  9536. A_SAL,
  9537. A_SHL:
  9538. begin
  9539. if (taicpu(next).opsize = S_B) or
  9540. { LEA doesn't support 8-bit operands }
  9541. (taicpu(next).oper[1]^.typ <> top_reg) or
  9542. { Must write to a register }
  9543. (taicpu(next).oper[0]^.typ <> top_const) or
  9544. (taicpu(next).oper[0]^.val < 0) or
  9545. (taicpu(next).oper[0]^.val > 3) then
  9546. Exit;
  9547. PotentialModified := True;
  9548. end;
  9549. A_IMUL:
  9550. begin
  9551. if (taicpu(next).ops <> 3) or
  9552. (taicpu(next).oper[1]^.typ <> top_reg) or
  9553. { Must write to a register }
  9554. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9555. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9556. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9557. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9558. Exit
  9559. else
  9560. PotentialModified := True;
  9561. end;
  9562. else
  9563. { Don't know how to change this, so abort }
  9564. Exit;
  9565. end;
  9566. { Contains highest index (so instruction count - 1) }
  9567. Inc(InstrMax);
  9568. if InstrMax > High(InstrList) then
  9569. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9570. InstrList[InstrMax] := taicpu(next);
  9571. end;
  9572. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9573. end;
  9574. if not Assigned(next) or (next <> hp1) then
  9575. { It should be equal to hp1 }
  9576. InternalError(2021051702);
  9577. { Cycle through each instruction and check to see if we can
  9578. change them to versions that don't modify the flags }
  9579. if (InstrMax >= 0) then
  9580. begin
  9581. for Index := 0 to InstrMax do
  9582. case InstrList[Index].opcode of
  9583. A_ADD:
  9584. begin
  9585. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9586. InstrList[Index].opcode := A_LEA;
  9587. reference_reset(NewRef, 1, []);
  9588. NewRef.base := InstrList[Index].oper[1]^.reg;
  9589. if InstrList[Index].oper[0]^.typ = top_reg then
  9590. begin
  9591. NewRef.index := InstrList[Index].oper[0]^.reg;
  9592. NewRef.scalefactor := 1;
  9593. end
  9594. else
  9595. NewRef.offset := InstrList[Index].oper[0]^.val;
  9596. InstrList[Index].loadref(0, NewRef);
  9597. end;
  9598. A_SUB:
  9599. begin
  9600. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9601. InstrList[Index].opcode := A_LEA;
  9602. reference_reset(NewRef, 1, []);
  9603. NewRef.base := InstrList[Index].oper[1]^.reg;
  9604. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9605. InstrList[Index].loadref(0, NewRef);
  9606. end;
  9607. A_SHL,
  9608. A_SAL:
  9609. begin
  9610. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9611. InstrList[Index].opcode := A_LEA;
  9612. reference_reset(NewRef, 1, []);
  9613. NewRef.index := InstrList[Index].oper[1]^.reg;
  9614. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9615. InstrList[Index].loadref(0, NewRef);
  9616. end;
  9617. A_IMUL:
  9618. begin
  9619. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9620. InstrList[Index].opcode := A_LEA;
  9621. reference_reset(NewRef, 1, []);
  9622. NewRef.index := InstrList[Index].oper[1]^.reg;
  9623. case InstrList[Index].oper[0]^.val of
  9624. 2, 4, 8:
  9625. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9626. else {3, 5 and 9}
  9627. begin
  9628. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9629. NewRef.base := InstrList[Index].oper[1]^.reg;
  9630. end;
  9631. end;
  9632. InstrList[Index].loadref(0, NewRef);
  9633. end;
  9634. else
  9635. InternalError(2021051710);
  9636. end;
  9637. end;
  9638. { Mark the FLAGS register as used across this whole block }
  9639. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9640. end;
  9641. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9642. JumpC := taicpu(hp2).condition;
  9643. Unconditional := False;
  9644. if conditions_equal(JumpC, C_E) then
  9645. SetC := inverse_cond(taicpu(p).condition)
  9646. else if conditions_equal(JumpC, C_NE) then
  9647. SetC := taicpu(p).condition
  9648. else
  9649. { We've got something weird here (and inefficent) }
  9650. begin
  9651. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9652. SetC := C_NONE;
  9653. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9654. if condition_in(C_AE, JumpC) then
  9655. Unconditional := True
  9656. else
  9657. { Not sure what to do with this jump - drop out }
  9658. Exit;
  9659. end;
  9660. RemoveInstruction(hp1);
  9661. if Unconditional then
  9662. MakeUnconditional(taicpu(hp2))
  9663. else
  9664. begin
  9665. if SetC = C_NONE then
  9666. InternalError(2018061402);
  9667. taicpu(hp2).SetCondition(SetC);
  9668. end;
  9669. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9670. TmpUsedRegs }
  9671. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9672. begin
  9673. RemoveCurrentp(p, hp2);
  9674. if taicpu(hp2).opcode = A_SETcc then
  9675. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9676. else
  9677. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9678. end
  9679. else
  9680. if taicpu(hp2).opcode = A_SETcc then
  9681. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9682. else
  9683. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9684. Result := True;
  9685. end
  9686. else if
  9687. { Make sure the instructions are adjacent }
  9688. (
  9689. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9690. GetNextInstruction(p, hp1)
  9691. ) and
  9692. MatchInstruction(hp1, A_MOV, [S_B]) and
  9693. { Writing to memory is allowed }
  9694. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9695. begin
  9696. {
  9697. Watch out for sequences such as:
  9698. set(c)b %regb
  9699. movb %regb,(ref)
  9700. movb $0,1(ref)
  9701. movb $0,2(ref)
  9702. movb $0,3(ref)
  9703. Much more efficient to turn it into:
  9704. movl $0,%regl
  9705. set(c)b %regb
  9706. movl %regl,(ref)
  9707. Or:
  9708. set(c)b %regb
  9709. movzbl %regb,%regl
  9710. movl %regl,(ref)
  9711. }
  9712. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9713. GetNextInstruction(hp1, hp2) and
  9714. MatchInstruction(hp2, A_MOV, [S_B]) and
  9715. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9716. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9717. begin
  9718. { Don't do anything else except set Result to True }
  9719. end
  9720. else
  9721. begin
  9722. if taicpu(p).oper[0]^.typ = top_reg then
  9723. begin
  9724. TransferUsedRegs(TmpUsedRegs);
  9725. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9726. end;
  9727. { If it's not a register, it's a memory address }
  9728. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9729. begin
  9730. { Even if the register is still in use, we can minimise the
  9731. pipeline stall by changing the MOV into another SETcc. }
  9732. taicpu(hp1).opcode := A_SETcc;
  9733. taicpu(hp1).condition := taicpu(p).condition;
  9734. if taicpu(hp1).oper[1]^.typ = top_ref then
  9735. begin
  9736. { Swapping the operand pointers like this is probably a
  9737. bit naughty, but it is far faster than using loadoper
  9738. to transfer the reference from oper[1] to oper[0] if
  9739. you take into account the extra procedure calls and
  9740. the memory allocation and deallocation required }
  9741. OperPtr := taicpu(hp1).oper[1];
  9742. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9743. taicpu(hp1).oper[0] := OperPtr;
  9744. end
  9745. else
  9746. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9747. taicpu(hp1).clearop(1);
  9748. taicpu(hp1).ops := 1;
  9749. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9750. end
  9751. else
  9752. begin
  9753. if taicpu(hp1).oper[1]^.typ = top_reg then
  9754. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9755. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9756. RemoveInstruction(hp1);
  9757. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9758. end
  9759. end;
  9760. Result := True;
  9761. end;
  9762. end;
  9763. end;
  9764. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9765. var
  9766. hp1: tai;
  9767. Count: Integer;
  9768. OrigLabel: TAsmLabel;
  9769. begin
  9770. result := False;
  9771. { Sometimes, the optimisations below can permit this }
  9772. RemoveDeadCodeAfterJump(p);
  9773. 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
  9774. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9775. begin
  9776. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9777. { Also a side-effect of optimisations }
  9778. if CollapseZeroDistJump(p, OrigLabel) then
  9779. begin
  9780. Result := True;
  9781. Exit;
  9782. end;
  9783. hp1 := GetLabelWithSym(OrigLabel);
  9784. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9785. begin
  9786. if taicpu(hp1).opcode = A_RET then
  9787. begin
  9788. {
  9789. change
  9790. jmp .L1
  9791. ...
  9792. .L1:
  9793. ret
  9794. into
  9795. ret
  9796. }
  9797. begin
  9798. ConvertJumpToRET(p, hp1);
  9799. result:=true;
  9800. end;
  9801. end
  9802. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9803. not (cs_opt_size in current_settings.optimizerswitches) and
  9804. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9805. begin
  9806. Result := True;
  9807. Exit;
  9808. end;
  9809. end;
  9810. end;
  9811. end;
  9812. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9813. begin
  9814. CanBeCMOV:=assigned(p) and
  9815. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9816. { we can't use cmov ref,reg because
  9817. ref could be nil and cmov still throws an exception
  9818. if ref=nil but the mov isn't done (FK)
  9819. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9820. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9821. }
  9822. (taicpu(p).oper[1]^.typ = top_reg) and
  9823. (
  9824. (taicpu(p).oper[0]^.typ = top_reg) or
  9825. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9826. it is not expected that this can cause a seg. violation }
  9827. (
  9828. (taicpu(p).oper[0]^.typ = top_ref) and
  9829. IsRefSafe(taicpu(p).oper[0]^.ref)
  9830. )
  9831. );
  9832. end;
  9833. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9834. var
  9835. hp1,hp2: tai;
  9836. {$ifndef i8086}
  9837. hp3,hp4,hpmov2, hp5: tai;
  9838. l : Longint;
  9839. condition : TAsmCond;
  9840. {$endif i8086}
  9841. carryadd_opcode : TAsmOp;
  9842. symbol: TAsmSymbol;
  9843. increg, tmpreg: TRegister;
  9844. begin
  9845. result:=false;
  9846. if GetNextInstruction(p,hp1) then
  9847. begin
  9848. if (hp1.typ=ait_label) then
  9849. begin
  9850. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9851. Exit;
  9852. end
  9853. else if (hp1.typ<>ait_instruction) then
  9854. Exit;
  9855. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9856. if (
  9857. (
  9858. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9859. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9860. (Taicpu(hp1).oper[0]^.val=1)
  9861. ) or
  9862. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9863. ) and
  9864. GetNextInstruction(hp1,hp2) and
  9865. SkipAligns(hp2, hp2) and
  9866. (hp2.typ = ait_label) and
  9867. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9868. { jb @@1 cmc
  9869. inc/dec operand --> adc/sbb operand,0
  9870. @@1:
  9871. ... and ...
  9872. jnb @@1
  9873. inc/dec operand --> adc/sbb operand,0
  9874. @@1: }
  9875. begin
  9876. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9877. begin
  9878. case taicpu(hp1).opcode of
  9879. A_INC,
  9880. A_ADD:
  9881. carryadd_opcode:=A_ADC;
  9882. A_DEC,
  9883. A_SUB:
  9884. carryadd_opcode:=A_SBB;
  9885. else
  9886. InternalError(2021011001);
  9887. end;
  9888. Taicpu(p).clearop(0);
  9889. Taicpu(p).ops:=0;
  9890. Taicpu(p).is_jmp:=false;
  9891. Taicpu(p).opcode:=A_CMC;
  9892. Taicpu(p).condition:=C_NONE;
  9893. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9894. Taicpu(hp1).ops:=2;
  9895. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9896. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9897. else
  9898. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9899. Taicpu(hp1).loadconst(0,0);
  9900. Taicpu(hp1).opcode:=carryadd_opcode;
  9901. result:=true;
  9902. exit;
  9903. end
  9904. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9905. begin
  9906. case taicpu(hp1).opcode of
  9907. A_INC,
  9908. A_ADD:
  9909. carryadd_opcode:=A_ADC;
  9910. A_DEC,
  9911. A_SUB:
  9912. carryadd_opcode:=A_SBB;
  9913. else
  9914. InternalError(2021011002);
  9915. end;
  9916. Taicpu(hp1).ops:=2;
  9917. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9918. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9919. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9920. else
  9921. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9922. Taicpu(hp1).loadconst(0,0);
  9923. Taicpu(hp1).opcode:=carryadd_opcode;
  9924. RemoveCurrentP(p, hp1);
  9925. result:=true;
  9926. exit;
  9927. end
  9928. {
  9929. jcc @@1 setcc tmpreg
  9930. inc/dec/add/sub operand -> (movzx tmpreg)
  9931. @@1: add/sub tmpreg,operand
  9932. While this increases code size slightly, it makes the code much faster if the
  9933. jump is unpredictable
  9934. }
  9935. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9936. begin
  9937. { search for an available register which is volatile }
  9938. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9939. if increg <> NR_NO then
  9940. begin
  9941. { We don't need to check if tmpreg is in hp1 or not, because
  9942. it will be marked as in use at p (if not, this is
  9943. indictive of a compiler bug). }
  9944. TAsmLabel(symbol).decrefs;
  9945. Taicpu(p).clearop(0);
  9946. Taicpu(p).ops:=1;
  9947. Taicpu(p).is_jmp:=false;
  9948. Taicpu(p).opcode:=A_SETcc;
  9949. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9950. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9951. Taicpu(p).loadreg(0,increg);
  9952. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9953. begin
  9954. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9955. R_SUBW:
  9956. begin
  9957. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9958. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9959. end;
  9960. R_SUBD:
  9961. begin
  9962. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9963. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9964. end;
  9965. {$ifdef x86_64}
  9966. R_SUBQ:
  9967. begin
  9968. { MOVZX doesn't have a 64-bit variant, because
  9969. the 32-bit version implicitly zeroes the
  9970. upper 32-bits of the destination register }
  9971. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9972. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9973. setsubreg(tmpreg, R_SUBQ);
  9974. end;
  9975. {$endif x86_64}
  9976. else
  9977. Internalerror(2020030601);
  9978. end;
  9979. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9980. asml.InsertAfter(hp2,p);
  9981. end
  9982. else
  9983. tmpreg := increg;
  9984. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9985. begin
  9986. Taicpu(hp1).ops:=2;
  9987. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9988. end;
  9989. Taicpu(hp1).loadreg(0,tmpreg);
  9990. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9991. Result := True;
  9992. { p is no longer a Jcc instruction, so exit }
  9993. Exit;
  9994. end;
  9995. end;
  9996. end;
  9997. { Detect the following:
  9998. jmp<cond> @Lbl1
  9999. jmp @Lbl2
  10000. ...
  10001. @Lbl1:
  10002. ret
  10003. Change to:
  10004. jmp<inv_cond> @Lbl2
  10005. ret
  10006. }
  10007. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10008. begin
  10009. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10010. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10011. MatchInstruction(hp2,A_RET,[S_NO]) then
  10012. begin
  10013. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10014. { Change label address to that of the unconditional jump }
  10015. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10016. TAsmLabel(symbol).DecRefs;
  10017. taicpu(hp1).opcode := A_RET;
  10018. taicpu(hp1).is_jmp := false;
  10019. taicpu(hp1).ops := taicpu(hp2).ops;
  10020. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10021. case taicpu(hp2).ops of
  10022. 0:
  10023. taicpu(hp1).clearop(0);
  10024. 1:
  10025. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10026. else
  10027. internalerror(2016041302);
  10028. end;
  10029. end;
  10030. {$ifndef i8086}
  10031. end
  10032. {
  10033. convert
  10034. j<c> .L1
  10035. mov 1,reg
  10036. jmp .L2
  10037. .L1
  10038. mov 0,reg
  10039. .L2
  10040. into
  10041. mov 0,reg
  10042. set<not(c)> reg
  10043. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10044. would destroy the flag contents
  10045. }
  10046. else if MatchInstruction(hp1,A_MOV,[]) and
  10047. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10048. {$ifdef i386}
  10049. (
  10050. { Under i386, ESI, EDI, EBP and ESP
  10051. don't have an 8-bit representation }
  10052. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10053. ) and
  10054. {$endif i386}
  10055. (taicpu(hp1).oper[0]^.val=1) and
  10056. GetNextInstruction(hp1,hp2) and
  10057. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10058. GetNextInstruction(hp2,hp3) and
  10059. { skip align }
  10060. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10061. (hp3.typ=ait_label) and
  10062. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10063. (tai_label(hp3).labsym.getrefs=1) and
  10064. GetNextInstruction(hp3,hp4) and
  10065. MatchInstruction(hp4,A_MOV,[]) and
  10066. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10067. (taicpu(hp4).oper[0]^.val=0) and
  10068. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10069. GetNextInstruction(hp4,hp5) and
  10070. (hp5.typ=ait_label) and
  10071. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10072. (tai_label(hp5).labsym.getrefs=1) then
  10073. begin
  10074. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10075. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10076. { remove last label }
  10077. RemoveInstruction(hp5);
  10078. { remove second label }
  10079. RemoveInstruction(hp3);
  10080. { if align is present remove it }
  10081. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10082. RemoveInstruction(hp3);
  10083. { remove jmp }
  10084. RemoveInstruction(hp2);
  10085. if taicpu(hp1).opsize=S_B then
  10086. RemoveInstruction(hp1)
  10087. else
  10088. taicpu(hp1).loadconst(0,0);
  10089. taicpu(hp4).opcode:=A_SETcc;
  10090. taicpu(hp4).opsize:=S_B;
  10091. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10092. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10093. taicpu(hp4).opercnt:=1;
  10094. taicpu(hp4).ops:=1;
  10095. taicpu(hp4).freeop(1);
  10096. RemoveCurrentP(p);
  10097. Result:=true;
  10098. exit;
  10099. end
  10100. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10101. begin
  10102. { check for
  10103. jCC xxx
  10104. <several movs>
  10105. xxx:
  10106. Also spot:
  10107. Jcc xxx
  10108. <several movs>
  10109. jmp xxx
  10110. Change to:
  10111. <several cmovs with inverted condition>
  10112. jmp xxx
  10113. }
  10114. l:=0;
  10115. while assigned(hp1) and
  10116. CanBeCMOV(hp1) and
  10117. { stop on labels }
  10118. not(hp1.typ=ait_label) do
  10119. begin
  10120. inc(l);
  10121. hp5 := hp1;
  10122. GetNextInstruction(hp1,hp1);
  10123. end;
  10124. if assigned(hp1) then
  10125. begin
  10126. TransferUsedRegs(TmpUsedRegs);
  10127. if (
  10128. MatchInstruction(hp1, A_JMP, []) and
  10129. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10130. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10131. ) or
  10132. FindLabel(tasmlabel(symbol),hp1) then
  10133. begin
  10134. if (l<=4) and (l>0) then
  10135. begin
  10136. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10137. condition:=inverse_cond(taicpu(p).condition);
  10138. UpdateUsedRegs(tai(p.next));
  10139. GetNextInstruction(p,hp1);
  10140. repeat
  10141. if not Assigned(hp1) then
  10142. InternalError(2018062900);
  10143. taicpu(hp1).opcode:=A_CMOVcc;
  10144. taicpu(hp1).condition:=condition;
  10145. UpdateUsedRegs(tai(hp1.next));
  10146. GetNextInstruction(hp1,hp1);
  10147. until not(CanBeCMOV(hp1));
  10148. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10149. hp2 := hp1;
  10150. repeat
  10151. if not Assigned(hp2) then
  10152. InternalError(2018062910);
  10153. case hp2.typ of
  10154. ait_label:
  10155. { What we expected - break out of the loop (it won't be a dead label at the top of
  10156. a cluster because that was optimised at an earlier stage) }
  10157. Break;
  10158. ait_align:
  10159. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10160. begin
  10161. hp2 := tai(hp2.Next);
  10162. Continue;
  10163. end;
  10164. ait_instruction:
  10165. begin
  10166. if taicpu(hp2).opcode<>A_JMP then
  10167. InternalError(2018062912);
  10168. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10169. Break;
  10170. end
  10171. else
  10172. begin
  10173. { Might be a comment or temporary allocation entry }
  10174. if not (hp2.typ in SkipInstr) then
  10175. InternalError(2018062911);
  10176. hp2 := tai(hp2.Next);
  10177. Continue;
  10178. end;
  10179. end;
  10180. until False;
  10181. { Now we can safely decrement the reference count }
  10182. tasmlabel(symbol).decrefs;
  10183. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10184. { Remove the original jump }
  10185. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10186. if hp2.typ=ait_instruction then
  10187. begin
  10188. p:=hp2;
  10189. Result:=True;
  10190. end
  10191. else
  10192. begin
  10193. UpdateUsedRegs(tai(hp2.next));
  10194. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10195. { Remove the label if this is its final reference }
  10196. if (tasmlabel(symbol).getrefs=0) then
  10197. StripLabelFast(hp1);
  10198. end;
  10199. exit;
  10200. end;
  10201. end
  10202. else
  10203. begin
  10204. { check further for
  10205. jCC xxx
  10206. <several movs 1>
  10207. jmp yyy
  10208. xxx:
  10209. <several movs 2>
  10210. yyy:
  10211. }
  10212. { hp2 points to jmp yyy }
  10213. hp2:=hp1;
  10214. { skip hp1 to xxx (or an align right before it) }
  10215. GetNextInstruction(hp1, hp1);
  10216. if assigned(hp2) and
  10217. assigned(hp1) and
  10218. (l<=3) and
  10219. (hp2.typ=ait_instruction) and
  10220. (taicpu(hp2).is_jmp) and
  10221. (taicpu(hp2).condition=C_None) and
  10222. { real label and jump, no further references to the
  10223. label are allowed }
  10224. (tasmlabel(symbol).getrefs=1) and
  10225. FindLabel(tasmlabel(symbol),hp1) then
  10226. begin
  10227. l:=0;
  10228. { skip hp1 to <several moves 2> }
  10229. if (hp1.typ = ait_align) then
  10230. GetNextInstruction(hp1, hp1);
  10231. GetNextInstruction(hp1, hpmov2);
  10232. hp1 := hpmov2;
  10233. while assigned(hp1) and
  10234. CanBeCMOV(hp1) do
  10235. begin
  10236. inc(l);
  10237. hp5 := hp1;
  10238. GetNextInstruction(hp1, hp1);
  10239. end;
  10240. { hp1 points to yyy (or an align right before it) }
  10241. hp3 := hp1;
  10242. if assigned(hp1) and
  10243. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10244. begin
  10245. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10246. condition:=inverse_cond(taicpu(p).condition);
  10247. UpdateUsedRegs(tai(p.next));
  10248. GetNextInstruction(p,hp1);
  10249. repeat
  10250. taicpu(hp1).opcode:=A_CMOVcc;
  10251. taicpu(hp1).condition:=condition;
  10252. UpdateUsedRegs(tai(hp1.next));
  10253. GetNextInstruction(hp1,hp1);
  10254. until not(assigned(hp1)) or
  10255. not(CanBeCMOV(hp1));
  10256. condition:=inverse_cond(condition);
  10257. if GetLastInstruction(hpmov2,hp1) then
  10258. UpdateUsedRegs(tai(hp1.next));
  10259. hp1 := hpmov2;
  10260. { hp1 is now at <several movs 2> }
  10261. while Assigned(hp1) and CanBeCMOV(hp1) do
  10262. begin
  10263. taicpu(hp1).opcode:=A_CMOVcc;
  10264. taicpu(hp1).condition:=condition;
  10265. UpdateUsedRegs(tai(hp1.next));
  10266. GetNextInstruction(hp1,hp1);
  10267. end;
  10268. hp1 := p;
  10269. { Get first instruction after label }
  10270. UpdateUsedRegs(tai(hp3.next));
  10271. GetNextInstruction(hp3, p);
  10272. if assigned(p) and (hp3.typ = ait_align) then
  10273. GetNextInstruction(p, p);
  10274. { Don't dereference yet, as doing so will cause
  10275. GetNextInstruction to skip the label and
  10276. optional align marker. [Kit] }
  10277. GetNextInstruction(hp2, hp4);
  10278. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10279. { remove jCC }
  10280. RemoveInstruction(hp1);
  10281. { Now we can safely decrement it }
  10282. tasmlabel(symbol).decrefs;
  10283. { Remove label xxx (it will have a ref of zero due to the initial check }
  10284. StripLabelFast(hp4);
  10285. { remove jmp }
  10286. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10287. RemoveInstruction(hp2);
  10288. { As before, now we can safely decrement it }
  10289. tasmlabel(symbol).decrefs;
  10290. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10291. if tasmlabel(symbol).getrefs = 0 then
  10292. StripLabelFast(hp3);
  10293. if Assigned(p) then
  10294. result:=true;
  10295. exit;
  10296. end;
  10297. end;
  10298. end;
  10299. end;
  10300. {$endif i8086}
  10301. end;
  10302. end;
  10303. end;
  10304. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10305. var
  10306. hp1,hp2,hp3: tai;
  10307. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10308. NewSize: TOpSize;
  10309. NewRegSize: TSubRegister;
  10310. Limit: TCgInt;
  10311. SwapOper: POper;
  10312. begin
  10313. result:=false;
  10314. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10315. GetNextInstruction(p,hp1) and
  10316. (hp1.typ = ait_instruction);
  10317. if reg_and_hp1_is_instr and
  10318. (
  10319. (taicpu(hp1).opcode <> A_LEA) or
  10320. { If the LEA instruction can be converted into an arithmetic instruction,
  10321. it may be possible to then fold it. }
  10322. (
  10323. { If the flags register is in use, don't change the instruction
  10324. to an ADD otherwise this will scramble the flags. [Kit] }
  10325. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10326. ConvertLEA(taicpu(hp1))
  10327. )
  10328. ) and
  10329. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10330. GetNextInstruction(hp1,hp2) and
  10331. MatchInstruction(hp2,A_MOV,[]) and
  10332. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10333. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10334. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10335. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10336. {$ifdef i386}
  10337. { not all registers have byte size sub registers on i386 }
  10338. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10339. {$endif i386}
  10340. (((taicpu(hp1).ops=2) and
  10341. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10342. ((taicpu(hp1).ops=1) and
  10343. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10344. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10345. begin
  10346. { change movsX/movzX reg/ref, reg2
  10347. add/sub/or/... reg3/$const, reg2
  10348. mov reg2 reg/ref
  10349. to add/sub/or/... reg3/$const, reg/ref }
  10350. { by example:
  10351. movswl %si,%eax movswl %si,%eax p
  10352. decl %eax addl %edx,%eax hp1
  10353. movw %ax,%si movw %ax,%si hp2
  10354. ->
  10355. movswl %si,%eax movswl %si,%eax p
  10356. decw %eax addw %edx,%eax hp1
  10357. movw %ax,%si movw %ax,%si hp2
  10358. }
  10359. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10360. {
  10361. ->
  10362. movswl %si,%eax movswl %si,%eax p
  10363. decw %si addw %dx,%si hp1
  10364. movw %ax,%si movw %ax,%si hp2
  10365. }
  10366. case taicpu(hp1).ops of
  10367. 1:
  10368. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10369. 2:
  10370. begin
  10371. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10372. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10373. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10374. end;
  10375. else
  10376. internalerror(2008042702);
  10377. end;
  10378. {
  10379. ->
  10380. decw %si addw %dx,%si p
  10381. }
  10382. DebugMsg(SPeepholeOptimization + 'var3',p);
  10383. RemoveCurrentP(p, hp1);
  10384. RemoveInstruction(hp2);
  10385. Result := True;
  10386. Exit;
  10387. end;
  10388. if reg_and_hp1_is_instr and
  10389. (taicpu(hp1).opcode = A_MOV) and
  10390. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10391. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10392. {$ifdef x86_64}
  10393. { check for implicit extension to 64 bit }
  10394. or
  10395. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10396. (taicpu(hp1).opsize=S_Q) and
  10397. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10398. )
  10399. {$endif x86_64}
  10400. )
  10401. then
  10402. begin
  10403. { change
  10404. movx %reg1,%reg2
  10405. mov %reg2,%reg3
  10406. dealloc %reg2
  10407. into
  10408. movx %reg,%reg3
  10409. }
  10410. TransferUsedRegs(TmpUsedRegs);
  10411. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10412. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10413. begin
  10414. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10415. {$ifdef x86_64}
  10416. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10417. (taicpu(hp1).opsize=S_Q) then
  10418. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10419. else
  10420. {$endif x86_64}
  10421. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10422. RemoveInstruction(hp1);
  10423. Result := True;
  10424. Exit;
  10425. end;
  10426. end;
  10427. if reg_and_hp1_is_instr and
  10428. ((taicpu(hp1).opcode=A_MOV) or
  10429. (taicpu(hp1).opcode=A_ADD) or
  10430. (taicpu(hp1).opcode=A_SUB) or
  10431. (taicpu(hp1).opcode=A_CMP) or
  10432. (taicpu(hp1).opcode=A_OR) or
  10433. (taicpu(hp1).opcode=A_XOR) or
  10434. (taicpu(hp1).opcode=A_AND)
  10435. ) and
  10436. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10437. begin
  10438. AndTest := (taicpu(hp1).opcode=A_AND) and
  10439. GetNextInstruction(hp1, hp2) and
  10440. (hp2.typ = ait_instruction) and
  10441. (
  10442. (
  10443. (taicpu(hp2).opcode=A_TEST) and
  10444. (
  10445. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10446. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10447. (
  10448. { If the AND and TEST instructions share a constant, this is also valid }
  10449. (taicpu(hp1).oper[0]^.typ = top_const) and
  10450. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10451. )
  10452. ) and
  10453. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10454. ) or
  10455. (
  10456. (taicpu(hp2).opcode=A_CMP) and
  10457. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10458. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10459. )
  10460. );
  10461. { change
  10462. movx (oper),%reg2
  10463. and $x,%reg2
  10464. test %reg2,%reg2
  10465. dealloc %reg2
  10466. into
  10467. op %reg1,%reg3
  10468. if the second op accesses only the bits stored in reg1
  10469. }
  10470. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10471. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10472. (taicpu(hp1).oper[0]^.typ = top_const) and
  10473. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10474. AndTest then
  10475. begin
  10476. { Check if the AND constant is in range }
  10477. case taicpu(p).opsize of
  10478. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10479. begin
  10480. NewSize := S_B;
  10481. Limit := $FF;
  10482. end;
  10483. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10484. begin
  10485. NewSize := S_W;
  10486. Limit := $FFFF;
  10487. end;
  10488. {$ifdef x86_64}
  10489. S_LQ:
  10490. begin
  10491. NewSize := S_L;
  10492. Limit := $FFFFFFFF;
  10493. end;
  10494. {$endif x86_64}
  10495. else
  10496. InternalError(2021120303);
  10497. end;
  10498. if (
  10499. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10500. { Check for negative operands }
  10501. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10502. ) and
  10503. GetNextInstruction(hp2,hp3) and
  10504. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10505. (taicpu(hp3).condition in [C_E,C_NE]) then
  10506. begin
  10507. TransferUsedRegs(TmpUsedRegs);
  10508. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10509. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10510. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10511. begin
  10512. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10513. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10514. taicpu(hp1).opcode := A_TEST;
  10515. taicpu(hp1).opsize := NewSize;
  10516. RemoveInstruction(hp2);
  10517. RemoveCurrentP(p, hp1);
  10518. Result:=true;
  10519. exit;
  10520. end;
  10521. end;
  10522. end;
  10523. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10524. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10525. (taicpu(hp1).opsize=S_B)) or
  10526. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10527. (taicpu(hp1).opsize=S_W))
  10528. {$ifdef x86_64}
  10529. or ((taicpu(p).opsize=S_LQ) and
  10530. (taicpu(hp1).opsize=S_L))
  10531. {$endif x86_64}
  10532. ) and
  10533. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10534. begin
  10535. { change
  10536. movx %reg1,%reg2
  10537. op %reg2,%reg3
  10538. dealloc %reg2
  10539. into
  10540. op %reg1,%reg3
  10541. if the second op accesses only the bits stored in reg1
  10542. }
  10543. TransferUsedRegs(TmpUsedRegs);
  10544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10545. if AndTest then
  10546. begin
  10547. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10548. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10549. end
  10550. else
  10551. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10552. if not RegUsed then
  10553. begin
  10554. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10555. if taicpu(p).oper[0]^.typ=top_reg then
  10556. begin
  10557. case taicpu(hp1).opsize of
  10558. S_B:
  10559. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10560. S_W:
  10561. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10562. S_L:
  10563. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10564. else
  10565. Internalerror(2020102301);
  10566. end;
  10567. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10568. end
  10569. else
  10570. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10571. RemoveCurrentP(p);
  10572. if AndTest then
  10573. RemoveInstruction(hp2);
  10574. result:=true;
  10575. exit;
  10576. end;
  10577. end
  10578. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10579. (
  10580. { Bitwise operations only }
  10581. (taicpu(hp1).opcode=A_AND) or
  10582. (taicpu(hp1).opcode=A_TEST) or
  10583. (
  10584. (taicpu(hp1).oper[0]^.typ = top_const) and
  10585. (
  10586. (taicpu(hp1).opcode=A_OR) or
  10587. (taicpu(hp1).opcode=A_XOR)
  10588. )
  10589. )
  10590. ) and
  10591. (
  10592. (taicpu(hp1).oper[0]^.typ = top_const) or
  10593. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10594. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10595. ) then
  10596. begin
  10597. { change
  10598. movx %reg2,%reg2
  10599. op const,%reg2
  10600. into
  10601. op const,%reg2 (smaller version)
  10602. movx %reg2,%reg2
  10603. also change
  10604. movx %reg1,%reg2
  10605. and/test (oper),%reg2
  10606. dealloc %reg2
  10607. into
  10608. and/test (oper),%reg1
  10609. }
  10610. case taicpu(p).opsize of
  10611. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10612. begin
  10613. NewSize := S_B;
  10614. NewRegSize := R_SUBL;
  10615. Limit := $FF;
  10616. end;
  10617. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10618. begin
  10619. NewSize := S_W;
  10620. NewRegSize := R_SUBW;
  10621. Limit := $FFFF;
  10622. end;
  10623. {$ifdef x86_64}
  10624. S_LQ:
  10625. begin
  10626. NewSize := S_L;
  10627. NewRegSize := R_SUBD;
  10628. Limit := $FFFFFFFF;
  10629. end;
  10630. {$endif x86_64}
  10631. else
  10632. Internalerror(2021120302);
  10633. end;
  10634. TransferUsedRegs(TmpUsedRegs);
  10635. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10636. if AndTest then
  10637. begin
  10638. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10639. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10640. end
  10641. else
  10642. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10643. if
  10644. (
  10645. (taicpu(p).opcode = A_MOVZX) and
  10646. (
  10647. (taicpu(hp1).opcode=A_AND) or
  10648. (taicpu(hp1).opcode=A_TEST)
  10649. ) and
  10650. not (
  10651. { If both are references, then the final instruction will have
  10652. both operands as references, which is not allowed }
  10653. (taicpu(p).oper[0]^.typ = top_ref) and
  10654. (taicpu(hp1).oper[0]^.typ = top_ref)
  10655. ) and
  10656. not RegUsed
  10657. ) or
  10658. (
  10659. (
  10660. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10661. not RegUsed
  10662. ) and
  10663. (taicpu(p).oper[0]^.typ = top_reg) and
  10664. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10665. (taicpu(hp1).oper[0]^.typ = top_const) and
  10666. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10667. ) then
  10668. begin
  10669. {$if defined(i386) or defined(i8086)}
  10670. { If the target size is 8-bit, make sure we can actually encode it }
  10671. 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
  10672. Exit;
  10673. {$endif i386 or i8086}
  10674. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10675. taicpu(hp1).opsize := NewSize;
  10676. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10677. if AndTest then
  10678. begin
  10679. RemoveInstruction(hp2);
  10680. if not RegUsed then
  10681. begin
  10682. taicpu(hp1).opcode := A_TEST;
  10683. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10684. begin
  10685. { Make sure the reference is the second operand }
  10686. SwapOper := taicpu(hp1).oper[0];
  10687. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10688. taicpu(hp1).oper[1] := SwapOper;
  10689. end;
  10690. end;
  10691. end;
  10692. case taicpu(hp1).oper[0]^.typ of
  10693. top_reg:
  10694. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10695. top_const:
  10696. { For the AND/TEST case }
  10697. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10698. else
  10699. ;
  10700. end;
  10701. if RegUsed then
  10702. begin
  10703. AsmL.Remove(p);
  10704. AsmL.InsertAfter(p, hp1);
  10705. p := hp1;
  10706. end
  10707. else
  10708. RemoveCurrentP(p, hp1);
  10709. result:=true;
  10710. exit;
  10711. end;
  10712. end;
  10713. end;
  10714. if reg_and_hp1_is_instr and
  10715. (taicpu(p).oper[0]^.typ = top_reg) and
  10716. (
  10717. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10718. ) and
  10719. (taicpu(hp1).oper[0]^.typ = top_const) and
  10720. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10721. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10722. { Minimum shift value allowed is the bit difference between the sizes }
  10723. (taicpu(hp1).oper[0]^.val >=
  10724. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10725. 8 * (
  10726. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10727. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10728. )
  10729. ) then
  10730. begin
  10731. { For:
  10732. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10733. shl/sal ##, %reg1
  10734. Remove the movsx/movzx instruction if the shift overwrites the
  10735. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10736. }
  10737. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10738. RemoveCurrentP(p, hp1);
  10739. Result := True;
  10740. Exit;
  10741. end
  10742. else if reg_and_hp1_is_instr and
  10743. (taicpu(p).oper[0]^.typ = top_reg) and
  10744. (
  10745. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10746. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10747. ) and
  10748. (taicpu(hp1).oper[0]^.typ = top_const) and
  10749. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10750. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10751. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10752. (taicpu(hp1).oper[0]^.val <
  10753. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10754. 8 * (
  10755. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10756. )
  10757. ) then
  10758. begin
  10759. { For:
  10760. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10761. sar ##, %reg1 shr ##, %reg1
  10762. Move the shift to before the movx instruction if the shift value
  10763. is not too large.
  10764. }
  10765. asml.Remove(hp1);
  10766. asml.InsertBefore(hp1, p);
  10767. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10768. case taicpu(p).opsize of
  10769. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10770. taicpu(hp1).opsize := S_B;
  10771. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10772. taicpu(hp1).opsize := S_W;
  10773. {$ifdef x86_64}
  10774. S_LQ:
  10775. taicpu(hp1).opsize := S_L;
  10776. {$endif}
  10777. else
  10778. InternalError(2020112401);
  10779. end;
  10780. if (taicpu(hp1).opcode = A_SHR) then
  10781. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10782. else
  10783. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10784. Result := True;
  10785. end;
  10786. if reg_and_hp1_is_instr and
  10787. (taicpu(p).oper[0]^.typ = top_reg) and
  10788. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10789. (
  10790. (taicpu(hp1).opcode = taicpu(p).opcode)
  10791. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10792. {$ifdef x86_64}
  10793. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10794. {$endif x86_64}
  10795. ) then
  10796. begin
  10797. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10798. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10799. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10800. begin
  10801. {
  10802. For example:
  10803. movzbw %al,%ax
  10804. movzwl %ax,%eax
  10805. Compress into:
  10806. movzbl %al,%eax
  10807. }
  10808. RegUsed := False;
  10809. case taicpu(p).opsize of
  10810. S_BW:
  10811. case taicpu(hp1).opsize of
  10812. S_WL:
  10813. begin
  10814. taicpu(p).opsize := S_BL;
  10815. RegUsed := True;
  10816. end;
  10817. {$ifdef x86_64}
  10818. S_WQ:
  10819. begin
  10820. if taicpu(p).opcode = A_MOVZX then
  10821. begin
  10822. taicpu(p).opsize := S_BL;
  10823. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10824. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10825. end
  10826. else
  10827. taicpu(p).opsize := S_BQ;
  10828. RegUsed := True;
  10829. end;
  10830. {$endif x86_64}
  10831. else
  10832. ;
  10833. end;
  10834. {$ifdef x86_64}
  10835. S_BL:
  10836. case taicpu(hp1).opsize of
  10837. S_LQ:
  10838. begin
  10839. if taicpu(p).opcode = A_MOVZX then
  10840. begin
  10841. taicpu(p).opsize := S_BL;
  10842. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10843. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10844. end
  10845. else
  10846. taicpu(p).opsize := S_BQ;
  10847. RegUsed := True;
  10848. end;
  10849. else
  10850. ;
  10851. end;
  10852. S_WL:
  10853. case taicpu(hp1).opsize of
  10854. S_LQ:
  10855. begin
  10856. if taicpu(p).opcode = A_MOVZX then
  10857. begin
  10858. taicpu(p).opsize := S_WL;
  10859. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10860. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10861. end
  10862. else
  10863. taicpu(p).opsize := S_WQ;
  10864. RegUsed := True;
  10865. end;
  10866. else
  10867. ;
  10868. end;
  10869. {$endif x86_64}
  10870. else
  10871. ;
  10872. end;
  10873. if RegUsed then
  10874. begin
  10875. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10876. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10877. RemoveInstruction(hp1);
  10878. Result := True;
  10879. Exit;
  10880. end;
  10881. end;
  10882. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10883. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10884. GetNextInstruction(hp1, hp2) and
  10885. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10886. (
  10887. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10888. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10889. {$ifdef x86_64}
  10890. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10891. {$endif x86_64}
  10892. ) and
  10893. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10894. (
  10895. (
  10896. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10897. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10898. ) or
  10899. (
  10900. { Only allow the operands in reverse order for TEST instructions }
  10901. (taicpu(hp2).opcode = A_TEST) and
  10902. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10903. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10904. )
  10905. ) then
  10906. begin
  10907. {
  10908. For example:
  10909. movzbl %al,%eax
  10910. movzbl (ref),%edx
  10911. andl %edx,%eax
  10912. (%edx deallocated)
  10913. Change to:
  10914. andb (ref),%al
  10915. movzbl %al,%eax
  10916. Rules are:
  10917. - First two instructions have the same opcode and opsize
  10918. - First instruction's operands are the same super-register
  10919. - Second instruction operates on a different register
  10920. - Third instruction is AND, OR, XOR or TEST
  10921. - Third instruction's operands are the destination registers of the first two instructions
  10922. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10923. - Second instruction's destination register is deallocated afterwards
  10924. }
  10925. TransferUsedRegs(TmpUsedRegs);
  10926. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10927. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10928. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10929. begin
  10930. case taicpu(p).opsize of
  10931. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10932. NewSize := S_B;
  10933. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10934. NewSize := S_W;
  10935. {$ifdef x86_64}
  10936. S_LQ:
  10937. NewSize := S_L;
  10938. {$endif x86_64}
  10939. else
  10940. InternalError(2021120301);
  10941. end;
  10942. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10943. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10944. taicpu(hp2).opsize := NewSize;
  10945. RemoveInstruction(hp1);
  10946. { With TEST, it's best to keep the MOVX instruction at the top }
  10947. if (taicpu(hp2).opcode <> A_TEST) then
  10948. begin
  10949. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10950. asml.Remove(p);
  10951. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10952. asml.InsertAfter(p, hp2);
  10953. p := hp2;
  10954. end
  10955. else
  10956. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10957. Result := True;
  10958. Exit;
  10959. end;
  10960. end;
  10961. end;
  10962. if taicpu(p).opcode=A_MOVZX then
  10963. begin
  10964. { removes superfluous And's after movzx's }
  10965. if reg_and_hp1_is_instr and
  10966. (taicpu(hp1).opcode = A_AND) and
  10967. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10968. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10969. {$ifdef x86_64}
  10970. { check for implicit extension to 64 bit }
  10971. or
  10972. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10973. (taicpu(hp1).opsize=S_Q) and
  10974. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10975. )
  10976. {$endif x86_64}
  10977. )
  10978. then
  10979. begin
  10980. case taicpu(p).opsize Of
  10981. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10982. if (taicpu(hp1).oper[0]^.val = $ff) then
  10983. begin
  10984. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10985. RemoveInstruction(hp1);
  10986. Result:=true;
  10987. exit;
  10988. end;
  10989. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10990. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10991. begin
  10992. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10993. RemoveInstruction(hp1);
  10994. Result:=true;
  10995. exit;
  10996. end;
  10997. {$ifdef x86_64}
  10998. S_LQ:
  10999. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11000. begin
  11001. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11002. RemoveInstruction(hp1);
  11003. Result:=true;
  11004. exit;
  11005. end;
  11006. {$endif x86_64}
  11007. else
  11008. ;
  11009. end;
  11010. { we cannot get rid of the and, but can we get rid of the movz ?}
  11011. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11012. begin
  11013. case taicpu(p).opsize Of
  11014. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11015. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11016. begin
  11017. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11018. RemoveCurrentP(p,hp1);
  11019. Result:=true;
  11020. exit;
  11021. end;
  11022. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11023. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11024. begin
  11025. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11026. RemoveCurrentP(p,hp1);
  11027. Result:=true;
  11028. exit;
  11029. end;
  11030. {$ifdef x86_64}
  11031. S_LQ:
  11032. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11033. begin
  11034. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11035. RemoveCurrentP(p,hp1);
  11036. Result:=true;
  11037. exit;
  11038. end;
  11039. {$endif x86_64}
  11040. else
  11041. ;
  11042. end;
  11043. end;
  11044. end;
  11045. { changes some movzx constructs to faster synonyms (all examples
  11046. are given with eax/ax, but are also valid for other registers)}
  11047. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11048. begin
  11049. case taicpu(p).opsize of
  11050. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11051. (the machine code is equivalent to movzbl %al,%eax), but the
  11052. code generator still generates that assembler instruction and
  11053. it is silently converted. This should probably be checked.
  11054. [Kit] }
  11055. S_BW:
  11056. begin
  11057. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11058. (
  11059. not IsMOVZXAcceptable
  11060. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11061. or (
  11062. (cs_opt_size in current_settings.optimizerswitches) and
  11063. (taicpu(p).oper[1]^.reg = NR_AX)
  11064. )
  11065. ) then
  11066. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11067. begin
  11068. DebugMsg(SPeepholeOptimization + 'var7',p);
  11069. taicpu(p).opcode := A_AND;
  11070. taicpu(p).changeopsize(S_W);
  11071. taicpu(p).loadConst(0,$ff);
  11072. Result := True;
  11073. end
  11074. else if not IsMOVZXAcceptable and
  11075. GetNextInstruction(p, hp1) and
  11076. (tai(hp1).typ = ait_instruction) and
  11077. (taicpu(hp1).opcode = A_AND) and
  11078. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11079. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11080. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11081. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11082. begin
  11083. DebugMsg(SPeepholeOptimization + 'var8',p);
  11084. taicpu(p).opcode := A_MOV;
  11085. taicpu(p).changeopsize(S_W);
  11086. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11087. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11088. Result := True;
  11089. end;
  11090. end;
  11091. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11092. S_BL:
  11093. begin
  11094. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11095. (
  11096. not IsMOVZXAcceptable
  11097. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  11098. or (
  11099. (cs_opt_size in current_settings.optimizerswitches) and
  11100. (taicpu(p).oper[1]^.reg = NR_EAX)
  11101. )
  11102. ) then
  11103. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11104. begin
  11105. DebugMsg(SPeepholeOptimization + 'var9',p);
  11106. taicpu(p).opcode := A_AND;
  11107. taicpu(p).changeopsize(S_L);
  11108. taicpu(p).loadConst(0,$ff);
  11109. Result := True;
  11110. end
  11111. else if not IsMOVZXAcceptable and
  11112. GetNextInstruction(p, hp1) and
  11113. (tai(hp1).typ = ait_instruction) and
  11114. (taicpu(hp1).opcode = A_AND) and
  11115. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11116. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11117. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11118. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11119. begin
  11120. DebugMsg(SPeepholeOptimization + 'var10',p);
  11121. taicpu(p).opcode := A_MOV;
  11122. taicpu(p).changeopsize(S_L);
  11123. { do not use R_SUBWHOLE
  11124. as movl %rdx,%eax
  11125. is invalid in assembler PM }
  11126. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11127. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11128. Result := True;
  11129. end;
  11130. end;
  11131. {$endif i8086}
  11132. S_WL:
  11133. if not IsMOVZXAcceptable then
  11134. begin
  11135. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11136. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11137. begin
  11138. DebugMsg(SPeepholeOptimization + 'var11',p);
  11139. taicpu(p).opcode := A_AND;
  11140. taicpu(p).changeopsize(S_L);
  11141. taicpu(p).loadConst(0,$ffff);
  11142. Result := True;
  11143. end
  11144. else if GetNextInstruction(p, hp1) and
  11145. (tai(hp1).typ = ait_instruction) and
  11146. (taicpu(hp1).opcode = A_AND) and
  11147. (taicpu(hp1).oper[0]^.typ = top_const) and
  11148. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11149. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11150. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11151. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11152. begin
  11153. DebugMsg(SPeepholeOptimization + 'var12',p);
  11154. taicpu(p).opcode := A_MOV;
  11155. taicpu(p).changeopsize(S_L);
  11156. { do not use R_SUBWHOLE
  11157. as movl %rdx,%eax
  11158. is invalid in assembler PM }
  11159. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11160. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11161. Result := True;
  11162. end;
  11163. end;
  11164. else
  11165. InternalError(2017050705);
  11166. end;
  11167. end
  11168. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11169. begin
  11170. if GetNextInstruction(p, hp1) and
  11171. (tai(hp1).typ = ait_instruction) and
  11172. (taicpu(hp1).opcode = A_AND) and
  11173. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11174. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11175. begin
  11176. //taicpu(p).opcode := A_MOV;
  11177. case taicpu(p).opsize Of
  11178. S_BL:
  11179. begin
  11180. DebugMsg(SPeepholeOptimization + 'var13',p);
  11181. taicpu(hp1).changeopsize(S_L);
  11182. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11183. end;
  11184. S_WL:
  11185. begin
  11186. DebugMsg(SPeepholeOptimization + 'var14',p);
  11187. taicpu(hp1).changeopsize(S_L);
  11188. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11189. end;
  11190. S_BW:
  11191. begin
  11192. DebugMsg(SPeepholeOptimization + 'var15',p);
  11193. taicpu(hp1).changeopsize(S_W);
  11194. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11195. end;
  11196. else
  11197. Internalerror(2017050704)
  11198. end;
  11199. Result := True;
  11200. end;
  11201. end;
  11202. end;
  11203. end;
  11204. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11205. var
  11206. hp1, hp2 : tai;
  11207. MaskLength : Cardinal;
  11208. MaskedBits : TCgInt;
  11209. ActiveReg : TRegister;
  11210. begin
  11211. Result:=false;
  11212. { There are no optimisations for reference targets }
  11213. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11214. Exit;
  11215. while GetNextInstruction(p, hp1) and
  11216. (hp1.typ = ait_instruction) do
  11217. begin
  11218. if (taicpu(p).oper[0]^.typ = top_const) then
  11219. begin
  11220. case taicpu(hp1).opcode of
  11221. A_AND:
  11222. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11223. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11224. { the second register must contain the first one, so compare their subreg types }
  11225. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11226. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11227. { change
  11228. and const1, reg
  11229. and const2, reg
  11230. to
  11231. and (const1 and const2), reg
  11232. }
  11233. begin
  11234. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11235. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11236. RemoveCurrentP(p, hp1);
  11237. Result:=true;
  11238. exit;
  11239. end;
  11240. A_CMP:
  11241. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11242. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11243. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11244. { Just check that the condition on the next instruction is compatible }
  11245. GetNextInstruction(hp1, hp2) and
  11246. (hp2.typ = ait_instruction) and
  11247. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11248. then
  11249. { change
  11250. and 2^n, reg
  11251. cmp 2^n, reg
  11252. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11253. to
  11254. and 2^n, reg
  11255. test reg, reg
  11256. j(~c) / set(~c) / cmov(~c)
  11257. }
  11258. begin
  11259. { Keep TEST instruction in, rather than remove it, because
  11260. it may trigger other optimisations such as MovAndTest2Test }
  11261. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11262. taicpu(hp1).opcode := A_TEST;
  11263. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11264. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11265. Result := True;
  11266. Exit;
  11267. end;
  11268. A_MOVZX:
  11269. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11270. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11271. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11272. (
  11273. (
  11274. (taicpu(p).opsize=S_W) and
  11275. (taicpu(hp1).opsize=S_BW)
  11276. ) or
  11277. (
  11278. (taicpu(p).opsize=S_L) and
  11279. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11280. )
  11281. {$ifdef x86_64}
  11282. or
  11283. (
  11284. (taicpu(p).opsize=S_Q) and
  11285. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11286. )
  11287. {$endif x86_64}
  11288. ) then
  11289. begin
  11290. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11291. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11292. ) or
  11293. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11294. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11295. then
  11296. begin
  11297. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11298. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11299. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11300. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11301. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11302. }
  11303. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11304. RemoveInstruction(hp1);
  11305. { See if there are other optimisations possible }
  11306. Continue;
  11307. end;
  11308. end;
  11309. A_SHL:
  11310. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11311. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11312. begin
  11313. {$ifopt R+}
  11314. {$define RANGE_WAS_ON}
  11315. {$R-}
  11316. {$endif}
  11317. { get length of potential and mask }
  11318. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11319. { really a mask? }
  11320. {$ifdef RANGE_WAS_ON}
  11321. {$R+}
  11322. {$endif}
  11323. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11324. { unmasked part shifted out? }
  11325. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11326. begin
  11327. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11328. RemoveCurrentP(p, hp1);
  11329. Result:=true;
  11330. exit;
  11331. end;
  11332. end;
  11333. A_SHR:
  11334. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11335. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11336. (taicpu(hp1).oper[0]^.val <= 63) then
  11337. begin
  11338. { Does SHR combined with the AND cover all the bits?
  11339. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11340. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11341. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11342. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11343. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11344. begin
  11345. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11346. RemoveCurrentP(p, hp1);
  11347. Result := True;
  11348. Exit;
  11349. end;
  11350. end;
  11351. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11352. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11353. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11354. begin
  11355. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11356. (
  11357. (
  11358. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11359. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11360. ) or (
  11361. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11362. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11363. {$ifdef x86_64}
  11364. ) or (
  11365. (taicpu(hp1).opsize = S_LQ) and
  11366. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11367. {$endif x86_64}
  11368. )
  11369. ) then
  11370. begin
  11371. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11372. begin
  11373. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11374. RemoveInstruction(hp1);
  11375. { See if there are other optimisations possible }
  11376. Continue;
  11377. end;
  11378. { The super-registers are the same though.
  11379. Note that this change by itself doesn't improve
  11380. code speed, but it opens up other optimisations. }
  11381. {$ifdef x86_64}
  11382. { Convert 64-bit register to 32-bit }
  11383. case taicpu(hp1).opsize of
  11384. S_BQ:
  11385. begin
  11386. taicpu(hp1).opsize := S_BL;
  11387. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11388. end;
  11389. S_WQ:
  11390. begin
  11391. taicpu(hp1).opsize := S_WL;
  11392. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11393. end
  11394. else
  11395. ;
  11396. end;
  11397. {$endif x86_64}
  11398. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11399. taicpu(hp1).opcode := A_MOVZX;
  11400. { See if there are other optimisations possible }
  11401. Continue;
  11402. end;
  11403. end;
  11404. else
  11405. ;
  11406. end;
  11407. end
  11408. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11409. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11410. begin
  11411. {$ifdef x86_64}
  11412. if (taicpu(p).opsize = S_Q) then
  11413. begin
  11414. { Never necessary }
  11415. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11416. RemoveCurrentP(p, hp1);
  11417. Result := True;
  11418. Exit;
  11419. end;
  11420. {$endif x86_64}
  11421. { Forward check to determine necessity of and %reg,%reg }
  11422. TransferUsedRegs(TmpUsedRegs);
  11423. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11424. { Saves on a bunch of dereferences }
  11425. ActiveReg := taicpu(p).oper[1]^.reg;
  11426. case taicpu(hp1).opcode of
  11427. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11428. if (
  11429. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11430. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11431. ) and
  11432. (
  11433. (taicpu(hp1).opcode <> A_MOV) or
  11434. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11435. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11436. ) and
  11437. not (
  11438. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11439. (taicpu(hp1).opcode = A_MOV) and
  11440. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11441. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11442. ) and
  11443. (
  11444. (
  11445. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11446. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11447. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11448. ) or
  11449. (
  11450. {$ifdef x86_64}
  11451. (
  11452. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11453. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11454. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11455. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11456. ) and
  11457. {$endif x86_64}
  11458. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11459. )
  11460. ) then
  11461. begin
  11462. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11463. RemoveCurrentP(p, hp1);
  11464. Result := True;
  11465. Exit;
  11466. end;
  11467. A_ADD,
  11468. A_AND,
  11469. A_BSF,
  11470. A_BSR,
  11471. A_BTC,
  11472. A_BTR,
  11473. A_BTS,
  11474. A_OR,
  11475. A_SUB,
  11476. A_XOR:
  11477. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11478. if (
  11479. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11480. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11481. ) and
  11482. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11483. begin
  11484. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11485. RemoveCurrentP(p, hp1);
  11486. Result := True;
  11487. Exit;
  11488. end;
  11489. A_CMP,
  11490. A_TEST:
  11491. if (
  11492. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11493. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11494. ) and
  11495. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11496. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11497. begin
  11498. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11499. RemoveCurrentP(p, hp1);
  11500. Result := True;
  11501. Exit;
  11502. end;
  11503. A_BSWAP,
  11504. A_NEG,
  11505. A_NOT:
  11506. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11507. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11508. begin
  11509. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11510. RemoveCurrentP(p, hp1);
  11511. Result := True;
  11512. Exit;
  11513. end;
  11514. else
  11515. ;
  11516. end;
  11517. end;
  11518. if (taicpu(hp1).is_jmp) and
  11519. (taicpu(hp1).opcode<>A_JMP) and
  11520. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11521. begin
  11522. { change
  11523. and x, reg
  11524. jxx
  11525. to
  11526. test x, reg
  11527. jxx
  11528. if reg is deallocated before the
  11529. jump, but only if it's a conditional jump (PFV)
  11530. }
  11531. taicpu(p).opcode := A_TEST;
  11532. Exit;
  11533. end;
  11534. Break;
  11535. end;
  11536. { Lone AND tests }
  11537. if (taicpu(p).oper[0]^.typ = top_const) then
  11538. begin
  11539. {
  11540. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11541. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11542. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11543. }
  11544. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11545. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11546. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11547. begin
  11548. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11549. if taicpu(p).opsize = S_L then
  11550. begin
  11551. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11552. Result := True;
  11553. end;
  11554. end;
  11555. end;
  11556. { Backward check to determine necessity of and %reg,%reg }
  11557. if (taicpu(p).oper[0]^.typ = top_reg) and
  11558. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11559. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11560. GetLastInstruction(p, hp2) and
  11561. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11562. { Check size of adjacent instruction to determine if the AND is
  11563. effectively a null operation }
  11564. (
  11565. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11566. { Note: Don't include S_Q }
  11567. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11568. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11569. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11570. ) then
  11571. begin
  11572. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11573. { If GetNextInstruction returned False, hp1 will be nil }
  11574. RemoveCurrentP(p, hp1);
  11575. Result := True;
  11576. Exit;
  11577. end;
  11578. end;
  11579. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11580. var
  11581. hp1, hp2: tai;
  11582. NewRef: TReference;
  11583. Distance: Cardinal;
  11584. TempTracking: TAllUsedRegs;
  11585. { This entire nested function is used in an if-statement below, but we
  11586. want to avoid all the used reg transfers and GetNextInstruction calls
  11587. until we really have to check }
  11588. function MemRegisterNotUsedLater: Boolean; inline;
  11589. var
  11590. hp2: tai;
  11591. begin
  11592. TransferUsedRegs(TmpUsedRegs);
  11593. hp2 := p;
  11594. repeat
  11595. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11596. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11597. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11598. end;
  11599. begin
  11600. Result := False;
  11601. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11602. (taicpu(p).oper[1]^.typ = top_reg) then
  11603. begin
  11604. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11605. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11606. (hp1.typ <> ait_instruction) or
  11607. not
  11608. (
  11609. (cs_opt_level3 in current_settings.optimizerswitches) or
  11610. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11611. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11612. ) then
  11613. Exit;
  11614. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11615. addq $x, %rax
  11616. movq %rax, %rdx
  11617. sarq $63, %rdx
  11618. (%rax still in use)
  11619. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11620. leaq $x(%rax),%rdx
  11621. addq $x, %rax
  11622. sarq $63, %rdx
  11623. ...which is okay since it breaks the dependency chain between
  11624. addq and movq, but if OptPass2MOV is called first:
  11625. addq $x, %rax
  11626. cqto
  11627. ...which is better in all ways, taking only 2 cycles to execute
  11628. and much smaller in code size.
  11629. }
  11630. { The extra register tracking is quite strenuous }
  11631. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11632. MatchInstruction(hp1, A_MOV, []) then
  11633. begin
  11634. { Update the register tracking to the MOV instruction }
  11635. CopyUsedRegs(TempTracking);
  11636. hp2 := p;
  11637. repeat
  11638. UpdateUsedRegs(tai(hp2.Next));
  11639. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11640. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11641. OptPass2ADD get called again }
  11642. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11643. begin
  11644. { Reset the tracking to the current instruction }
  11645. RestoreUsedRegs(TempTracking);
  11646. ReleaseUsedRegs(TempTracking);
  11647. Result := True;
  11648. Exit;
  11649. end;
  11650. { Reset the tracking to the current instruction }
  11651. RestoreUsedRegs(TempTracking);
  11652. ReleaseUsedRegs(TempTracking);
  11653. { If OptPass2MOV returned True, we don't need to set Result to
  11654. True if hp1 didn't change because the ADD instruction didn't
  11655. get modified and we'll be evaluating hp1 again when the
  11656. peephole optimizer reaches it }
  11657. end;
  11658. { Change:
  11659. add %reg2,%reg1
  11660. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11661. To:
  11662. mov/s/z #(%reg1,%reg2),%reg1
  11663. }
  11664. if (taicpu(p).oper[0]^.typ = top_reg) and
  11665. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11666. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11667. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11668. (
  11669. (
  11670. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11671. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11672. { r/esp cannot be an index }
  11673. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11674. ) or (
  11675. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11676. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11677. )
  11678. ) and (
  11679. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11680. (
  11681. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11682. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11683. MemRegisterNotUsedLater
  11684. )
  11685. ) then
  11686. begin
  11687. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  11688. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11689. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11690. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11691. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11692. { hp1 may not be the immediate next instruction under -O3 }
  11693. RemoveCurrentp(p)
  11694. else
  11695. RemoveCurrentp(p, hp1);
  11696. Result := True;
  11697. Exit;
  11698. end;
  11699. { Change:
  11700. addl/q $x,%reg1
  11701. movl/q %reg1,%reg2
  11702. To:
  11703. leal/q $x(%reg1),%reg2
  11704. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11705. Breaks the dependency chain.
  11706. }
  11707. if (taicpu(p).oper[0]^.typ = top_const) and
  11708. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11709. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11710. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11711. (
  11712. { Instructions are guaranteed to be adjacent on -O2 and under }
  11713. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11714. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11715. ) then
  11716. begin
  11717. TransferUsedRegs(TmpUsedRegs);
  11718. hp2 := p;
  11719. repeat
  11720. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11721. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11722. if (
  11723. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11724. not (cs_opt_size in current_settings.optimizerswitches) or
  11725. (
  11726. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11727. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11728. )
  11729. ) then
  11730. begin
  11731. { Change the MOV instruction to a LEA instruction, and update the
  11732. first operand }
  11733. reference_reset(NewRef, 1, []);
  11734. NewRef.base := taicpu(p).oper[1]^.reg;
  11735. NewRef.scalefactor := 1;
  11736. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11737. taicpu(hp1).opcode := A_LEA;
  11738. taicpu(hp1).loadref(0, NewRef);
  11739. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11740. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11741. begin
  11742. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11743. { Move what is now the LEA instruction to before the ADD instruction }
  11744. Asml.Remove(hp1);
  11745. Asml.InsertBefore(hp1, p);
  11746. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11747. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11748. p := hp1;
  11749. end
  11750. else
  11751. begin
  11752. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11753. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  11754. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11755. { hp1 may not be the immediate next instruction under -O3 }
  11756. RemoveCurrentp(p)
  11757. else
  11758. RemoveCurrentp(p, hp1);
  11759. end;
  11760. Result := True;
  11761. end;
  11762. end;
  11763. end;
  11764. end;
  11765. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11766. var
  11767. SubReg: TSubRegister;
  11768. begin
  11769. Result:=false;
  11770. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11771. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11772. with taicpu(p).oper[0]^.ref^ do
  11773. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11774. begin
  11775. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11776. begin
  11777. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11778. taicpu(p).opcode := A_ADD;
  11779. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11780. Result := True;
  11781. end
  11782. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11783. begin
  11784. if (base <> NR_NO) then
  11785. begin
  11786. if (scalefactor <= 1) then
  11787. begin
  11788. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11789. taicpu(p).opcode := A_ADD;
  11790. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11791. Result := True;
  11792. end;
  11793. end
  11794. else
  11795. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11796. if (scalefactor in [2, 4, 8]) then
  11797. begin
  11798. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11799. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11800. taicpu(p).opcode := A_SHL;
  11801. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11802. Result := True;
  11803. end;
  11804. end;
  11805. end;
  11806. end;
  11807. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11808. var
  11809. hp1, hp2: tai;
  11810. NewRef: TReference;
  11811. Distance: Cardinal;
  11812. TempTracking: TAllUsedRegs;
  11813. begin
  11814. Result := False;
  11815. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11816. MatchOpType(taicpu(p),top_const,top_reg) then
  11817. begin
  11818. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11819. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11820. (hp1.typ <> ait_instruction) or
  11821. not
  11822. (
  11823. (cs_opt_level3 in current_settings.optimizerswitches) or
  11824. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11825. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11826. ) then
  11827. Exit;
  11828. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11829. subq $x, %rax
  11830. movq %rax, %rdx
  11831. sarq $63, %rdx
  11832. (%rax still in use)
  11833. ...letting OptPass2SUB run its course (and without -Os) will produce:
  11834. leaq $-x(%rax),%rdx
  11835. movq $x, %rax
  11836. sarq $63, %rdx
  11837. ...which is okay since it breaks the dependency chain between
  11838. subq and movq, but if OptPass2MOV is called first:
  11839. subq $x, %rax
  11840. cqto
  11841. ...which is better in all ways, taking only 2 cycles to execute
  11842. and much smaller in code size.
  11843. }
  11844. { The extra register tracking is quite strenuous }
  11845. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11846. MatchInstruction(hp1, A_MOV, []) then
  11847. begin
  11848. { Update the register tracking to the MOV instruction }
  11849. CopyUsedRegs(TempTracking);
  11850. hp2 := p;
  11851. repeat
  11852. UpdateUsedRegs(tai(hp2.Next));
  11853. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11854. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11855. OptPass2SUB get called again }
  11856. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11857. begin
  11858. { Reset the tracking to the current instruction }
  11859. RestoreUsedRegs(TempTracking);
  11860. ReleaseUsedRegs(TempTracking);
  11861. Result := True;
  11862. Exit;
  11863. end;
  11864. { Reset the tracking to the current instruction }
  11865. RestoreUsedRegs(TempTracking);
  11866. ReleaseUsedRegs(TempTracking);
  11867. { If OptPass2MOV returned True, we don't need to set Result to
  11868. True if hp1 didn't change because the SUB instruction didn't
  11869. get modified and we'll be evaluating hp1 again when the
  11870. peephole optimizer reaches it }
  11871. end;
  11872. { Change:
  11873. subl/q $x,%reg1
  11874. movl/q %reg1,%reg2
  11875. To:
  11876. leal/q $-x(%reg1),%reg2
  11877. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11878. Breaks the dependency chain and potentially permits the removal of
  11879. a CMP instruction if one follows.
  11880. }
  11881. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11882. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11883. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11884. (
  11885. { Instructions are guaranteed to be adjacent on -O2 and under }
  11886. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11887. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11888. ) then
  11889. begin
  11890. TransferUsedRegs(TmpUsedRegs);
  11891. hp2 := p;
  11892. repeat
  11893. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11894. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11895. if (
  11896. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11897. not (cs_opt_size in current_settings.optimizerswitches) or
  11898. (
  11899. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11900. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11901. )
  11902. ) then
  11903. begin
  11904. { Change the MOV instruction to a LEA instruction, and update the
  11905. first operand }
  11906. reference_reset(NewRef, 1, []);
  11907. NewRef.base := taicpu(p).oper[1]^.reg;
  11908. NewRef.scalefactor := 1;
  11909. NewRef.offset := -taicpu(p).oper[0]^.val;
  11910. taicpu(hp1).opcode := A_LEA;
  11911. taicpu(hp1).loadref(0, NewRef);
  11912. TransferUsedRegs(TmpUsedRegs);
  11913. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11914. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11915. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11916. begin
  11917. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11918. { Move what is now the LEA instruction to before the SUB instruction }
  11919. Asml.Remove(hp1);
  11920. Asml.InsertBefore(hp1, p);
  11921. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11922. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11923. p := hp1;
  11924. end
  11925. else
  11926. begin
  11927. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11928. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  11929. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11930. { hp1 may not be the immediate next instruction under -O3 }
  11931. RemoveCurrentp(p)
  11932. else
  11933. RemoveCurrentp(p, hp1);
  11934. end;
  11935. Result := True;
  11936. end;
  11937. end;
  11938. end;
  11939. end;
  11940. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11941. begin
  11942. { we can skip all instructions not messing with the stack pointer }
  11943. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11944. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11945. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11946. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11947. ({(taicpu(hp1).ops=0) or }
  11948. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11949. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11950. ) and }
  11951. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11952. )
  11953. ) do
  11954. GetNextInstruction(hp1,hp1);
  11955. Result:=assigned(hp1);
  11956. end;
  11957. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11958. var
  11959. hp1, hp2, hp3, hp4, hp5: tai;
  11960. begin
  11961. Result:=false;
  11962. hp5:=nil;
  11963. { replace
  11964. leal(q) x(<stackpointer>),<stackpointer>
  11965. call procname
  11966. leal(q) -x(<stackpointer>),<stackpointer>
  11967. ret
  11968. by
  11969. jmp procname
  11970. but do it only on level 4 because it destroys stack back traces
  11971. }
  11972. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11973. MatchOpType(taicpu(p),top_ref,top_reg) and
  11974. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11975. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11976. { the -8 or -24 are not required, but bail out early if possible,
  11977. higher values are unlikely }
  11978. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11979. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11980. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11981. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11982. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11983. GetNextInstruction(p, hp1) and
  11984. { Take a copy of hp1 }
  11985. SetAndTest(hp1, hp4) and
  11986. { trick to skip label }
  11987. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11988. SkipSimpleInstructions(hp1) and
  11989. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11990. GetNextInstruction(hp1, hp2) and
  11991. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11992. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11993. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11994. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11995. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11996. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11997. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11998. { Segment register will be NR_NO }
  11999. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12000. GetNextInstruction(hp2, hp3) and
  12001. { trick to skip label }
  12002. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12003. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12004. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12005. SetAndTest(hp3,hp5) and
  12006. GetNextInstruction(hp3,hp3) and
  12007. MatchInstruction(hp3,A_RET,[S_NO])
  12008. )
  12009. ) and
  12010. (taicpu(hp3).ops=0) then
  12011. begin
  12012. taicpu(hp1).opcode := A_JMP;
  12013. taicpu(hp1).is_jmp := true;
  12014. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12015. RemoveCurrentP(p, hp4);
  12016. RemoveInstruction(hp2);
  12017. RemoveInstruction(hp3);
  12018. if Assigned(hp5) then
  12019. begin
  12020. AsmL.Remove(hp5);
  12021. ASmL.InsertBefore(hp5,hp1)
  12022. end;
  12023. Result:=true;
  12024. end;
  12025. end;
  12026. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12027. {$ifdef x86_64}
  12028. var
  12029. hp1, hp2, hp3, hp4, hp5: tai;
  12030. {$endif x86_64}
  12031. begin
  12032. Result:=false;
  12033. {$ifdef x86_64}
  12034. hp5:=nil;
  12035. { replace
  12036. push %rax
  12037. call procname
  12038. pop %rcx
  12039. ret
  12040. by
  12041. jmp procname
  12042. but do it only on level 4 because it destroys stack back traces
  12043. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12044. for all supported calling conventions
  12045. }
  12046. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12047. MatchOpType(taicpu(p),top_reg) and
  12048. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12049. GetNextInstruction(p, hp1) and
  12050. { Take a copy of hp1 }
  12051. SetAndTest(hp1, hp4) and
  12052. { trick to skip label }
  12053. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12054. SkipSimpleInstructions(hp1) and
  12055. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12056. GetNextInstruction(hp1, hp2) and
  12057. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12058. MatchOpType(taicpu(hp2),top_reg) and
  12059. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12060. GetNextInstruction(hp2, hp3) and
  12061. { trick to skip label }
  12062. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12063. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12064. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12065. SetAndTest(hp3,hp5) and
  12066. GetNextInstruction(hp3,hp3) and
  12067. MatchInstruction(hp3,A_RET,[S_NO])
  12068. )
  12069. ) and
  12070. (taicpu(hp3).ops=0) then
  12071. begin
  12072. taicpu(hp1).opcode := A_JMP;
  12073. taicpu(hp1).is_jmp := true;
  12074. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12075. RemoveCurrentP(p, hp4);
  12076. RemoveInstruction(hp2);
  12077. RemoveInstruction(hp3);
  12078. if Assigned(hp5) then
  12079. begin
  12080. AsmL.Remove(hp5);
  12081. ASmL.InsertBefore(hp5,hp1)
  12082. end;
  12083. Result:=true;
  12084. end;
  12085. {$endif x86_64}
  12086. end;
  12087. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12088. var
  12089. Value, RegName: string;
  12090. begin
  12091. Result:=false;
  12092. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12093. begin
  12094. case taicpu(p).oper[0]^.val of
  12095. 0:
  12096. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12097. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12098. begin
  12099. { change "mov $0,%reg" into "xor %reg,%reg" }
  12100. taicpu(p).opcode := A_XOR;
  12101. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12102. Result := True;
  12103. {$ifdef x86_64}
  12104. end
  12105. else if (taicpu(p).opsize = S_Q) then
  12106. begin
  12107. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12108. { The actual optimization }
  12109. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12110. taicpu(p).changeopsize(S_L);
  12111. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12112. Result := True;
  12113. end;
  12114. $1..$FFFFFFFF:
  12115. begin
  12116. { Code size reduction by J. Gareth "Kit" Moreton }
  12117. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12118. case taicpu(p).opsize of
  12119. S_Q:
  12120. begin
  12121. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12122. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12123. { The actual optimization }
  12124. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12125. taicpu(p).changeopsize(S_L);
  12126. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12127. Result := True;
  12128. end;
  12129. else
  12130. { Do nothing };
  12131. end;
  12132. {$endif x86_64}
  12133. end;
  12134. -1:
  12135. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12136. if (cs_opt_size in current_settings.optimizerswitches) and
  12137. (taicpu(p).opsize <> S_B) and
  12138. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12139. begin
  12140. { change "mov $-1,%reg" into "or $-1,%reg" }
  12141. { NOTES:
  12142. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12143. - This operation creates a false dependency on the register, so only do it when optimising for size
  12144. - 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
  12145. }
  12146. taicpu(p).opcode := A_OR;
  12147. Result := True;
  12148. end;
  12149. else
  12150. { Do nothing };
  12151. end;
  12152. end;
  12153. end;
  12154. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12155. var
  12156. hp1: tai;
  12157. begin
  12158. { Detect:
  12159. andw x, %ax (0 <= x < $8000)
  12160. ...
  12161. movzwl %ax,%eax
  12162. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12163. }
  12164. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  12165. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12166. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12167. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12168. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12169. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12170. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12171. begin
  12172. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12173. taicpu(hp1).opcode := A_CWDE;
  12174. taicpu(hp1).clearop(0);
  12175. taicpu(hp1).clearop(1);
  12176. taicpu(hp1).ops := 0;
  12177. { A change was made, but not with p, so move forward 1 }
  12178. p := tai(p.Next);
  12179. Result := True;
  12180. end;
  12181. end;
  12182. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12183. begin
  12184. Result := False;
  12185. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12186. Exit;
  12187. { Convert:
  12188. movswl %ax,%eax -> cwtl
  12189. movslq %eax,%rax -> cdqe
  12190. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12191. refer to the same opcode and depends only on the assembler's
  12192. current operand-size attribute. [Kit]
  12193. }
  12194. with taicpu(p) do
  12195. case opsize of
  12196. S_WL:
  12197. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12198. begin
  12199. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12200. opcode := A_CWDE;
  12201. clearop(0);
  12202. clearop(1);
  12203. ops := 0;
  12204. Result := True;
  12205. end;
  12206. {$ifdef x86_64}
  12207. S_LQ:
  12208. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12209. begin
  12210. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12211. opcode := A_CDQE;
  12212. clearop(0);
  12213. clearop(1);
  12214. ops := 0;
  12215. Result := True;
  12216. end;
  12217. {$endif x86_64}
  12218. else
  12219. ;
  12220. end;
  12221. end;
  12222. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12223. var
  12224. hp1, hp2: tai;
  12225. IdentityMask, Shift: TCGInt;
  12226. LimitSize: Topsize;
  12227. DoNotMerge: Boolean;
  12228. begin
  12229. Result := False;
  12230. { All these optimisations work on "shr const,%reg" }
  12231. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12232. Exit;
  12233. DoNotMerge := False;
  12234. Shift := taicpu(p).oper[0]^.val;
  12235. LimitSize := taicpu(p).opsize;
  12236. hp1 := p;
  12237. repeat
  12238. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12239. Break;
  12240. { Detect:
  12241. shr x, %reg
  12242. and y, %reg
  12243. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12244. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12245. }
  12246. case taicpu(hp1).opcode of
  12247. A_AND:
  12248. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12249. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12250. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12251. begin
  12252. { Make sure the FLAGS register isn't in use }
  12253. TransferUsedRegs(TmpUsedRegs);
  12254. hp2 := p;
  12255. repeat
  12256. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12257. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12258. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12259. begin
  12260. { Generate the identity mask }
  12261. case taicpu(p).opsize of
  12262. S_B:
  12263. IdentityMask := $FF shr Shift;
  12264. S_W:
  12265. IdentityMask := $FFFF shr Shift;
  12266. S_L:
  12267. IdentityMask := $FFFFFFFF shr Shift;
  12268. {$ifdef x86_64}
  12269. S_Q:
  12270. { We need to force the operands to be unsigned 64-bit
  12271. integers otherwise the wrong value is generated }
  12272. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12273. {$endif x86_64}
  12274. else
  12275. InternalError(2022081501);
  12276. end;
  12277. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12278. begin
  12279. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12280. { All the possible 1 bits are covered, so we can remove the AND }
  12281. hp2 := tai(hp1.Previous);
  12282. RemoveInstruction(hp1);
  12283. { p wasn't actually changed, so don't set Result to True,
  12284. but a change was nonetheless made elsewhere }
  12285. Include(OptsToCheck, aoc_ForceNewIteration);
  12286. { Do another pass in case other AND or MOVZX instructions
  12287. follow }
  12288. hp1 := hp2;
  12289. Continue;
  12290. end;
  12291. end;
  12292. end;
  12293. A_TEST, A_CMP, A_Jcc:
  12294. { Skip over conditional jumps and relevant comparisons }
  12295. Continue;
  12296. A_MOVZX:
  12297. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12298. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12299. begin
  12300. { Since the original register is being read as is, subsequent
  12301. SHRs must not be merged at this point }
  12302. DoNotMerge := True;
  12303. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12304. begin
  12305. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12306. begin
  12307. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12308. { All the possible 1 bits are covered, so we can remove the AND }
  12309. hp2 := tai(hp1.Previous);
  12310. RemoveInstruction(hp1);
  12311. hp1 := hp2;
  12312. end
  12313. else { Different register target }
  12314. begin
  12315. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12316. taicpu(hp1).opcode := A_MOV;
  12317. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12318. case taicpu(hp1).opsize of
  12319. S_BW:
  12320. taicpu(hp1).opsize := S_W;
  12321. S_BL, S_WL:
  12322. taicpu(hp1).opsize := S_L;
  12323. else
  12324. InternalError(2022081503);
  12325. end;
  12326. end;
  12327. end
  12328. else if (Shift > 0) and
  12329. (taicpu(p).opsize = S_W) and
  12330. (taicpu(hp1).opsize = S_WL) and
  12331. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12332. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12333. begin
  12334. { Detect:
  12335. shr x, %ax (x > 0)
  12336. ...
  12337. movzwl %ax,%eax
  12338. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12339. }
  12340. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12341. taicpu(hp1).opcode := A_CWDE;
  12342. taicpu(hp1).clearop(0);
  12343. taicpu(hp1).clearop(1);
  12344. taicpu(hp1).ops := 0;
  12345. end;
  12346. { Move onto the next instruction }
  12347. Continue;
  12348. end;
  12349. A_SHL, A_SAL, A_SHR:
  12350. if (taicpu(hp1).opsize <= LimitSize) and
  12351. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12352. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12353. begin
  12354. { Make sure the sizes don't exceed the register size limit
  12355. (measured by the shift value falling below the limit) }
  12356. if taicpu(hp1).opsize < LimitSize then
  12357. LimitSize := taicpu(hp1).opsize;
  12358. if taicpu(hp1).opcode = A_SHR then
  12359. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12360. else
  12361. begin
  12362. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12363. DoNotMerge := True;
  12364. end;
  12365. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12366. Break;
  12367. { Since we've established that the combined shift is within
  12368. limits, we can actually combine the adjacent SHR
  12369. instructions even if they're different sizes }
  12370. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12371. begin
  12372. hp2 := tai(hp1.Previous);
  12373. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12374. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12375. RemoveInstruction(hp1);
  12376. hp1 := hp2;
  12377. end;
  12378. { Move onto the next instruction }
  12379. Continue;
  12380. end;
  12381. else
  12382. ;
  12383. end;
  12384. Break;
  12385. until False;
  12386. { Detect the following (looking backwards):
  12387. shr %cl,%reg
  12388. shr x, %reg
  12389. Swap the two SHR instructions to minimise a pipeline stall.
  12390. }
  12391. if GetLastInstruction(p, hp1) and
  12392. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12393. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12394. { First operand will be %cl }
  12395. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12396. { Just to be sure }
  12397. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12398. begin
  12399. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12400. { Moving the entries this way ensures the register tracking remains correct }
  12401. Asml.Remove(p);
  12402. Asml.InsertBefore(p, hp1);
  12403. p := hp1;
  12404. { Don't set Result to True because the current instruction is now
  12405. "shr %cl,%reg" and there's nothing more we can do with it }
  12406. end;
  12407. end;
  12408. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12409. var
  12410. hp1, hp2: tai;
  12411. Opposite, SecondOpposite: TAsmOp;
  12412. NewCond: TAsmCond;
  12413. begin
  12414. Result := False;
  12415. { Change:
  12416. add/sub 128,(dest)
  12417. To:
  12418. sub/add -128,(dest)
  12419. This generaally takes fewer bytes to encode because -128 can be stored
  12420. in a signed byte, whereas +128 cannot.
  12421. }
  12422. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12423. begin
  12424. if taicpu(p).opcode = A_ADD then
  12425. Opposite := A_SUB
  12426. else
  12427. Opposite := A_ADD;
  12428. { Be careful if the flags are in use, because the CF flag inverts
  12429. when changing from ADD to SUB and vice versa }
  12430. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12431. GetNextInstruction(p, hp1) then
  12432. begin
  12433. TransferUsedRegs(TmpUsedRegs);
  12434. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12435. hp2 := hp1;
  12436. { Scan ahead to check if everything's safe }
  12437. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12438. begin
  12439. if (hp1.typ <> ait_instruction) then
  12440. { Probably unsafe since the flags are still in use }
  12441. Exit;
  12442. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12443. { Stop searching at an unconditional jump }
  12444. Break;
  12445. if not
  12446. (
  12447. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12448. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12449. ) and
  12450. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12451. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12452. Exit;
  12453. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12454. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12455. { Move to the next instruction }
  12456. GetNextInstruction(hp1, hp1);
  12457. end;
  12458. while Assigned(hp2) and (hp2 <> hp1) do
  12459. begin
  12460. NewCond := C_None;
  12461. case taicpu(hp2).condition of
  12462. C_A, C_NBE:
  12463. NewCond := C_BE;
  12464. C_B, C_C, C_NAE:
  12465. NewCond := C_AE;
  12466. C_AE, C_NB, C_NC:
  12467. NewCond := C_B;
  12468. C_BE, C_NA:
  12469. NewCond := C_A;
  12470. else
  12471. { No change needed };
  12472. end;
  12473. if NewCond <> C_None then
  12474. begin
  12475. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12476. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12477. taicpu(hp2).condition := NewCond;
  12478. end
  12479. else
  12480. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12481. begin
  12482. { Because of the flipping of the carry bit, to ensure
  12483. the operation remains equivalent, ADC becomes SBB
  12484. and vice versa, and the constant is not-inverted.
  12485. If multiple ADCs or SBBs appear in a row, each one
  12486. changed causes the carry bit to invert, so they all
  12487. need to be flipped }
  12488. if taicpu(hp2).opcode = A_ADC then
  12489. SecondOpposite := A_SBB
  12490. else
  12491. SecondOpposite := A_ADC;
  12492. if taicpu(hp2).oper[0]^.typ <> top_const then
  12493. { Should have broken out of this optimisation already }
  12494. InternalError(2021112901);
  12495. 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]^) + ' -> ' +
  12496. 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);
  12497. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12498. taicpu(hp2).opcode := SecondOpposite;
  12499. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12500. end;
  12501. { Move to the next instruction }
  12502. GetNextInstruction(hp2, hp2);
  12503. end;
  12504. if (hp2 <> hp1) then
  12505. InternalError(2021111501);
  12506. end;
  12507. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12508. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12509. taicpu(p).opcode := Opposite;
  12510. taicpu(p).oper[0]^.val := -128;
  12511. { No further optimisations can be made on this instruction, so move
  12512. onto the next one to save time }
  12513. p := tai(p.Next);
  12514. UpdateUsedRegs(p);
  12515. Result := True;
  12516. Exit;
  12517. end;
  12518. { Detect:
  12519. add/sub %reg2,(dest)
  12520. add/sub x, (dest)
  12521. (dest can be a register or a reference)
  12522. Swap the instructions to minimise a pipeline stall. This reverses the
  12523. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12524. optimisations could be made.
  12525. }
  12526. if (taicpu(p).oper[0]^.typ = top_reg) and
  12527. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12528. (
  12529. (
  12530. (taicpu(p).oper[1]^.typ = top_reg) and
  12531. { We can try searching further ahead if we're writing to a register }
  12532. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12533. ) or
  12534. (
  12535. (taicpu(p).oper[1]^.typ = top_ref) and
  12536. GetNextInstruction(p, hp1)
  12537. )
  12538. ) and
  12539. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12540. (taicpu(hp1).oper[0]^.typ = top_const) and
  12541. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12542. begin
  12543. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12544. TransferUsedRegs(TmpUsedRegs);
  12545. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12546. hp2 := p;
  12547. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  12548. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  12549. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  12550. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12551. begin
  12552. asml.remove(hp1);
  12553. asml.InsertBefore(hp1, p);
  12554. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  12555. Result := True;
  12556. end;
  12557. end;
  12558. end;
  12559. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  12560. begin
  12561. Result:=false;
  12562. { change "cmp $0, %reg" to "test %reg, %reg" }
  12563. if MatchOpType(taicpu(p),top_const,top_reg) and
  12564. (taicpu(p).oper[0]^.val = 0) then
  12565. begin
  12566. taicpu(p).opcode := A_TEST;
  12567. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  12568. Result:=true;
  12569. end;
  12570. end;
  12571. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  12572. var
  12573. IsTestConstX : Boolean;
  12574. hp1,hp2 : tai;
  12575. begin
  12576. Result:=false;
  12577. { removes the line marked with (x) from the sequence
  12578. and/or/xor/add/sub/... $x, %y
  12579. test/or %y, %y | test $-1, %y (x)
  12580. j(n)z _Label
  12581. as the first instruction already adjusts the ZF
  12582. %y operand may also be a reference }
  12583. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  12584. MatchOperand(taicpu(p).oper[0]^,-1);
  12585. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  12586. GetLastInstruction(p, hp1) and
  12587. (tai(hp1).typ = ait_instruction) and
  12588. GetNextInstruction(p,hp2) and
  12589. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  12590. case taicpu(hp1).opcode Of
  12591. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  12592. { These two instructions set the zero flag if the result is zero }
  12593. A_POPCNT, A_LZCNT:
  12594. begin
  12595. if (
  12596. { With POPCNT, an input of zero will set the zero flag
  12597. because the population count of zero is zero }
  12598. (taicpu(hp1).opcode = A_POPCNT) and
  12599. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  12600. (
  12601. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  12602. { Faster than going through the second half of the 'or'
  12603. condition below }
  12604. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  12605. )
  12606. ) or (
  12607. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  12608. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12609. { and in case of carry for A(E)/B(E)/C/NC }
  12610. (
  12611. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  12612. (
  12613. (taicpu(hp1).opcode <> A_ADD) and
  12614. (taicpu(hp1).opcode <> A_SUB) and
  12615. (taicpu(hp1).opcode <> A_LZCNT)
  12616. )
  12617. )
  12618. ) then
  12619. begin
  12620. RemoveCurrentP(p, hp2);
  12621. Result:=true;
  12622. Exit;
  12623. end;
  12624. end;
  12625. A_SHL, A_SAL, A_SHR, A_SAR:
  12626. begin
  12627. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  12628. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  12629. { therefore, it's only safe to do this optimization for }
  12630. { shifts by a (nonzero) constant }
  12631. (taicpu(hp1).oper[0]^.typ = top_const) and
  12632. (taicpu(hp1).oper[0]^.val <> 0) and
  12633. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12634. { and in case of carry for A(E)/B(E)/C/NC }
  12635. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12636. begin
  12637. RemoveCurrentP(p, hp2);
  12638. Result:=true;
  12639. Exit;
  12640. end;
  12641. end;
  12642. A_DEC, A_INC, A_NEG:
  12643. begin
  12644. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  12645. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12646. { and in case of carry for A(E)/B(E)/C/NC }
  12647. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12648. begin
  12649. RemoveCurrentP(p, hp2);
  12650. Result:=true;
  12651. Exit;
  12652. end;
  12653. end
  12654. else
  12655. ;
  12656. end; { case }
  12657. { change "test $-1,%reg" into "test %reg,%reg" }
  12658. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  12659. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  12660. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  12661. if MatchInstruction(p, A_OR, []) and
  12662. { Can only match if they're both registers }
  12663. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  12664. begin
  12665. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  12666. taicpu(p).opcode := A_TEST;
  12667. { No need to set Result to True, as we've done all the optimisations we can }
  12668. end;
  12669. end;
  12670. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  12671. var
  12672. hp1,hp3 : tai;
  12673. {$ifndef x86_64}
  12674. hp2 : taicpu;
  12675. {$endif x86_64}
  12676. begin
  12677. Result:=false;
  12678. hp3:=nil;
  12679. {$ifndef x86_64}
  12680. { don't do this on modern CPUs, this really hurts them due to
  12681. broken call/ret pairing }
  12682. if (current_settings.optimizecputype < cpu_Pentium2) and
  12683. not(cs_create_pic in current_settings.moduleswitches) and
  12684. GetNextInstruction(p, hp1) and
  12685. MatchInstruction(hp1,A_JMP,[S_NO]) and
  12686. MatchOpType(taicpu(hp1),top_ref) and
  12687. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12688. begin
  12689. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  12690. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  12691. InsertLLItem(p.previous, p, hp2);
  12692. taicpu(p).opcode := A_JMP;
  12693. taicpu(p).is_jmp := true;
  12694. RemoveInstruction(hp1);
  12695. Result:=true;
  12696. end
  12697. else
  12698. {$endif x86_64}
  12699. { replace
  12700. call procname
  12701. ret
  12702. by
  12703. jmp procname
  12704. but do it only on level 4 because it destroys stack back traces
  12705. else if the subroutine is marked as no return, remove the ret
  12706. }
  12707. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12708. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12709. GetNextInstruction(p, hp1) and
  12710. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12711. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12712. SetAndTest(hp1,hp3) and
  12713. GetNextInstruction(hp1,hp1) and
  12714. MatchInstruction(hp1,A_RET,[S_NO])
  12715. )
  12716. ) and
  12717. (taicpu(hp1).ops=0) then
  12718. begin
  12719. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12720. { we might destroy stack alignment here if we do not do a call }
  12721. (target_info.stackalign<=sizeof(SizeUInt)) then
  12722. begin
  12723. taicpu(p).opcode := A_JMP;
  12724. taicpu(p).is_jmp := true;
  12725. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12726. end
  12727. else
  12728. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12729. RemoveInstruction(hp1);
  12730. if Assigned(hp3) then
  12731. begin
  12732. AsmL.Remove(hp3);
  12733. AsmL.InsertBefore(hp3,p)
  12734. end;
  12735. Result:=true;
  12736. end;
  12737. end;
  12738. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12739. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12740. begin
  12741. case OpSize of
  12742. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12743. Result := (Val <= $FF) and (Val >= -128);
  12744. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12745. Result := (Val <= $FFFF) and (Val >= -32768);
  12746. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12747. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12748. else
  12749. Result := True;
  12750. end;
  12751. end;
  12752. var
  12753. hp1, hp2 : tai;
  12754. SizeChange: Boolean;
  12755. PreMessage: string;
  12756. begin
  12757. Result := False;
  12758. if (taicpu(p).oper[0]^.typ = top_reg) and
  12759. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12760. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12761. begin
  12762. { Change (using movzbl %al,%eax as an example):
  12763. movzbl %al, %eax movzbl %al, %eax
  12764. cmpl x, %eax testl %eax,%eax
  12765. To:
  12766. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12767. movzbl %al, %eax movzbl %al, %eax
  12768. Smaller instruction and minimises pipeline stall as the CPU
  12769. doesn't have to wait for the register to get zero-extended. [Kit]
  12770. Also allow if the smaller of the two registers is being checked,
  12771. as this still removes the false dependency.
  12772. }
  12773. if
  12774. (
  12775. (
  12776. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12777. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12778. ) or (
  12779. { If MatchOperand returns True, they must both be registers }
  12780. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12781. )
  12782. ) and
  12783. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12784. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12785. begin
  12786. 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);
  12787. asml.Remove(hp1);
  12788. asml.InsertBefore(hp1, p);
  12789. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12790. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12791. begin
  12792. taicpu(hp1).opcode := A_TEST;
  12793. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12794. end;
  12795. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12796. case taicpu(p).opsize of
  12797. S_BW, S_BL:
  12798. begin
  12799. SizeChange := taicpu(hp1).opsize <> S_B;
  12800. taicpu(hp1).changeopsize(S_B);
  12801. end;
  12802. S_WL:
  12803. begin
  12804. SizeChange := taicpu(hp1).opsize <> S_W;
  12805. taicpu(hp1).changeopsize(S_W);
  12806. end
  12807. else
  12808. InternalError(2020112701);
  12809. end;
  12810. UpdateUsedRegs(tai(p.Next));
  12811. { Check if the register is used aferwards - if not, we can
  12812. remove the movzx instruction completely }
  12813. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12814. begin
  12815. { Hp1 is a better position than p for debugging purposes }
  12816. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12817. RemoveCurrentp(p, hp1);
  12818. Result := True;
  12819. end;
  12820. if SizeChange then
  12821. DebugMsg(SPeepholeOptimization + PreMessage +
  12822. 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)
  12823. else
  12824. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12825. Exit;
  12826. end;
  12827. { Change (using movzwl %ax,%eax as an example):
  12828. movzwl %ax, %eax
  12829. movb %al, (dest) (Register is smaller than read register in movz)
  12830. To:
  12831. movb %al, (dest) (Move one back to avoid a false dependency)
  12832. movzwl %ax, %eax
  12833. }
  12834. if (taicpu(hp1).opcode = A_MOV) and
  12835. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12836. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12837. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12838. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12839. begin
  12840. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12841. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12842. asml.Remove(hp1);
  12843. asml.InsertBefore(hp1, p);
  12844. if taicpu(hp1).oper[1]^.typ = top_reg then
  12845. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12846. { Check if the register is used aferwards - if not, we can
  12847. remove the movzx instruction completely }
  12848. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12849. begin
  12850. { Hp1 is a better position than p for debugging purposes }
  12851. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12852. RemoveCurrentp(p, hp1);
  12853. Result := True;
  12854. end;
  12855. Exit;
  12856. end;
  12857. end;
  12858. end;
  12859. {$ifdef x86_64}
  12860. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12861. var
  12862. PreMessage, RegName: string;
  12863. begin
  12864. { Code size reduction by J. Gareth "Kit" Moreton }
  12865. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12866. as this removes the REX prefix }
  12867. Result := False;
  12868. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12869. Exit;
  12870. if taicpu(p).oper[0]^.typ <> top_reg then
  12871. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12872. InternalError(2018011500);
  12873. case taicpu(p).opsize of
  12874. S_Q:
  12875. begin
  12876. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12877. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12878. { The actual optimization }
  12879. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12880. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12881. taicpu(p).changeopsize(S_L);
  12882. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12883. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12884. end;
  12885. else
  12886. ;
  12887. end;
  12888. end;
  12889. {$endif}
  12890. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12891. var
  12892. XReg: TRegister;
  12893. begin
  12894. Result := False;
  12895. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12896. Smaller encoding and slightly faster on some platforms (also works for
  12897. ZMM-sized registers) }
  12898. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12899. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12900. begin
  12901. XReg := taicpu(p).oper[0]^.reg;
  12902. if (taicpu(p).oper[1]^.reg = XReg) then
  12903. begin
  12904. taicpu(p).changeopsize(S_XMM);
  12905. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12906. if (cs_opt_size in current_settings.optimizerswitches) then
  12907. begin
  12908. { Change input registers to %xmm0 to reduce size. Note that
  12909. there's a risk of a false dependency doing this, so only
  12910. optimise for size here }
  12911. XReg := NR_XMM0;
  12912. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12913. end
  12914. else
  12915. begin
  12916. setsubreg(XReg, R_SUBMMX);
  12917. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12918. end;
  12919. taicpu(p).oper[0]^.reg := XReg;
  12920. taicpu(p).oper[1]^.reg := XReg;
  12921. Result := True;
  12922. end;
  12923. end;
  12924. end;
  12925. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12926. var
  12927. OperIdx: Integer;
  12928. begin
  12929. for OperIdx := 0 to p.ops - 1 do
  12930. if p.oper[OperIdx]^.typ = top_ref then
  12931. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12932. end;
  12933. end.