aoptx86.pas 540 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function PrePeepholeOptSxx(var p : tai) : boolean;
  107. function PrePeepholeOptIMUL(var p : tai) : boolean;
  108. function PrePeepholeOptAND(var p : tai) : boolean;
  109. function OptPass1Test(var p: tai): boolean;
  110. function OptPass1Add(var p: tai): boolean;
  111. function OptPass1AND(var p : tai) : boolean;
  112. function OptPass1_V_MOVAP(var p : tai) : boolean;
  113. function OptPass1VOP(var p : tai) : boolean;
  114. function OptPass1MOV(var p : tai) : boolean;
  115. function OptPass1Movx(var p : tai) : boolean;
  116. function OptPass1MOVXX(var p : tai) : boolean;
  117. function OptPass1OP(var p : tai) : boolean;
  118. function OptPass1LEA(var p : tai) : boolean;
  119. function OptPass1Sub(var p : tai) : boolean;
  120. function OptPass1SHLSAL(var p : tai) : boolean;
  121. function OptPass1FSTP(var p : tai) : boolean;
  122. function OptPass1FLD(var p : tai) : boolean;
  123. function OptPass1Cmp(var p : tai) : boolean;
  124. function OptPass1PXor(var p : tai) : boolean;
  125. function OptPass1VPXor(var p: tai): boolean;
  126. function OptPass1Imul(var p : tai) : boolean;
  127. function OptPass1Jcc(var p : tai) : boolean;
  128. function OptPass1SHXX(var p: tai): boolean;
  129. function OptPass1VMOVDQ(var p: tai): Boolean;
  130. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  131. function OptPass2Movx(var p : tai): Boolean;
  132. function OptPass2MOV(var p : tai) : boolean;
  133. function OptPass2Imul(var p : tai) : boolean;
  134. function OptPass2Jmp(var p : tai) : boolean;
  135. function OptPass2Jcc(var p : tai) : boolean;
  136. function OptPass2Lea(var p: tai): Boolean;
  137. function OptPass2SUB(var p: tai): Boolean;
  138. function OptPass2ADD(var p : tai): Boolean;
  139. function OptPass2SETcc(var p : tai) : boolean;
  140. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  141. function PostPeepholeOptMov(var p : tai) : Boolean;
  142. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  143. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  144. function PostPeepholeOptXor(var p : tai) : Boolean;
  145. {$endif x86_64}
  146. function PostPeepholeOptAnd(var p : tai) : boolean;
  147. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  148. function PostPeepholeOptCmp(var p : tai) : Boolean;
  149. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  150. function PostPeepholeOptCall(var p : tai) : Boolean;
  151. function PostPeepholeOptLea(var p : tai) : Boolean;
  152. function PostPeepholeOptPush(var p: tai): Boolean;
  153. function PostPeepholeOptShr(var p : tai) : boolean;
  154. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  155. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  156. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  157. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  158. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  159. { Processor-dependent reference optimisation }
  160. class procedure OptimizeRefs(var p: taicpu); static;
  161. end;
  162. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  163. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  166. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  167. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  168. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  169. {$if max_operands>2}
  170. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  171. {$endif max_operands>2}
  172. function RefsEqual(const r1, r2: treference): boolean;
  173. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  174. { returns true, if ref is a reference using only the registers passed as base and index
  175. and having an offset }
  176. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  177. implementation
  178. uses
  179. cutils,verbose,
  180. systems,
  181. globals,
  182. cpuinfo,
  183. procinfo,
  184. paramgr,
  185. aasmbase,
  186. aoptbase,aoptutils,
  187. symconst,symsym,
  188. cgx86,
  189. itcpugas;
  190. {$ifdef DEBUG_AOPTCPU}
  191. const
  192. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  193. {$else DEBUG_AOPTCPU}
  194. { Empty strings help the optimizer to remove string concatenations that won't
  195. ever appear to the user on release builds. [Kit] }
  196. const
  197. SPeepholeOptimization = '';
  198. {$endif DEBUG_AOPTCPU}
  199. LIST_STEP_SIZE = 4;
  200. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. (taicpu(instr).opcode = op) and
  205. ((opsize = []) or (taicpu(instr).opsize in opsize));
  206. end;
  207. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  208. begin
  209. result :=
  210. (instr.typ = ait_instruction) and
  211. ((taicpu(instr).opcode = op1) or
  212. (taicpu(instr).opcode = op2)
  213. ) and
  214. ((opsize = []) or (taicpu(instr).opsize in opsize));
  215. end;
  216. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  217. begin
  218. result :=
  219. (instr.typ = ait_instruction) and
  220. ((taicpu(instr).opcode = op1) or
  221. (taicpu(instr).opcode = op2) or
  222. (taicpu(instr).opcode = op3)
  223. ) and
  224. ((opsize = []) or (taicpu(instr).opsize in opsize));
  225. end;
  226. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  227. const opsize : topsizes) : boolean;
  228. var
  229. op : TAsmOp;
  230. begin
  231. result:=false;
  232. if (instr.typ <> ait_instruction) or
  233. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  234. exit;
  235. for op in ops do
  236. begin
  237. if taicpu(instr).opcode = op then
  238. begin
  239. result:=true;
  240. exit;
  241. end;
  242. end;
  243. end;
  244. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  245. begin
  246. result := (oper.typ = top_reg) and (oper.reg = reg);
  247. end;
  248. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  249. begin
  250. result := (oper.typ = top_const) and (oper.val = a);
  251. end;
  252. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  253. begin
  254. result := oper1.typ = oper2.typ;
  255. if result then
  256. case oper1.typ of
  257. top_const:
  258. Result:=oper1.val = oper2.val;
  259. top_reg:
  260. Result:=oper1.reg = oper2.reg;
  261. top_ref:
  262. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  263. else
  264. internalerror(2013102801);
  265. end
  266. end;
  267. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  268. begin
  269. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  270. if result then
  271. case oper1.typ of
  272. top_const:
  273. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  274. top_reg:
  275. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  276. top_ref:
  277. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  278. else
  279. internalerror(2020052401);
  280. end
  281. end;
  282. function RefsEqual(const r1, r2: treference): boolean;
  283. begin
  284. RefsEqual :=
  285. (r1.offset = r2.offset) and
  286. (r1.segment = r2.segment) and (r1.base = r2.base) and
  287. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  288. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  289. (r1.relsymbol = r2.relsymbol) and
  290. (r1.volatility=[]) and
  291. (r2.volatility=[]);
  292. end;
  293. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  294. begin
  295. Result:=(ref.offset=0) and
  296. (ref.scalefactor in [0,1]) and
  297. (ref.segment=NR_NO) and
  298. (ref.symbol=nil) and
  299. (ref.relsymbol=nil) and
  300. ((base=NR_INVALID) or
  301. (ref.base=base)) and
  302. ((index=NR_INVALID) or
  303. (ref.index=index)) and
  304. (ref.volatility=[]);
  305. end;
  306. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  307. begin
  308. Result:=(ref.scalefactor in [0,1]) and
  309. (ref.segment=NR_NO) and
  310. (ref.symbol=nil) and
  311. (ref.relsymbol=nil) and
  312. ((base=NR_INVALID) or
  313. (ref.base=base)) and
  314. ((index=NR_INVALID) or
  315. (ref.index=index)) and
  316. (ref.volatility=[]);
  317. end;
  318. function InstrReadsFlags(p: tai): boolean;
  319. begin
  320. InstrReadsFlags := true;
  321. case p.typ of
  322. ait_instruction:
  323. if InsProp[taicpu(p).opcode].Ch*
  324. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  325. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  326. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  327. exit;
  328. ait_label:
  329. exit;
  330. else
  331. ;
  332. end;
  333. InstrReadsFlags := false;
  334. end;
  335. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  336. begin
  337. Next:=Current;
  338. repeat
  339. Result:=GetNextInstruction(Next,Next);
  340. until not (Result) or
  341. not(cs_opt_level3 in current_settings.optimizerswitches) or
  342. (Next.typ<>ait_instruction) or
  343. RegInInstruction(reg,Next) or
  344. is_calljmp(taicpu(Next).opcode);
  345. end;
  346. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  347. begin
  348. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  349. Next := Current;
  350. repeat
  351. Result := GetNextInstruction(Next,Next);
  352. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  353. if is_calljmpuncondret(taicpu(Next).opcode) then
  354. begin
  355. Result := False;
  356. Exit;
  357. end
  358. else
  359. CrossJump := True;
  360. until not Result or
  361. not (cs_opt_level3 in current_settings.optimizerswitches) or
  362. (Next.typ <> ait_instruction) or
  363. RegInInstruction(reg,Next);
  364. end;
  365. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  366. begin
  367. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  368. begin
  369. Result:=GetNextInstruction(Current,Next);
  370. exit;
  371. end;
  372. Next:=tai(Current.Next);
  373. Result:=false;
  374. while assigned(Next) do
  375. begin
  376. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  377. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  378. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  379. exit
  380. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  381. begin
  382. Result:=true;
  383. exit;
  384. end;
  385. Next:=tai(Next.Next);
  386. end;
  387. end;
  388. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  389. begin
  390. Result:=RegReadByInstruction(reg,hp);
  391. end;
  392. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  393. var
  394. p: taicpu;
  395. opcount: longint;
  396. begin
  397. RegReadByInstruction := false;
  398. if hp.typ <> ait_instruction then
  399. exit;
  400. p := taicpu(hp);
  401. case p.opcode of
  402. A_CALL:
  403. regreadbyinstruction := true;
  404. A_IMUL:
  405. case p.ops of
  406. 1:
  407. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  408. (
  409. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  410. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  411. );
  412. 2,3:
  413. regReadByInstruction :=
  414. reginop(reg,p.oper[0]^) or
  415. reginop(reg,p.oper[1]^);
  416. else
  417. InternalError(2019112801);
  418. end;
  419. A_MUL:
  420. begin
  421. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  422. (
  423. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  424. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  425. );
  426. end;
  427. A_IDIV,A_DIV:
  428. begin
  429. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  430. (
  431. (getregtype(reg)=R_INTREGISTER) and
  432. (
  433. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  434. )
  435. );
  436. end;
  437. else
  438. begin
  439. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  440. begin
  441. RegReadByInstruction := false;
  442. exit;
  443. end;
  444. for opcount := 0 to p.ops-1 do
  445. if (p.oper[opCount]^.typ = top_ref) and
  446. RegInRef(reg,p.oper[opcount]^.ref^) then
  447. begin
  448. RegReadByInstruction := true;
  449. exit
  450. end;
  451. { special handling for SSE MOVSD }
  452. if (p.opcode=A_MOVSD) and (p.ops>0) then
  453. begin
  454. if p.ops<>2 then
  455. internalerror(2017042702);
  456. regReadByInstruction := reginop(reg,p.oper[0]^) or
  457. (
  458. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  459. );
  460. exit;
  461. end;
  462. with insprop[p.opcode] do
  463. begin
  464. case getregtype(reg) of
  465. R_INTREGISTER:
  466. begin
  467. case getsupreg(reg) of
  468. RS_EAX:
  469. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ECX:
  475. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EDX:
  481. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_EBX:
  487. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_ESP:
  493. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. RS_EBP:
  499. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  500. begin
  501. RegReadByInstruction := true;
  502. exit
  503. end;
  504. RS_ESI:
  505. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  506. begin
  507. RegReadByInstruction := true;
  508. exit
  509. end;
  510. RS_EDI:
  511. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  512. begin
  513. RegReadByInstruction := true;
  514. exit
  515. end;
  516. end;
  517. end;
  518. R_MMREGISTER:
  519. begin
  520. case getsupreg(reg) of
  521. RS_XMM0:
  522. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  523. begin
  524. RegReadByInstruction := true;
  525. exit
  526. end;
  527. end;
  528. end;
  529. else
  530. ;
  531. end;
  532. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  533. begin
  534. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  535. begin
  536. case p.condition of
  537. C_A,C_NBE, { CF=0 and ZF=0 }
  538. C_BE,C_NA: { CF=1 or ZF=1 }
  539. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  540. C_AE,C_NB,C_NC, { CF=0 }
  541. C_B,C_NAE,C_C: { CF=1 }
  542. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  543. C_NE,C_NZ, { ZF=0 }
  544. C_E,C_Z: { ZF=1 }
  545. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  546. C_G,C_NLE, { ZF=0 and SF=OF }
  547. C_LE,C_NG: { ZF=1 or SF<>OF }
  548. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  549. C_GE,C_NL, { SF=OF }
  550. C_L,C_NGE: { SF<>OF }
  551. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  552. C_NO, { OF=0 }
  553. C_O: { OF=1 }
  554. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  555. C_NP,C_PO, { PF=0 }
  556. C_P,C_PE: { PF=1 }
  557. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  558. C_NS, { SF=0 }
  559. C_S: { SF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  561. else
  562. internalerror(2017042701);
  563. end;
  564. if RegReadByInstruction then
  565. exit;
  566. end;
  567. case getsubreg(reg) of
  568. R_SUBW,R_SUBD,R_SUBQ:
  569. RegReadByInstruction :=
  570. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  571. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  572. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  573. R_SUBFLAGCARRY:
  574. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  575. R_SUBFLAGPARITY:
  576. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGAUXILIARY:
  578. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGZERO:
  580. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGSIGN:
  582. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGOVERFLOW:
  584. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. R_SUBFLAGINTERRUPT:
  586. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  587. R_SUBFLAGDIRECTION:
  588. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  589. else
  590. internalerror(2017042601);
  591. end;
  592. exit;
  593. end;
  594. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  595. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  596. (p.oper[0]^.reg=p.oper[1]^.reg) then
  597. exit;
  598. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  599. begin
  600. RegReadByInstruction := true;
  601. exit
  602. end;
  603. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  604. begin
  605. RegReadByInstruction := true;
  606. exit
  607. end;
  608. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  609. begin
  610. RegReadByInstruction := true;
  611. exit
  612. end;
  613. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  614. begin
  615. RegReadByInstruction := true;
  616. exit
  617. end;
  618. end;
  619. end;
  620. end;
  621. end;
  622. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  623. begin
  624. result:=false;
  625. if p1.typ<>ait_instruction then
  626. exit;
  627. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  628. exit(true);
  629. if (getregtype(reg)=R_INTREGISTER) and
  630. { change information for xmm movsd are not correct }
  631. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  632. begin
  633. case getsupreg(reg) of
  634. { RS_EAX = RS_RAX on x86-64 }
  635. RS_EAX:
  636. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. RS_ECX:
  638. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_EDX:
  640. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_EBX:
  642. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_ESP:
  644. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_EBP:
  646. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. RS_ESI:
  648. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. RS_EDI:
  650. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  651. else
  652. ;
  653. end;
  654. if result then
  655. exit;
  656. end
  657. else if getregtype(reg)=R_MMREGISTER then
  658. begin
  659. case getsupreg(reg) of
  660. RS_XMM0:
  661. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. else
  663. ;
  664. end;
  665. if result then
  666. exit;
  667. end
  668. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  669. begin
  670. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  671. exit(true);
  672. case getsubreg(reg) of
  673. R_SUBFLAGCARRY:
  674. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  675. R_SUBFLAGPARITY:
  676. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGAUXILIARY:
  678. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGZERO:
  680. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGSIGN:
  682. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGOVERFLOW:
  684. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. R_SUBFLAGINTERRUPT:
  686. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  687. R_SUBFLAGDIRECTION:
  688. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  689. R_SUBW,R_SUBD,R_SUBQ:
  690. { Everything except the direction bits }
  691. Result:=
  692. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  693. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  694. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  695. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  696. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  697. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  698. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  699. else
  700. ;
  701. end;
  702. if result then
  703. exit;
  704. end
  705. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  706. exit(true);
  707. Result:=inherited RegInInstruction(Reg, p1);
  708. end;
  709. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  710. const
  711. WriteOps: array[0..3] of set of TInsChange =
  712. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  713. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  714. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  715. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  716. var
  717. OperIdx: Integer;
  718. begin
  719. Result := False;
  720. if p1.typ <> ait_instruction then
  721. exit;
  722. with insprop[taicpu(p1).opcode] do
  723. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  724. begin
  725. case getsubreg(reg) of
  726. R_SUBW,R_SUBD,R_SUBQ:
  727. Result :=
  728. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  729. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  730. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  731. R_SUBFLAGCARRY:
  732. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  733. R_SUBFLAGPARITY:
  734. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  735. R_SUBFLAGAUXILIARY:
  736. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  737. R_SUBFLAGZERO:
  738. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  739. R_SUBFLAGSIGN:
  740. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  741. R_SUBFLAGOVERFLOW:
  742. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  743. R_SUBFLAGINTERRUPT:
  744. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  745. R_SUBFLAGDIRECTION:
  746. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  747. else
  748. internalerror(2017042602);
  749. end;
  750. exit;
  751. end;
  752. case taicpu(p1).opcode of
  753. A_CALL:
  754. { We could potentially set Result to False if the register in
  755. question is non-volatile for the subroutine's calling convention,
  756. but this would require detecting the calling convention in use and
  757. also assuming that the routine doesn't contain malformed assembly
  758. language, for example... so it could only be done under -O4 as it
  759. would be considered a side-effect. [Kit] }
  760. Result := True;
  761. A_MOVSD:
  762. { special handling for SSE MOVSD }
  763. if (taicpu(p1).ops>0) then
  764. begin
  765. if taicpu(p1).ops<>2 then
  766. internalerror(2017042703);
  767. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  768. end;
  769. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  770. so fix it here (FK)
  771. }
  772. A_VMOVSS,
  773. A_VMOVSD:
  774. begin
  775. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  776. exit;
  777. end;
  778. A_IMUL:
  779. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  780. else
  781. ;
  782. end;
  783. if Result then
  784. exit;
  785. with insprop[taicpu(p1).opcode] do
  786. begin
  787. if getregtype(reg)=R_INTREGISTER then
  788. begin
  789. case getsupreg(reg) of
  790. RS_EAX:
  791. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  792. begin
  793. Result := True;
  794. exit
  795. end;
  796. RS_ECX:
  797. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  798. begin
  799. Result := True;
  800. exit
  801. end;
  802. RS_EDX:
  803. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  804. begin
  805. Result := True;
  806. exit
  807. end;
  808. RS_EBX:
  809. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  810. begin
  811. Result := True;
  812. exit
  813. end;
  814. RS_ESP:
  815. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  816. begin
  817. Result := True;
  818. exit
  819. end;
  820. RS_EBP:
  821. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  822. begin
  823. Result := True;
  824. exit
  825. end;
  826. RS_ESI:
  827. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  828. begin
  829. Result := True;
  830. exit
  831. end;
  832. RS_EDI:
  833. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  834. begin
  835. Result := True;
  836. exit
  837. end;
  838. end;
  839. end;
  840. for OperIdx := 0 to taicpu(p1).ops - 1 do
  841. if (WriteOps[OperIdx]*Ch<>[]) and
  842. { The register doesn't get modified inside a reference }
  843. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  844. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  845. begin
  846. Result := true;
  847. exit
  848. end;
  849. end;
  850. end;
  851. {$ifdef DEBUG_AOPTCPU}
  852. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  853. begin
  854. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  855. end;
  856. function debug_tostr(i: tcgint): string; inline;
  857. begin
  858. Result := tostr(i);
  859. end;
  860. function debug_regname(r: TRegister): string; inline;
  861. begin
  862. Result := '%' + std_regname(r);
  863. end;
  864. { Debug output function - creates a string representation of an operator }
  865. function debug_operstr(oper: TOper): string;
  866. begin
  867. case oper.typ of
  868. top_const:
  869. Result := '$' + debug_tostr(oper.val);
  870. top_reg:
  871. Result := debug_regname(oper.reg);
  872. top_ref:
  873. begin
  874. if oper.ref^.offset <> 0 then
  875. Result := debug_tostr(oper.ref^.offset) + '('
  876. else
  877. Result := '(';
  878. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  879. begin
  880. Result := Result + debug_regname(oper.ref^.base);
  881. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  882. Result := Result + ',' + debug_regname(oper.ref^.index);
  883. end
  884. else
  885. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  886. Result := Result + debug_regname(oper.ref^.index);
  887. if (oper.ref^.scalefactor > 1) then
  888. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  889. else
  890. Result := Result + ')';
  891. end;
  892. else
  893. Result := '[UNKNOWN]';
  894. end;
  895. end;
  896. function debug_op2str(opcode: tasmop): string; inline;
  897. begin
  898. Result := std_op2str[opcode];
  899. end;
  900. function debug_opsize2str(opsize: topsize): string; inline;
  901. begin
  902. Result := gas_opsize2str[opsize];
  903. end;
  904. {$else DEBUG_AOPTCPU}
  905. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  906. begin
  907. end;
  908. function debug_tostr(i: tcgint): string; inline;
  909. begin
  910. Result := '';
  911. end;
  912. function debug_regname(r: TRegister): string; inline;
  913. begin
  914. Result := '';
  915. end;
  916. function debug_operstr(oper: TOper): string; inline;
  917. begin
  918. Result := '';
  919. end;
  920. function debug_op2str(opcode: tasmop): string; inline;
  921. begin
  922. Result := '';
  923. end;
  924. function debug_opsize2str(opsize: topsize): string; inline;
  925. begin
  926. Result := '';
  927. end;
  928. {$endif DEBUG_AOPTCPU}
  929. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  930. begin
  931. {$ifdef x86_64}
  932. { Always fine on x86-64 }
  933. Result := True;
  934. {$else x86_64}
  935. Result :=
  936. {$ifdef i8086}
  937. (current_settings.cputype >= cpu_386) and
  938. {$endif i8086}
  939. (
  940. { Always accept if optimising for size }
  941. (cs_opt_size in current_settings.optimizerswitches) or
  942. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  943. (current_settings.optimizecputype >= cpu_Pentium2)
  944. );
  945. {$endif x86_64}
  946. end;
  947. { Attempts to allocate a volatile integer register for use between p and hp,
  948. using AUsedRegs for the current register usage information. Returns NR_NO
  949. if no free register could be found }
  950. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  951. var
  952. RegSet: TCPURegisterSet;
  953. CurrentSuperReg: Integer;
  954. CurrentReg: TRegister;
  955. Currentp: tai;
  956. Breakout: Boolean;
  957. begin
  958. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  959. Result := NR_NO;
  960. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  961. for CurrentSuperReg in RegSet do
  962. begin
  963. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  964. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  965. {$if defined(i386) or defined(i8086)}
  966. { If the target size is 8-bit, make sure we can actually encode it }
  967. and (
  968. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  969. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  970. )
  971. {$endif i386 or i8086}
  972. then
  973. begin
  974. Currentp := p;
  975. Breakout := False;
  976. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  977. begin
  978. case Currentp.typ of
  979. ait_instruction:
  980. begin
  981. if RegInInstruction(CurrentReg, Currentp) then
  982. begin
  983. Breakout := True;
  984. Break;
  985. end;
  986. { Cannot allocate across an unconditional jump }
  987. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  988. Exit;
  989. end;
  990. ait_marker:
  991. { Don't try anything more if a marker is hit }
  992. Exit;
  993. ait_regalloc:
  994. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  995. begin
  996. Breakout := True;
  997. Break;
  998. end;
  999. else
  1000. ;
  1001. end;
  1002. end;
  1003. if Breakout then
  1004. { Try the next register }
  1005. Continue;
  1006. { We have a free register available }
  1007. Result := CurrentReg;
  1008. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1009. Exit;
  1010. end;
  1011. end;
  1012. end;
  1013. { Attempts to allocate a volatile MM register for use between p and hp,
  1014. using AUsedRegs for the current register usage information. Returns NR_NO
  1015. if no free register could be found }
  1016. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1017. var
  1018. RegSet: TCPURegisterSet;
  1019. CurrentSuperReg: Integer;
  1020. CurrentReg: TRegister;
  1021. Currentp: tai;
  1022. Breakout: Boolean;
  1023. begin
  1024. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1025. Result := NR_NO;
  1026. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1027. for CurrentSuperReg in RegSet do
  1028. begin
  1029. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1030. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1031. begin
  1032. Currentp := p;
  1033. Breakout := False;
  1034. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1035. begin
  1036. case Currentp.typ of
  1037. ait_instruction:
  1038. begin
  1039. if RegInInstruction(CurrentReg, Currentp) then
  1040. begin
  1041. Breakout := True;
  1042. Break;
  1043. end;
  1044. { Cannot allocate across an unconditional jump }
  1045. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1046. Exit;
  1047. end;
  1048. ait_marker:
  1049. { Don't try anything more if a marker is hit }
  1050. Exit;
  1051. ait_regalloc:
  1052. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1053. begin
  1054. Breakout := True;
  1055. Break;
  1056. end;
  1057. else
  1058. ;
  1059. end;
  1060. end;
  1061. if Breakout then
  1062. { Try the next register }
  1063. Continue;
  1064. { We have a free register available }
  1065. Result := CurrentReg;
  1066. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1067. Exit;
  1068. end;
  1069. end;
  1070. end;
  1071. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1072. begin
  1073. if not SuperRegistersEqual(reg1,reg2) then
  1074. exit(false);
  1075. if getregtype(reg1)<>R_INTREGISTER then
  1076. exit(true); {because SuperRegisterEqual is true}
  1077. case getsubreg(reg1) of
  1078. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1079. higher, it preserves the high bits, so the new value depends on
  1080. reg2's previous value. In other words, it is equivalent to doing:
  1081. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1082. R_SUBL:
  1083. exit(getsubreg(reg2)=R_SUBL);
  1084. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1085. higher, it actually does a:
  1086. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1087. R_SUBH:
  1088. exit(getsubreg(reg2)=R_SUBH);
  1089. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1090. bits of reg2:
  1091. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1092. R_SUBW:
  1093. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1094. { a write to R_SUBD always overwrites every other subregister,
  1095. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1096. R_SUBD,
  1097. R_SUBQ:
  1098. exit(true);
  1099. else
  1100. internalerror(2017042801);
  1101. end;
  1102. end;
  1103. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1104. begin
  1105. if not SuperRegistersEqual(reg1,reg2) then
  1106. exit(false);
  1107. if getregtype(reg1)<>R_INTREGISTER then
  1108. exit(true); {because SuperRegisterEqual is true}
  1109. case getsubreg(reg1) of
  1110. R_SUBL:
  1111. exit(getsubreg(reg2)<>R_SUBH);
  1112. R_SUBH:
  1113. exit(getsubreg(reg2)<>R_SUBL);
  1114. R_SUBW,
  1115. R_SUBD,
  1116. R_SUBQ:
  1117. exit(true);
  1118. else
  1119. internalerror(2017042802);
  1120. end;
  1121. end;
  1122. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1123. var
  1124. hp1 : tai;
  1125. l : TCGInt;
  1126. begin
  1127. result:=false;
  1128. { changes the code sequence
  1129. shr/sar const1, x
  1130. shl const2, x
  1131. to
  1132. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1133. if GetNextInstruction(p, hp1) and
  1134. MatchInstruction(hp1,A_SHL,[]) and
  1135. (taicpu(p).oper[0]^.typ = top_const) and
  1136. (taicpu(hp1).oper[0]^.typ = top_const) and
  1137. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1138. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1139. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1140. begin
  1141. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1142. not(cs_opt_size in current_settings.optimizerswitches) then
  1143. begin
  1144. { shr/sar const1, %reg
  1145. shl const2, %reg
  1146. with const1 > const2 }
  1147. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1148. taicpu(hp1).opcode := A_AND;
  1149. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1150. case taicpu(p).opsize Of
  1151. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1152. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1153. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1154. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1155. else
  1156. Internalerror(2017050703)
  1157. end;
  1158. end
  1159. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1160. not(cs_opt_size in current_settings.optimizerswitches) then
  1161. begin
  1162. { shr/sar const1, %reg
  1163. shl const2, %reg
  1164. with const1 < const2 }
  1165. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1166. taicpu(p).opcode := A_AND;
  1167. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1168. case taicpu(p).opsize Of
  1169. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1170. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1171. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1172. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1173. else
  1174. Internalerror(2017050702)
  1175. end;
  1176. end
  1177. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1178. begin
  1179. { shr/sar const1, %reg
  1180. shl const2, %reg
  1181. with const1 = const2 }
  1182. taicpu(p).opcode := A_AND;
  1183. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1184. case taicpu(p).opsize Of
  1185. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1186. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1187. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1188. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1189. else
  1190. Internalerror(2017050701)
  1191. end;
  1192. RemoveInstruction(hp1);
  1193. end;
  1194. end;
  1195. end;
  1196. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1197. var
  1198. opsize : topsize;
  1199. hp1 : tai;
  1200. tmpref : treference;
  1201. ShiftValue : Cardinal;
  1202. BaseValue : TCGInt;
  1203. begin
  1204. result:=false;
  1205. opsize:=taicpu(p).opsize;
  1206. { changes certain "imul const, %reg"'s to lea sequences }
  1207. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1208. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1209. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1210. if (taicpu(p).oper[0]^.val = 1) then
  1211. if (taicpu(p).ops = 2) then
  1212. { remove "imul $1, reg" }
  1213. begin
  1214. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1215. Result := RemoveCurrentP(p);
  1216. end
  1217. else
  1218. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1219. begin
  1220. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1221. InsertLLItem(p.previous, p.next, hp1);
  1222. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1223. p.free;
  1224. p := hp1;
  1225. end
  1226. else if ((taicpu(p).ops <= 2) or
  1227. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1228. not(cs_opt_size in current_settings.optimizerswitches) and
  1229. (not(GetNextInstruction(p, hp1)) or
  1230. not((tai(hp1).typ = ait_instruction) and
  1231. ((taicpu(hp1).opcode=A_Jcc) and
  1232. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1233. begin
  1234. {
  1235. imul X, reg1, reg2 to
  1236. lea (reg1,reg1,Y), reg2
  1237. shl ZZ,reg2
  1238. imul XX, reg1 to
  1239. lea (reg1,reg1,YY), reg1
  1240. shl ZZ,reg2
  1241. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1242. it does not exist as a separate optimization target in FPC though.
  1243. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1244. at most two zeros
  1245. }
  1246. reference_reset(tmpref,1,[]);
  1247. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1248. begin
  1249. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1250. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1251. TmpRef.base := taicpu(p).oper[1]^.reg;
  1252. TmpRef.index := taicpu(p).oper[1]^.reg;
  1253. if not(BaseValue in [3,5,9]) then
  1254. Internalerror(2018110101);
  1255. TmpRef.ScaleFactor := BaseValue-1;
  1256. if (taicpu(p).ops = 2) then
  1257. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1258. else
  1259. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1260. AsmL.InsertAfter(hp1,p);
  1261. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1262. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1263. RemoveCurrentP(p, hp1);
  1264. if ShiftValue>0 then
  1265. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1266. end;
  1267. end;
  1268. end;
  1269. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1270. begin
  1271. Result := False;
  1272. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1273. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1274. begin
  1275. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1276. taicpu(p).opcode := A_MOV;
  1277. Result := True;
  1278. end;
  1279. end;
  1280. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1281. var
  1282. p: taicpu absolute hp;
  1283. i: Integer;
  1284. begin
  1285. Result := False;
  1286. if not assigned(hp) or
  1287. (hp.typ <> ait_instruction) then
  1288. Exit;
  1289. // p := taicpu(hp);
  1290. Prefetch(insprop[p.opcode]);
  1291. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1292. with insprop[p.opcode] do
  1293. begin
  1294. case getsubreg(reg) of
  1295. R_SUBW,R_SUBD,R_SUBQ:
  1296. Result:=
  1297. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1298. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1299. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1300. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1301. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1302. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1303. R_SUBFLAGCARRY:
  1304. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1305. R_SUBFLAGPARITY:
  1306. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1307. R_SUBFLAGAUXILIARY:
  1308. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGZERO:
  1310. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1311. R_SUBFLAGSIGN:
  1312. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1313. R_SUBFLAGOVERFLOW:
  1314. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1315. R_SUBFLAGINTERRUPT:
  1316. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1317. R_SUBFLAGDIRECTION:
  1318. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1319. else
  1320. begin
  1321. writeln(getsubreg(reg));
  1322. internalerror(2017050501);
  1323. end;
  1324. end;
  1325. exit;
  1326. end;
  1327. { Handle special cases first }
  1328. case p.opcode of
  1329. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1330. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1331. begin
  1332. Result :=
  1333. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1334. (p.oper[1]^.typ = top_reg) and
  1335. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1336. (
  1337. (p.oper[0]^.typ = top_const) or
  1338. (
  1339. (p.oper[0]^.typ = top_reg) and
  1340. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1341. ) or (
  1342. (p.oper[0]^.typ = top_ref) and
  1343. not RegInRef(reg,p.oper[0]^.ref^)
  1344. )
  1345. );
  1346. end;
  1347. A_MUL, A_IMUL:
  1348. Result :=
  1349. (
  1350. (p.ops=3) and { IMUL only }
  1351. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1352. (
  1353. (
  1354. (p.oper[1]^.typ=top_reg) and
  1355. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1356. ) or (
  1357. (p.oper[1]^.typ=top_ref) and
  1358. not RegInRef(reg,p.oper[1]^.ref^)
  1359. )
  1360. )
  1361. ) or (
  1362. (
  1363. (p.ops=1) and
  1364. (
  1365. (
  1366. (
  1367. (p.oper[0]^.typ=top_reg) and
  1368. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1369. )
  1370. ) or (
  1371. (p.oper[0]^.typ=top_ref) and
  1372. not RegInRef(reg,p.oper[0]^.ref^)
  1373. )
  1374. ) and (
  1375. (
  1376. (p.opsize=S_B) and
  1377. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1378. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1379. ) or (
  1380. (p.opsize=S_W) and
  1381. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1382. ) or (
  1383. (p.opsize=S_L) and
  1384. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1385. {$ifdef x86_64}
  1386. ) or (
  1387. (p.opsize=S_Q) and
  1388. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1389. {$endif x86_64}
  1390. )
  1391. )
  1392. )
  1393. );
  1394. A_CBW:
  1395. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1396. {$ifndef x86_64}
  1397. A_LDS:
  1398. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1399. A_LES:
  1400. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1401. {$endif not x86_64}
  1402. A_LFS:
  1403. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1404. A_LGS:
  1405. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1406. A_LSS:
  1407. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1408. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1409. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1410. A_LODSB:
  1411. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1412. A_LODSW:
  1413. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1414. {$ifdef x86_64}
  1415. A_LODSQ:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1417. {$endif x86_64}
  1418. A_LODSD:
  1419. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1420. A_FSTSW, A_FNSTSW:
  1421. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1422. else
  1423. begin
  1424. with insprop[p.opcode] do
  1425. begin
  1426. if (
  1427. { xor %reg,%reg etc. is classed as a new value }
  1428. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1429. MatchOpType(p, top_reg, top_reg) and
  1430. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1431. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1432. ) then
  1433. begin
  1434. Result := True;
  1435. Exit;
  1436. end;
  1437. { Make sure the entire register is overwritten }
  1438. if (getregtype(reg) = R_INTREGISTER) then
  1439. begin
  1440. if (p.ops > 0) then
  1441. begin
  1442. if RegInOp(reg, p.oper[0]^) then
  1443. begin
  1444. if (p.oper[0]^.typ = top_ref) then
  1445. begin
  1446. if RegInRef(reg, p.oper[0]^.ref^) then
  1447. begin
  1448. Result := False;
  1449. Exit;
  1450. end;
  1451. end
  1452. else if (p.oper[0]^.typ = top_reg) then
  1453. begin
  1454. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1455. begin
  1456. Result := False;
  1457. Exit;
  1458. end
  1459. else if ([Ch_WOp1]*Ch<>[]) then
  1460. begin
  1461. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1462. Result := True
  1463. else
  1464. begin
  1465. Result := False;
  1466. Exit;
  1467. end;
  1468. end;
  1469. end;
  1470. end;
  1471. if (p.ops > 1) then
  1472. begin
  1473. if RegInOp(reg, p.oper[1]^) then
  1474. begin
  1475. if (p.oper[1]^.typ = top_ref) then
  1476. begin
  1477. if RegInRef(reg, p.oper[1]^.ref^) then
  1478. begin
  1479. Result := False;
  1480. Exit;
  1481. end;
  1482. end
  1483. else if (p.oper[1]^.typ = top_reg) then
  1484. begin
  1485. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1486. begin
  1487. Result := False;
  1488. Exit;
  1489. end
  1490. else if ([Ch_WOp2]*Ch<>[]) then
  1491. begin
  1492. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1493. Result := True
  1494. else
  1495. begin
  1496. Result := False;
  1497. Exit;
  1498. end;
  1499. end;
  1500. end;
  1501. end;
  1502. if (p.ops > 2) then
  1503. begin
  1504. if RegInOp(reg, p.oper[2]^) then
  1505. begin
  1506. if (p.oper[2]^.typ = top_ref) then
  1507. begin
  1508. if RegInRef(reg, p.oper[2]^.ref^) then
  1509. begin
  1510. Result := False;
  1511. Exit;
  1512. end;
  1513. end
  1514. else if (p.oper[2]^.typ = top_reg) then
  1515. begin
  1516. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1517. begin
  1518. Result := False;
  1519. Exit;
  1520. end
  1521. else if ([Ch_WOp3]*Ch<>[]) then
  1522. begin
  1523. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1524. Result := True
  1525. else
  1526. begin
  1527. Result := False;
  1528. Exit;
  1529. end;
  1530. end;
  1531. end;
  1532. end;
  1533. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1534. begin
  1535. if (p.oper[3]^.typ = top_ref) then
  1536. begin
  1537. if RegInRef(reg, p.oper[3]^.ref^) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end;
  1542. end
  1543. else if (p.oper[3]^.typ = top_reg) then
  1544. begin
  1545. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1546. begin
  1547. Result := False;
  1548. Exit;
  1549. end
  1550. else if ([Ch_WOp4]*Ch<>[]) then
  1551. begin
  1552. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1553. Result := True
  1554. else
  1555. begin
  1556. Result := False;
  1557. Exit;
  1558. end;
  1559. end;
  1560. end;
  1561. end;
  1562. end;
  1563. end;
  1564. end;
  1565. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1566. case getsupreg(reg) of
  1567. RS_EAX:
  1568. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1569. begin
  1570. Result := True;
  1571. Exit;
  1572. end;
  1573. RS_ECX:
  1574. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1575. begin
  1576. Result := True;
  1577. Exit;
  1578. end;
  1579. RS_EDX:
  1580. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1581. begin
  1582. Result := True;
  1583. Exit;
  1584. end;
  1585. RS_EBX:
  1586. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1587. begin
  1588. Result := True;
  1589. Exit;
  1590. end;
  1591. RS_ESP:
  1592. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1593. begin
  1594. Result := True;
  1595. Exit;
  1596. end;
  1597. RS_EBP:
  1598. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1599. begin
  1600. Result := True;
  1601. Exit;
  1602. end;
  1603. RS_ESI:
  1604. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1605. begin
  1606. Result := True;
  1607. Exit;
  1608. end;
  1609. RS_EDI:
  1610. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1611. begin
  1612. Result := True;
  1613. Exit;
  1614. end;
  1615. else
  1616. ;
  1617. end;
  1618. end;
  1619. end;
  1620. end;
  1621. end;
  1622. end;
  1623. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1624. var
  1625. hp2,hp3 : tai;
  1626. begin
  1627. { some x86-64 issue a NOP before the real exit code }
  1628. if MatchInstruction(p,A_NOP,[]) then
  1629. GetNextInstruction(p,p);
  1630. result:=assigned(p) and (p.typ=ait_instruction) and
  1631. ((taicpu(p).opcode = A_RET) or
  1632. ((taicpu(p).opcode=A_LEAVE) and
  1633. GetNextInstruction(p,hp2) and
  1634. MatchInstruction(hp2,A_RET,[S_NO])
  1635. ) or
  1636. (((taicpu(p).opcode=A_LEA) and
  1637. MatchOpType(taicpu(p),top_ref,top_reg) and
  1638. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1639. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1640. ) and
  1641. GetNextInstruction(p,hp2) and
  1642. MatchInstruction(hp2,A_RET,[S_NO])
  1643. ) or
  1644. ((((taicpu(p).opcode=A_MOV) and
  1645. MatchOpType(taicpu(p),top_reg,top_reg) and
  1646. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1647. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1648. ((taicpu(p).opcode=A_LEA) and
  1649. MatchOpType(taicpu(p),top_ref,top_reg) and
  1650. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1651. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1652. )
  1653. ) and
  1654. GetNextInstruction(p,hp2) and
  1655. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1656. MatchOpType(taicpu(hp2),top_reg) and
  1657. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1658. GetNextInstruction(hp2,hp3) and
  1659. MatchInstruction(hp3,A_RET,[S_NO])
  1660. )
  1661. );
  1662. end;
  1663. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1664. begin
  1665. isFoldableArithOp := False;
  1666. case hp1.opcode of
  1667. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1668. isFoldableArithOp :=
  1669. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1670. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1671. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1672. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1673. (taicpu(hp1).oper[1]^.reg = reg);
  1674. A_INC,A_DEC,A_NEG,A_NOT:
  1675. isFoldableArithOp :=
  1676. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1677. (taicpu(hp1).oper[0]^.reg = reg);
  1678. else
  1679. ;
  1680. end;
  1681. end;
  1682. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1683. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1684. var
  1685. hp2: tai;
  1686. begin
  1687. hp2 := p;
  1688. repeat
  1689. hp2 := tai(hp2.previous);
  1690. if assigned(hp2) and
  1691. (hp2.typ = ait_regalloc) and
  1692. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1693. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1694. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1695. begin
  1696. RemoveInstruction(hp2);
  1697. break;
  1698. end;
  1699. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1700. end;
  1701. begin
  1702. case current_procinfo.procdef.returndef.typ of
  1703. arraydef,recorddef,pointerdef,
  1704. stringdef,enumdef,procdef,objectdef,errordef,
  1705. filedef,setdef,procvardef,
  1706. classrefdef,forwarddef:
  1707. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1708. orddef:
  1709. if current_procinfo.procdef.returndef.size <> 0 then
  1710. begin
  1711. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1712. { for int64/qword }
  1713. if current_procinfo.procdef.returndef.size = 8 then
  1714. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1715. end;
  1716. else
  1717. ;
  1718. end;
  1719. end;
  1720. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1721. var
  1722. hp1,hp2 : tai;
  1723. begin
  1724. result:=false;
  1725. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1726. begin
  1727. { vmova* reg1,reg1
  1728. =>
  1729. <nop> }
  1730. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1731. begin
  1732. RemoveCurrentP(p);
  1733. result:=true;
  1734. exit;
  1735. end
  1736. else if GetNextInstruction(p,hp1) then
  1737. begin
  1738. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1739. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1740. begin
  1741. { vmova* reg1,reg2
  1742. vmova* reg2,reg3
  1743. dealloc reg2
  1744. =>
  1745. vmova* reg1,reg3 }
  1746. TransferUsedRegs(TmpUsedRegs);
  1747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1748. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1749. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1750. begin
  1751. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1753. RemoveInstruction(hp1);
  1754. result:=true;
  1755. exit;
  1756. end
  1757. { special case:
  1758. vmova* reg1,<op>
  1759. vmova* <op>,reg1
  1760. =>
  1761. vmova* reg1,<op> }
  1762. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1763. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1764. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1765. ) then
  1766. begin
  1767. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1768. RemoveInstruction(hp1);
  1769. result:=true;
  1770. exit;
  1771. end
  1772. end
  1773. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1774. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1775. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1776. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1777. ) and
  1778. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1779. begin
  1780. { vmova* reg1,reg2
  1781. vmovs* reg2,<op>
  1782. dealloc reg2
  1783. =>
  1784. vmovs* reg1,reg3 }
  1785. TransferUsedRegs(TmpUsedRegs);
  1786. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1787. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1788. begin
  1789. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1790. taicpu(p).opcode:=taicpu(hp1).opcode;
  1791. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1792. RemoveInstruction(hp1);
  1793. result:=true;
  1794. exit;
  1795. end
  1796. end;
  1797. end;
  1798. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1799. begin
  1800. if MatchInstruction(hp1,[A_VFMADDPD,
  1801. A_VFMADD132PD,
  1802. A_VFMADD132PS,
  1803. A_VFMADD132SD,
  1804. A_VFMADD132SS,
  1805. A_VFMADD213PD,
  1806. A_VFMADD213PS,
  1807. A_VFMADD213SD,
  1808. A_VFMADD213SS,
  1809. A_VFMADD231PD,
  1810. A_VFMADD231PS,
  1811. A_VFMADD231SD,
  1812. A_VFMADD231SS,
  1813. A_VFMADDSUB132PD,
  1814. A_VFMADDSUB132PS,
  1815. A_VFMADDSUB213PD,
  1816. A_VFMADDSUB213PS,
  1817. A_VFMADDSUB231PD,
  1818. A_VFMADDSUB231PS,
  1819. A_VFMSUB132PD,
  1820. A_VFMSUB132PS,
  1821. A_VFMSUB132SD,
  1822. A_VFMSUB132SS,
  1823. A_VFMSUB213PD,
  1824. A_VFMSUB213PS,
  1825. A_VFMSUB213SD,
  1826. A_VFMSUB213SS,
  1827. A_VFMSUB231PD,
  1828. A_VFMSUB231PS,
  1829. A_VFMSUB231SD,
  1830. A_VFMSUB231SS,
  1831. A_VFMSUBADD132PD,
  1832. A_VFMSUBADD132PS,
  1833. A_VFMSUBADD213PD,
  1834. A_VFMSUBADD213PS,
  1835. A_VFMSUBADD231PD,
  1836. A_VFMSUBADD231PS,
  1837. A_VFNMADD132PD,
  1838. A_VFNMADD132PS,
  1839. A_VFNMADD132SD,
  1840. A_VFNMADD132SS,
  1841. A_VFNMADD213PD,
  1842. A_VFNMADD213PS,
  1843. A_VFNMADD213SD,
  1844. A_VFNMADD213SS,
  1845. A_VFNMADD231PD,
  1846. A_VFNMADD231PS,
  1847. A_VFNMADD231SD,
  1848. A_VFNMADD231SS,
  1849. A_VFNMSUB132PD,
  1850. A_VFNMSUB132PS,
  1851. A_VFNMSUB132SD,
  1852. A_VFNMSUB132SS,
  1853. A_VFNMSUB213PD,
  1854. A_VFNMSUB213PS,
  1855. A_VFNMSUB213SD,
  1856. A_VFNMSUB213SS,
  1857. A_VFNMSUB231PD,
  1858. A_VFNMSUB231PS,
  1859. A_VFNMSUB231SD,
  1860. A_VFNMSUB231SS],[S_NO]) and
  1861. { we mix single and double opperations here because we assume that the compiler
  1862. generates vmovapd only after double operations and vmovaps only after single operations }
  1863. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1864. GetNextInstruction(hp1,hp2) and
  1865. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1866. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1867. begin
  1868. TransferUsedRegs(TmpUsedRegs);
  1869. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1870. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1871. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1872. begin
  1873. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1874. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1875. RemoveInstruction(hp2);
  1876. end;
  1877. end
  1878. else if (hp1.typ = ait_instruction) and
  1879. GetNextInstruction(hp1, hp2) and
  1880. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1881. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1882. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1883. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1884. (((taicpu(p).opcode=A_MOVAPS) and
  1885. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1886. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1887. ((taicpu(p).opcode=A_MOVAPD) and
  1888. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1889. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1890. ) then
  1891. { change
  1892. movapX reg,reg2
  1893. addsX/subsX/... reg3, reg2
  1894. movapX reg2,reg
  1895. to
  1896. addsX/subsX/... reg3,reg
  1897. }
  1898. begin
  1899. TransferUsedRegs(TmpUsedRegs);
  1900. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1901. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1902. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1903. begin
  1904. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1905. debug_op2str(taicpu(p).opcode)+' '+
  1906. debug_op2str(taicpu(hp1).opcode)+' '+
  1907. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1908. { we cannot eliminate the first move if
  1909. the operations uses the same register for source and dest }
  1910. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1911. RemoveCurrentP(p, nil);
  1912. p:=hp1;
  1913. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1914. RemoveInstruction(hp2);
  1915. result:=true;
  1916. end;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1922. var
  1923. hp1 : tai;
  1924. begin
  1925. result:=false;
  1926. { replace
  1927. V<Op>X %mreg1,%mreg2,%mreg3
  1928. VMovX %mreg3,%mreg4
  1929. dealloc %mreg3
  1930. by
  1931. V<Op>X %mreg1,%mreg2,%mreg4
  1932. ?
  1933. }
  1934. if GetNextInstruction(p,hp1) and
  1935. { we mix single and double operations here because we assume that the compiler
  1936. generates vmovapd only after double operations and vmovaps only after single operations }
  1937. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1938. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1939. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1940. begin
  1941. TransferUsedRegs(TmpUsedRegs);
  1942. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1943. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1946. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. end;
  1950. end;
  1951. end;
  1952. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1953. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1954. begin
  1955. Result := False;
  1956. { For safety reasons, only check for exact register matches }
  1957. { Check base register }
  1958. if (ref.base = AOldReg) then
  1959. begin
  1960. ref.base := ANewReg;
  1961. Result := True;
  1962. end;
  1963. { Check index register }
  1964. if (ref.index = AOldReg) then
  1965. begin
  1966. ref.index := ANewReg;
  1967. Result := True;
  1968. end;
  1969. end;
  1970. { Replaces all references to AOldReg in an operand to ANewReg }
  1971. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1972. var
  1973. OldSupReg, NewSupReg: TSuperRegister;
  1974. OldSubReg, NewSubReg: TSubRegister;
  1975. OldRegType: TRegisterType;
  1976. ThisOper: POper;
  1977. begin
  1978. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1979. Result := False;
  1980. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1981. InternalError(2020011801);
  1982. OldSupReg := getsupreg(AOldReg);
  1983. OldSubReg := getsubreg(AOldReg);
  1984. OldRegType := getregtype(AOldReg);
  1985. NewSupReg := getsupreg(ANewReg);
  1986. NewSubReg := getsubreg(ANewReg);
  1987. if OldRegType <> getregtype(ANewReg) then
  1988. InternalError(2020011802);
  1989. if OldSubReg <> NewSubReg then
  1990. InternalError(2020011803);
  1991. case ThisOper^.typ of
  1992. top_reg:
  1993. if (
  1994. (ThisOper^.reg = AOldReg) or
  1995. (
  1996. (OldRegType = R_INTREGISTER) and
  1997. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1998. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1999. (
  2000. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2001. {$ifndef x86_64}
  2002. and (
  2003. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2004. don't have an 8-bit representation }
  2005. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2006. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2007. )
  2008. {$endif x86_64}
  2009. )
  2010. )
  2011. ) then
  2012. begin
  2013. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2014. Result := True;
  2015. end;
  2016. top_ref:
  2017. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2018. Result := True;
  2019. else
  2020. ;
  2021. end;
  2022. end;
  2023. { Replaces all references to AOldReg in an instruction to ANewReg }
  2024. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2025. const
  2026. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2027. var
  2028. OperIdx: Integer;
  2029. begin
  2030. Result := False;
  2031. for OperIdx := 0 to p.ops - 1 do
  2032. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2033. begin
  2034. { The shift and rotate instructions can only use CL }
  2035. if not (
  2036. (OperIdx = 0) and
  2037. { This second condition just helps to avoid unnecessarily
  2038. calling MatchInstruction for 10 different opcodes }
  2039. (p.oper[0]^.reg = NR_CL) and
  2040. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2041. ) then
  2042. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2043. end
  2044. else if p.oper[OperIdx]^.typ = top_ref then
  2045. { It's okay to replace registers in references that get written to }
  2046. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2047. end;
  2048. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2049. begin
  2050. with ref^ do
  2051. Result :=
  2052. (index = NR_NO) and
  2053. (
  2054. {$ifdef x86_64}
  2055. (
  2056. (base = NR_RIP) and
  2057. (refaddr in [addr_pic, addr_pic_no_got])
  2058. ) or
  2059. {$endif x86_64}
  2060. (base = NR_STACK_POINTER_REG) or
  2061. (base = current_procinfo.framepointer)
  2062. );
  2063. end;
  2064. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2065. var
  2066. l: asizeint;
  2067. begin
  2068. Result := False;
  2069. { Should have been checked previously }
  2070. if p.opcode <> A_LEA then
  2071. InternalError(2020072501);
  2072. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2073. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2074. not(cs_opt_size in current_settings.optimizerswitches) then
  2075. exit;
  2076. with p.oper[0]^.ref^ do
  2077. begin
  2078. if (base <> p.oper[1]^.reg) or
  2079. (index <> NR_NO) or
  2080. assigned(symbol) then
  2081. exit;
  2082. l:=offset;
  2083. if (l=1) and UseIncDec then
  2084. begin
  2085. p.opcode:=A_INC;
  2086. p.loadreg(0,p.oper[1]^.reg);
  2087. p.ops:=1;
  2088. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2089. end
  2090. else if (l=-1) and UseIncDec then
  2091. begin
  2092. p.opcode:=A_DEC;
  2093. p.loadreg(0,p.oper[1]^.reg);
  2094. p.ops:=1;
  2095. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2096. end
  2097. else
  2098. begin
  2099. if (l<0) and (l<>-2147483648) then
  2100. begin
  2101. p.opcode:=A_SUB;
  2102. p.loadConst(0,-l);
  2103. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2104. end
  2105. else
  2106. begin
  2107. p.opcode:=A_ADD;
  2108. p.loadConst(0,l);
  2109. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2110. end;
  2111. end;
  2112. end;
  2113. Result := True;
  2114. end;
  2115. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2116. var
  2117. CurrentReg, ReplaceReg: TRegister;
  2118. begin
  2119. Result := False;
  2120. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2121. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2122. case hp.opcode of
  2123. A_FSTSW, A_FNSTSW,
  2124. A_IN, A_INS, A_OUT, A_OUTS,
  2125. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2126. { These routines have explicit operands, but they are restricted in
  2127. what they can be (e.g. IN and OUT can only read from AL, AX or
  2128. EAX. }
  2129. Exit;
  2130. A_IMUL:
  2131. begin
  2132. { The 1-operand version writes to implicit registers
  2133. The 2-operand version reads from the first operator, and reads
  2134. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2135. the 3-operand version reads from a register that it doesn't write to
  2136. }
  2137. case hp.ops of
  2138. 1:
  2139. if (
  2140. (
  2141. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2142. ) or
  2143. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2144. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2145. begin
  2146. Result := True;
  2147. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2148. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2149. end;
  2150. 2:
  2151. { Only modify the first parameter }
  2152. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2153. begin
  2154. Result := True;
  2155. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2156. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2157. end;
  2158. 3:
  2159. { Only modify the second parameter }
  2160. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2161. begin
  2162. Result := True;
  2163. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2164. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2165. end;
  2166. else
  2167. InternalError(2020012901);
  2168. end;
  2169. end;
  2170. else
  2171. if (hp.ops > 0) and
  2172. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2173. begin
  2174. Result := True;
  2175. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2176. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2177. end;
  2178. end;
  2179. end;
  2180. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2181. var
  2182. hp1, hp2, hp3: tai;
  2183. DoOptimisation, TempBool: Boolean;
  2184. {$ifdef x86_64}
  2185. NewConst: TCGInt;
  2186. {$endif x86_64}
  2187. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2188. begin
  2189. if taicpu(hp1).opcode = signed_movop then
  2190. begin
  2191. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2192. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2193. end
  2194. else
  2195. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2196. end;
  2197. function TryConstMerge(var p1, p2: tai): Boolean;
  2198. var
  2199. ThisRef: TReference;
  2200. begin
  2201. Result := False;
  2202. ThisRef := taicpu(p2).oper[1]^.ref^;
  2203. { Only permit writes to the stack, since we can guarantee alignment with that }
  2204. if (ThisRef.index = NR_NO) and
  2205. (
  2206. (ThisRef.base = NR_STACK_POINTER_REG) or
  2207. (ThisRef.base = current_procinfo.framepointer)
  2208. ) then
  2209. begin
  2210. case taicpu(p).opsize of
  2211. S_B:
  2212. begin
  2213. { Word writes must be on a 2-byte boundary }
  2214. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2215. begin
  2216. { Reduce offset of second reference to see if it is sequential with the first }
  2217. Dec(ThisRef.offset, 1);
  2218. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2219. begin
  2220. { Make sure the constants aren't represented as a
  2221. negative number, as these won't merge properly }
  2222. taicpu(p1).opsize := S_W;
  2223. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2224. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2225. RemoveInstruction(p2);
  2226. Result := True;
  2227. end;
  2228. end;
  2229. end;
  2230. S_W:
  2231. begin
  2232. { Longword writes must be on a 4-byte boundary }
  2233. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2234. begin
  2235. { Reduce offset of second reference to see if it is sequential with the first }
  2236. Dec(ThisRef.offset, 2);
  2237. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2238. begin
  2239. { Make sure the constants aren't represented as a
  2240. negative number, as these won't merge properly }
  2241. taicpu(p1).opsize := S_L;
  2242. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2243. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2244. RemoveInstruction(p2);
  2245. Result := True;
  2246. end;
  2247. end;
  2248. end;
  2249. {$ifdef x86_64}
  2250. S_L:
  2251. begin
  2252. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2253. see if the constants can be encoded this way. }
  2254. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2255. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2256. { Quadword writes must be on an 8-byte boundary }
  2257. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2258. begin
  2259. { Reduce offset of second reference to see if it is sequential with the first }
  2260. Dec(ThisRef.offset, 4);
  2261. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2262. begin
  2263. { Make sure the constants aren't represented as a
  2264. negative number, as these won't merge properly }
  2265. taicpu(p1).opsize := S_Q;
  2266. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2267. taicpu(p1).oper[0]^.val := NewConst;
  2268. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2269. RemoveInstruction(p2);
  2270. Result := True;
  2271. end;
  2272. end;
  2273. end;
  2274. {$endif x86_64}
  2275. else
  2276. ;
  2277. end;
  2278. end;
  2279. end;
  2280. var
  2281. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2282. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2283. NewSize: topsize;
  2284. CurrentReg, ActiveReg: TRegister;
  2285. SourceRef, TargetRef: TReference;
  2286. MovAligned, MovUnaligned: TAsmOp;
  2287. begin
  2288. Result:=false;
  2289. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2290. { remove mov reg1,reg1? }
  2291. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2292. then
  2293. begin
  2294. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2295. { take care of the register (de)allocs following p }
  2296. RemoveCurrentP(p, hp1);
  2297. Result:=true;
  2298. exit;
  2299. end;
  2300. { All the next optimisations require a next instruction }
  2301. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2302. Exit;
  2303. { Look for:
  2304. mov %reg1,%reg2
  2305. ??? %reg2,r/m
  2306. Change to:
  2307. mov %reg1,%reg2
  2308. ??? %reg1,r/m
  2309. }
  2310. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2311. begin
  2312. CurrentReg := taicpu(p).oper[1]^.reg;
  2313. if RegReadByInstruction(CurrentReg, hp1) and
  2314. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2315. begin
  2316. { A change has occurred, just not in p }
  2317. Result := True;
  2318. TransferUsedRegs(TmpUsedRegs);
  2319. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2320. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2321. { Just in case something didn't get modified (e.g. an
  2322. implicit register) }
  2323. not RegReadByInstruction(CurrentReg, hp1) then
  2324. begin
  2325. { We can remove the original MOV }
  2326. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2327. RemoveCurrentp(p, hp1);
  2328. { UsedRegs got updated by RemoveCurrentp }
  2329. Result := True;
  2330. Exit;
  2331. end;
  2332. { If we know a MOV instruction has become a null operation, we might as well
  2333. get rid of it now to save time. }
  2334. if (taicpu(hp1).opcode = A_MOV) and
  2335. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2336. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2337. { Just being a register is enough to confirm it's a null operation }
  2338. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2339. begin
  2340. Result := True;
  2341. { Speed-up to reduce a pipeline stall... if we had something like...
  2342. movl %eax,%edx
  2343. movw %dx,%ax
  2344. ... the second instruction would change to movw %ax,%ax, but
  2345. given that it is now %ax that's active rather than %eax,
  2346. penalties might occur due to a partial register write, so instead,
  2347. change it to a MOVZX instruction when optimising for speed.
  2348. }
  2349. if not (cs_opt_size in current_settings.optimizerswitches) and
  2350. IsMOVZXAcceptable and
  2351. (taicpu(hp1).opsize < taicpu(p).opsize)
  2352. {$ifdef x86_64}
  2353. { operations already implicitly set the upper 64 bits to zero }
  2354. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2355. {$endif x86_64}
  2356. then
  2357. begin
  2358. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2359. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2360. case taicpu(p).opsize of
  2361. S_W:
  2362. if taicpu(hp1).opsize = S_B then
  2363. taicpu(hp1).opsize := S_BL
  2364. else
  2365. InternalError(2020012911);
  2366. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2367. case taicpu(hp1).opsize of
  2368. S_B:
  2369. taicpu(hp1).opsize := S_BL;
  2370. S_W:
  2371. taicpu(hp1).opsize := S_WL;
  2372. else
  2373. InternalError(2020012912);
  2374. end;
  2375. else
  2376. InternalError(2020012910);
  2377. end;
  2378. taicpu(hp1).opcode := A_MOVZX;
  2379. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2380. end
  2381. else
  2382. begin
  2383. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2384. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2385. RemoveInstruction(hp1);
  2386. { The instruction after what was hp1 is now the immediate next instruction,
  2387. so we can continue to make optimisations if it's present }
  2388. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2389. Exit;
  2390. hp1 := hp2;
  2391. end;
  2392. end;
  2393. end;
  2394. end;
  2395. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2396. overwrites the original destination register. e.g.
  2397. movl ###,%reg2d
  2398. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2399. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2400. }
  2401. if (taicpu(p).oper[1]^.typ = top_reg) and
  2402. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2403. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2404. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2405. begin
  2406. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2407. begin
  2408. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2409. case taicpu(p).oper[0]^.typ of
  2410. top_const:
  2411. { We have something like:
  2412. movb $x, %regb
  2413. movzbl %regb,%regd
  2414. Change to:
  2415. movl $x, %regd
  2416. }
  2417. begin
  2418. case taicpu(hp1).opsize of
  2419. S_BW:
  2420. begin
  2421. convert_mov_value(A_MOVSX, $FF);
  2422. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2423. taicpu(p).opsize := S_W;
  2424. end;
  2425. S_BL:
  2426. begin
  2427. convert_mov_value(A_MOVSX, $FF);
  2428. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2429. taicpu(p).opsize := S_L;
  2430. end;
  2431. S_WL:
  2432. begin
  2433. convert_mov_value(A_MOVSX, $FFFF);
  2434. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2435. taicpu(p).opsize := S_L;
  2436. end;
  2437. {$ifdef x86_64}
  2438. S_BQ:
  2439. begin
  2440. convert_mov_value(A_MOVSX, $FF);
  2441. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2442. taicpu(p).opsize := S_Q;
  2443. end;
  2444. S_WQ:
  2445. begin
  2446. convert_mov_value(A_MOVSX, $FFFF);
  2447. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2448. taicpu(p).opsize := S_Q;
  2449. end;
  2450. S_LQ:
  2451. begin
  2452. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2453. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2454. taicpu(p).opsize := S_Q;
  2455. end;
  2456. {$endif x86_64}
  2457. else
  2458. { If hp1 was a MOV instruction, it should have been
  2459. optimised already }
  2460. InternalError(2020021001);
  2461. end;
  2462. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2463. RemoveInstruction(hp1);
  2464. Result := True;
  2465. Exit;
  2466. end;
  2467. top_ref:
  2468. { We have something like:
  2469. movb mem, %regb
  2470. movzbl %regb,%regd
  2471. Change to:
  2472. movzbl mem, %regd
  2473. }
  2474. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2475. begin
  2476. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2477. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2478. RemoveCurrentP(p, hp1);
  2479. Result:=True;
  2480. Exit;
  2481. end;
  2482. else
  2483. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2484. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2485. Exit;
  2486. end;
  2487. end
  2488. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2489. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2490. optimised }
  2491. else
  2492. begin
  2493. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2494. RemoveCurrentP(p, hp1);
  2495. Result := True;
  2496. Exit;
  2497. end;
  2498. end;
  2499. if (taicpu(hp1).opcode = A_AND) and
  2500. (taicpu(p).oper[1]^.typ = top_reg) and
  2501. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2502. begin
  2503. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2504. begin
  2505. case taicpu(p).opsize of
  2506. S_L:
  2507. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2508. begin
  2509. { Optimize out:
  2510. mov x, %reg
  2511. and ffffffffh, %reg
  2512. }
  2513. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2514. RemoveInstruction(hp1);
  2515. Result:=true;
  2516. exit;
  2517. end;
  2518. S_Q: { TODO: Confirm if this is even possible }
  2519. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2520. begin
  2521. { Optimize out:
  2522. mov x, %reg
  2523. and ffffffffffffffffh, %reg
  2524. }
  2525. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2526. RemoveInstruction(hp1);
  2527. Result:=true;
  2528. exit;
  2529. end;
  2530. else
  2531. ;
  2532. end;
  2533. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2534. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2535. GetNextInstruction(hp1,hp2) and
  2536. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2537. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2538. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2539. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2540. GetNextInstruction(hp2,hp3) and
  2541. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2542. (taicpu(hp3).condition in [C_E,C_NE]) then
  2543. begin
  2544. TransferUsedRegs(TmpUsedRegs);
  2545. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2546. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2547. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2548. begin
  2549. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2550. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2551. taicpu(hp1).opcode:=A_TEST;
  2552. RemoveInstruction(hp2);
  2553. RemoveCurrentP(p, hp1);
  2554. Result:=true;
  2555. exit;
  2556. end;
  2557. end;
  2558. end
  2559. else if IsMOVZXAcceptable and
  2560. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2561. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2562. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2563. then
  2564. begin
  2565. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2566. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2567. case taicpu(p).opsize of
  2568. S_B:
  2569. if (taicpu(hp1).oper[0]^.val = $ff) then
  2570. begin
  2571. { Convert:
  2572. movb x, %regl movb x, %regl
  2573. andw ffh, %regw andl ffh, %regd
  2574. To:
  2575. movzbw x, %regd movzbl x, %regd
  2576. (Identical registers, just different sizes)
  2577. }
  2578. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2579. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2580. case taicpu(hp1).opsize of
  2581. S_W: NewSize := S_BW;
  2582. S_L: NewSize := S_BL;
  2583. {$ifdef x86_64}
  2584. S_Q: NewSize := S_BQ;
  2585. {$endif x86_64}
  2586. else
  2587. InternalError(2018011510);
  2588. end;
  2589. end
  2590. else
  2591. NewSize := S_NO;
  2592. S_W:
  2593. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2594. begin
  2595. { Convert:
  2596. movw x, %regw
  2597. andl ffffh, %regd
  2598. To:
  2599. movzwl x, %regd
  2600. (Identical registers, just different sizes)
  2601. }
  2602. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2603. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2604. case taicpu(hp1).opsize of
  2605. S_L: NewSize := S_WL;
  2606. {$ifdef x86_64}
  2607. S_Q: NewSize := S_WQ;
  2608. {$endif x86_64}
  2609. else
  2610. InternalError(2018011511);
  2611. end;
  2612. end
  2613. else
  2614. NewSize := S_NO;
  2615. else
  2616. NewSize := S_NO;
  2617. end;
  2618. if NewSize <> S_NO then
  2619. begin
  2620. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2621. { The actual optimization }
  2622. taicpu(p).opcode := A_MOVZX;
  2623. taicpu(p).changeopsize(NewSize);
  2624. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2625. { Safeguard if "and" is followed by a conditional command }
  2626. TransferUsedRegs(TmpUsedRegs);
  2627. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2628. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2629. begin
  2630. { At this point, the "and" command is effectively equivalent to
  2631. "test %reg,%reg". This will be handled separately by the
  2632. Peephole Optimizer. [Kit] }
  2633. DebugMsg(SPeepholeOptimization + PreMessage +
  2634. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2635. end
  2636. else
  2637. begin
  2638. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2639. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2640. RemoveInstruction(hp1);
  2641. end;
  2642. Result := True;
  2643. Exit;
  2644. end;
  2645. end;
  2646. end;
  2647. if (taicpu(hp1).opcode = A_OR) and
  2648. (taicpu(p).oper[1]^.typ = top_reg) and
  2649. MatchOperand(taicpu(p).oper[0]^, 0) and
  2650. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2651. begin
  2652. { mov 0, %reg
  2653. or ###,%reg
  2654. Change to (only if the flags are not used):
  2655. mov ###,%reg
  2656. }
  2657. TransferUsedRegs(TmpUsedRegs);
  2658. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2659. DoOptimisation := True;
  2660. { Even if the flags are used, we might be able to do the optimisation
  2661. if the conditions are predictable }
  2662. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2663. begin
  2664. { Only perform if ### = %reg (the same register) or equal to 0,
  2665. so %reg is guaranteed to still have a value of zero }
  2666. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2667. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2668. begin
  2669. hp2 := hp1;
  2670. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2671. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2672. GetNextInstruction(hp2, hp3) do
  2673. begin
  2674. { Don't continue modifying if the flags state is getting changed }
  2675. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2676. Break;
  2677. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2678. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2679. begin
  2680. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2681. begin
  2682. { Condition is always true }
  2683. case taicpu(hp3).opcode of
  2684. A_Jcc:
  2685. begin
  2686. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2687. { Check for jump shortcuts before we destroy the condition }
  2688. DoJumpOptimizations(hp3, TempBool);
  2689. MakeUnconditional(taicpu(hp3));
  2690. Result := True;
  2691. end;
  2692. A_CMOVcc:
  2693. begin
  2694. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2695. taicpu(hp3).opcode := A_MOV;
  2696. taicpu(hp3).condition := C_None;
  2697. Result := True;
  2698. end;
  2699. A_SETcc:
  2700. begin
  2701. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2702. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2703. taicpu(hp3).opcode := A_MOV;
  2704. taicpu(hp3).ops := 2;
  2705. taicpu(hp3).condition := C_None;
  2706. taicpu(hp3).opsize := S_B;
  2707. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2708. taicpu(hp3).loadconst(0, 1);
  2709. Result := True;
  2710. end;
  2711. else
  2712. InternalError(2021090701);
  2713. end;
  2714. end
  2715. 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
  2716. begin
  2717. { Condition is always false }
  2718. case taicpu(hp3).opcode of
  2719. A_Jcc:
  2720. begin
  2721. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2722. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2723. RemoveInstruction(hp3);
  2724. Result := True;
  2725. { Since hp3 was deleted, hp2 must not be updated }
  2726. Continue;
  2727. end;
  2728. A_CMOVcc:
  2729. begin
  2730. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2731. RemoveInstruction(hp3);
  2732. Result := True;
  2733. { Since hp3 was deleted, hp2 must not be updated }
  2734. Continue;
  2735. end;
  2736. A_SETcc:
  2737. begin
  2738. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2739. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2740. taicpu(hp3).opcode := A_MOV;
  2741. taicpu(hp3).ops := 2;
  2742. taicpu(hp3).condition := C_None;
  2743. taicpu(hp3).opsize := S_B;
  2744. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2745. taicpu(hp3).loadconst(0, 0);
  2746. Result := True;
  2747. end;
  2748. else
  2749. InternalError(2021090702);
  2750. end;
  2751. end
  2752. else
  2753. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2754. DoOptimisation := False;
  2755. end;
  2756. hp2 := hp3;
  2757. end;
  2758. { Flags are still in use - don't optimise }
  2759. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2760. DoOptimisation := False;
  2761. end
  2762. else
  2763. DoOptimisation := False;
  2764. end;
  2765. if DoOptimisation then
  2766. begin
  2767. {$ifdef x86_64}
  2768. { OR only supports 32-bit sign-extended constants for 64-bit
  2769. instructions, so compensate for this if the constant is
  2770. encoded as a value greater than or equal to 2^31 }
  2771. if (taicpu(hp1).opsize = S_Q) and
  2772. (taicpu(hp1).oper[0]^.typ = top_const) and
  2773. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2774. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2775. {$endif x86_64}
  2776. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2777. taicpu(hp1).opcode := A_MOV;
  2778. RemoveCurrentP(p, hp1);
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. { Next instruction is also a MOV ? }
  2784. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2785. begin
  2786. if MatchOpType(taicpu(p), top_const, top_ref) and
  2787. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2788. TryConstMerge(p, hp1) then
  2789. begin
  2790. Result := True;
  2791. { In case we have four byte writes in a row, check for 2 more
  2792. right now so we don't have to wait for another iteration of
  2793. pass 1
  2794. }
  2795. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2796. case taicpu(p).opsize of
  2797. S_W:
  2798. begin
  2799. if GetNextInstruction(p, hp1) and
  2800. MatchInstruction(hp1, A_MOV, [S_B]) and
  2801. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2802. GetNextInstruction(hp1, hp2) and
  2803. MatchInstruction(hp2, A_MOV, [S_B]) and
  2804. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2805. { Try to merge the two bytes }
  2806. TryConstMerge(hp1, hp2) then
  2807. { Now try to merge the two words (hp2 will get deleted) }
  2808. TryConstMerge(p, hp1);
  2809. end;
  2810. S_L:
  2811. begin
  2812. { Though this only really benefits x86_64 and not i386, it
  2813. gets a potential optimisation done faster and hence
  2814. reduces the number of times OptPass1MOV is entered }
  2815. if GetNextInstruction(p, hp1) and
  2816. MatchInstruction(hp1, A_MOV, [S_W]) and
  2817. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2818. GetNextInstruction(hp1, hp2) and
  2819. MatchInstruction(hp2, A_MOV, [S_W]) and
  2820. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2821. { Try to merge the two words }
  2822. TryConstMerge(hp1, hp2) then
  2823. { This will always fail on i386, so don't bother
  2824. calling it unless we're doing x86_64 }
  2825. {$ifdef x86_64}
  2826. { Now try to merge the two longwords (hp2 will get deleted) }
  2827. TryConstMerge(p, hp1)
  2828. {$endif x86_64}
  2829. ;
  2830. end;
  2831. else
  2832. ;
  2833. end;
  2834. Exit;
  2835. end;
  2836. if (taicpu(p).oper[1]^.typ = top_reg) and
  2837. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2838. begin
  2839. CurrentReg := taicpu(p).oper[1]^.reg;
  2840. TransferUsedRegs(TmpUsedRegs);
  2841. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2842. { we have
  2843. mov x, %treg
  2844. mov %treg, y
  2845. }
  2846. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2847. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2848. { we've got
  2849. mov x, %treg
  2850. mov %treg, y
  2851. with %treg is not used after }
  2852. case taicpu(p).oper[0]^.typ Of
  2853. { top_reg is covered by DeepMOVOpt }
  2854. top_const:
  2855. begin
  2856. { change
  2857. mov const, %treg
  2858. mov %treg, y
  2859. to
  2860. mov const, y
  2861. }
  2862. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2863. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2864. begin
  2865. if taicpu(hp1).oper[1]^.typ=top_reg then
  2866. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2867. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2868. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2869. RemoveInstruction(hp1);
  2870. Result:=true;
  2871. Exit;
  2872. end;
  2873. end;
  2874. top_ref:
  2875. case taicpu(hp1).oper[1]^.typ of
  2876. top_reg:
  2877. begin
  2878. { change
  2879. mov mem, %treg
  2880. mov %treg, %reg
  2881. to
  2882. mov mem, %reg"
  2883. }
  2884. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2885. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2886. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2887. RemoveInstruction(hp1);
  2888. Result:=true;
  2889. Exit;
  2890. end;
  2891. top_ref:
  2892. begin
  2893. {$ifdef x86_64}
  2894. { Look for the following to simplify:
  2895. mov x(mem1), %reg
  2896. mov %reg, y(mem2)
  2897. mov x+8(mem1), %reg
  2898. mov %reg, y+8(mem2)
  2899. Change to:
  2900. movdqu x(mem1), %xmmreg
  2901. movdqu %xmmreg, y(mem2)
  2902. }
  2903. SourceRef := taicpu(p).oper[0]^.ref^;
  2904. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2905. if (taicpu(p).opsize = S_Q) and
  2906. GetNextInstruction(hp1, hp2) and
  2907. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2908. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2909. begin
  2910. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2911. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2912. Inc(SourceRef.offset, 8);
  2913. if UseAVX then
  2914. begin
  2915. MovAligned := A_VMOVDQA;
  2916. MovUnaligned := A_VMOVDQU;
  2917. end
  2918. else
  2919. begin
  2920. MovAligned := A_MOVDQA;
  2921. MovUnaligned := A_MOVDQU;
  2922. end;
  2923. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2924. begin
  2925. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2926. Inc(TargetRef.offset, 8);
  2927. if GetNextInstruction(hp2, hp3) and
  2928. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2929. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2930. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2931. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2932. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2933. begin
  2934. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2935. if CurrentReg <> NR_NO then
  2936. begin
  2937. { Remember that the offsets are 8 ahead }
  2938. if ((SourceRef.offset mod 16) = 8) and
  2939. (
  2940. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2941. (SourceRef.base = current_procinfo.framepointer) or
  2942. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2943. ) then
  2944. taicpu(p).opcode := MovAligned
  2945. else
  2946. taicpu(p).opcode := MovUnaligned;
  2947. taicpu(p).opsize := S_XMM;
  2948. taicpu(p).oper[1]^.reg := CurrentReg;
  2949. if ((TargetRef.offset mod 16) = 8) and
  2950. (
  2951. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2952. (TargetRef.base = current_procinfo.framepointer) or
  2953. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2954. ) then
  2955. taicpu(hp1).opcode := MovAligned
  2956. else
  2957. taicpu(hp1).opcode := MovUnaligned;
  2958. taicpu(hp1).opsize := S_XMM;
  2959. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2960. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2961. RemoveInstruction(hp2);
  2962. RemoveInstruction(hp3);
  2963. Result := True;
  2964. Exit;
  2965. end;
  2966. end;
  2967. end
  2968. else
  2969. begin
  2970. { See if the next references are 8 less rather than 8 greater }
  2971. Dec(SourceRef.offset, 16); { -8 the other way }
  2972. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2973. begin
  2974. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2975. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2976. if GetNextInstruction(hp2, hp3) and
  2977. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2978. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2979. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2980. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2981. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2982. begin
  2983. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2984. if CurrentReg <> NR_NO then
  2985. begin
  2986. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2987. if ((SourceRef.offset mod 16) = 0) and
  2988. (
  2989. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2990. (SourceRef.base = current_procinfo.framepointer) or
  2991. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2992. ) then
  2993. taicpu(hp2).opcode := MovAligned
  2994. else
  2995. taicpu(hp2).opcode := MovUnaligned;
  2996. taicpu(hp2).opsize := S_XMM;
  2997. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2998. if ((TargetRef.offset mod 16) = 0) and
  2999. (
  3000. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3001. (TargetRef.base = current_procinfo.framepointer) or
  3002. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3003. ) then
  3004. taicpu(hp3).opcode := MovAligned
  3005. else
  3006. taicpu(hp3).opcode := MovUnaligned;
  3007. taicpu(hp3).opsize := S_XMM;
  3008. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3009. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3010. RemoveInstruction(hp1);
  3011. RemoveCurrentP(p, hp2);
  3012. Result := True;
  3013. Exit;
  3014. end;
  3015. end;
  3016. end;
  3017. end;
  3018. end;
  3019. {$endif x86_64}
  3020. end;
  3021. else
  3022. { The write target should be a reg or a ref }
  3023. InternalError(2021091601);
  3024. end;
  3025. else
  3026. ;
  3027. end
  3028. else
  3029. { %treg is used afterwards, but all eventualities
  3030. other than the first MOV instruction being a constant
  3031. are covered by DeepMOVOpt, so only check for that }
  3032. if (taicpu(p).oper[0]^.typ = top_const) and
  3033. (
  3034. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3035. not (cs_opt_size in current_settings.optimizerswitches) or
  3036. (taicpu(hp1).opsize = S_B)
  3037. ) and
  3038. (
  3039. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3040. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3041. ) then
  3042. begin
  3043. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3044. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3045. end;
  3046. end;
  3047. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3048. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3049. { mov reg1, mem1 or mov mem1, reg1
  3050. mov mem2, reg2 mov reg2, mem2}
  3051. begin
  3052. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3053. { mov reg1, mem1 or mov mem1, reg1
  3054. mov mem2, reg1 mov reg2, mem1}
  3055. begin
  3056. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3057. { Removes the second statement from
  3058. mov reg1, mem1/reg2
  3059. mov mem1/reg2, reg1 }
  3060. begin
  3061. if taicpu(p).oper[0]^.typ=top_reg then
  3062. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3063. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3064. RemoveInstruction(hp1);
  3065. Result:=true;
  3066. exit;
  3067. end
  3068. else
  3069. begin
  3070. TransferUsedRegs(TmpUsedRegs);
  3071. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3072. if (taicpu(p).oper[1]^.typ = top_ref) and
  3073. { mov reg1, mem1
  3074. mov mem2, reg1 }
  3075. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3076. GetNextInstruction(hp1, hp2) and
  3077. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3078. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3079. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3080. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3081. { change to
  3082. mov reg1, mem1 mov reg1, mem1
  3083. mov mem2, reg1 cmp reg1, mem2
  3084. cmp mem1, reg1
  3085. }
  3086. begin
  3087. RemoveInstruction(hp2);
  3088. taicpu(hp1).opcode := A_CMP;
  3089. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3090. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3091. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3092. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3093. end;
  3094. end;
  3095. end
  3096. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3097. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3098. begin
  3099. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3100. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3101. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3102. end
  3103. else
  3104. begin
  3105. TransferUsedRegs(TmpUsedRegs);
  3106. if GetNextInstruction(hp1, hp2) and
  3107. MatchOpType(taicpu(p),top_ref,top_reg) and
  3108. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3109. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3110. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3111. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3112. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3113. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3114. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3115. { mov mem1, %reg1
  3116. mov %reg1, mem2
  3117. mov mem2, reg2
  3118. to:
  3119. mov mem1, reg2
  3120. mov reg2, mem2}
  3121. begin
  3122. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3123. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3124. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3125. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3126. RemoveInstruction(hp2);
  3127. Result := True;
  3128. end
  3129. {$ifdef i386}
  3130. { this is enabled for i386 only, as the rules to create the reg sets below
  3131. are too complicated for x86-64, so this makes this code too error prone
  3132. on x86-64
  3133. }
  3134. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3135. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3136. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3137. { mov mem1, reg1 mov mem1, reg1
  3138. mov reg1, mem2 mov reg1, mem2
  3139. mov mem2, reg2 mov mem2, reg1
  3140. to: to:
  3141. mov mem1, reg1 mov mem1, reg1
  3142. mov mem1, reg2 mov reg1, mem2
  3143. mov reg1, mem2
  3144. or (if mem1 depends on reg1
  3145. and/or if mem2 depends on reg2)
  3146. to:
  3147. mov mem1, reg1
  3148. mov reg1, mem2
  3149. mov reg1, reg2
  3150. }
  3151. begin
  3152. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3153. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3154. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3155. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3156. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3157. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3158. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3159. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3160. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3161. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3162. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3163. end
  3164. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3165. begin
  3166. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3167. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3168. end
  3169. else
  3170. begin
  3171. RemoveInstruction(hp2);
  3172. end
  3173. {$endif i386}
  3174. ;
  3175. end;
  3176. end
  3177. { movl [mem1],reg1
  3178. movl [mem1],reg2
  3179. to
  3180. movl [mem1],reg1
  3181. movl reg1,reg2
  3182. }
  3183. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3184. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3185. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3186. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3187. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3188. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3189. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3190. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3191. begin
  3192. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3193. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3194. end;
  3195. { movl const1,[mem1]
  3196. movl [mem1],reg1
  3197. to
  3198. movl const1,reg1
  3199. movl reg1,[mem1]
  3200. }
  3201. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3202. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3203. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3204. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3205. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3206. begin
  3207. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3208. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3209. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3210. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3211. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3212. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3213. Result:=true;
  3214. exit;
  3215. end;
  3216. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3217. end;
  3218. { search further than the next instruction for a mov (as long as it's not a jump) }
  3219. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3220. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3221. (taicpu(p).oper[1]^.typ = top_reg) and
  3222. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3223. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3224. begin
  3225. { we work with hp2 here, so hp1 can be still used later on when
  3226. checking for GetNextInstruction_p }
  3227. hp3 := hp1;
  3228. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3229. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3230. { Saves on a large number of dereferences }
  3231. ActiveReg := taicpu(p).oper[1]^.reg;
  3232. TransferUsedRegs(TmpUsedRegs);
  3233. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3234. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3235. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3236. (hp2.typ=ait_instruction) do
  3237. begin
  3238. case taicpu(hp2).opcode of
  3239. A_POP:
  3240. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3241. begin
  3242. if not CrossJump and
  3243. not RegUsedBetween(ActiveReg, p, hp2) then
  3244. begin
  3245. { We can remove the original MOV since the register
  3246. wasn't used between it and its popping from the stack }
  3247. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3248. RemoveCurrentp(p, hp1);
  3249. Result := True;
  3250. Exit;
  3251. end;
  3252. { Can't go any further }
  3253. Break;
  3254. end;
  3255. A_MOV:
  3256. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3257. ((taicpu(p).oper[0]^.typ=top_const) or
  3258. ((taicpu(p).oper[0]^.typ=top_reg) and
  3259. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3260. )
  3261. ) then
  3262. begin
  3263. { we have
  3264. mov x, %treg
  3265. mov %treg, y
  3266. }
  3267. { We don't need to call UpdateUsedRegs for every instruction between
  3268. p and hp2 because the register we're concerned about will not
  3269. become deallocated (otherwise GetNextInstructionUsingReg would
  3270. have stopped at an earlier instruction). [Kit] }
  3271. TempRegUsed :=
  3272. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3273. RegReadByInstruction(ActiveReg, hp3) or
  3274. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3275. case taicpu(p).oper[0]^.typ Of
  3276. top_reg:
  3277. begin
  3278. { change
  3279. mov %reg, %treg
  3280. mov %treg, y
  3281. to
  3282. mov %reg, y
  3283. }
  3284. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3285. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3286. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3287. begin
  3288. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3289. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3290. if TempRegUsed then
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3293. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3294. { Set the start of the next GetNextInstructionUsingRegCond search
  3295. to start at the entry right before hp2 (which is about to be removed) }
  3296. hp3 := tai(hp2.Previous);
  3297. RemoveInstruction(hp2);
  3298. { See if there's more we can optimise }
  3299. Continue;
  3300. end
  3301. else
  3302. begin
  3303. RemoveInstruction(hp2);
  3304. { We can remove the original MOV too }
  3305. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3306. RemoveCurrentP(p, hp1);
  3307. Result:=true;
  3308. Exit;
  3309. end;
  3310. end
  3311. else
  3312. begin
  3313. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3314. taicpu(hp2).loadReg(0, CurrentReg);
  3315. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3316. { Check to see if the register also appears in the reference }
  3317. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3318. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3319. { Don't remove the first instruction if the temporary register is in use }
  3320. if not TempRegUsed and
  3321. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3322. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3323. begin
  3324. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3325. RemoveCurrentP(p, hp1);
  3326. Result:=true;
  3327. Exit;
  3328. end;
  3329. { No need to set Result to True here. If there's another instruction later
  3330. on that can be optimised, it will be detected when the main Pass 1 loop
  3331. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3332. end;
  3333. end;
  3334. top_const:
  3335. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3336. begin
  3337. { change
  3338. mov const, %treg
  3339. mov %treg, y
  3340. to
  3341. mov const, y
  3342. }
  3343. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3344. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3345. begin
  3346. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3347. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3348. if TempRegUsed then
  3349. begin
  3350. { Don't remove the first instruction if the temporary register is in use }
  3351. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3352. { No need to set Result to True. If there's another instruction later on
  3353. that can be optimised, it will be detected when the main Pass 1 loop
  3354. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3355. end
  3356. else
  3357. begin
  3358. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3359. RemoveCurrentP(p, hp1);
  3360. Result:=true;
  3361. Exit;
  3362. end;
  3363. end;
  3364. end;
  3365. else
  3366. Internalerror(2019103001);
  3367. end;
  3368. end
  3369. else
  3370. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3371. begin
  3372. if not CrossJump and
  3373. not RegUsedBetween(ActiveReg, p, hp2) and
  3374. not RegReadByInstruction(ActiveReg, hp2) then
  3375. begin
  3376. { Register is not used before it is overwritten }
  3377. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3378. RemoveCurrentp(p, hp1);
  3379. Result := True;
  3380. Exit;
  3381. end;
  3382. if (taicpu(p).oper[0]^.typ = top_const) and
  3383. (taicpu(hp2).oper[0]^.typ = top_const) then
  3384. begin
  3385. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3386. begin
  3387. { Same value - register hasn't changed }
  3388. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3389. RemoveInstruction(hp2);
  3390. Result := True;
  3391. { See if there's more we can optimise }
  3392. Continue;
  3393. end;
  3394. end;
  3395. end;
  3396. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3397. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3398. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3399. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3400. begin
  3401. {
  3402. Change from:
  3403. mov ###, %reg
  3404. ...
  3405. movs/z %reg,%reg (Same register, just different sizes)
  3406. To:
  3407. movs/z ###, %reg (Longer version)
  3408. ...
  3409. (remove)
  3410. }
  3411. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3412. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3413. { Keep the first instruction as mov if ### is a constant }
  3414. if taicpu(p).oper[0]^.typ = top_const then
  3415. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3416. else
  3417. begin
  3418. taicpu(p).opcode := taicpu(hp2).opcode;
  3419. taicpu(p).opsize := taicpu(hp2).opsize;
  3420. end;
  3421. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3422. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3423. RemoveInstruction(hp2);
  3424. Result := True;
  3425. Exit;
  3426. end;
  3427. else
  3428. { Move down to the MatchOpType if-block below };
  3429. end;
  3430. { Also catches MOV/S/Z instructions that aren't modified }
  3431. if taicpu(p).oper[0]^.typ = top_reg then
  3432. begin
  3433. CurrentReg := taicpu(p).oper[0]^.reg;
  3434. if
  3435. not RegModifiedByInstruction(CurrentReg, hp3) and
  3436. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3437. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3438. begin
  3439. Result := True;
  3440. { Just in case something didn't get modified (e.g. an
  3441. implicit register). Also, if it does read from this
  3442. register, then there's no longer an advantage to
  3443. changing the register on subsequent instructions.}
  3444. if not RegReadByInstruction(ActiveReg, hp2) then
  3445. begin
  3446. { If a conditional jump was crossed, do not delete
  3447. the original MOV no matter what }
  3448. if not CrossJump and
  3449. { RegEndOfLife returns True if the register is
  3450. deallocated before the next instruction or has
  3451. been loaded with a new value }
  3452. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3453. begin
  3454. { We can remove the original MOV }
  3455. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3456. RemoveCurrentp(p, hp1);
  3457. Exit;
  3458. end;
  3459. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3460. begin
  3461. { See if there's more we can optimise }
  3462. hp3 := hp2;
  3463. Continue;
  3464. end;
  3465. end;
  3466. end;
  3467. end;
  3468. { Break out of the while loop under normal circumstances }
  3469. Break;
  3470. end;
  3471. end;
  3472. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3473. (taicpu(p).oper[1]^.typ = top_reg) and
  3474. (taicpu(p).opsize = S_L) and
  3475. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3476. (taicpu(hp2).opcode = A_AND) and
  3477. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3478. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3479. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3480. ) then
  3481. begin
  3482. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3483. begin
  3484. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3485. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3486. begin
  3487. { Optimize out:
  3488. mov x, %reg
  3489. and ffffffffh, %reg
  3490. }
  3491. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3492. RemoveInstruction(hp2);
  3493. Result:=true;
  3494. exit;
  3495. end;
  3496. end;
  3497. end;
  3498. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3499. x >= RetOffset) as it doesn't do anything (it writes either to a
  3500. parameter or to the temporary storage room for the function
  3501. result)
  3502. }
  3503. if IsExitCode(hp1) and
  3504. (taicpu(p).oper[1]^.typ = top_ref) and
  3505. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3506. (
  3507. (
  3508. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3509. not (
  3510. assigned(current_procinfo.procdef.funcretsym) and
  3511. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3512. )
  3513. ) or
  3514. { Also discard writes to the stack that are below the base pointer,
  3515. as this is temporary storage rather than a function result on the
  3516. stack, say. }
  3517. (
  3518. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3519. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3520. )
  3521. ) then
  3522. begin
  3523. RemoveCurrentp(p, hp1);
  3524. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3525. RemoveLastDeallocForFuncRes(p);
  3526. Result:=true;
  3527. exit;
  3528. end;
  3529. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3530. begin
  3531. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3532. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3533. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3534. begin
  3535. { change
  3536. mov reg1, mem1
  3537. test/cmp x, mem1
  3538. to
  3539. mov reg1, mem1
  3540. test/cmp x, reg1
  3541. }
  3542. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3543. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3544. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3545. Result := True;
  3546. Exit;
  3547. end;
  3548. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3549. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3550. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3551. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3552. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3553. (
  3554. (
  3555. (taicpu(hp1).opcode = A_TEST)
  3556. ) or (
  3557. (taicpu(hp1).opcode = A_CMP) and
  3558. { A sanity check more than anything }
  3559. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3560. )
  3561. ) then
  3562. begin
  3563. { change
  3564. mov mem, %reg
  3565. cmp/test x, %reg / test %reg,%reg
  3566. (reg deallocated)
  3567. to
  3568. cmp/test x, mem / cmp 0, mem
  3569. }
  3570. TransferUsedRegs(TmpUsedRegs);
  3571. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3572. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3573. begin
  3574. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3575. if (taicpu(hp1).opcode = A_TEST) and
  3576. (
  3577. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3578. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3579. ) then
  3580. begin
  3581. taicpu(hp1).opcode := A_CMP;
  3582. taicpu(hp1).loadconst(0, 0);
  3583. end;
  3584. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3585. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3586. RemoveCurrentP(p, hp1);
  3587. Result := True;
  3588. Exit;
  3589. end;
  3590. end;
  3591. end;
  3592. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3593. { If the flags register is in use, don't change the instruction to an
  3594. ADD otherwise this will scramble the flags. [Kit] }
  3595. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3596. begin
  3597. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3598. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3599. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3600. ) or
  3601. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3602. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3603. )
  3604. ) then
  3605. { mov reg1,ref
  3606. lea reg2,[reg1,reg2]
  3607. to
  3608. add reg2,ref}
  3609. begin
  3610. TransferUsedRegs(TmpUsedRegs);
  3611. { reg1 may not be used afterwards }
  3612. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3613. begin
  3614. Taicpu(hp1).opcode:=A_ADD;
  3615. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3616. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3617. RemoveCurrentp(p, hp1);
  3618. result:=true;
  3619. exit;
  3620. end;
  3621. end;
  3622. { If the LEA instruction can be converted into an arithmetic instruction,
  3623. it may be possible to then fold it in the next optimisation, otherwise
  3624. there's nothing more that can be optimised here. }
  3625. if not ConvertLEA(taicpu(hp1)) then
  3626. Exit;
  3627. end;
  3628. if (taicpu(p).oper[1]^.typ = top_reg) and
  3629. (hp1.typ = ait_instruction) and
  3630. GetNextInstruction(hp1, hp2) and
  3631. MatchInstruction(hp2,A_MOV,[]) and
  3632. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3633. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3634. (
  3635. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3636. {$ifdef x86_64}
  3637. or
  3638. (
  3639. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3640. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3641. )
  3642. {$endif x86_64}
  3643. ) then
  3644. begin
  3645. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3646. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3647. { change movsX/movzX reg/ref, reg2
  3648. add/sub/or/... reg3/$const, reg2
  3649. mov reg2 reg/ref
  3650. dealloc reg2
  3651. to
  3652. add/sub/or/... reg3/$const, reg/ref }
  3653. begin
  3654. TransferUsedRegs(TmpUsedRegs);
  3655. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3656. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3657. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3658. begin
  3659. { by example:
  3660. movswl %si,%eax movswl %si,%eax p
  3661. decl %eax addl %edx,%eax hp1
  3662. movw %ax,%si movw %ax,%si hp2
  3663. ->
  3664. movswl %si,%eax movswl %si,%eax p
  3665. decw %eax addw %edx,%eax hp1
  3666. movw %ax,%si movw %ax,%si hp2
  3667. }
  3668. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3669. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3670. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3671. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3672. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3673. {
  3674. ->
  3675. movswl %si,%eax movswl %si,%eax p
  3676. decw %si addw %dx,%si hp1
  3677. movw %ax,%si movw %ax,%si hp2
  3678. }
  3679. case taicpu(hp1).ops of
  3680. 1:
  3681. begin
  3682. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3683. if taicpu(hp1).oper[0]^.typ=top_reg then
  3684. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3685. end;
  3686. 2:
  3687. begin
  3688. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3689. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3690. (taicpu(hp1).opcode<>A_SHL) and
  3691. (taicpu(hp1).opcode<>A_SHR) and
  3692. (taicpu(hp1).opcode<>A_SAR) then
  3693. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3694. end;
  3695. else
  3696. internalerror(2008042701);
  3697. end;
  3698. {
  3699. ->
  3700. decw %si addw %dx,%si p
  3701. }
  3702. RemoveInstruction(hp2);
  3703. RemoveCurrentP(p, hp1);
  3704. Result:=True;
  3705. Exit;
  3706. end;
  3707. end;
  3708. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3709. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3710. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3711. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3712. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3713. )
  3714. {$ifdef i386}
  3715. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3716. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3717. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3718. {$endif i386}
  3719. then
  3720. { change movsX/movzX reg/ref, reg2
  3721. add/sub/or/... regX/$const, reg2
  3722. mov reg2, reg3
  3723. dealloc reg2
  3724. to
  3725. movsX/movzX reg/ref, reg3
  3726. add/sub/or/... reg3/$const, reg3
  3727. }
  3728. begin
  3729. TransferUsedRegs(TmpUsedRegs);
  3730. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3731. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3732. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3733. begin
  3734. { by example:
  3735. movswl %si,%eax movswl %si,%eax p
  3736. decl %eax addl %edx,%eax hp1
  3737. movw %ax,%si movw %ax,%si hp2
  3738. ->
  3739. movswl %si,%eax movswl %si,%eax p
  3740. decw %eax addw %edx,%eax hp1
  3741. movw %ax,%si movw %ax,%si hp2
  3742. }
  3743. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3744. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3745. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3746. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3747. { limit size of constants as well to avoid assembler errors, but
  3748. check opsize to avoid overflow when left shifting the 1 }
  3749. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3750. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3751. {$ifdef x86_64}
  3752. { Be careful of, for example:
  3753. movl %reg1,%reg2
  3754. addl %reg3,%reg2
  3755. movq %reg2,%reg4
  3756. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3757. }
  3758. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3759. begin
  3760. taicpu(hp2).changeopsize(S_L);
  3761. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3762. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3763. end;
  3764. {$endif x86_64}
  3765. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3766. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3767. if taicpu(p).oper[0]^.typ=top_reg then
  3768. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3769. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3770. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3771. {
  3772. ->
  3773. movswl %si,%eax movswl %si,%eax p
  3774. decw %si addw %dx,%si hp1
  3775. movw %ax,%si movw %ax,%si hp2
  3776. }
  3777. case taicpu(hp1).ops of
  3778. 1:
  3779. begin
  3780. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3781. if taicpu(hp1).oper[0]^.typ=top_reg then
  3782. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3783. end;
  3784. 2:
  3785. begin
  3786. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3787. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3788. (taicpu(hp1).opcode<>A_SHL) and
  3789. (taicpu(hp1).opcode<>A_SHR) and
  3790. (taicpu(hp1).opcode<>A_SAR) then
  3791. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3792. end;
  3793. else
  3794. internalerror(2018111801);
  3795. end;
  3796. {
  3797. ->
  3798. decw %si addw %dx,%si p
  3799. }
  3800. RemoveInstruction(hp2);
  3801. end;
  3802. end;
  3803. end;
  3804. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3805. GetNextInstruction(hp1, hp2) and
  3806. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3807. MatchOperand(Taicpu(p).oper[0]^,0) and
  3808. (Taicpu(p).oper[1]^.typ = top_reg) and
  3809. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3810. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3811. { mov reg1,0
  3812. bts reg1,operand1 --> mov reg1,operand2
  3813. or reg1,operand2 bts reg1,operand1}
  3814. begin
  3815. Taicpu(hp2).opcode:=A_MOV;
  3816. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3817. asml.remove(hp1);
  3818. insertllitem(hp2,hp2.next,hp1);
  3819. RemoveCurrentp(p, hp1);
  3820. Result:=true;
  3821. exit;
  3822. end;
  3823. {
  3824. mov ref,reg0
  3825. <op> reg0,reg1
  3826. dealloc reg0
  3827. to
  3828. <op> ref,reg1
  3829. }
  3830. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3831. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3832. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3833. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3834. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3835. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3836. begin
  3837. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3838. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3839. RemoveCurrentp(p, hp1);
  3840. Result:=true;
  3841. exit;
  3842. end;
  3843. {$ifdef x86_64}
  3844. { Convert:
  3845. movq x(ref),%reg64
  3846. shrq y,%reg64
  3847. To:
  3848. movq x+4(ref),%reg32
  3849. shrq y-32,%reg32 (Remove if y = 32)
  3850. }
  3851. if (taicpu(p).opsize = S_Q) and
  3852. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3853. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3854. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3855. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3856. (taicpu(hp1).oper[0]^.val >= 32) and
  3857. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3858. begin
  3859. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3860. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3861. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3862. { Convert to 32-bit }
  3863. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3864. taicpu(p).opsize := S_L;
  3865. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3866. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3867. if (taicpu(hp1).oper[0]^.val = 32) then
  3868. begin
  3869. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3870. RemoveInstruction(hp1);
  3871. end
  3872. else
  3873. begin
  3874. { This will potentially open up more arithmetic operations since
  3875. the peephole optimizer now has a big hint that only the lower
  3876. 32 bits are currently in use (and opcodes are smaller in size) }
  3877. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3878. taicpu(hp1).opsize := S_L;
  3879. Dec(taicpu(hp1).oper[0]^.val, 32);
  3880. DebugMsg(SPeepholeOptimization + PreMessage +
  3881. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3882. end;
  3883. Result := True;
  3884. Exit;
  3885. end;
  3886. {$endif x86_64}
  3887. end;
  3888. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3889. var
  3890. hp1 : tai;
  3891. begin
  3892. Result:=false;
  3893. if taicpu(p).ops <> 2 then
  3894. exit;
  3895. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3896. GetNextInstruction(p,hp1) then
  3897. begin
  3898. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3899. (taicpu(hp1).ops = 2) then
  3900. begin
  3901. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3902. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3903. { movXX reg1, mem1 or movXX mem1, reg1
  3904. movXX mem2, reg2 movXX reg2, mem2}
  3905. begin
  3906. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3907. { movXX reg1, mem1 or movXX mem1, reg1
  3908. movXX mem2, reg1 movXX reg2, mem1}
  3909. begin
  3910. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3911. begin
  3912. { Removes the second statement from
  3913. movXX reg1, mem1/reg2
  3914. movXX mem1/reg2, reg1
  3915. }
  3916. if taicpu(p).oper[0]^.typ=top_reg then
  3917. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3918. { Removes the second statement from
  3919. movXX mem1/reg1, reg2
  3920. movXX reg2, mem1/reg1
  3921. }
  3922. if (taicpu(p).oper[1]^.typ=top_reg) and
  3923. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3924. begin
  3925. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3926. RemoveInstruction(hp1);
  3927. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3928. Result:=true;
  3929. exit;
  3930. end
  3931. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3932. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3933. begin
  3934. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3935. RemoveInstruction(hp1);
  3936. Result:=true;
  3937. exit;
  3938. end;
  3939. end
  3940. end;
  3941. end;
  3942. end;
  3943. end;
  3944. end;
  3945. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3946. var
  3947. hp1 : tai;
  3948. begin
  3949. result:=false;
  3950. { replace
  3951. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3952. MovX %mreg2,%mreg1
  3953. dealloc %mreg2
  3954. by
  3955. <Op>X %mreg2,%mreg1
  3956. ?
  3957. }
  3958. if GetNextInstruction(p,hp1) and
  3959. { we mix single and double opperations here because we assume that the compiler
  3960. generates vmovapd only after double operations and vmovaps only after single operations }
  3961. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3962. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3963. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3964. (taicpu(p).oper[0]^.typ=top_reg) then
  3965. begin
  3966. TransferUsedRegs(TmpUsedRegs);
  3967. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3968. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3969. begin
  3970. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3971. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3972. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3973. RemoveInstruction(hp1);
  3974. result:=true;
  3975. end;
  3976. end;
  3977. end;
  3978. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3979. var
  3980. hp1, p_label, p_dist, hp1_dist: tai;
  3981. JumpLabel, JumpLabel_dist: TAsmLabel;
  3982. FirstValue, SecondValue: TCGInt;
  3983. begin
  3984. Result := False;
  3985. if (taicpu(p).oper[0]^.typ = top_const) and
  3986. (taicpu(p).oper[0]^.val <> -1) then
  3987. begin
  3988. { Convert unsigned maximum constants to -1 to aid optimisation }
  3989. case taicpu(p).opsize of
  3990. S_B:
  3991. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  3992. begin
  3993. taicpu(p).oper[0]^.val := -1;
  3994. Result := True;
  3995. Exit;
  3996. end;
  3997. S_W:
  3998. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  3999. begin
  4000. taicpu(p).oper[0]^.val := -1;
  4001. Result := True;
  4002. Exit;
  4003. end;
  4004. S_L:
  4005. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4006. begin
  4007. taicpu(p).oper[0]^.val := -1;
  4008. Result := True;
  4009. Exit;
  4010. end;
  4011. {$ifdef x86_64}
  4012. S_Q:
  4013. { Storing anything greater than $7FFFFFFF is not possible so do
  4014. nothing };
  4015. {$endif x86_64}
  4016. else
  4017. InternalError(2021121001);
  4018. end;
  4019. end;
  4020. if GetNextInstruction(p, hp1) and
  4021. TrySwapMovCmp(p, hp1) then
  4022. begin
  4023. Result := True;
  4024. Exit;
  4025. end;
  4026. { Search for:
  4027. test $x,(reg/ref)
  4028. jne @lbl1
  4029. test $y,(reg/ref) (same register or reference)
  4030. jne @lbl1
  4031. Change to:
  4032. test $(x or y),(reg/ref)
  4033. jne @lbl1
  4034. (Note, this doesn't work with je instead of jne)
  4035. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4036. Also search for:
  4037. test $x,(reg/ref)
  4038. je @lbl1
  4039. test $y,(reg/ref)
  4040. je/jne @lbl2
  4041. If (x or y) = x, then the second jump is deterministic
  4042. }
  4043. if (
  4044. (
  4045. (taicpu(p).oper[0]^.typ = top_const) or
  4046. (
  4047. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4048. (taicpu(p).oper[0]^.typ = top_reg) and
  4049. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4050. )
  4051. ) and
  4052. MatchInstruction(hp1, A_JCC, [])
  4053. ) then
  4054. begin
  4055. if (taicpu(p).oper[0]^.typ = top_reg) and
  4056. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4057. FirstValue := -1
  4058. else
  4059. FirstValue := taicpu(p).oper[0]^.val;
  4060. { If we have several test/jne's in a row, it might be the case that
  4061. the second label doesn't go to the same location, but the one
  4062. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4063. so accommodate for this with a while loop.
  4064. }
  4065. hp1_dist := hp1;
  4066. if GetNextInstruction(hp1, p_dist) and
  4067. (p_dist.typ = ait_instruction) and
  4068. (
  4069. (
  4070. (taicpu(p_dist).opcode = A_TEST) and
  4071. (
  4072. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4073. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4074. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4075. )
  4076. ) or
  4077. (
  4078. { cmp 0,%reg = test %reg,%reg }
  4079. (taicpu(p_dist).opcode = A_CMP) and
  4080. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4081. )
  4082. ) and
  4083. { Make sure the destination operands are actually the same }
  4084. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4085. GetNextInstruction(p_dist, hp1_dist) and
  4086. MatchInstruction(hp1_dist, A_JCC, []) then
  4087. begin
  4088. if
  4089. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4090. (
  4091. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4092. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4093. ) then
  4094. SecondValue := -1
  4095. else
  4096. SecondValue := taicpu(p_dist).oper[0]^.val;
  4097. { If both of the TEST constants are identical, delete the second
  4098. TEST that is unnecessary. }
  4099. if (FirstValue = SecondValue) then
  4100. begin
  4101. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4102. RemoveInstruction(p_dist);
  4103. { Don't let the flags register become deallocated and reallocated between the jumps }
  4104. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4105. Result := True;
  4106. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4107. begin
  4108. { Since the second jump's condition is a subset of the first, we
  4109. know it will never branch because the first jump dominates it.
  4110. Get it out of the way now rather than wait for the jump
  4111. optimisations for a speed boost. }
  4112. if IsJumpToLabel(taicpu(hp1_dist)) then
  4113. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4114. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4115. RemoveInstruction(hp1_dist);
  4116. end
  4117. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4118. begin
  4119. { If the inverse of the first condition is a subset of the second,
  4120. the second one will definitely branch if the first one doesn't }
  4121. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4122. MakeUnconditional(taicpu(hp1_dist));
  4123. RemoveDeadCodeAfterJump(hp1_dist);
  4124. end;
  4125. Exit;
  4126. end;
  4127. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4128. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4129. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4130. then the second jump will never branch, so it can also be
  4131. removed regardless of where it goes }
  4132. (
  4133. (FirstValue = -1) or
  4134. (SecondValue = -1) or
  4135. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4136. ) then
  4137. begin
  4138. { Same jump location... can be a register since nothing's changed }
  4139. { If any of the entries are equivalent to test %reg,%reg, then the
  4140. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4141. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4142. if IsJumpToLabel(taicpu(hp1_dist)) then
  4143. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4144. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4145. RemoveInstruction(hp1_dist);
  4146. { Only remove the second test if no jumps or other conditional instructions follow }
  4147. TransferUsedRegs(TmpUsedRegs);
  4148. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4149. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4150. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4151. RemoveInstruction(p_dist);
  4152. Result := True;
  4153. Exit;
  4154. end;
  4155. end;
  4156. end;
  4157. { Search for:
  4158. test %reg,%reg
  4159. j(c1) @lbl1
  4160. ...
  4161. @lbl:
  4162. test %reg,%reg (same register)
  4163. j(c2) @lbl2
  4164. If c2 is a subset of c1, change to:
  4165. test %reg,%reg
  4166. j(c1) @lbl2
  4167. (@lbl1 may become a dead label as a result)
  4168. }
  4169. if (taicpu(p).oper[1]^.typ = top_reg) and
  4170. (taicpu(p).oper[0]^.typ = top_reg) and
  4171. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4172. MatchInstruction(hp1, A_JCC, []) and
  4173. IsJumpToLabel(taicpu(hp1)) then
  4174. begin
  4175. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4176. p_label := nil;
  4177. if Assigned(JumpLabel) then
  4178. p_label := getlabelwithsym(JumpLabel);
  4179. if Assigned(p_label) and
  4180. GetNextInstruction(p_label, p_dist) and
  4181. MatchInstruction(p_dist, A_TEST, []) and
  4182. { It's fine if the second test uses smaller sub-registers }
  4183. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4184. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4185. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4186. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4187. GetNextInstruction(p_dist, hp1_dist) and
  4188. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4189. begin
  4190. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4191. if JumpLabel = JumpLabel_dist then
  4192. { This is an infinite loop }
  4193. Exit;
  4194. { Best optimisation when the first condition is a subset (or equal) of the second }
  4195. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4196. begin
  4197. { Any registers used here will already be allocated }
  4198. if Assigned(JumpLabel_dist) then
  4199. JumpLabel_dist.IncRefs;
  4200. if Assigned(JumpLabel) then
  4201. JumpLabel.DecRefs;
  4202. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4203. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4204. Result := True;
  4205. Exit;
  4206. end;
  4207. end;
  4208. end;
  4209. end;
  4210. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4211. var
  4212. hp1, hp2: tai;
  4213. ActiveReg: TRegister;
  4214. OldOffset: asizeint;
  4215. ThisConst: TCGInt;
  4216. function RegDeallocated: Boolean;
  4217. begin
  4218. TransferUsedRegs(TmpUsedRegs);
  4219. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4220. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4221. end;
  4222. begin
  4223. result:=false;
  4224. hp1 := nil;
  4225. { replace
  4226. addX const,%reg1
  4227. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4228. dealloc %reg1
  4229. by
  4230. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4231. }
  4232. if MatchOpType(taicpu(p),top_const,top_reg) then
  4233. begin
  4234. ActiveReg := taicpu(p).oper[1]^.reg;
  4235. { Ensures the entire register was updated }
  4236. if (taicpu(p).opsize >= S_L) and
  4237. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4238. MatchInstruction(hp1,A_LEA,[]) and
  4239. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4240. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4241. (
  4242. { Cover the case where the register in the reference is also the destination register }
  4243. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4244. (
  4245. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4246. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4247. RegDeallocated
  4248. )
  4249. ) then
  4250. begin
  4251. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4252. {$push}
  4253. {$R-}{$Q-}
  4254. { Explicitly disable overflow checking for these offset calculation
  4255. as those do not matter for the final result }
  4256. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4257. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4258. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4259. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4260. {$pop}
  4261. {$ifdef x86_64}
  4262. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4263. begin
  4264. { Overflow; abort }
  4265. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4266. end
  4267. else
  4268. {$endif x86_64}
  4269. begin
  4270. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4271. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4272. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4273. RemoveCurrentP(p, hp1)
  4274. else
  4275. RemoveCurrentP(p);
  4276. result:=true;
  4277. Exit;
  4278. end;
  4279. end;
  4280. if (
  4281. { Save calling GetNextInstructionUsingReg again }
  4282. Assigned(hp1) or
  4283. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4284. ) and
  4285. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4286. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4287. begin
  4288. if taicpu(hp1).oper[0]^.typ = top_const then
  4289. begin
  4290. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4291. if taicpu(hp1).opcode = A_ADD then
  4292. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4293. else
  4294. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4295. Result := True;
  4296. { Handle any overflows }
  4297. case taicpu(p).opsize of
  4298. S_B:
  4299. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4300. S_W:
  4301. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4302. S_L:
  4303. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4304. {$ifdef x86_64}
  4305. S_Q:
  4306. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4307. { Overflow; abort }
  4308. Result := False
  4309. else
  4310. taicpu(p).oper[0]^.val := ThisConst;
  4311. {$endif x86_64}
  4312. else
  4313. InternalError(2021102610);
  4314. end;
  4315. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4316. if Result then
  4317. begin
  4318. if (taicpu(p).oper[0]^.val < 0) and
  4319. (
  4320. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4321. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4322. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4323. ) then
  4324. begin
  4325. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4326. taicpu(p).opcode := A_SUB;
  4327. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4328. end
  4329. else
  4330. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4331. RemoveInstruction(hp1);
  4332. end;
  4333. end
  4334. else
  4335. begin
  4336. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4337. TransferUsedRegs(TmpUsedRegs);
  4338. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4339. hp2 := p;
  4340. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4341. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4342. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4343. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4344. begin
  4345. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4346. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4347. Asml.Remove(p);
  4348. Asml.InsertAfter(p, hp1);
  4349. p := hp1;
  4350. Result := True;
  4351. end;
  4352. end;
  4353. end;
  4354. end;
  4355. end;
  4356. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4357. var
  4358. hp1: tai;
  4359. ref: Integer;
  4360. saveref: treference;
  4361. TempReg: TRegister;
  4362. Multiple: TCGInt;
  4363. begin
  4364. Result:=false;
  4365. { removes seg register prefixes from LEA operations, as they
  4366. don't do anything}
  4367. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4368. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4369. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4370. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4371. (
  4372. { do not mess with leas accessing the stack pointer
  4373. unless it's a null operation }
  4374. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4375. (
  4376. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4377. (taicpu(p).oper[0]^.ref^.offset = 0)
  4378. )
  4379. ) and
  4380. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4381. begin
  4382. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4383. begin
  4384. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4385. begin
  4386. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4387. taicpu(p).oper[1]^.reg);
  4388. InsertLLItem(p.previous,p.next, hp1);
  4389. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4390. p.free;
  4391. p:=hp1;
  4392. end
  4393. else
  4394. begin
  4395. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4396. RemoveCurrentP(p);
  4397. end;
  4398. Result:=true;
  4399. exit;
  4400. end
  4401. else if (
  4402. { continue to use lea to adjust the stack pointer,
  4403. it is the recommended way, but only if not optimizing for size }
  4404. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4405. (cs_opt_size in current_settings.optimizerswitches)
  4406. ) and
  4407. { If the flags register is in use, don't change the instruction
  4408. to an ADD otherwise this will scramble the flags. [Kit] }
  4409. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4410. ConvertLEA(taicpu(p)) then
  4411. begin
  4412. Result:=true;
  4413. exit;
  4414. end;
  4415. end;
  4416. if GetNextInstruction(p,hp1) and
  4417. (hp1.typ=ait_instruction) then
  4418. begin
  4419. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4420. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4421. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4422. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4423. begin
  4424. TransferUsedRegs(TmpUsedRegs);
  4425. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4426. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4427. begin
  4428. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4429. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4430. RemoveInstruction(hp1);
  4431. result:=true;
  4432. exit;
  4433. end;
  4434. end;
  4435. { changes
  4436. lea <ref1>, reg1
  4437. <op> ...,<ref. with reg1>,...
  4438. to
  4439. <op> ...,<ref1>,... }
  4440. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4441. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4442. not(MatchInstruction(hp1,A_LEA,[])) then
  4443. begin
  4444. { find a reference which uses reg1 }
  4445. 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
  4446. ref:=0
  4447. 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
  4448. ref:=1
  4449. else
  4450. ref:=-1;
  4451. if (ref<>-1) and
  4452. { reg1 must be either the base or the index }
  4453. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4454. begin
  4455. { reg1 can be removed from the reference }
  4456. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4457. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4458. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4459. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4460. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4461. else
  4462. Internalerror(2019111201);
  4463. { check if the can insert all data of the lea into the second instruction }
  4464. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4465. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4466. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4467. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4468. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4469. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4470. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4471. {$ifdef x86_64}
  4472. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4473. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4474. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4475. )
  4476. {$endif x86_64}
  4477. then
  4478. begin
  4479. { reg1 might not used by the second instruction after it is remove from the reference }
  4480. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4481. begin
  4482. TransferUsedRegs(TmpUsedRegs);
  4483. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4484. { reg1 is not updated so it might not be used afterwards }
  4485. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4486. begin
  4487. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4488. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4489. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4490. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4491. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4492. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4493. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4494. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4495. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4496. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4497. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4498. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4499. RemoveCurrentP(p, hp1);
  4500. result:=true;
  4501. exit;
  4502. end
  4503. end;
  4504. end;
  4505. { recover }
  4506. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4507. end;
  4508. end;
  4509. end;
  4510. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4511. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4512. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4513. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4514. begin
  4515. { Check common LEA/LEA conditions }
  4516. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4517. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4518. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4519. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4520. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4521. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4522. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4523. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4524. (
  4525. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4526. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4527. ) and (
  4528. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4529. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4530. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4531. ) then
  4532. begin
  4533. { changes
  4534. lea (regX,scale), reg1
  4535. lea offset(reg1,reg1), reg1
  4536. to
  4537. lea offset(regX,scale*2), reg1
  4538. and
  4539. lea (regX,scale1), reg1
  4540. lea offset(reg1,scale2), reg1
  4541. to
  4542. lea offset(regX,scale1*scale2), reg1
  4543. ... so long as the final scale does not exceed 8
  4544. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4545. }
  4546. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4547. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4548. (
  4549. (
  4550. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4551. ) or (
  4552. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4553. (
  4554. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4555. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4556. )
  4557. )
  4558. ) and (
  4559. (
  4560. { lea (reg1,scale2), reg1 variant }
  4561. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4562. (
  4563. (
  4564. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4565. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4566. ) or (
  4567. { lea (regX,regX), reg1 variant }
  4568. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4569. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4570. )
  4571. )
  4572. ) or (
  4573. { lea (reg1,reg1), reg1 variant }
  4574. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4575. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4576. )
  4577. ) then
  4578. begin
  4579. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4580. { Make everything homogeneous to make calculations easier }
  4581. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4582. begin
  4583. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4584. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4585. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4586. else
  4587. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4588. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4589. end;
  4590. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4591. begin
  4592. { Just to prevent miscalculations }
  4593. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4594. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4595. else
  4596. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4597. end
  4598. else
  4599. begin
  4600. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4601. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4602. end;
  4603. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4604. RemoveCurrentP(p);
  4605. result:=true;
  4606. exit;
  4607. end
  4608. { changes
  4609. lea offset1(regX), reg1
  4610. lea offset2(reg1), reg1
  4611. to
  4612. lea offset1+offset2(regX), reg1 }
  4613. else if
  4614. (
  4615. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4616. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4617. ) or (
  4618. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4619. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4620. (
  4621. (
  4622. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4623. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4624. ) or (
  4625. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4626. (
  4627. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4628. (
  4629. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4630. (
  4631. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4632. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4633. )
  4634. )
  4635. )
  4636. )
  4637. )
  4638. ) then
  4639. begin
  4640. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4641. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4642. begin
  4643. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4644. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4645. { if the register is used as index and base, we have to increase for base as well
  4646. and adapt base }
  4647. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4648. begin
  4649. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4650. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4651. end;
  4652. end
  4653. else
  4654. begin
  4655. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4656. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4657. end;
  4658. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4659. begin
  4660. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4661. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4662. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4663. end;
  4664. RemoveCurrentP(p);
  4665. result:=true;
  4666. exit;
  4667. end;
  4668. end;
  4669. { Change:
  4670. leal/q $x(%reg1),%reg2
  4671. ...
  4672. shll/q $y,%reg2
  4673. To:
  4674. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4675. }
  4676. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4677. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4678. (taicpu(hp1).oper[0]^.val <= 3) then
  4679. begin
  4680. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4681. TransferUsedRegs(TmpUsedRegs);
  4682. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4683. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4684. if
  4685. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4686. (this works even if scalefactor is zero) }
  4687. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4688. { Ensure offset doesn't go out of bounds }
  4689. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4690. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4691. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4692. (
  4693. (
  4694. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4695. (
  4696. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4697. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4698. (
  4699. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4700. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4701. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4702. )
  4703. )
  4704. ) or (
  4705. (
  4706. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4707. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4708. ) and
  4709. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4710. )
  4711. ) then
  4712. begin
  4713. repeat
  4714. with taicpu(p).oper[0]^.ref^ do
  4715. begin
  4716. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4717. if index = base then
  4718. begin
  4719. if Multiple > 4 then
  4720. { Optimisation will no longer work because resultant
  4721. scale factor will exceed 8 }
  4722. Break;
  4723. base := NR_NO;
  4724. scalefactor := 2;
  4725. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4726. end
  4727. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4728. begin
  4729. { Scale factor only works on the index register }
  4730. index := base;
  4731. base := NR_NO;
  4732. end;
  4733. { For safety }
  4734. if scalefactor <= 1 then
  4735. begin
  4736. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4737. scalefactor := Multiple;
  4738. end
  4739. else
  4740. begin
  4741. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4742. scalefactor := scalefactor * Multiple;
  4743. end;
  4744. offset := offset * Multiple;
  4745. end;
  4746. RemoveInstruction(hp1);
  4747. Result := True;
  4748. Exit;
  4749. { This repeat..until loop exists for the benefit of Break }
  4750. until True;
  4751. end;
  4752. end;
  4753. end;
  4754. end;
  4755. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4756. var
  4757. hp1 : tai;
  4758. begin
  4759. DoSubAddOpt := False;
  4760. if taicpu(p).oper[0]^.typ <> top_const then
  4761. { Should have been confirmed before calling }
  4762. InternalError(2021102601);
  4763. if GetLastInstruction(p, hp1) and
  4764. (hp1.typ = ait_instruction) and
  4765. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4766. case taicpu(hp1).opcode Of
  4767. A_DEC:
  4768. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4769. begin
  4770. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4771. RemoveInstruction(hp1);
  4772. end;
  4773. A_SUB:
  4774. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4775. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4776. begin
  4777. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4778. RemoveInstruction(hp1);
  4779. end;
  4780. A_ADD:
  4781. begin
  4782. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4783. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4784. begin
  4785. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4786. RemoveInstruction(hp1);
  4787. if (taicpu(p).oper[0]^.val = 0) then
  4788. begin
  4789. hp1 := tai(p.next);
  4790. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4791. if not GetLastInstruction(hp1, p) then
  4792. p := hp1;
  4793. DoSubAddOpt := True;
  4794. end
  4795. end;
  4796. end;
  4797. else
  4798. ;
  4799. end;
  4800. end;
  4801. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4802. var
  4803. hp1, hp2: tai;
  4804. ActiveReg: TRegister;
  4805. OldOffset: asizeint;
  4806. ThisConst: TCGInt;
  4807. function RegDeallocated: Boolean;
  4808. begin
  4809. TransferUsedRegs(TmpUsedRegs);
  4810. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4811. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4812. end;
  4813. begin
  4814. Result:=false;
  4815. hp1 := nil;
  4816. { replace
  4817. subX const,%reg1
  4818. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4819. dealloc %reg1
  4820. by
  4821. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4822. }
  4823. if MatchOpType(taicpu(p),top_const,top_reg) then
  4824. begin
  4825. ActiveReg := taicpu(p).oper[1]^.reg;
  4826. { Ensures the entire register was updated }
  4827. if (taicpu(p).opsize >= S_L) and
  4828. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4829. MatchInstruction(hp1,A_LEA,[]) and
  4830. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4831. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4832. (
  4833. { Cover the case where the register in the reference is also the destination register }
  4834. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4835. (
  4836. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4837. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4838. RegDeallocated
  4839. )
  4840. ) then
  4841. begin
  4842. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4843. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4844. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4845. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4846. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4847. {$ifdef x86_64}
  4848. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4849. begin
  4850. { Overflow; abort }
  4851. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4852. end
  4853. else
  4854. {$endif x86_64}
  4855. begin
  4856. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4857. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4858. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4859. RemoveCurrentP(p, hp1)
  4860. else
  4861. RemoveCurrentP(p);
  4862. result:=true;
  4863. Exit;
  4864. end;
  4865. end;
  4866. if (
  4867. { Save calling GetNextInstructionUsingReg again }
  4868. Assigned(hp1) or
  4869. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4870. ) and
  4871. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4872. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4873. begin
  4874. if taicpu(hp1).oper[0]^.typ = top_const then
  4875. begin
  4876. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4877. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4878. Result := True;
  4879. { Handle any overflows }
  4880. case taicpu(p).opsize of
  4881. S_B:
  4882. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4883. S_W:
  4884. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4885. S_L:
  4886. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4887. {$ifdef x86_64}
  4888. S_Q:
  4889. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4890. { Overflow; abort }
  4891. Result := False
  4892. else
  4893. taicpu(p).oper[0]^.val := ThisConst;
  4894. {$endif x86_64}
  4895. else
  4896. InternalError(2021102610);
  4897. end;
  4898. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4899. if Result then
  4900. begin
  4901. if (taicpu(p).oper[0]^.val < 0) and
  4902. (
  4903. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4904. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4905. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4906. ) then
  4907. begin
  4908. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4909. taicpu(p).opcode := A_SUB;
  4910. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4911. end
  4912. else
  4913. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4914. RemoveInstruction(hp1);
  4915. end;
  4916. end
  4917. else
  4918. begin
  4919. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4920. TransferUsedRegs(TmpUsedRegs);
  4921. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4922. hp2 := p;
  4923. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4924. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4925. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4926. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4927. begin
  4928. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4929. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4930. Asml.Remove(p);
  4931. Asml.InsertAfter(p, hp1);
  4932. p := hp1;
  4933. Result := True;
  4934. Exit;
  4935. end;
  4936. end;
  4937. end;
  4938. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4939. { * change "sub/add const1, reg" or "dec reg" followed by
  4940. "sub const2, reg" to one "sub ..., reg" }
  4941. {$ifdef i386}
  4942. if (taicpu(p).oper[0]^.val = 2) and
  4943. (ActiveReg = NR_ESP) and
  4944. { Don't do the sub/push optimization if the sub }
  4945. { comes from setting up the stack frame (JM) }
  4946. (not(GetLastInstruction(p,hp1)) or
  4947. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4948. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4949. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4950. begin
  4951. hp1 := tai(p.next);
  4952. while Assigned(hp1) and
  4953. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4954. not RegReadByInstruction(NR_ESP,hp1) and
  4955. not RegModifiedByInstruction(NR_ESP,hp1) do
  4956. hp1 := tai(hp1.next);
  4957. if Assigned(hp1) and
  4958. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4959. begin
  4960. taicpu(hp1).changeopsize(S_L);
  4961. if taicpu(hp1).oper[0]^.typ=top_reg then
  4962. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4963. hp1 := tai(p.next);
  4964. RemoveCurrentp(p, hp1);
  4965. Result:=true;
  4966. exit;
  4967. end;
  4968. end;
  4969. {$endif i386}
  4970. if DoSubAddOpt(p) then
  4971. Result:=true;
  4972. end;
  4973. end;
  4974. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4975. var
  4976. TmpBool1,TmpBool2 : Boolean;
  4977. tmpref : treference;
  4978. hp1,hp2: tai;
  4979. mask: tcgint;
  4980. begin
  4981. Result:=false;
  4982. { All these optimisations work on "shl/sal const,%reg" }
  4983. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4984. Exit;
  4985. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4986. (taicpu(p).oper[0]^.val <= 3) then
  4987. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4988. begin
  4989. { should we check the next instruction? }
  4990. TmpBool1 := True;
  4991. { have we found an add/sub which could be
  4992. integrated in the lea? }
  4993. TmpBool2 := False;
  4994. reference_reset(tmpref,2,[]);
  4995. TmpRef.index := taicpu(p).oper[1]^.reg;
  4996. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4997. while TmpBool1 and
  4998. GetNextInstruction(p, hp1) and
  4999. (tai(hp1).typ = ait_instruction) and
  5000. ((((taicpu(hp1).opcode = A_ADD) or
  5001. (taicpu(hp1).opcode = A_SUB)) and
  5002. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5003. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5004. (((taicpu(hp1).opcode = A_INC) or
  5005. (taicpu(hp1).opcode = A_DEC)) and
  5006. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5007. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5008. ((taicpu(hp1).opcode = A_LEA) and
  5009. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5010. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5011. (not GetNextInstruction(hp1,hp2) or
  5012. not instrReadsFlags(hp2)) Do
  5013. begin
  5014. TmpBool1 := False;
  5015. if taicpu(hp1).opcode=A_LEA then
  5016. begin
  5017. if (TmpRef.base = NR_NO) and
  5018. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5019. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5020. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5021. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5022. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5023. begin
  5024. TmpBool1 := True;
  5025. TmpBool2 := True;
  5026. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5027. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5028. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5029. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5030. RemoveInstruction(hp1);
  5031. end
  5032. end
  5033. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5034. begin
  5035. TmpBool1 := True;
  5036. TmpBool2 := True;
  5037. case taicpu(hp1).opcode of
  5038. A_ADD:
  5039. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5040. A_SUB:
  5041. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5042. else
  5043. internalerror(2019050536);
  5044. end;
  5045. RemoveInstruction(hp1);
  5046. end
  5047. else
  5048. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5049. (((taicpu(hp1).opcode = A_ADD) and
  5050. (TmpRef.base = NR_NO)) or
  5051. (taicpu(hp1).opcode = A_INC) or
  5052. (taicpu(hp1).opcode = A_DEC)) then
  5053. begin
  5054. TmpBool1 := True;
  5055. TmpBool2 := True;
  5056. case taicpu(hp1).opcode of
  5057. A_ADD:
  5058. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5059. A_INC:
  5060. inc(TmpRef.offset);
  5061. A_DEC:
  5062. dec(TmpRef.offset);
  5063. else
  5064. internalerror(2019050535);
  5065. end;
  5066. RemoveInstruction(hp1);
  5067. end;
  5068. end;
  5069. if TmpBool2
  5070. {$ifndef x86_64}
  5071. or
  5072. ((current_settings.optimizecputype < cpu_Pentium2) and
  5073. (taicpu(p).oper[0]^.val <= 3) and
  5074. not(cs_opt_size in current_settings.optimizerswitches))
  5075. {$endif x86_64}
  5076. then
  5077. begin
  5078. if not(TmpBool2) and
  5079. (taicpu(p).oper[0]^.val=1) then
  5080. begin
  5081. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5082. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5083. end
  5084. else
  5085. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5086. taicpu(p).oper[1]^.reg);
  5087. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5088. InsertLLItem(p.previous, p.next, hp1);
  5089. p.free;
  5090. p := hp1;
  5091. end;
  5092. end
  5093. {$ifndef x86_64}
  5094. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5095. begin
  5096. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5097. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5098. (unlike shl, which is only Tairable in the U pipe) }
  5099. if taicpu(p).oper[0]^.val=1 then
  5100. begin
  5101. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5102. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5103. InsertLLItem(p.previous, p.next, hp1);
  5104. p.free;
  5105. p := hp1;
  5106. end
  5107. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5108. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5109. else if (taicpu(p).opsize = S_L) and
  5110. (taicpu(p).oper[0]^.val<= 3) then
  5111. begin
  5112. reference_reset(tmpref,2,[]);
  5113. TmpRef.index := taicpu(p).oper[1]^.reg;
  5114. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5115. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5116. InsertLLItem(p.previous, p.next, hp1);
  5117. p.free;
  5118. p := hp1;
  5119. end;
  5120. end
  5121. {$endif x86_64}
  5122. else if
  5123. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5124. (
  5125. (
  5126. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5127. SetAndTest(hp1, hp2)
  5128. {$ifdef x86_64}
  5129. ) or
  5130. (
  5131. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5132. GetNextInstruction(hp1, hp2) and
  5133. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5134. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5135. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5136. {$endif x86_64}
  5137. )
  5138. ) and
  5139. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5140. begin
  5141. { Change:
  5142. shl x, %reg1
  5143. mov -(1<<x), %reg2
  5144. and %reg2, %reg1
  5145. Or:
  5146. shl x, %reg1
  5147. and -(1<<x), %reg1
  5148. To just:
  5149. shl x, %reg1
  5150. Since the and operation only zeroes bits that are already zero from the shl operation
  5151. }
  5152. case taicpu(p).oper[0]^.val of
  5153. 8:
  5154. mask:=$FFFFFFFFFFFFFF00;
  5155. 16:
  5156. mask:=$FFFFFFFFFFFF0000;
  5157. 32:
  5158. mask:=$FFFFFFFF00000000;
  5159. 63:
  5160. { Constant pre-calculated to prevent overflow errors with Int64 }
  5161. mask:=$8000000000000000;
  5162. else
  5163. begin
  5164. if taicpu(p).oper[0]^.val >= 64 then
  5165. { Shouldn't happen realistically, since the register
  5166. is guaranteed to be set to zero at this point }
  5167. mask := 0
  5168. else
  5169. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5170. end;
  5171. end;
  5172. if taicpu(hp1).oper[0]^.val = mask then
  5173. begin
  5174. { Everything checks out, perform the optimisation, as long as
  5175. the FLAGS register isn't being used}
  5176. TransferUsedRegs(TmpUsedRegs);
  5177. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5178. {$ifdef x86_64}
  5179. if (hp1 <> hp2) then
  5180. begin
  5181. { "shl/mov/and" version }
  5182. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5183. { Don't do the optimisation if the FLAGS register is in use }
  5184. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5185. begin
  5186. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5187. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5188. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5189. begin
  5190. RemoveInstruction(hp1);
  5191. Result := True;
  5192. end;
  5193. { Only set Result to True if the 'mov' instruction was removed }
  5194. RemoveInstruction(hp2);
  5195. end;
  5196. end
  5197. else
  5198. {$endif x86_64}
  5199. begin
  5200. { "shl/and" version }
  5201. { Don't do the optimisation if the FLAGS register is in use }
  5202. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5203. begin
  5204. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5205. RemoveInstruction(hp1);
  5206. Result := True;
  5207. end;
  5208. end;
  5209. Exit;
  5210. end
  5211. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5212. begin
  5213. { Even if the mask doesn't allow for its removal, we might be
  5214. able to optimise the mask for the "shl/and" version, which
  5215. may permit other peephole optimisations }
  5216. {$ifdef DEBUG_AOPTCPU}
  5217. mask := taicpu(hp1).oper[0]^.val and mask;
  5218. if taicpu(hp1).oper[0]^.val <> mask then
  5219. begin
  5220. DebugMsg(
  5221. SPeepholeOptimization +
  5222. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5223. ' to $' + debug_tostr(mask) +
  5224. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5225. taicpu(hp1).oper[0]^.val := mask;
  5226. end;
  5227. {$else DEBUG_AOPTCPU}
  5228. { If debugging is off, just set the operand even if it's the same }
  5229. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5230. {$endif DEBUG_AOPTCPU}
  5231. end;
  5232. end;
  5233. {
  5234. change
  5235. shl/sal const,reg
  5236. <op> ...(...,reg,1),...
  5237. into
  5238. <op> ...(...,reg,1 shl const),...
  5239. if const in 1..3
  5240. }
  5241. if MatchOpType(taicpu(p), top_const, top_reg) and
  5242. (taicpu(p).oper[0]^.val in [1..3]) and
  5243. GetNextInstruction(p, hp1) and
  5244. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5245. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5246. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5247. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5248. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5249. begin
  5250. TransferUsedRegs(TmpUsedRegs);
  5251. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5252. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5253. begin
  5254. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5255. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5256. RemoveCurrentP(p);
  5257. Result:=true;
  5258. end;
  5259. end;
  5260. end;
  5261. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5262. var
  5263. CurrentRef: TReference;
  5264. FullReg: TRegister;
  5265. hp1, hp2: tai;
  5266. begin
  5267. Result := False;
  5268. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5269. Exit;
  5270. { We assume you've checked if the operand is actually a reference by
  5271. this point. If it isn't, you'll most likely get an access violation }
  5272. CurrentRef := first_mov.oper[1]^.ref^;
  5273. { Memory must be aligned }
  5274. if (CurrentRef.offset mod 4) <> 0 then
  5275. Exit;
  5276. Inc(CurrentRef.offset);
  5277. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5278. if MatchOperand(second_mov.oper[0]^, 0) and
  5279. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5280. GetNextInstruction(second_mov, hp1) and
  5281. (hp1.typ = ait_instruction) and
  5282. (taicpu(hp1).opcode = A_MOV) and
  5283. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5284. (taicpu(hp1).oper[0]^.val = 0) then
  5285. begin
  5286. Inc(CurrentRef.offset);
  5287. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5288. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5289. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5290. begin
  5291. case taicpu(hp1).opsize of
  5292. S_B:
  5293. if GetNextInstruction(hp1, hp2) and
  5294. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5295. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5296. (taicpu(hp2).oper[0]^.val = 0) then
  5297. begin
  5298. Inc(CurrentRef.offset);
  5299. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5300. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5301. (taicpu(hp2).opsize = S_B) then
  5302. begin
  5303. RemoveInstruction(hp1);
  5304. RemoveInstruction(hp2);
  5305. first_mov.opsize := S_L;
  5306. if first_mov.oper[0]^.typ = top_reg then
  5307. begin
  5308. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5309. { Reuse second_mov as a MOVZX instruction }
  5310. second_mov.opcode := A_MOVZX;
  5311. second_mov.opsize := S_BL;
  5312. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5313. second_mov.loadreg(1, FullReg);
  5314. first_mov.oper[0]^.reg := FullReg;
  5315. asml.Remove(second_mov);
  5316. asml.InsertBefore(second_mov, first_mov);
  5317. end
  5318. else
  5319. { It's a value }
  5320. begin
  5321. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5322. RemoveInstruction(second_mov);
  5323. end;
  5324. Result := True;
  5325. Exit;
  5326. end;
  5327. end;
  5328. S_W:
  5329. begin
  5330. RemoveInstruction(hp1);
  5331. first_mov.opsize := S_L;
  5332. if first_mov.oper[0]^.typ = top_reg then
  5333. begin
  5334. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5335. { Reuse second_mov as a MOVZX instruction }
  5336. second_mov.opcode := A_MOVZX;
  5337. second_mov.opsize := S_BL;
  5338. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5339. second_mov.loadreg(1, FullReg);
  5340. first_mov.oper[0]^.reg := FullReg;
  5341. asml.Remove(second_mov);
  5342. asml.InsertBefore(second_mov, first_mov);
  5343. end
  5344. else
  5345. { It's a value }
  5346. begin
  5347. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5348. RemoveInstruction(second_mov);
  5349. end;
  5350. Result := True;
  5351. Exit;
  5352. end;
  5353. else
  5354. ;
  5355. end;
  5356. end;
  5357. end;
  5358. end;
  5359. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5360. { returns true if a "continue" should be done after this optimization }
  5361. var
  5362. hp1, hp2: tai;
  5363. begin
  5364. Result := false;
  5365. if MatchOpType(taicpu(p),top_ref) and
  5366. GetNextInstruction(p, hp1) and
  5367. (hp1.typ = ait_instruction) and
  5368. (((taicpu(hp1).opcode = A_FLD) and
  5369. (taicpu(p).opcode = A_FSTP)) or
  5370. ((taicpu(p).opcode = A_FISTP) and
  5371. (taicpu(hp1).opcode = A_FILD))) and
  5372. MatchOpType(taicpu(hp1),top_ref) and
  5373. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5374. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5375. begin
  5376. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5377. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5378. GetNextInstruction(hp1, hp2) and
  5379. (hp2.typ = ait_instruction) and
  5380. IsExitCode(hp2) and
  5381. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5382. not(assigned(current_procinfo.procdef.funcretsym) and
  5383. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5384. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5385. begin
  5386. RemoveInstruction(hp1);
  5387. RemoveCurrentP(p, hp2);
  5388. RemoveLastDeallocForFuncRes(p);
  5389. Result := true;
  5390. end
  5391. else
  5392. { we can do this only in fast math mode as fstp is rounding ...
  5393. ... still disabled as it breaks the compiler and/or rtl }
  5394. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5395. { ... or if another fstp equal to the first one follows }
  5396. (GetNextInstruction(hp1,hp2) and
  5397. (hp2.typ = ait_instruction) and
  5398. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5399. (taicpu(p).opsize=taicpu(hp2).opsize))
  5400. ) and
  5401. { fst can't store an extended/comp value }
  5402. (taicpu(p).opsize <> S_FX) and
  5403. (taicpu(p).opsize <> S_IQ) then
  5404. begin
  5405. if (taicpu(p).opcode = A_FSTP) then
  5406. taicpu(p).opcode := A_FST
  5407. else
  5408. taicpu(p).opcode := A_FIST;
  5409. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5410. RemoveInstruction(hp1);
  5411. end;
  5412. end;
  5413. end;
  5414. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5415. var
  5416. hp1, hp2: tai;
  5417. begin
  5418. result:=false;
  5419. if MatchOpType(taicpu(p),top_reg) and
  5420. GetNextInstruction(p, hp1) and
  5421. (hp1.typ = Ait_Instruction) and
  5422. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5423. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5424. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5425. { change to
  5426. fld reg fxxx reg,st
  5427. fxxxp st, st1 (hp1)
  5428. Remark: non commutative operations must be reversed!
  5429. }
  5430. begin
  5431. case taicpu(hp1).opcode Of
  5432. A_FMULP,A_FADDP,
  5433. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5434. begin
  5435. case taicpu(hp1).opcode Of
  5436. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5437. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5438. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5439. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5440. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5441. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5442. else
  5443. internalerror(2019050534);
  5444. end;
  5445. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5446. taicpu(hp1).oper[1]^.reg := NR_ST;
  5447. RemoveCurrentP(p, hp1);
  5448. Result:=true;
  5449. exit;
  5450. end;
  5451. else
  5452. ;
  5453. end;
  5454. end
  5455. else
  5456. if MatchOpType(taicpu(p),top_ref) and
  5457. GetNextInstruction(p, hp2) and
  5458. (hp2.typ = Ait_Instruction) and
  5459. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5460. (taicpu(p).opsize in [S_FS, S_FL]) and
  5461. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5462. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5463. if GetLastInstruction(p, hp1) and
  5464. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5465. MatchOpType(taicpu(hp1),top_ref) and
  5466. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5467. if ((taicpu(hp2).opcode = A_FMULP) or
  5468. (taicpu(hp2).opcode = A_FADDP)) then
  5469. { change to
  5470. fld/fst mem1 (hp1) fld/fst mem1
  5471. fld mem1 (p) fadd/
  5472. faddp/ fmul st, st
  5473. fmulp st, st1 (hp2) }
  5474. begin
  5475. RemoveCurrentP(p, hp1);
  5476. if (taicpu(hp2).opcode = A_FADDP) then
  5477. taicpu(hp2).opcode := A_FADD
  5478. else
  5479. taicpu(hp2).opcode := A_FMUL;
  5480. taicpu(hp2).oper[1]^.reg := NR_ST;
  5481. end
  5482. else
  5483. { change to
  5484. fld/fst mem1 (hp1) fld/fst mem1
  5485. fld mem1 (p) fld st}
  5486. begin
  5487. taicpu(p).changeopsize(S_FL);
  5488. taicpu(p).loadreg(0,NR_ST);
  5489. end
  5490. else
  5491. begin
  5492. case taicpu(hp2).opcode Of
  5493. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5494. { change to
  5495. fld/fst mem1 (hp1) fld/fst mem1
  5496. fld mem2 (p) fxxx mem2
  5497. fxxxp st, st1 (hp2) }
  5498. begin
  5499. case taicpu(hp2).opcode Of
  5500. A_FADDP: taicpu(p).opcode := A_FADD;
  5501. A_FMULP: taicpu(p).opcode := A_FMUL;
  5502. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5503. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5504. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5505. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5506. else
  5507. internalerror(2019050533);
  5508. end;
  5509. RemoveInstruction(hp2);
  5510. end
  5511. else
  5512. ;
  5513. end
  5514. end
  5515. end;
  5516. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5517. begin
  5518. Result := condition_in(cond1, cond2) or
  5519. { Not strictly subsets due to the actual flags checked, but because we're
  5520. comparing integers, E is a subset of AE and GE and their aliases }
  5521. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5522. end;
  5523. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5524. var
  5525. v: TCGInt;
  5526. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5527. FirstMatch: Boolean;
  5528. NewReg: TRegister;
  5529. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5530. begin
  5531. Result:=false;
  5532. { All these optimisations need a next instruction }
  5533. if not GetNextInstruction(p, hp1) then
  5534. Exit;
  5535. { Search for:
  5536. cmp ###,###
  5537. j(c1) @lbl1
  5538. ...
  5539. @lbl:
  5540. cmp ###.### (same comparison as above)
  5541. j(c2) @lbl2
  5542. If c1 is a subset of c2, change to:
  5543. cmp ###,###
  5544. j(c2) @lbl2
  5545. (@lbl1 may become a dead label as a result)
  5546. }
  5547. { Also handle cases where there are multiple jumps in a row }
  5548. p_jump := hp1;
  5549. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5550. begin
  5551. if IsJumpToLabel(taicpu(p_jump)) then
  5552. begin
  5553. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5554. p_label := nil;
  5555. if Assigned(JumpLabel) then
  5556. p_label := getlabelwithsym(JumpLabel);
  5557. if Assigned(p_label) and
  5558. GetNextInstruction(p_label, p_dist) and
  5559. MatchInstruction(p_dist, A_CMP, []) and
  5560. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5561. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5562. GetNextInstruction(p_dist, hp1_dist) and
  5563. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5564. begin
  5565. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5566. if JumpLabel = JumpLabel_dist then
  5567. { This is an infinite loop }
  5568. Exit;
  5569. { Best optimisation when the first condition is a subset (or equal) of the second }
  5570. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5571. begin
  5572. { Any registers used here will already be allocated }
  5573. if Assigned(JumpLabel_dist) then
  5574. JumpLabel_dist.IncRefs;
  5575. if Assigned(JumpLabel) then
  5576. JumpLabel.DecRefs;
  5577. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5578. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5579. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5580. Result := True;
  5581. { Don't exit yet. Since p and p_jump haven't actually been
  5582. removed, we can check for more on this iteration }
  5583. end
  5584. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5585. GetNextInstruction(hp1_dist, hp1_label) and
  5586. SkipAligns(hp1_label, hp1_label) and
  5587. (hp1_label.typ = ait_label) then
  5588. begin
  5589. JumpLabel_far := tai_label(hp1_label).labsym;
  5590. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5591. { This is an infinite loop }
  5592. Exit;
  5593. if Assigned(JumpLabel_far) then
  5594. begin
  5595. { In this situation, if the first jump branches, the second one will never,
  5596. branch so change the destination label to after the second jump }
  5597. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5598. if Assigned(JumpLabel) then
  5599. JumpLabel.DecRefs;
  5600. JumpLabel_far.IncRefs;
  5601. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5602. Result := True;
  5603. { Don't exit yet. Since p and p_jump haven't actually been
  5604. removed, we can check for more on this iteration }
  5605. Continue;
  5606. end;
  5607. end;
  5608. end;
  5609. end;
  5610. { Search for:
  5611. cmp ###,###
  5612. j(c1) @lbl1
  5613. cmp ###,### (same as first)
  5614. Remove second cmp
  5615. }
  5616. if GetNextInstruction(p_jump, hp2) and
  5617. (
  5618. (
  5619. MatchInstruction(hp2, A_CMP, []) and
  5620. (
  5621. (
  5622. MatchOpType(taicpu(p), top_const, top_reg) and
  5623. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5624. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5625. ) or (
  5626. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5627. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5628. )
  5629. )
  5630. ) or (
  5631. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5632. MatchOperand(taicpu(p).oper[0]^, 0) and
  5633. (taicpu(p).oper[1]^.typ = top_reg) and
  5634. MatchInstruction(hp2, A_TEST, []) and
  5635. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5636. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5637. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5638. )
  5639. ) then
  5640. begin
  5641. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5642. RemoveInstruction(hp2);
  5643. Result := True;
  5644. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5645. end;
  5646. GetNextInstruction(p_jump, p_jump);
  5647. end;
  5648. {
  5649. Try to optimise the following:
  5650. cmp $x,### ($x and $y can be registers or constants)
  5651. je @lbl1 (only reference)
  5652. cmp $y,### (### are identical)
  5653. @Lbl:
  5654. sete %reg1
  5655. Change to:
  5656. cmp $x,###
  5657. sete %reg2 (allocate new %reg2)
  5658. cmp $y,###
  5659. sete %reg1
  5660. orb %reg2,%reg1
  5661. (dealloc %reg2)
  5662. This adds an instruction (so don't perform under -Os), but it removes
  5663. a conditional branch.
  5664. }
  5665. if not (cs_opt_size in current_settings.optimizerswitches) and
  5666. MatchInstruction(hp1, A_Jcc, []) and
  5667. IsJumpToLabel(taicpu(hp1)) and
  5668. (taicpu(hp1).condition in [C_E, C_Z]) and
  5669. GetNextInstruction(hp1, hp2) and
  5670. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  5671. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  5672. { The first operand of CMP instructions can only be a register or
  5673. operand anyway, so no need to check }
  5674. GetNextInstruction(hp2, p_label) and
  5675. (p_label.typ = ait_label) and
  5676. (tai_label(p_label).labsym.getrefs = 1) and
  5677. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  5678. GetNextInstruction(p_label, p_dist) and
  5679. MatchInstruction(p_dist, A_SETcc, []) and
  5680. (taicpu(p_dist).condition in [C_E, C_Z]) and
  5681. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  5682. begin
  5683. TransferUsedRegs(TmpUsedRegs);
  5684. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5685. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5686. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  5687. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5688. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  5689. { Get the instruction after the SETcc instruction so we can
  5690. allocate a new register over the entire range }
  5691. GetNextInstruction(p_dist, hp1_dist) then
  5692. begin
  5693. { Register can appear in p if it's not used afterwards, so only
  5694. allocate between hp1 and hp1_dist }
  5695. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  5696. if NewReg <> NR_NO then
  5697. begin
  5698. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  5699. { Change the jump instruction into a SETcc instruction }
  5700. taicpu(hp1).opcode := A_SETcc;
  5701. taicpu(hp1).opsize := S_B;
  5702. taicpu(hp1).loadreg(0, NewReg);
  5703. { This is now a dead label }
  5704. tai_label(p_label).labsym.decrefs;
  5705. { Prefer adding before the next instruction so the FLAGS
  5706. register is deallicated first }
  5707. AsmL.InsertBefore(
  5708. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  5709. hp1_dist
  5710. );
  5711. Result := True;
  5712. { Don't exit yet, as p wasn't changed and hp1, while
  5713. modified, is still intact and might be optimised by the
  5714. SETcc optimisation below }
  5715. end;
  5716. end;
  5717. end;
  5718. if taicpu(p).oper[0]^.typ = top_const then
  5719. begin
  5720. if (taicpu(p).oper[0]^.val = 0) and
  5721. (taicpu(p).oper[1]^.typ = top_reg) and
  5722. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5723. begin
  5724. hp2 := p;
  5725. FirstMatch := True;
  5726. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5727. anything meaningful once it's converted to "test %reg,%reg";
  5728. additionally, some jumps will always (or never) branch, so
  5729. evaluate every jump immediately following the
  5730. comparison, optimising the conditions if possible.
  5731. Similarly with SETcc... those that are always set to 0 or 1
  5732. are changed to MOV instructions }
  5733. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5734. (
  5735. GetNextInstruction(hp2, hp1) and
  5736. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5737. ) do
  5738. begin
  5739. FirstMatch := False;
  5740. case taicpu(hp1).condition of
  5741. C_B, C_C, C_NAE, C_O:
  5742. { For B/NAE:
  5743. Will never branch since an unsigned integer can never be below zero
  5744. For C/O:
  5745. Result cannot overflow because 0 is being subtracted
  5746. }
  5747. begin
  5748. if taicpu(hp1).opcode = A_Jcc then
  5749. begin
  5750. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5751. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5752. RemoveInstruction(hp1);
  5753. { Since hp1 was deleted, hp2 must not be updated }
  5754. Continue;
  5755. end
  5756. else
  5757. begin
  5758. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5759. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5760. taicpu(hp1).opcode := A_MOV;
  5761. taicpu(hp1).ops := 2;
  5762. taicpu(hp1).condition := C_None;
  5763. taicpu(hp1).opsize := S_B;
  5764. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5765. taicpu(hp1).loadconst(0, 0);
  5766. end;
  5767. end;
  5768. C_BE, C_NA:
  5769. begin
  5770. { Will only branch if equal to zero }
  5771. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5772. taicpu(hp1).condition := C_E;
  5773. end;
  5774. C_A, C_NBE:
  5775. begin
  5776. { Will only branch if not equal to zero }
  5777. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5778. taicpu(hp1).condition := C_NE;
  5779. end;
  5780. C_AE, C_NB, C_NC, C_NO:
  5781. begin
  5782. { Will always branch }
  5783. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5784. if taicpu(hp1).opcode = A_Jcc then
  5785. begin
  5786. MakeUnconditional(taicpu(hp1));
  5787. { Any jumps/set that follow will now be dead code }
  5788. RemoveDeadCodeAfterJump(taicpu(hp1));
  5789. Break;
  5790. end
  5791. else
  5792. begin
  5793. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5794. taicpu(hp1).opcode := A_MOV;
  5795. taicpu(hp1).ops := 2;
  5796. taicpu(hp1).condition := C_None;
  5797. taicpu(hp1).opsize := S_B;
  5798. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5799. taicpu(hp1).loadconst(0, 1);
  5800. end;
  5801. end;
  5802. C_None:
  5803. InternalError(2020012201);
  5804. C_P, C_PE, C_NP, C_PO:
  5805. { We can't handle parity checks and they should never be generated
  5806. after a general-purpose CMP (it's used in some floating-point
  5807. comparisons that don't use CMP) }
  5808. InternalError(2020012202);
  5809. else
  5810. { Zero/Equality, Sign, their complements and all of the
  5811. signed comparisons do not need to be converted };
  5812. end;
  5813. hp2 := hp1;
  5814. end;
  5815. { Convert the instruction to a TEST }
  5816. taicpu(p).opcode := A_TEST;
  5817. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5818. Result := True;
  5819. Exit;
  5820. end
  5821. else if (taicpu(p).oper[0]^.val = 1) and
  5822. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5823. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5824. begin
  5825. { Convert; To:
  5826. cmp $1,r/m cmp $0,r/m
  5827. jl @lbl jle @lbl
  5828. }
  5829. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5830. taicpu(p).oper[0]^.val := 0;
  5831. taicpu(hp1).condition := C_LE;
  5832. { If the instruction is now "cmp $0,%reg", convert it to a
  5833. TEST (and effectively do the work of the "cmp $0,%reg" in
  5834. the block above)
  5835. If it's a reference, we can get away with not setting
  5836. Result to True because he haven't evaluated the jump
  5837. in this pass yet.
  5838. }
  5839. if (taicpu(p).oper[1]^.typ = top_reg) then
  5840. begin
  5841. taicpu(p).opcode := A_TEST;
  5842. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5843. Result := True;
  5844. end;
  5845. Exit;
  5846. end
  5847. else if (taicpu(p).oper[1]^.typ = top_reg)
  5848. {$ifdef x86_64}
  5849. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5850. {$endif x86_64}
  5851. then
  5852. begin
  5853. { cmp register,$8000 neg register
  5854. je target --> jo target
  5855. .... only if register is deallocated before jump.}
  5856. case Taicpu(p).opsize of
  5857. S_B: v:=$80;
  5858. S_W: v:=$8000;
  5859. S_L: v:=qword($80000000);
  5860. else
  5861. internalerror(2013112905);
  5862. end;
  5863. if (taicpu(p).oper[0]^.val=v) and
  5864. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5865. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5866. begin
  5867. TransferUsedRegs(TmpUsedRegs);
  5868. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5869. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5870. begin
  5871. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5872. Taicpu(p).opcode:=A_NEG;
  5873. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5874. Taicpu(p).clearop(1);
  5875. Taicpu(p).ops:=1;
  5876. if Taicpu(hp1).condition=C_E then
  5877. Taicpu(hp1).condition:=C_O
  5878. else
  5879. Taicpu(hp1).condition:=C_NO;
  5880. Result:=true;
  5881. exit;
  5882. end;
  5883. end;
  5884. end;
  5885. end;
  5886. if TrySwapMovCmp(p, hp1) then
  5887. begin
  5888. Result := True;
  5889. Exit;
  5890. end;
  5891. end;
  5892. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5893. var
  5894. hp1: tai;
  5895. begin
  5896. {
  5897. remove the second (v)pxor from
  5898. pxor reg,reg
  5899. ...
  5900. pxor reg,reg
  5901. }
  5902. Result:=false;
  5903. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5904. MatchOpType(taicpu(p),top_reg,top_reg) and
  5905. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5906. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5907. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5908. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5909. begin
  5910. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5911. RemoveInstruction(hp1);
  5912. Result:=true;
  5913. Exit;
  5914. end
  5915. {
  5916. replace
  5917. pxor reg1,reg1
  5918. movapd/s reg1,reg2
  5919. dealloc reg1
  5920. by
  5921. pxor reg2,reg2
  5922. }
  5923. else if GetNextInstruction(p,hp1) and
  5924. { we mix single and double opperations here because we assume that the compiler
  5925. generates vmovapd only after double operations and vmovaps only after single operations }
  5926. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5927. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5928. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5929. (taicpu(p).oper[0]^.typ=top_reg) then
  5930. begin
  5931. TransferUsedRegs(TmpUsedRegs);
  5932. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5933. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5934. begin
  5935. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5936. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5937. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5938. RemoveInstruction(hp1);
  5939. result:=true;
  5940. end;
  5941. end;
  5942. end;
  5943. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5944. var
  5945. hp1: tai;
  5946. begin
  5947. {
  5948. remove the second (v)pxor from
  5949. (v)pxor reg,reg
  5950. ...
  5951. (v)pxor reg,reg
  5952. }
  5953. Result:=false;
  5954. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5955. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5956. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5957. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5958. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5959. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5960. begin
  5961. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5962. RemoveInstruction(hp1);
  5963. Result:=true;
  5964. Exit;
  5965. end
  5966. else
  5967. Result:=OptPass1VOP(p);
  5968. end;
  5969. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5970. var
  5971. hp1 : tai;
  5972. begin
  5973. result:=false;
  5974. { replace
  5975. IMul const,%mreg1,%mreg2
  5976. Mov %reg2,%mreg3
  5977. dealloc %mreg3
  5978. by
  5979. Imul const,%mreg1,%mreg23
  5980. }
  5981. if (taicpu(p).ops=3) and
  5982. GetNextInstruction(p,hp1) and
  5983. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5984. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5985. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5986. begin
  5987. TransferUsedRegs(TmpUsedRegs);
  5988. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5989. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5990. begin
  5991. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5992. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5993. RemoveInstruction(hp1);
  5994. result:=true;
  5995. end;
  5996. end;
  5997. end;
  5998. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5999. var
  6000. hp1 : tai;
  6001. begin
  6002. result:=false;
  6003. { replace
  6004. IMul %reg0,%reg1,%reg2
  6005. Mov %reg2,%reg3
  6006. dealloc %reg2
  6007. by
  6008. Imul %reg0,%reg1,%reg3
  6009. }
  6010. if GetNextInstruction(p,hp1) and
  6011. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6012. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6013. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6014. begin
  6015. TransferUsedRegs(TmpUsedRegs);
  6016. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6017. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6018. begin
  6019. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6020. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6021. RemoveInstruction(hp1);
  6022. result:=true;
  6023. end;
  6024. end;
  6025. end;
  6026. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6027. var
  6028. hp1: tai;
  6029. begin
  6030. Result:=false;
  6031. { get rid of
  6032. (v)cvtss2sd reg0,<reg1,>reg2
  6033. (v)cvtss2sd reg2,<reg2,>reg0
  6034. }
  6035. if GetNextInstruction(p,hp1) and
  6036. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6037. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6038. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6039. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6040. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6041. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6042. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6043. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6044. )
  6045. ) then
  6046. begin
  6047. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6048. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6049. begin
  6050. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6051. RemoveCurrentP(p);
  6052. RemoveInstruction(hp1);
  6053. end
  6054. else
  6055. begin
  6056. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6057. if taicpu(hp1).opcode=A_CVTSD2SS then
  6058. begin
  6059. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6060. taicpu(p).opcode:=A_MOVAPS;
  6061. end
  6062. else
  6063. begin
  6064. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6065. taicpu(p).opcode:=A_VMOVAPS;
  6066. end;
  6067. taicpu(p).ops:=2;
  6068. RemoveInstruction(hp1);
  6069. end;
  6070. Result:=true;
  6071. Exit;
  6072. end;
  6073. end;
  6074. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6075. var
  6076. hp1, hp2, hp3, hp4, hp5: tai;
  6077. ThisReg: TRegister;
  6078. begin
  6079. Result := False;
  6080. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6081. Exit;
  6082. {
  6083. convert
  6084. j<c> .L1
  6085. mov 1,reg
  6086. jmp .L2
  6087. .L1
  6088. mov 0,reg
  6089. .L2
  6090. into
  6091. mov 0,reg
  6092. set<not(c)> reg
  6093. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6094. would destroy the flag contents
  6095. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6096. executed at the same time as a previous comparison.
  6097. set<not(c)> reg
  6098. movzx reg, reg
  6099. }
  6100. if MatchInstruction(hp1,A_MOV,[]) and
  6101. (taicpu(hp1).oper[0]^.typ = top_const) and
  6102. (
  6103. (
  6104. (taicpu(hp1).oper[1]^.typ = top_reg)
  6105. {$ifdef i386}
  6106. { Under i386, ESI, EDI, EBP and ESP
  6107. don't have an 8-bit representation }
  6108. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6109. {$endif i386}
  6110. ) or (
  6111. {$ifdef i386}
  6112. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6113. {$endif i386}
  6114. (taicpu(hp1).opsize = S_B)
  6115. )
  6116. ) and
  6117. GetNextInstruction(hp1,hp2) and
  6118. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6119. GetNextInstruction(hp2,hp3) and
  6120. SkipAligns(hp3, hp3) and
  6121. (hp3.typ=ait_label) and
  6122. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6123. GetNextInstruction(hp3,hp4) and
  6124. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6125. (taicpu(hp4).oper[0]^.typ = top_const) and
  6126. (
  6127. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6128. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6129. ) and
  6130. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6131. GetNextInstruction(hp4,hp5) and
  6132. SkipAligns(hp5, hp5) and
  6133. (hp5.typ=ait_label) and
  6134. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6135. begin
  6136. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6137. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6138. tai_label(hp3).labsym.DecRefs;
  6139. { If this isn't the only reference to the middle label, we can
  6140. still make a saving - only that the first jump and everything
  6141. that follows will remain. }
  6142. if (tai_label(hp3).labsym.getrefs = 0) then
  6143. begin
  6144. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6145. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6146. else
  6147. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6148. { remove jump, first label and second MOV (also catching any aligns) }
  6149. repeat
  6150. if not GetNextInstruction(hp2, hp3) then
  6151. InternalError(2021040810);
  6152. RemoveInstruction(hp2);
  6153. hp2 := hp3;
  6154. until hp2 = hp5;
  6155. { Don't decrement reference count before the removal loop
  6156. above, otherwise GetNextInstruction won't stop on the
  6157. the label }
  6158. tai_label(hp5).labsym.DecRefs;
  6159. end
  6160. else
  6161. begin
  6162. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6163. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6164. else
  6165. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6166. end;
  6167. taicpu(p).opcode:=A_SETcc;
  6168. taicpu(p).opsize:=S_B;
  6169. taicpu(p).is_jmp:=False;
  6170. if taicpu(hp1).opsize=S_B then
  6171. begin
  6172. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6173. if taicpu(hp1).oper[1]^.typ = top_reg then
  6174. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6175. RemoveInstruction(hp1);
  6176. end
  6177. else
  6178. begin
  6179. { Will be a register because the size can't be S_B otherwise }
  6180. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6181. taicpu(p).loadreg(0, ThisReg);
  6182. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6183. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6184. begin
  6185. case taicpu(hp1).opsize of
  6186. S_W:
  6187. taicpu(hp1).opsize := S_BW;
  6188. S_L:
  6189. taicpu(hp1).opsize := S_BL;
  6190. {$ifdef x86_64}
  6191. S_Q:
  6192. begin
  6193. taicpu(hp1).opsize := S_BL;
  6194. { Change the destination register to 32-bit }
  6195. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6196. end;
  6197. {$endif x86_64}
  6198. else
  6199. InternalError(2021040820);
  6200. end;
  6201. taicpu(hp1).opcode := A_MOVZX;
  6202. taicpu(hp1).loadreg(0, ThisReg);
  6203. end
  6204. else
  6205. begin
  6206. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6207. { hp1 is already a MOV instruction with the correct register }
  6208. taicpu(hp1).loadconst(0, 0);
  6209. { Inserting it right before p will guarantee that the flags are also tracked }
  6210. asml.Remove(hp1);
  6211. asml.InsertBefore(hp1, p);
  6212. end;
  6213. end;
  6214. Result:=true;
  6215. exit;
  6216. end
  6217. end;
  6218. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6219. var
  6220. hp1, hp2, hp3: tai;
  6221. SourceRef, TargetRef: TReference;
  6222. CurrentReg: TRegister;
  6223. begin
  6224. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6225. if not UseAVX then
  6226. InternalError(2021100501);
  6227. Result := False;
  6228. { Look for the following to simplify:
  6229. vmovdqa/u x(mem1), %xmmreg
  6230. vmovdqa/u %xmmreg, y(mem2)
  6231. vmovdqa/u x+16(mem1), %xmmreg
  6232. vmovdqa/u %xmmreg, y+16(mem2)
  6233. Change to:
  6234. vmovdqa/u x(mem1), %ymmreg
  6235. vmovdqa/u %ymmreg, y(mem2)
  6236. vpxor %ymmreg, %ymmreg, %ymmreg
  6237. ( The VPXOR instruction is to zero the upper half, thus removing the
  6238. need to call the potentially expensive VZEROUPPER instruction. Other
  6239. peephole optimisations can remove VPXOR if it's unnecessary )
  6240. }
  6241. TransferUsedRegs(TmpUsedRegs);
  6242. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6243. { NOTE: In the optimisations below, if the references dictate that an
  6244. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6245. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6246. if (taicpu(p).opsize = S_XMM) and
  6247. MatchOpType(taicpu(p), top_ref, top_reg) and
  6248. GetNextInstruction(p, hp1) and
  6249. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6250. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6251. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6252. begin
  6253. SourceRef := taicpu(p).oper[0]^.ref^;
  6254. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6255. if GetNextInstruction(hp1, hp2) and
  6256. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6257. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6258. begin
  6259. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6260. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6261. Inc(SourceRef.offset, 16);
  6262. { Reuse the register in the first block move }
  6263. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6264. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6265. begin
  6266. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6267. Inc(TargetRef.offset, 16);
  6268. if GetNextInstruction(hp2, hp3) and
  6269. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6270. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6271. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6272. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6273. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6274. begin
  6275. { Update the register tracking to the new size }
  6276. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6277. { Remember that the offsets are 16 ahead }
  6278. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6279. if not (
  6280. ((SourceRef.offset mod 32) = 16) and
  6281. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6282. ) then
  6283. taicpu(p).opcode := A_VMOVDQU;
  6284. taicpu(p).opsize := S_YMM;
  6285. taicpu(p).oper[1]^.reg := CurrentReg;
  6286. if not (
  6287. ((TargetRef.offset mod 32) = 16) and
  6288. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6289. ) then
  6290. taicpu(hp1).opcode := A_VMOVDQU;
  6291. taicpu(hp1).opsize := S_YMM;
  6292. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6293. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6294. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6295. if (pi_uses_ymm in current_procinfo.flags) then
  6296. RemoveInstruction(hp2)
  6297. else
  6298. begin
  6299. taicpu(hp2).opcode := A_VPXOR;
  6300. taicpu(hp2).opsize := S_YMM;
  6301. taicpu(hp2).loadreg(0, CurrentReg);
  6302. taicpu(hp2).loadreg(1, CurrentReg);
  6303. taicpu(hp2).loadreg(2, CurrentReg);
  6304. taicpu(hp2).ops := 3;
  6305. end;
  6306. RemoveInstruction(hp3);
  6307. Result := True;
  6308. Exit;
  6309. end;
  6310. end
  6311. else
  6312. begin
  6313. { See if the next references are 16 less rather than 16 greater }
  6314. Dec(SourceRef.offset, 32); { -16 the other way }
  6315. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6316. begin
  6317. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6318. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6319. if GetNextInstruction(hp2, hp3) and
  6320. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6321. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6322. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6323. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6324. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6325. begin
  6326. { Update the register tracking to the new size }
  6327. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6328. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6329. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6330. if not(
  6331. ((SourceRef.offset mod 32) = 0) and
  6332. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6333. ) then
  6334. taicpu(hp2).opcode := A_VMOVDQU;
  6335. taicpu(hp2).opsize := S_YMM;
  6336. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6337. if not (
  6338. ((TargetRef.offset mod 32) = 0) and
  6339. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6340. ) then
  6341. taicpu(hp3).opcode := A_VMOVDQU;
  6342. taicpu(hp3).opsize := S_YMM;
  6343. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6344. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6345. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6346. if (pi_uses_ymm in current_procinfo.flags) then
  6347. RemoveInstruction(hp1)
  6348. else
  6349. begin
  6350. taicpu(hp1).opcode := A_VPXOR;
  6351. taicpu(hp1).opsize := S_YMM;
  6352. taicpu(hp1).loadreg(0, CurrentReg);
  6353. taicpu(hp1).loadreg(1, CurrentReg);
  6354. taicpu(hp1).loadreg(2, CurrentReg);
  6355. taicpu(hp1).ops := 3;
  6356. Asml.Remove(hp1);
  6357. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6358. end;
  6359. RemoveCurrentP(p, hp2);
  6360. Result := True;
  6361. Exit;
  6362. end;
  6363. end;
  6364. end;
  6365. end;
  6366. end;
  6367. end;
  6368. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6369. var
  6370. hp2, hp3, first_assignment: tai;
  6371. IncCount, OperIdx: Integer;
  6372. OrigLabel: TAsmLabel;
  6373. begin
  6374. Count := 0;
  6375. Result := False;
  6376. first_assignment := nil;
  6377. if (LoopCount >= 20) then
  6378. begin
  6379. { Guard against infinite loops }
  6380. Exit;
  6381. end;
  6382. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6383. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6384. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6385. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6386. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6387. Exit;
  6388. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6389. {
  6390. change
  6391. jmp .L1
  6392. ...
  6393. .L1:
  6394. mov ##, ## ( multiple movs possible )
  6395. jmp/ret
  6396. into
  6397. mov ##, ##
  6398. jmp/ret
  6399. }
  6400. if not Assigned(hp1) then
  6401. begin
  6402. hp1 := GetLabelWithSym(OrigLabel);
  6403. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6404. Exit;
  6405. end;
  6406. hp2 := hp1;
  6407. while Assigned(hp2) do
  6408. begin
  6409. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6410. SkipLabels(hp2,hp2);
  6411. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6412. Break;
  6413. case taicpu(hp2).opcode of
  6414. A_MOVSS:
  6415. begin
  6416. if taicpu(hp2).ops = 0 then
  6417. { Wrong MOVSS }
  6418. Break;
  6419. Inc(Count);
  6420. if Count >= 5 then
  6421. { Too many to be worthwhile }
  6422. Break;
  6423. GetNextInstruction(hp2, hp2);
  6424. Continue;
  6425. end;
  6426. A_MOV,
  6427. A_MOVD,
  6428. A_MOVQ,
  6429. A_MOVSX,
  6430. {$ifdef x86_64}
  6431. A_MOVSXD,
  6432. {$endif x86_64}
  6433. A_MOVZX,
  6434. A_MOVAPS,
  6435. A_MOVUPS,
  6436. A_MOVSD,
  6437. A_MOVAPD,
  6438. A_MOVUPD,
  6439. A_MOVDQA,
  6440. A_MOVDQU,
  6441. A_VMOVSS,
  6442. A_VMOVAPS,
  6443. A_VMOVUPS,
  6444. A_VMOVSD,
  6445. A_VMOVAPD,
  6446. A_VMOVUPD,
  6447. A_VMOVDQA,
  6448. A_VMOVDQU:
  6449. begin
  6450. Inc(Count);
  6451. if Count >= 5 then
  6452. { Too many to be worthwhile }
  6453. Break;
  6454. GetNextInstruction(hp2, hp2);
  6455. Continue;
  6456. end;
  6457. A_JMP:
  6458. begin
  6459. { Guard against infinite loops }
  6460. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6461. Exit;
  6462. { Analyse this jump first in case it also duplicates assignments }
  6463. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6464. begin
  6465. { Something did change! }
  6466. Result := True;
  6467. Inc(Count, IncCount);
  6468. if Count >= 5 then
  6469. begin
  6470. { Too many to be worthwhile }
  6471. Exit;
  6472. end;
  6473. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6474. Break;
  6475. end;
  6476. Result := True;
  6477. Break;
  6478. end;
  6479. A_RET:
  6480. begin
  6481. Result := True;
  6482. Break;
  6483. end;
  6484. else
  6485. Break;
  6486. end;
  6487. end;
  6488. if Result then
  6489. begin
  6490. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6491. if Count = 0 then
  6492. begin
  6493. Result := False;
  6494. Exit;
  6495. end;
  6496. hp3 := p;
  6497. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6498. while True do
  6499. begin
  6500. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6501. SkipLabels(hp1,hp1);
  6502. if (hp1.typ <> ait_instruction) then
  6503. InternalError(2021040720);
  6504. case taicpu(hp1).opcode of
  6505. A_JMP:
  6506. begin
  6507. { Change the original jump to the new destination }
  6508. OrigLabel.decrefs;
  6509. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6510. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6511. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6512. if not Assigned(first_assignment) then
  6513. InternalError(2021040810)
  6514. else
  6515. p := first_assignment;
  6516. Exit;
  6517. end;
  6518. A_RET:
  6519. begin
  6520. { Now change the jump into a RET instruction }
  6521. ConvertJumpToRET(p, hp1);
  6522. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6523. if not Assigned(first_assignment) then
  6524. InternalError(2021040811)
  6525. else
  6526. p := first_assignment;
  6527. Exit;
  6528. end;
  6529. else
  6530. begin
  6531. { Duplicate the MOV instruction }
  6532. hp3:=tai(hp1.getcopy);
  6533. if first_assignment = nil then
  6534. first_assignment := hp3;
  6535. asml.InsertBefore(hp3, p);
  6536. { Make sure the compiler knows about any final registers written here }
  6537. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6538. with taicpu(hp3).oper[OperIdx]^ do
  6539. begin
  6540. case typ of
  6541. top_ref:
  6542. begin
  6543. if (ref^.base <> NR_NO) and
  6544. (getsupreg(ref^.base) <> RS_ESP) and
  6545. (getsupreg(ref^.base) <> RS_EBP)
  6546. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6547. then
  6548. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6549. if (ref^.index <> NR_NO) and
  6550. (getsupreg(ref^.index) <> RS_ESP) and
  6551. (getsupreg(ref^.index) <> RS_EBP)
  6552. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6553. (ref^.index <> ref^.base) then
  6554. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6555. end;
  6556. top_reg:
  6557. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6558. else
  6559. ;
  6560. end;
  6561. end;
  6562. end;
  6563. end;
  6564. if not GetNextInstruction(hp1, hp1) then
  6565. { Should have dropped out earlier }
  6566. InternalError(2021040710);
  6567. end;
  6568. end;
  6569. end;
  6570. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6571. var
  6572. hp2: tai;
  6573. X: Integer;
  6574. const
  6575. WriteOp: array[0..3] of set of TInsChange = (
  6576. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6577. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6578. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6579. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6580. RegWriteFlags: array[0..7] of set of TInsChange = (
  6581. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6582. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6583. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6584. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6585. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6586. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6587. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6588. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6589. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6590. begin
  6591. { If we have something like:
  6592. cmp ###,%reg1
  6593. mov 0,%reg2
  6594. And no modified registers are shared, move the instruction to before
  6595. the comparison as this means it can be optimised without worrying
  6596. about the FLAGS register. (CMP/MOV is generated by
  6597. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6598. As long as the second instruction doesn't use the flags or one of the
  6599. registers used by CMP or TEST (also check any references that use the
  6600. registers), then it can be moved prior to the comparison.
  6601. }
  6602. Result := False;
  6603. if (hp1.typ <> ait_instruction) or
  6604. taicpu(hp1).is_jmp or
  6605. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6606. Exit;
  6607. { NOP is a pipeline fence, likely marking the beginning of the function
  6608. epilogue, so drop out. Similarly, drop out if POP or RET are
  6609. encountered }
  6610. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6611. Exit;
  6612. if (taicpu(hp1).opcode = A_MOVSS) and
  6613. (taicpu(hp1).ops = 0) then
  6614. { Wrong MOVSS }
  6615. Exit;
  6616. { Check for writes to specific registers first }
  6617. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6618. for X := 0 to 7 do
  6619. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6620. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6621. Exit;
  6622. for X := 0 to taicpu(hp1).ops - 1 do
  6623. begin
  6624. { Check to see if this operand writes to something }
  6625. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6626. { And matches something in the CMP/TEST instruction }
  6627. (
  6628. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6629. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6630. (
  6631. { If it's a register, make sure the register written to doesn't
  6632. appear in the cmp instruction as part of a reference }
  6633. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6634. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6635. )
  6636. ) then
  6637. Exit;
  6638. end;
  6639. { The instruction can be safely moved }
  6640. asml.Remove(hp1);
  6641. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6642. if not GetLastInstruction(p, hp2) then
  6643. asml.InsertBefore(hp1, p)
  6644. else
  6645. asml.InsertAfter(hp1, hp2);
  6646. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6647. for X := 0 to taicpu(hp1).ops - 1 do
  6648. case taicpu(hp1).oper[X]^.typ of
  6649. top_reg:
  6650. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6651. top_ref:
  6652. begin
  6653. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6654. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6655. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6656. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6657. end;
  6658. else
  6659. ;
  6660. end;
  6661. if taicpu(hp1).opcode = A_LEA then
  6662. { The flags will be overwritten by the CMP/TEST instruction }
  6663. ConvertLEA(taicpu(hp1));
  6664. Result := True;
  6665. end;
  6666. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6667. function IsXCHGAcceptable: Boolean; inline;
  6668. begin
  6669. { Always accept if optimising for size }
  6670. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6671. (
  6672. {$ifdef x86_64}
  6673. { XCHG takes 3 cycles on AMD Athlon64 }
  6674. (current_settings.optimizecputype >= cpu_core_i)
  6675. {$else x86_64}
  6676. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6677. than 3, so it becomes a saving compared to three MOVs with two of
  6678. them able to execute simultaneously. [Kit] }
  6679. (current_settings.optimizecputype >= cpu_PentiumM)
  6680. {$endif x86_64}
  6681. );
  6682. end;
  6683. var
  6684. NewRef: TReference;
  6685. hp1, hp2, hp3, hp4: Tai;
  6686. {$ifndef x86_64}
  6687. OperIdx: Integer;
  6688. {$endif x86_64}
  6689. NewInstr : Taicpu;
  6690. NewAligh : Tai_align;
  6691. DestLabel: TAsmLabel;
  6692. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6693. var
  6694. NextInstr: tai;
  6695. begin
  6696. Result := False;
  6697. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6698. if not GetNextInstruction(InputInstr, NextInstr) or
  6699. (
  6700. { The FLAGS register isn't always tracked properly, so do not
  6701. perform this optimisation if a conditional statement follows }
  6702. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6703. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6704. ) then
  6705. begin
  6706. reference_reset(NewRef, 1, []);
  6707. NewRef.base := taicpu(p).oper[0]^.reg;
  6708. NewRef.scalefactor := 1;
  6709. if taicpu(InputInstr).opcode = A_ADD then
  6710. begin
  6711. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6712. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6713. end
  6714. else
  6715. begin
  6716. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6717. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6718. end;
  6719. taicpu(p).opcode := A_LEA;
  6720. taicpu(p).loadref(0, NewRef);
  6721. RemoveInstruction(InputInstr);
  6722. Result := True;
  6723. end;
  6724. end;
  6725. begin
  6726. Result:=false;
  6727. { This optimisation adds an instruction, so only do it for speed }
  6728. if not (cs_opt_size in current_settings.optimizerswitches) and
  6729. MatchOpType(taicpu(p), top_const, top_reg) and
  6730. (taicpu(p).oper[0]^.val = 0) then
  6731. begin
  6732. { To avoid compiler warning }
  6733. DestLabel := nil;
  6734. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6735. InternalError(2021040750);
  6736. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6737. Exit;
  6738. case hp1.typ of
  6739. ait_label:
  6740. begin
  6741. { Change:
  6742. mov $0,%reg mov $0,%reg
  6743. @Lbl1: @Lbl1:
  6744. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6745. je @Lbl2 jne @Lbl2
  6746. To: To:
  6747. mov $0,%reg mov $0,%reg
  6748. jmp @Lbl2 jmp @Lbl3
  6749. (align) (align)
  6750. @Lbl1: @Lbl1:
  6751. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6752. je @Lbl2 je @Lbl2
  6753. @Lbl3: <-- Only if label exists
  6754. (Not if it's optimised for size)
  6755. }
  6756. if not GetNextInstruction(hp1, hp2) then
  6757. Exit;
  6758. if not (cs_opt_size in current_settings.optimizerswitches) and
  6759. (hp2.typ = ait_instruction) and
  6760. (
  6761. { Register sizes must exactly match }
  6762. (
  6763. (taicpu(hp2).opcode = A_CMP) and
  6764. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6765. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6766. ) or (
  6767. (taicpu(hp2).opcode = A_TEST) and
  6768. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6769. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6770. )
  6771. ) and GetNextInstruction(hp2, hp3) and
  6772. (hp3.typ = ait_instruction) and
  6773. (taicpu(hp3).opcode = A_JCC) and
  6774. (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
  6775. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6776. begin
  6777. { Check condition of jump }
  6778. { Always true? }
  6779. if condition_in(C_E, taicpu(hp3).condition) then
  6780. begin
  6781. { Copy label symbol and obtain matching label entry for the
  6782. conditional jump, as this will be our destination}
  6783. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6784. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6785. Result := True;
  6786. end
  6787. { Always false? }
  6788. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6789. begin
  6790. { This is only worth it if there's a jump to take }
  6791. case hp2.typ of
  6792. ait_instruction:
  6793. begin
  6794. if taicpu(hp2).opcode = A_JMP then
  6795. begin
  6796. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6797. { An unconditional jump follows the conditional jump which will always be false,
  6798. so use this jump's destination for the new jump }
  6799. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6800. Result := True;
  6801. end
  6802. else if taicpu(hp2).opcode = A_JCC then
  6803. begin
  6804. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6805. if condition_in(C_E, taicpu(hp2).condition) then
  6806. begin
  6807. { A second conditional jump follows the conditional jump which will always be false,
  6808. while the second jump is always True, so use this jump's destination for the new jump }
  6809. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6810. Result := True;
  6811. end;
  6812. { Don't risk it if the jump isn't always true (Result remains False) }
  6813. end;
  6814. end;
  6815. else
  6816. { If anything else don't optimise };
  6817. end;
  6818. end;
  6819. if Result then
  6820. begin
  6821. { Just so we have something to insert as a paremeter}
  6822. reference_reset(NewRef, 1, []);
  6823. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6824. { Now actually load the correct parameter }
  6825. NewInstr.loadsymbol(0, DestLabel, 0);
  6826. { Get instruction before original label (may not be p under -O3) }
  6827. if not GetLastInstruction(hp1, hp2) then
  6828. { Shouldn't fail here }
  6829. InternalError(2021040701);
  6830. DestLabel.increfs;
  6831. AsmL.InsertAfter(NewInstr, hp2);
  6832. { Add new alignment field }
  6833. (* AsmL.InsertAfter(
  6834. cai_align.create_max(
  6835. current_settings.alignment.jumpalign,
  6836. current_settings.alignment.jumpalignskipmax
  6837. ),
  6838. NewInstr
  6839. ); *)
  6840. end;
  6841. Exit;
  6842. end;
  6843. end;
  6844. else
  6845. ;
  6846. end;
  6847. end;
  6848. if not GetNextInstruction(p, hp1) then
  6849. Exit;
  6850. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6851. begin
  6852. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6853. further, but we can't just put this jump optimisation in pass 1
  6854. because it tends to perform worse when conditional jumps are
  6855. nearby (e.g. when converting CMOV instructions). [Kit] }
  6856. if OptPass2JMP(hp1) then
  6857. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6858. Result := OptPass1MOV(p)
  6859. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6860. returned True and the instruction is still a MOV, thus checking
  6861. the optimisations below }
  6862. { If OptPass2JMP returned False, no optimisations were done to
  6863. the jump and there are no further optimisations that can be done
  6864. to the MOV instruction on this pass }
  6865. end
  6866. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6867. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6868. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6869. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6870. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6871. begin
  6872. { Change:
  6873. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6874. addl/q $x,%reg2 subl/q $x,%reg2
  6875. To:
  6876. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6877. }
  6878. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6879. { be lazy, checking separately for sub would be slightly better }
  6880. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6881. begin
  6882. TransferUsedRegs(TmpUsedRegs);
  6883. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6884. if TryMovArith2Lea(hp1) then
  6885. begin
  6886. Result := True;
  6887. Exit;
  6888. end
  6889. end
  6890. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6891. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6892. { Same as above, but also adds or subtracts to %reg2 in between.
  6893. It's still valid as long as the flags aren't in use }
  6894. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6895. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6896. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6897. { be lazy, checking separately for sub would be slightly better }
  6898. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6899. begin
  6900. TransferUsedRegs(TmpUsedRegs);
  6901. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6903. if TryMovArith2Lea(hp2) then
  6904. begin
  6905. Result := True;
  6906. Exit;
  6907. end;
  6908. end;
  6909. end
  6910. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6911. {$ifdef x86_64}
  6912. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6913. {$else x86_64}
  6914. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6915. {$endif x86_64}
  6916. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6917. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6918. { mov reg1, reg2 mov reg1, reg2
  6919. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6920. begin
  6921. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6922. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6923. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6924. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6925. TransferUsedRegs(TmpUsedRegs);
  6926. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6927. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6928. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6929. then
  6930. begin
  6931. RemoveCurrentP(p, hp1);
  6932. Result:=true;
  6933. end;
  6934. exit;
  6935. end
  6936. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6937. IsXCHGAcceptable and
  6938. { XCHG doesn't support 8-byte registers }
  6939. (taicpu(p).opsize <> S_B) and
  6940. MatchInstruction(hp1, A_MOV, []) and
  6941. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6942. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6943. GetNextInstruction(hp1, hp2) and
  6944. MatchInstruction(hp2, A_MOV, []) and
  6945. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6946. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6947. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6948. begin
  6949. { mov %reg1,%reg2
  6950. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6951. mov %reg2,%reg3
  6952. (%reg2 not used afterwards)
  6953. Note that xchg takes 3 cycles to execute, and generally mov's take
  6954. only one cycle apiece, but the first two mov's can be executed in
  6955. parallel, only taking 2 cycles overall. Older processors should
  6956. therefore only optimise for size. [Kit]
  6957. }
  6958. TransferUsedRegs(TmpUsedRegs);
  6959. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6960. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6961. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6962. begin
  6963. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6964. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6965. taicpu(hp1).opcode := A_XCHG;
  6966. RemoveCurrentP(p, hp1);
  6967. RemoveInstruction(hp2);
  6968. Result := True;
  6969. Exit;
  6970. end;
  6971. end
  6972. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6973. MatchInstruction(hp1, A_SAR, []) then
  6974. begin
  6975. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6976. begin
  6977. { the use of %edx also covers the opsize being S_L }
  6978. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6979. begin
  6980. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6981. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6982. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6983. begin
  6984. { Change:
  6985. movl %eax,%edx
  6986. sarl $31,%edx
  6987. To:
  6988. cltd
  6989. }
  6990. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6991. RemoveInstruction(hp1);
  6992. taicpu(p).opcode := A_CDQ;
  6993. taicpu(p).opsize := S_NO;
  6994. taicpu(p).clearop(1);
  6995. taicpu(p).clearop(0);
  6996. taicpu(p).ops:=0;
  6997. Result := True;
  6998. end
  6999. else if (cs_opt_size in current_settings.optimizerswitches) and
  7000. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7001. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7002. begin
  7003. { Change:
  7004. movl %edx,%eax
  7005. sarl $31,%edx
  7006. To:
  7007. movl %edx,%eax
  7008. cltd
  7009. Note that this creates a dependency between the two instructions,
  7010. so only perform if optimising for size.
  7011. }
  7012. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7013. taicpu(hp1).opcode := A_CDQ;
  7014. taicpu(hp1).opsize := S_NO;
  7015. taicpu(hp1).clearop(1);
  7016. taicpu(hp1).clearop(0);
  7017. taicpu(hp1).ops:=0;
  7018. end;
  7019. {$ifndef x86_64}
  7020. end
  7021. { Don't bother if CMOV is supported, because a more optimal
  7022. sequence would have been generated for the Abs() intrinsic }
  7023. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7024. { the use of %eax also covers the opsize being S_L }
  7025. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7026. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7027. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7028. GetNextInstruction(hp1, hp2) and
  7029. MatchInstruction(hp2, A_XOR, [S_L]) and
  7030. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7031. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7032. GetNextInstruction(hp2, hp3) and
  7033. MatchInstruction(hp3, A_SUB, [S_L]) and
  7034. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7035. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7036. begin
  7037. { Change:
  7038. movl %eax,%edx
  7039. sarl $31,%eax
  7040. xorl %eax,%edx
  7041. subl %eax,%edx
  7042. (Instruction that uses %edx)
  7043. (%eax deallocated)
  7044. (%edx deallocated)
  7045. To:
  7046. cltd
  7047. xorl %edx,%eax <-- Note the registers have swapped
  7048. subl %edx,%eax
  7049. (Instruction that uses %eax) <-- %eax rather than %edx
  7050. }
  7051. TransferUsedRegs(TmpUsedRegs);
  7052. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7053. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7054. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7055. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7056. begin
  7057. if GetNextInstruction(hp3, hp4) and
  7058. not RegModifiedByInstruction(NR_EDX, hp4) and
  7059. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7060. begin
  7061. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7062. taicpu(p).opcode := A_CDQ;
  7063. taicpu(p).clearop(1);
  7064. taicpu(p).clearop(0);
  7065. taicpu(p).ops:=0;
  7066. RemoveInstruction(hp1);
  7067. taicpu(hp2).loadreg(0, NR_EDX);
  7068. taicpu(hp2).loadreg(1, NR_EAX);
  7069. taicpu(hp3).loadreg(0, NR_EDX);
  7070. taicpu(hp3).loadreg(1, NR_EAX);
  7071. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7072. { Convert references in the following instruction (hp4) from %edx to %eax }
  7073. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7074. with taicpu(hp4).oper[OperIdx]^ do
  7075. case typ of
  7076. top_reg:
  7077. if getsupreg(reg) = RS_EDX then
  7078. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7079. top_ref:
  7080. begin
  7081. if getsupreg(reg) = RS_EDX then
  7082. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7083. if getsupreg(reg) = RS_EDX then
  7084. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7085. end;
  7086. else
  7087. ;
  7088. end;
  7089. end;
  7090. end;
  7091. {$else x86_64}
  7092. end;
  7093. end
  7094. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7095. { the use of %rdx also covers the opsize being S_Q }
  7096. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7097. begin
  7098. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7099. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7100. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7101. begin
  7102. { Change:
  7103. movq %rax,%rdx
  7104. sarq $63,%rdx
  7105. To:
  7106. cqto
  7107. }
  7108. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7109. RemoveInstruction(hp1);
  7110. taicpu(p).opcode := A_CQO;
  7111. taicpu(p).opsize := S_NO;
  7112. taicpu(p).clearop(1);
  7113. taicpu(p).clearop(0);
  7114. taicpu(p).ops:=0;
  7115. Result := True;
  7116. end
  7117. else if (cs_opt_size in current_settings.optimizerswitches) and
  7118. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7119. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7120. begin
  7121. { Change:
  7122. movq %rdx,%rax
  7123. sarq $63,%rdx
  7124. To:
  7125. movq %rdx,%rax
  7126. cqto
  7127. Note that this creates a dependency between the two instructions,
  7128. so only perform if optimising for size.
  7129. }
  7130. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7131. taicpu(hp1).opcode := A_CQO;
  7132. taicpu(hp1).opsize := S_NO;
  7133. taicpu(hp1).clearop(1);
  7134. taicpu(hp1).clearop(0);
  7135. taicpu(hp1).ops:=0;
  7136. {$endif x86_64}
  7137. end;
  7138. end;
  7139. end
  7140. else if MatchInstruction(hp1, A_MOV, []) and
  7141. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7142. { Though "GetNextInstruction" could be factored out, along with
  7143. the instructions that depend on hp2, it is an expensive call that
  7144. should be delayed for as long as possible, hence we do cheaper
  7145. checks first that are likely to be False. [Kit] }
  7146. begin
  7147. if (
  7148. (
  7149. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7150. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7151. (
  7152. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7153. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7154. )
  7155. ) or
  7156. (
  7157. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7158. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7159. (
  7160. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7161. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7162. )
  7163. )
  7164. ) and
  7165. GetNextInstruction(hp1, hp2) and
  7166. MatchInstruction(hp2, A_SAR, []) and
  7167. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7168. begin
  7169. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7170. begin
  7171. { Change:
  7172. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7173. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7174. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7175. To:
  7176. movl r/m,%eax <- Note the change in register
  7177. cltd
  7178. }
  7179. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7180. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7181. taicpu(p).loadreg(1, NR_EAX);
  7182. taicpu(hp1).opcode := A_CDQ;
  7183. taicpu(hp1).clearop(1);
  7184. taicpu(hp1).clearop(0);
  7185. taicpu(hp1).ops:=0;
  7186. RemoveInstruction(hp2);
  7187. (*
  7188. {$ifdef x86_64}
  7189. end
  7190. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7191. { This code sequence does not get generated - however it might become useful
  7192. if and when 128-bit signed integer types make an appearance, so the code
  7193. is kept here for when it is eventually needed. [Kit] }
  7194. (
  7195. (
  7196. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7197. (
  7198. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7199. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7200. )
  7201. ) or
  7202. (
  7203. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7204. (
  7205. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7206. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7207. )
  7208. )
  7209. ) and
  7210. GetNextInstruction(hp1, hp2) and
  7211. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7212. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7213. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7214. begin
  7215. { Change:
  7216. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7217. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7218. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7219. To:
  7220. movq r/m,%rax <- Note the change in register
  7221. cqto
  7222. }
  7223. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7224. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7225. taicpu(p).loadreg(1, NR_RAX);
  7226. taicpu(hp1).opcode := A_CQO;
  7227. taicpu(hp1).clearop(1);
  7228. taicpu(hp1).clearop(0);
  7229. taicpu(hp1).ops:=0;
  7230. RemoveInstruction(hp2);
  7231. {$endif x86_64}
  7232. *)
  7233. end;
  7234. end;
  7235. {$ifdef x86_64}
  7236. end
  7237. else if (taicpu(p).opsize = S_L) and
  7238. (taicpu(p).oper[1]^.typ = top_reg) and
  7239. (
  7240. MatchInstruction(hp1, A_MOV,[]) and
  7241. (taicpu(hp1).opsize = S_L) and
  7242. (taicpu(hp1).oper[1]^.typ = top_reg)
  7243. ) and (
  7244. GetNextInstruction(hp1, hp2) and
  7245. (tai(hp2).typ=ait_instruction) and
  7246. (taicpu(hp2).opsize = S_Q) and
  7247. (
  7248. (
  7249. MatchInstruction(hp2, A_ADD,[]) and
  7250. (taicpu(hp2).opsize = S_Q) and
  7251. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7252. (
  7253. (
  7254. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7255. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7256. ) or (
  7257. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7258. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7259. )
  7260. )
  7261. ) or (
  7262. MatchInstruction(hp2, A_LEA,[]) and
  7263. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7264. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7265. (
  7266. (
  7267. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7268. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7269. ) or (
  7270. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7271. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7272. )
  7273. ) and (
  7274. (
  7275. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7276. ) or (
  7277. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7278. )
  7279. )
  7280. )
  7281. )
  7282. ) and (
  7283. GetNextInstruction(hp2, hp3) and
  7284. MatchInstruction(hp3, A_SHR,[]) and
  7285. (taicpu(hp3).opsize = S_Q) and
  7286. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7287. (taicpu(hp3).oper[0]^.val = 1) and
  7288. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7289. ) then
  7290. begin
  7291. { Change movl x, reg1d movl x, reg1d
  7292. movl y, reg2d movl y, reg2d
  7293. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7294. shrq $1, reg1q shrq $1, reg1q
  7295. ( reg1d and reg2d can be switched around in the first two instructions )
  7296. To movl x, reg1d
  7297. addl y, reg1d
  7298. rcrl $1, reg1d
  7299. This corresponds to the common expression (x + y) shr 1, where
  7300. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7301. smaller code, but won't account for x + y causing an overflow). [Kit]
  7302. }
  7303. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7304. { Change first MOV command to have the same register as the final output }
  7305. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7306. else
  7307. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7308. { Change second MOV command to an ADD command. This is easier than
  7309. converting the existing command because it means we don't have to
  7310. touch 'y', which might be a complicated reference, and also the
  7311. fact that the third command might either be ADD or LEA. [Kit] }
  7312. taicpu(hp1).opcode := A_ADD;
  7313. { Delete old ADD/LEA instruction }
  7314. RemoveInstruction(hp2);
  7315. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7316. taicpu(hp3).opcode := A_RCR;
  7317. taicpu(hp3).changeopsize(S_L);
  7318. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7319. {$endif x86_64}
  7320. end;
  7321. end;
  7322. {$push}
  7323. {$q-}{$r-}
  7324. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7325. var
  7326. ThisReg: TRegister;
  7327. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7328. TargetSubReg: TSubRegister;
  7329. hp1, hp2: tai;
  7330. RegInUse, RegChanged, p_removed: Boolean;
  7331. { Store list of found instructions so we don't have to call
  7332. GetNextInstructionUsingReg multiple times }
  7333. InstrList: array of taicpu;
  7334. InstrMax, Index: Integer;
  7335. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7336. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7337. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7338. WorkingValue: TCgInt;
  7339. PreMessage: string;
  7340. { Data flow analysis }
  7341. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7342. BitwiseOnly, OrXorUsed,
  7343. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7344. function CheckOverflowConditions: Boolean;
  7345. begin
  7346. Result := True;
  7347. if (TestValSignedMax > SignedUpperLimit) then
  7348. UpperSignedOverflow := True;
  7349. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7350. LowerSignedOverflow := True;
  7351. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7352. LowerUnsignedOverflow := True;
  7353. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7354. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7355. begin
  7356. { Absolute overflow }
  7357. Result := False;
  7358. Exit;
  7359. end;
  7360. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7361. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7362. ShiftDownOverflow := True;
  7363. if (TestValMin < 0) or (TestValMax < 0) then
  7364. begin
  7365. LowerUnsignedOverflow := True;
  7366. UpperUnsignedOverflow := True;
  7367. end;
  7368. end;
  7369. procedure AdjustFinalLoad;
  7370. begin
  7371. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7372. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7373. begin
  7374. { Convert the output MOVZX to a MOV }
  7375. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7376. begin
  7377. { Or remove it completely! }
  7378. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7379. { Be careful; if p = hp1 and p was also removed, p
  7380. will become a dangling pointer }
  7381. if p = hp1 then
  7382. begin
  7383. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7384. p_removed := True;
  7385. end
  7386. else
  7387. RemoveInstruction(hp1);
  7388. end
  7389. else
  7390. begin
  7391. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7392. taicpu(hp1).opcode := A_MOV;
  7393. taicpu(hp1).oper[0]^.reg := ThisReg;
  7394. taicpu(hp1).opsize := TargetSize;
  7395. end;
  7396. end
  7397. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7398. begin
  7399. { Need to change the size of the output }
  7400. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7401. taicpu(hp1).oper[0]^.reg := ThisReg;
  7402. taicpu(hp1).opsize := S_BL;
  7403. end;
  7404. end;
  7405. function CompressInstructions: Boolean;
  7406. var
  7407. LocalIndex: Integer;
  7408. begin
  7409. Result := False;
  7410. { The objective here is to try to find a combination that
  7411. removes one of the MOV/Z instructions. }
  7412. if (
  7413. (taicpu(p).oper[0]^.typ <> top_reg) or
  7414. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7415. ) and
  7416. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7417. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7418. begin
  7419. { Make a preference to remove the second MOVZX instruction }
  7420. case taicpu(hp1).opsize of
  7421. S_BL, S_WL:
  7422. begin
  7423. TargetSize := S_L;
  7424. TargetSubReg := R_SUBD;
  7425. end;
  7426. S_BW:
  7427. begin
  7428. TargetSize := S_W;
  7429. TargetSubReg := R_SUBW;
  7430. end;
  7431. else
  7432. InternalError(2020112302);
  7433. end;
  7434. end
  7435. else
  7436. begin
  7437. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7438. begin
  7439. { Exceeded lower bound but not upper bound }
  7440. TargetSize := MaxSize;
  7441. end
  7442. else if not LowerUnsignedOverflow then
  7443. begin
  7444. { Size didn't exceed lower bound }
  7445. TargetSize := MinSize;
  7446. end
  7447. else
  7448. Exit;
  7449. end;
  7450. case TargetSize of
  7451. S_B:
  7452. TargetSubReg := R_SUBL;
  7453. S_W:
  7454. TargetSubReg := R_SUBW;
  7455. S_L:
  7456. TargetSubReg := R_SUBD;
  7457. else
  7458. InternalError(2020112350);
  7459. end;
  7460. { Update the register to its new size }
  7461. setsubreg(ThisReg, TargetSubReg);
  7462. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7463. begin
  7464. { Check to see if the active register is used afterwards;
  7465. if not, we can change it and make a saving. }
  7466. RegInUse := False;
  7467. TransferUsedRegs(TmpUsedRegs);
  7468. { The target register may be marked as in use to cross
  7469. a jump to a distant label, so exclude it }
  7470. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7471. hp2 := p;
  7472. repeat
  7473. { Explicitly check for the excluded register (don't include the first
  7474. instruction as it may be reading from here }
  7475. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7476. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7477. begin
  7478. RegInUse := True;
  7479. Break;
  7480. end;
  7481. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7482. if not GetNextInstruction(hp2, hp2) then
  7483. InternalError(2020112340);
  7484. until (hp2 = hp1);
  7485. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7486. { We might still be able to get away with this }
  7487. RegInUse := not
  7488. (
  7489. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7490. (hp2.typ = ait_instruction) and
  7491. (
  7492. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7493. instruction that doesn't actually contain ThisReg }
  7494. (cs_opt_level3 in current_settings.optimizerswitches) or
  7495. RegInInstruction(ThisReg, hp2)
  7496. ) and
  7497. RegLoadedWithNewValue(ThisReg, hp2)
  7498. );
  7499. if not RegInUse then
  7500. begin
  7501. { Force the register size to the same as this instruction so it can be removed}
  7502. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7503. begin
  7504. TargetSize := S_L;
  7505. TargetSubReg := R_SUBD;
  7506. end
  7507. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7508. begin
  7509. TargetSize := S_W;
  7510. TargetSubReg := R_SUBW;
  7511. end;
  7512. ThisReg := taicpu(hp1).oper[1]^.reg;
  7513. setsubreg(ThisReg, TargetSubReg);
  7514. RegChanged := True;
  7515. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7516. TransferUsedRegs(TmpUsedRegs);
  7517. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7518. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7519. if p = hp1 then
  7520. begin
  7521. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7522. p_removed := True;
  7523. end
  7524. else
  7525. RemoveInstruction(hp1);
  7526. { Instruction will become "mov %reg,%reg" }
  7527. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7528. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7529. begin
  7530. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7531. RemoveCurrentP(p);
  7532. p_removed := True;
  7533. end
  7534. else
  7535. taicpu(p).oper[1]^.reg := ThisReg;
  7536. Result := True;
  7537. end
  7538. else
  7539. begin
  7540. if TargetSize <> MaxSize then
  7541. begin
  7542. { Since the register is in use, we have to force it to
  7543. MaxSize otherwise part of it may become undefined later on }
  7544. TargetSize := MaxSize;
  7545. case TargetSize of
  7546. S_B:
  7547. TargetSubReg := R_SUBL;
  7548. S_W:
  7549. TargetSubReg := R_SUBW;
  7550. S_L:
  7551. TargetSubReg := R_SUBD;
  7552. else
  7553. InternalError(2020112351);
  7554. end;
  7555. setsubreg(ThisReg, TargetSubReg);
  7556. end;
  7557. AdjustFinalLoad;
  7558. end;
  7559. end
  7560. else
  7561. AdjustFinalLoad;
  7562. if not p_removed then
  7563. begin
  7564. if TargetSize = MinSize then
  7565. begin
  7566. { Convert the input MOVZX to a MOV }
  7567. if (taicpu(p).oper[0]^.typ = top_reg) and
  7568. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7569. begin
  7570. { Or remove it completely! }
  7571. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7572. DebugMsg(SPeepholeOptimization + tostr(InstrMax), p);
  7573. RemoveCurrentP(p);
  7574. p_removed := True;
  7575. end
  7576. else
  7577. begin
  7578. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7579. taicpu(p).opcode := A_MOV;
  7580. taicpu(p).oper[1]^.reg := ThisReg;
  7581. taicpu(p).opsize := TargetSize;
  7582. end;
  7583. Result := True;
  7584. end
  7585. else if TargetSize <> MaxSize then
  7586. begin
  7587. case MaxSize of
  7588. S_L:
  7589. if TargetSize = S_W then
  7590. begin
  7591. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7592. taicpu(p).opsize := S_BW;
  7593. taicpu(p).oper[1]^.reg := ThisReg;
  7594. Result := True;
  7595. end
  7596. else
  7597. InternalError(2020112341);
  7598. S_W:
  7599. if TargetSize = S_L then
  7600. begin
  7601. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7602. taicpu(p).opsize := S_BL;
  7603. taicpu(p).oper[1]^.reg := ThisReg;
  7604. Result := True;
  7605. end
  7606. else
  7607. InternalError(2020112342);
  7608. else
  7609. ;
  7610. end;
  7611. end;
  7612. end;
  7613. { Now go through every instruction we found and change the
  7614. size. If TargetSize = MaxSize, then almost no changes are
  7615. needed and Result can remain False if it hasn't been set
  7616. yet.
  7617. If RegChanged is True, then the register requires changing
  7618. and so the point about TargetSize = MaxSize doesn't apply. }
  7619. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7620. begin
  7621. for LocalIndex := 0 to InstrMax do
  7622. begin
  7623. { If p_removed is true, then the original MOV/Z was removed
  7624. and removing the AND instruction may not be safe if it
  7625. appears first }
  7626. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7627. InternalError(2020112310);
  7628. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7629. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7630. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7631. InstrList[LocalIndex].opsize := TargetSize;
  7632. end;
  7633. Result := True;
  7634. end;
  7635. end;
  7636. begin
  7637. Result := False;
  7638. p_removed := False;
  7639. ThisReg := taicpu(p).oper[1]^.reg;
  7640. { Check for:
  7641. movs/z ###,%ecx (or %cx or %rcx)
  7642. ...
  7643. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7644. (dealloc %ecx)
  7645. Change to:
  7646. mov ###,%cl (if ### = %cl, then remove completely)
  7647. ...
  7648. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7649. }
  7650. if (getsupreg(ThisReg) = RS_ECX) and
  7651. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7652. (hp1.typ = ait_instruction) and
  7653. (
  7654. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7655. instruction that doesn't actually contain ECX }
  7656. (cs_opt_level3 in current_settings.optimizerswitches) or
  7657. RegInInstruction(NR_ECX, hp1) or
  7658. (
  7659. { It's common for the shift/rotate's read/write register to be
  7660. initialised in between, so under -O2 and under, search ahead
  7661. one more instruction
  7662. }
  7663. GetNextInstruction(hp1, hp1) and
  7664. (hp1.typ = ait_instruction) and
  7665. RegInInstruction(NR_ECX, hp1)
  7666. )
  7667. ) and
  7668. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7669. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7670. begin
  7671. TransferUsedRegs(TmpUsedRegs);
  7672. hp2 := p;
  7673. repeat
  7674. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7675. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7676. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7677. begin
  7678. case taicpu(p).opsize of
  7679. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7680. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7681. begin
  7682. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7683. RemoveCurrentP(p);
  7684. end
  7685. else
  7686. begin
  7687. taicpu(p).opcode := A_MOV;
  7688. taicpu(p).opsize := S_B;
  7689. taicpu(p).oper[1]^.reg := NR_CL;
  7690. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7691. end;
  7692. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7693. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7694. begin
  7695. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7696. RemoveCurrentP(p);
  7697. end
  7698. else
  7699. begin
  7700. taicpu(p).opcode := A_MOV;
  7701. taicpu(p).opsize := S_W;
  7702. taicpu(p).oper[1]^.reg := NR_CX;
  7703. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7704. end;
  7705. {$ifdef x86_64}
  7706. S_LQ:
  7707. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7708. begin
  7709. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7710. RemoveCurrentP(p);
  7711. end
  7712. else
  7713. begin
  7714. taicpu(p).opcode := A_MOV;
  7715. taicpu(p).opsize := S_L;
  7716. taicpu(p).oper[1]^.reg := NR_ECX;
  7717. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7718. end;
  7719. {$endif x86_64}
  7720. else
  7721. InternalError(2021120401);
  7722. end;
  7723. Result := True;
  7724. Exit;
  7725. end;
  7726. end;
  7727. { This is anything but quick! }
  7728. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7729. Exit;
  7730. SetLength(InstrList, 0);
  7731. InstrMax := -1;
  7732. case taicpu(p).opsize of
  7733. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7734. begin
  7735. {$if defined(i386) or defined(i8086)}
  7736. { If the target size is 8-bit, make sure we can actually encode it }
  7737. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7738. Exit;
  7739. {$endif i386 or i8086}
  7740. LowerLimit := $FF;
  7741. SignedLowerLimit := $7F;
  7742. SignedLowerLimitBottom := -128;
  7743. MinSize := S_B;
  7744. if taicpu(p).opsize = S_BW then
  7745. begin
  7746. MaxSize := S_W;
  7747. UpperLimit := $FFFF;
  7748. SignedUpperLimit := $7FFF;
  7749. SignedUpperLimitBottom := -32768;
  7750. end
  7751. else
  7752. begin
  7753. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7754. MaxSize := S_L;
  7755. UpperLimit := $FFFFFFFF;
  7756. SignedUpperLimit := $7FFFFFFF;
  7757. SignedUpperLimitBottom := -2147483648;
  7758. end;
  7759. end;
  7760. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7761. begin
  7762. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7763. LowerLimit := $FFFF;
  7764. SignedLowerLimit := $7FFF;
  7765. SignedLowerLimitBottom := -32768;
  7766. UpperLimit := $FFFFFFFF;
  7767. SignedUpperLimit := $7FFFFFFF;
  7768. SignedUpperLimitBottom := -2147483648;
  7769. MinSize := S_W;
  7770. MaxSize := S_L;
  7771. end;
  7772. {$ifdef x86_64}
  7773. S_LQ:
  7774. begin
  7775. { Both the lower and upper limits are set to 32-bit. If a limit
  7776. is breached, then optimisation is impossible }
  7777. LowerLimit := $FFFFFFFF;
  7778. SignedLowerLimit := $7FFFFFFF;
  7779. SignedLowerLimitBottom := -2147483648;
  7780. UpperLimit := $FFFFFFFF;
  7781. SignedUpperLimit := $7FFFFFFF;
  7782. SignedUpperLimitBottom := -2147483648;
  7783. MinSize := S_L;
  7784. MaxSize := S_L;
  7785. end;
  7786. {$endif x86_64}
  7787. else
  7788. InternalError(2020112301);
  7789. end;
  7790. TestValMin := 0;
  7791. TestValMax := LowerLimit;
  7792. TestValSignedMax := SignedLowerLimit;
  7793. TryShiftDownLimit := LowerLimit;
  7794. TryShiftDown := S_NO;
  7795. ShiftDownOverflow := False;
  7796. RegChanged := False;
  7797. BitwiseOnly := True;
  7798. OrXorUsed := False;
  7799. UpperSignedOverflow := False;
  7800. LowerSignedOverflow := False;
  7801. UpperUnsignedOverflow := False;
  7802. LowerUnsignedOverflow := False;
  7803. hp1 := p;
  7804. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7805. (hp1.typ = ait_instruction) and
  7806. (
  7807. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7808. instruction that doesn't actually contain ThisReg }
  7809. (cs_opt_level3 in current_settings.optimizerswitches) or
  7810. RegInInstruction(ThisReg, hp1)
  7811. ) do
  7812. begin
  7813. case taicpu(hp1).opcode of
  7814. A_INC,A_DEC:
  7815. begin
  7816. { Has to be an exact match on the register }
  7817. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7818. Break;
  7819. if taicpu(hp1).opcode = A_INC then
  7820. begin
  7821. Inc(TestValMin);
  7822. Inc(TestValMax);
  7823. Inc(TestValSignedMax);
  7824. end
  7825. else
  7826. begin
  7827. Dec(TestValMin);
  7828. Dec(TestValMax);
  7829. Dec(TestValSignedMax);
  7830. end;
  7831. end;
  7832. A_TEST, A_CMP:
  7833. begin
  7834. if (
  7835. { Too high a risk of non-linear behaviour that breaks DFA
  7836. here, unless it's cmp $0,%reg, which is equivalent to
  7837. test %reg,%reg }
  7838. OrXorUsed and
  7839. (taicpu(hp1).opcode = A_CMP) and
  7840. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  7841. ) or
  7842. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7843. { Has to be an exact match on the register }
  7844. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7845. (
  7846. { Permit "test %reg,%reg" }
  7847. (taicpu(hp1).opcode = A_TEST) and
  7848. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7849. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  7850. ) or
  7851. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7852. { Make sure the comparison value is not smaller than the
  7853. smallest allowed signed value for the minimum size (e.g.
  7854. -128 for 8-bit) }
  7855. not (
  7856. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  7857. { Is it in the negative range? }
  7858. (
  7859. (taicpu(hp1).oper[0]^.val < 0) and
  7860. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  7861. )
  7862. ) then
  7863. Break;
  7864. (*
  7865. { ANDing can't increase the value past the limit or decrease
  7866. it below 0, so we can skip the checks, plus the test value
  7867. won't change afterwards }
  7868. if (taicpu(hp1).opcode = A_CMP) and
  7869. { cmp $0,$reg is equivalent to test %reg,%reg, plus the
  7870. test values aren't being modified anyway }
  7871. (taicpu(hp1).oper[0]^.val <> 0) then
  7872. begin
  7873. WorkingValue := taicpu(hp1).oper[0]^.val;
  7874. TestValMin := TestValMin - WorkingValue;
  7875. TestValMax := TestValMax - WorkingValue;
  7876. TestValSignedMax := TestValSignedMax - WorkingValue;
  7877. if not CheckOverflowConditions then
  7878. Break;
  7879. { Because the register isn't actually adjusted, we can
  7880. restore the test values to what they were previously }
  7881. TestValMin := TestValMin + WorkingValue;
  7882. TestValMax := TestValMax + WorkingValue;
  7883. TestValSignedMax := TestValSignedMax + WorkingValue;
  7884. end; *)
  7885. { Check to see if the active register is used afterwards }
  7886. TransferUsedRegs(TmpUsedRegs);
  7887. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7888. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7889. begin
  7890. { Make sure the comparison or any previous instructions
  7891. hasn't pushed the test values outside of the range of
  7892. MinSize }
  7893. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7894. begin
  7895. { Exceeded lower bound but not upper bound }
  7896. TargetSize := MaxSize;
  7897. end
  7898. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  7899. begin
  7900. { Size didn't exceed lower bound }
  7901. TargetSize := MinSize;
  7902. end
  7903. else
  7904. Break;
  7905. case TargetSize of
  7906. S_B:
  7907. TargetSubReg := R_SUBL;
  7908. S_W:
  7909. TargetSubReg := R_SUBW;
  7910. S_L:
  7911. TargetSubReg := R_SUBD;
  7912. else
  7913. InternalError(2021051002);
  7914. end;
  7915. { Update the register to its new size }
  7916. setsubreg(ThisReg, TargetSubReg);
  7917. taicpu(hp1).oper[1]^.reg := ThisReg;
  7918. taicpu(hp1).opsize := MinSize;
  7919. { Convert the input MOVZX to a MOV }
  7920. if (taicpu(p).oper[0]^.typ = top_reg) and
  7921. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7922. begin
  7923. { Or remove it completely! }
  7924. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7925. RemoveCurrentP(p);
  7926. p_removed := True;
  7927. end
  7928. else
  7929. begin
  7930. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7931. taicpu(p).opcode := A_MOV;
  7932. taicpu(p).oper[1]^.reg := ThisReg;
  7933. taicpu(p).opsize := MinSize;
  7934. end;
  7935. if (InstrMax >= 0) then
  7936. begin
  7937. for Index := 0 to InstrMax do
  7938. begin
  7939. { If p_removed is true, then the original MOV/Z was removed
  7940. and removing the AND instruction may not be safe if it
  7941. appears first }
  7942. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7943. InternalError(2020112311);
  7944. if InstrList[Index].oper[0]^.typ = top_reg then
  7945. InstrList[Index].oper[0]^.reg := ThisReg;
  7946. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7947. InstrList[Index].opsize := MinSize;
  7948. end;
  7949. end;
  7950. Result := True;
  7951. Exit;
  7952. end;
  7953. end;
  7954. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  7955. begin
  7956. if
  7957. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7958. { Has to be an exact match on the register }
  7959. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  7960. (
  7961. (
  7962. (taicpu(hp1).oper[0]^.typ = top_const) and
  7963. (
  7964. (
  7965. (taicpu(hp1).opcode = A_SHL) and
  7966. (
  7967. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  7968. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  7969. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  7970. )
  7971. ) or (
  7972. (taicpu(hp1).opcode <> A_SHL) and
  7973. (
  7974. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7975. { Is it in the negative range? }
  7976. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7977. )
  7978. )
  7979. )
  7980. ) or (
  7981. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  7982. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  7983. )
  7984. ) then
  7985. Break;
  7986. { Only process OR and XOR if there are only bitwise operations,
  7987. since otherwise they can too easily fool the data flow
  7988. analysis (they can cause non-linear behaviour) }
  7989. case taicpu(hp1).opcode of
  7990. A_ADD:
  7991. begin
  7992. if OrXorUsed then
  7993. { Too high a risk of non-linear behaviour that breaks DFA here }
  7994. Break
  7995. else
  7996. BitwiseOnly := False;
  7997. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7998. begin
  7999. TestValMin := TestValMin * 2;
  8000. TestValMax := TestValMax * 2;
  8001. TestValSignedMax := TestValSignedMax * 2;
  8002. end
  8003. else
  8004. begin
  8005. WorkingValue := taicpu(hp1).oper[0]^.val;
  8006. TestValMin := TestValMin + WorkingValue;
  8007. TestValMax := TestValMax + WorkingValue;
  8008. TestValSignedMax := TestValSignedMax + WorkingValue;
  8009. end;
  8010. end;
  8011. A_SUB:
  8012. begin
  8013. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8014. begin
  8015. TestValMin := 0;
  8016. TestValMax := 0;
  8017. TestValSignedMax := 0;
  8018. end
  8019. else
  8020. begin
  8021. if OrXorUsed then
  8022. { Too high a risk of non-linear behaviour that breaks DFA here }
  8023. Break
  8024. else
  8025. BitwiseOnly := False;
  8026. WorkingValue := taicpu(hp1).oper[0]^.val;
  8027. TestValMin := TestValMin - WorkingValue;
  8028. TestValMax := TestValMax - WorkingValue;
  8029. TestValSignedMax := TestValSignedMax - WorkingValue;
  8030. end;
  8031. end;
  8032. A_AND:
  8033. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8034. begin
  8035. { we might be able to go smaller if AND appears first }
  8036. if InstrMax = -1 then
  8037. case MinSize of
  8038. S_B:
  8039. ;
  8040. S_W:
  8041. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8042. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8043. begin
  8044. TryShiftDown := S_B;
  8045. TryShiftDownLimit := $FF;
  8046. end;
  8047. S_L:
  8048. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8049. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8050. begin
  8051. TryShiftDown := S_B;
  8052. TryShiftDownLimit := $FF;
  8053. end
  8054. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8055. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8056. begin
  8057. TryShiftDown := S_W;
  8058. TryShiftDownLimit := $FFFF;
  8059. end;
  8060. else
  8061. InternalError(2020112320);
  8062. end;
  8063. WorkingValue := taicpu(hp1).oper[0]^.val;
  8064. TestValMin := TestValMin and WorkingValue;
  8065. TestValMax := TestValMax and WorkingValue;
  8066. TestValSignedMax := TestValSignedMax and WorkingValue;
  8067. end;
  8068. A_OR:
  8069. begin
  8070. if not BitwiseOnly then
  8071. Break;
  8072. OrXorUsed := True;
  8073. WorkingValue := taicpu(hp1).oper[0]^.val;
  8074. TestValMin := TestValMin or WorkingValue;
  8075. TestValMax := TestValMax or WorkingValue;
  8076. TestValSignedMax := TestValSignedMax or WorkingValue;
  8077. end;
  8078. A_XOR:
  8079. begin
  8080. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8081. begin
  8082. TestValMin := 0;
  8083. TestValMax := 0;
  8084. TestValSignedMax := 0;
  8085. end
  8086. else
  8087. begin
  8088. if not BitwiseOnly then
  8089. Break;
  8090. OrXorUsed := True;
  8091. WorkingValue := taicpu(hp1).oper[0]^.val;
  8092. TestValMin := TestValMin xor WorkingValue;
  8093. TestValMax := TestValMax xor WorkingValue;
  8094. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8095. end;
  8096. end;
  8097. A_SHL:
  8098. begin
  8099. BitwiseOnly := False;
  8100. WorkingValue := taicpu(hp1).oper[0]^.val;
  8101. TestValMin := TestValMin shl WorkingValue;
  8102. TestValMax := TestValMax shl WorkingValue;
  8103. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8104. end;
  8105. A_SHR,
  8106. { The first instruction was MOVZX, so the value won't be negative }
  8107. A_SAR:
  8108. begin
  8109. if InstrMax <> -1 then
  8110. BitwiseOnly := False
  8111. else
  8112. { we might be able to go smaller if SHR appears first }
  8113. case MinSize of
  8114. S_B:
  8115. ;
  8116. S_W:
  8117. if (taicpu(hp1).oper[0]^.val >= 8) then
  8118. begin
  8119. TryShiftDown := S_B;
  8120. TryShiftDownLimit := $FF;
  8121. TryShiftDownSignedLimit := $7F;
  8122. TryShiftDownSignedLimitLower := -128;
  8123. end;
  8124. S_L:
  8125. if (taicpu(hp1).oper[0]^.val >= 24) then
  8126. begin
  8127. TryShiftDown := S_B;
  8128. TryShiftDownLimit := $FF;
  8129. TryShiftDownSignedLimit := $7F;
  8130. TryShiftDownSignedLimitLower := -128;
  8131. end
  8132. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8133. begin
  8134. TryShiftDown := S_W;
  8135. TryShiftDownLimit := $FFFF;
  8136. TryShiftDownSignedLimit := $7FFF;
  8137. TryShiftDownSignedLimitLower := -32768;
  8138. end;
  8139. else
  8140. InternalError(2020112321);
  8141. end;
  8142. WorkingValue := taicpu(hp1).oper[0]^.val;
  8143. if taicpu(hp1).opcode = A_SAR then
  8144. begin
  8145. TestValMin := SarInt64(TestValMin, WorkingValue);
  8146. TestValMax := SarInt64(TestValMax, WorkingValue);
  8147. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8148. end
  8149. else
  8150. begin
  8151. TestValMin := TestValMin shr WorkingValue;
  8152. TestValMax := TestValMax shr WorkingValue;
  8153. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8154. end;
  8155. end;
  8156. else
  8157. InternalError(2020112303);
  8158. end;
  8159. end;
  8160. (*
  8161. A_IMUL:
  8162. case taicpu(hp1).ops of
  8163. 2:
  8164. begin
  8165. if not MatchOpType(hp1, top_reg, top_reg) or
  8166. { Has to be an exact match on the register }
  8167. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8168. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8169. Break;
  8170. TestValMin := TestValMin * TestValMin;
  8171. TestValMax := TestValMax * TestValMax;
  8172. TestValSignedMax := TestValSignedMax * TestValMax;
  8173. end;
  8174. 3:
  8175. begin
  8176. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8177. { Has to be an exact match on the register }
  8178. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8179. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8180. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8181. { Is it in the negative range? }
  8182. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8183. Break;
  8184. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8185. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8186. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8187. end;
  8188. else
  8189. Break;
  8190. end;
  8191. A_IDIV:
  8192. case taicpu(hp1).ops of
  8193. 3:
  8194. begin
  8195. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8196. { Has to be an exact match on the register }
  8197. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8198. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8199. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8200. { Is it in the negative range? }
  8201. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8202. Break;
  8203. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8204. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8205. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8206. end;
  8207. else
  8208. Break;
  8209. end;
  8210. *)
  8211. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8212. begin
  8213. { If there are no instructions in between, then we might be able to make a saving }
  8214. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8215. Break;
  8216. { We have something like:
  8217. movzbw %dl,%dx
  8218. ...
  8219. movswl %dx,%edx
  8220. Change the latter to a zero-extension then enter the
  8221. A_MOVZX case branch.
  8222. }
  8223. {$ifdef x86_64}
  8224. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8225. begin
  8226. { this becomes a zero extension from 32-bit to 64-bit, but
  8227. the upper 32 bits are already zero, so just delete the
  8228. instruction }
  8229. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8230. RemoveInstruction(hp1);
  8231. Result := True;
  8232. Exit;
  8233. end
  8234. else
  8235. {$endif x86_64}
  8236. begin
  8237. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8238. taicpu(hp1).opcode := A_MOVZX;
  8239. {$ifdef x86_64}
  8240. case taicpu(hp1).opsize of
  8241. S_BQ:
  8242. begin
  8243. taicpu(hp1).opsize := S_BL;
  8244. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8245. end;
  8246. S_WQ:
  8247. begin
  8248. taicpu(hp1).opsize := S_WL;
  8249. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8250. end;
  8251. S_LQ:
  8252. begin
  8253. taicpu(hp1).opcode := A_MOV;
  8254. taicpu(hp1).opsize := S_L;
  8255. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8256. { In this instance, we need to break out because the
  8257. instruction is no longer MOVZX or MOVSXD }
  8258. Result := True;
  8259. Exit;
  8260. end;
  8261. else
  8262. ;
  8263. end;
  8264. {$endif x86_64}
  8265. Result := CompressInstructions;
  8266. Exit;
  8267. end;
  8268. end;
  8269. A_MOVZX:
  8270. begin
  8271. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8272. Break;
  8273. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8274. begin
  8275. if (InstrMax = -1) and
  8276. { Will return false if the second parameter isn't ThisReg
  8277. (can happen on -O2 and under) }
  8278. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8279. begin
  8280. { The two MOVZX instructions are adjacent, so remove the first one }
  8281. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8282. RemoveCurrentP(p);
  8283. Result := True;
  8284. Exit;
  8285. end;
  8286. Break;
  8287. end;
  8288. Result := CompressInstructions;
  8289. Exit;
  8290. end;
  8291. else
  8292. { This includes ADC, SBB, IDIV and SAR }
  8293. Break;
  8294. end;
  8295. if not CheckOverflowConditions then
  8296. Break;
  8297. { Contains highest index (so instruction count - 1) }
  8298. Inc(InstrMax);
  8299. if InstrMax > High(InstrList) then
  8300. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8301. InstrList[InstrMax] := taicpu(hp1);
  8302. end;
  8303. end;
  8304. {$pop}
  8305. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8306. var
  8307. hp1 : tai;
  8308. begin
  8309. Result:=false;
  8310. if (taicpu(p).ops >= 2) and
  8311. ((taicpu(p).oper[0]^.typ = top_const) or
  8312. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8313. (taicpu(p).oper[1]^.typ = top_reg) and
  8314. ((taicpu(p).ops = 2) or
  8315. ((taicpu(p).oper[2]^.typ = top_reg) and
  8316. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8317. GetLastInstruction(p,hp1) and
  8318. MatchInstruction(hp1,A_MOV,[]) and
  8319. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8320. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8321. begin
  8322. TransferUsedRegs(TmpUsedRegs);
  8323. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8324. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8325. { change
  8326. mov reg1,reg2
  8327. imul y,reg2 to imul y,reg1,reg2 }
  8328. begin
  8329. taicpu(p).ops := 3;
  8330. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8331. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8332. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8333. RemoveInstruction(hp1);
  8334. result:=true;
  8335. end;
  8336. end;
  8337. end;
  8338. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8339. var
  8340. ThisLabel: TAsmLabel;
  8341. begin
  8342. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8343. ThisLabel.decrefs;
  8344. taicpu(p).opcode := A_RET;
  8345. taicpu(p).is_jmp := false;
  8346. taicpu(p).ops := taicpu(ret_p).ops;
  8347. case taicpu(ret_p).ops of
  8348. 0:
  8349. taicpu(p).clearop(0);
  8350. 1:
  8351. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8352. else
  8353. internalerror(2016041301);
  8354. end;
  8355. { If the original label is now dead, it might turn out that the label
  8356. immediately follows p. As a result, everything beyond it, which will
  8357. be just some final register configuration and a RET instruction, is
  8358. now dead code. [Kit] }
  8359. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8360. running RemoveDeadCodeAfterJump for each RET instruction, because
  8361. this optimisation rarely happens and most RETs appear at the end of
  8362. routines where there is nothing that can be stripped. [Kit] }
  8363. if not ThisLabel.is_used then
  8364. RemoveDeadCodeAfterJump(p);
  8365. end;
  8366. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8367. var
  8368. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8369. Unconditional, PotentialModified: Boolean;
  8370. OperPtr: POper;
  8371. NewRef: TReference;
  8372. InstrList: array of taicpu;
  8373. InstrMax, Index: Integer;
  8374. const
  8375. {$ifdef DEBUG_AOPTCPU}
  8376. SNoFlags: shortstring = ' so the flags aren''t modified';
  8377. {$else DEBUG_AOPTCPU}
  8378. SNoFlags = '';
  8379. {$endif DEBUG_AOPTCPU}
  8380. begin
  8381. Result:=false;
  8382. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8383. begin
  8384. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8385. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8386. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8387. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8388. GetNextInstruction(hp1, hp2) and
  8389. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8390. { Change from: To:
  8391. set(C) %reg j(~C) label
  8392. test %reg,%reg/cmp $0,%reg
  8393. je label
  8394. set(C) %reg j(C) label
  8395. test %reg,%reg/cmp $0,%reg
  8396. jne label
  8397. (Also do something similar with sete/setne instead of je/jne)
  8398. }
  8399. begin
  8400. { Before we do anything else, we need to check the instructions
  8401. in between SETcc and TEST to make sure they don't modify the
  8402. FLAGS register - if -O2 or under, there won't be any
  8403. instructions between SET and TEST }
  8404. TransferUsedRegs(TmpUsedRegs);
  8405. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8406. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8407. begin
  8408. next := p;
  8409. SetLength(InstrList, 0);
  8410. InstrMax := -1;
  8411. PotentialModified := False;
  8412. { Make a note of every instruction that modifies the FLAGS
  8413. register }
  8414. while GetNextInstruction(next, next) and (next <> hp1) do
  8415. begin
  8416. if next.typ <> ait_instruction then
  8417. { GetNextInstructionUsingReg should have returned False }
  8418. InternalError(2021051701);
  8419. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8420. begin
  8421. case taicpu(next).opcode of
  8422. A_SETcc,
  8423. A_CMOVcc,
  8424. A_Jcc:
  8425. begin
  8426. if PotentialModified then
  8427. { Not safe because the flags were modified earlier }
  8428. Exit
  8429. else
  8430. { Condition is the same as the initial SETcc, so this is safe
  8431. (don't add to instruction list though) }
  8432. Continue;
  8433. end;
  8434. A_ADD:
  8435. begin
  8436. if (taicpu(next).opsize = S_B) or
  8437. { LEA doesn't support 8-bit operands }
  8438. (taicpu(next).oper[1]^.typ <> top_reg) or
  8439. { Must write to a register }
  8440. (taicpu(next).oper[0]^.typ = top_ref) then
  8441. { Require a constant or a register }
  8442. Exit;
  8443. PotentialModified := True;
  8444. end;
  8445. A_SUB:
  8446. begin
  8447. if (taicpu(next).opsize = S_B) or
  8448. { LEA doesn't support 8-bit operands }
  8449. (taicpu(next).oper[1]^.typ <> top_reg) or
  8450. { Must write to a register }
  8451. (taicpu(next).oper[0]^.typ <> top_const) or
  8452. (taicpu(next).oper[0]^.val = $80000000) then
  8453. { Can't subtract a register with LEA - also
  8454. check that the value isn't -2^31, as this
  8455. can't be negated }
  8456. Exit;
  8457. PotentialModified := True;
  8458. end;
  8459. A_SAL,
  8460. A_SHL:
  8461. begin
  8462. if (taicpu(next).opsize = S_B) or
  8463. { LEA doesn't support 8-bit operands }
  8464. (taicpu(next).oper[1]^.typ <> top_reg) or
  8465. { Must write to a register }
  8466. (taicpu(next).oper[0]^.typ <> top_const) or
  8467. (taicpu(next).oper[0]^.val < 0) or
  8468. (taicpu(next).oper[0]^.val > 3) then
  8469. Exit;
  8470. PotentialModified := True;
  8471. end;
  8472. A_IMUL:
  8473. begin
  8474. if (taicpu(next).ops <> 3) or
  8475. (taicpu(next).oper[1]^.typ <> top_reg) or
  8476. { Must write to a register }
  8477. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8478. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8479. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8480. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8481. Exit
  8482. else
  8483. PotentialModified := True;
  8484. end;
  8485. else
  8486. { Don't know how to change this, so abort }
  8487. Exit;
  8488. end;
  8489. { Contains highest index (so instruction count - 1) }
  8490. Inc(InstrMax);
  8491. if InstrMax > High(InstrList) then
  8492. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8493. InstrList[InstrMax] := taicpu(next);
  8494. end;
  8495. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8496. end;
  8497. if not Assigned(next) or (next <> hp1) then
  8498. { It should be equal to hp1 }
  8499. InternalError(2021051702);
  8500. { Cycle through each instruction and check to see if we can
  8501. change them to versions that don't modify the flags }
  8502. if (InstrMax >= 0) then
  8503. begin
  8504. for Index := 0 to InstrMax do
  8505. case InstrList[Index].opcode of
  8506. A_ADD:
  8507. begin
  8508. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8509. InstrList[Index].opcode := A_LEA;
  8510. reference_reset(NewRef, 1, []);
  8511. NewRef.base := InstrList[Index].oper[1]^.reg;
  8512. if InstrList[Index].oper[0]^.typ = top_reg then
  8513. begin
  8514. NewRef.index := InstrList[Index].oper[0]^.reg;
  8515. NewRef.scalefactor := 1;
  8516. end
  8517. else
  8518. NewRef.offset := InstrList[Index].oper[0]^.val;
  8519. InstrList[Index].loadref(0, NewRef);
  8520. end;
  8521. A_SUB:
  8522. begin
  8523. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8524. InstrList[Index].opcode := A_LEA;
  8525. reference_reset(NewRef, 1, []);
  8526. NewRef.base := InstrList[Index].oper[1]^.reg;
  8527. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8528. InstrList[Index].loadref(0, NewRef);
  8529. end;
  8530. A_SHL,
  8531. A_SAL:
  8532. begin
  8533. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8534. InstrList[Index].opcode := A_LEA;
  8535. reference_reset(NewRef, 1, []);
  8536. NewRef.index := InstrList[Index].oper[1]^.reg;
  8537. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8538. InstrList[Index].loadref(0, NewRef);
  8539. end;
  8540. A_IMUL:
  8541. begin
  8542. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8543. InstrList[Index].opcode := A_LEA;
  8544. reference_reset(NewRef, 1, []);
  8545. NewRef.index := InstrList[Index].oper[1]^.reg;
  8546. case InstrList[Index].oper[0]^.val of
  8547. 2, 4, 8:
  8548. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8549. else {3, 5 and 9}
  8550. begin
  8551. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8552. NewRef.base := InstrList[Index].oper[1]^.reg;
  8553. end;
  8554. end;
  8555. InstrList[Index].loadref(0, NewRef);
  8556. end;
  8557. else
  8558. InternalError(2021051710);
  8559. end;
  8560. end;
  8561. { Mark the FLAGS register as used across this whole block }
  8562. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8563. end;
  8564. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8565. JumpC := taicpu(hp2).condition;
  8566. Unconditional := False;
  8567. if conditions_equal(JumpC, C_E) then
  8568. SetC := inverse_cond(taicpu(p).condition)
  8569. else if conditions_equal(JumpC, C_NE) then
  8570. SetC := taicpu(p).condition
  8571. else
  8572. { We've got something weird here (and inefficent) }
  8573. begin
  8574. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8575. SetC := C_NONE;
  8576. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8577. if condition_in(C_AE, JumpC) then
  8578. Unconditional := True
  8579. else
  8580. { Not sure what to do with this jump - drop out }
  8581. Exit;
  8582. end;
  8583. RemoveInstruction(hp1);
  8584. if Unconditional then
  8585. MakeUnconditional(taicpu(hp2))
  8586. else
  8587. begin
  8588. if SetC = C_NONE then
  8589. InternalError(2018061402);
  8590. taicpu(hp2).SetCondition(SetC);
  8591. end;
  8592. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8593. TmpUsedRegs }
  8594. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8595. begin
  8596. RemoveCurrentp(p, hp2);
  8597. if taicpu(hp2).opcode = A_SETcc then
  8598. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8599. else
  8600. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8601. end
  8602. else
  8603. if taicpu(hp2).opcode = A_SETcc then
  8604. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8605. else
  8606. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8607. Result := True;
  8608. end
  8609. else if
  8610. { Make sure the instructions are adjacent }
  8611. (
  8612. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8613. GetNextInstruction(p, hp1)
  8614. ) and
  8615. MatchInstruction(hp1, A_MOV, [S_B]) and
  8616. { Writing to memory is allowed }
  8617. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8618. begin
  8619. {
  8620. Watch out for sequences such as:
  8621. set(c)b %regb
  8622. movb %regb,(ref)
  8623. movb $0,1(ref)
  8624. movb $0,2(ref)
  8625. movb $0,3(ref)
  8626. Much more efficient to turn it into:
  8627. movl $0,%regl
  8628. set(c)b %regb
  8629. movl %regl,(ref)
  8630. Or:
  8631. set(c)b %regb
  8632. movzbl %regb,%regl
  8633. movl %regl,(ref)
  8634. }
  8635. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8636. GetNextInstruction(hp1, hp2) and
  8637. MatchInstruction(hp2, A_MOV, [S_B]) and
  8638. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8639. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8640. begin
  8641. { Don't do anything else except set Result to True }
  8642. end
  8643. else
  8644. begin
  8645. if taicpu(p).oper[0]^.typ = top_reg then
  8646. begin
  8647. TransferUsedRegs(TmpUsedRegs);
  8648. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8649. end;
  8650. { If it's not a register, it's a memory address }
  8651. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8652. begin
  8653. { Even if the register is still in use, we can minimise the
  8654. pipeline stall by changing the MOV into another SETcc. }
  8655. taicpu(hp1).opcode := A_SETcc;
  8656. taicpu(hp1).condition := taicpu(p).condition;
  8657. if taicpu(hp1).oper[1]^.typ = top_ref then
  8658. begin
  8659. { Swapping the operand pointers like this is probably a
  8660. bit naughty, but it is far faster than using loadoper
  8661. to transfer the reference from oper[1] to oper[0] if
  8662. you take into account the extra procedure calls and
  8663. the memory allocation and deallocation required }
  8664. OperPtr := taicpu(hp1).oper[1];
  8665. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8666. taicpu(hp1).oper[0] := OperPtr;
  8667. end
  8668. else
  8669. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8670. taicpu(hp1).clearop(1);
  8671. taicpu(hp1).ops := 1;
  8672. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8673. end
  8674. else
  8675. begin
  8676. if taicpu(hp1).oper[1]^.typ = top_reg then
  8677. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8678. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8679. RemoveInstruction(hp1);
  8680. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8681. end
  8682. end;
  8683. Result := True;
  8684. end;
  8685. end;
  8686. end;
  8687. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8688. var
  8689. hp1: tai;
  8690. Count: Integer;
  8691. OrigLabel: TAsmLabel;
  8692. begin
  8693. result := False;
  8694. { Sometimes, the optimisations below can permit this }
  8695. RemoveDeadCodeAfterJump(p);
  8696. 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
  8697. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8698. begin
  8699. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8700. { Also a side-effect of optimisations }
  8701. if CollapseZeroDistJump(p, OrigLabel) then
  8702. begin
  8703. Result := True;
  8704. Exit;
  8705. end;
  8706. hp1 := GetLabelWithSym(OrigLabel);
  8707. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8708. begin
  8709. case taicpu(hp1).opcode of
  8710. A_RET:
  8711. {
  8712. change
  8713. jmp .L1
  8714. ...
  8715. .L1:
  8716. ret
  8717. into
  8718. ret
  8719. }
  8720. begin
  8721. ConvertJumpToRET(p, hp1);
  8722. result:=true;
  8723. end;
  8724. { Check any kind of direct assignment instruction }
  8725. A_MOV,
  8726. A_MOVD,
  8727. A_MOVQ,
  8728. A_MOVSX,
  8729. {$ifdef x86_64}
  8730. A_MOVSXD,
  8731. {$endif x86_64}
  8732. A_MOVZX,
  8733. A_MOVAPS,
  8734. A_MOVUPS,
  8735. A_MOVSD,
  8736. A_MOVAPD,
  8737. A_MOVUPD,
  8738. A_MOVDQA,
  8739. A_MOVDQU,
  8740. A_VMOVSS,
  8741. A_VMOVAPS,
  8742. A_VMOVUPS,
  8743. A_VMOVSD,
  8744. A_VMOVAPD,
  8745. A_VMOVUPD,
  8746. A_VMOVDQA,
  8747. A_VMOVDQU:
  8748. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8749. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8750. begin
  8751. Result := True;
  8752. Exit;
  8753. end;
  8754. else
  8755. ;
  8756. end;
  8757. end;
  8758. end;
  8759. end;
  8760. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8761. begin
  8762. CanBeCMOV:=assigned(p) and
  8763. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8764. { we can't use cmov ref,reg because
  8765. ref could be nil and cmov still throws an exception
  8766. if ref=nil but the mov isn't done (FK)
  8767. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8768. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8769. }
  8770. (taicpu(p).oper[1]^.typ = top_reg) and
  8771. (
  8772. (taicpu(p).oper[0]^.typ = top_reg) or
  8773. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8774. it is not expected that this can cause a seg. violation }
  8775. (
  8776. (taicpu(p).oper[0]^.typ = top_ref) and
  8777. IsRefSafe(taicpu(p).oper[0]^.ref)
  8778. )
  8779. );
  8780. end;
  8781. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8782. var
  8783. hp1,hp2: tai;
  8784. {$ifndef i8086}
  8785. hp3,hp4,hpmov2, hp5: tai;
  8786. l : Longint;
  8787. condition : TAsmCond;
  8788. {$endif i8086}
  8789. carryadd_opcode : TAsmOp;
  8790. symbol: TAsmSymbol;
  8791. reg: tsuperregister;
  8792. increg, tmpreg: TRegister;
  8793. begin
  8794. result:=false;
  8795. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8796. begin
  8797. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8798. if (
  8799. (
  8800. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8801. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8802. (Taicpu(hp1).oper[0]^.val=1)
  8803. ) or
  8804. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8805. ) and
  8806. GetNextInstruction(hp1,hp2) and
  8807. SkipAligns(hp2, hp2) and
  8808. (hp2.typ = ait_label) and
  8809. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8810. { jb @@1 cmc
  8811. inc/dec operand --> adc/sbb operand,0
  8812. @@1:
  8813. ... and ...
  8814. jnb @@1
  8815. inc/dec operand --> adc/sbb operand,0
  8816. @@1: }
  8817. begin
  8818. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8819. begin
  8820. case taicpu(hp1).opcode of
  8821. A_INC,
  8822. A_ADD:
  8823. carryadd_opcode:=A_ADC;
  8824. A_DEC,
  8825. A_SUB:
  8826. carryadd_opcode:=A_SBB;
  8827. else
  8828. InternalError(2021011001);
  8829. end;
  8830. Taicpu(p).clearop(0);
  8831. Taicpu(p).ops:=0;
  8832. Taicpu(p).is_jmp:=false;
  8833. Taicpu(p).opcode:=A_CMC;
  8834. Taicpu(p).condition:=C_NONE;
  8835. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8836. Taicpu(hp1).ops:=2;
  8837. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8838. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8839. else
  8840. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8841. Taicpu(hp1).loadconst(0,0);
  8842. Taicpu(hp1).opcode:=carryadd_opcode;
  8843. result:=true;
  8844. exit;
  8845. end
  8846. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8847. begin
  8848. case taicpu(hp1).opcode of
  8849. A_INC,
  8850. A_ADD:
  8851. carryadd_opcode:=A_ADC;
  8852. A_DEC,
  8853. A_SUB:
  8854. carryadd_opcode:=A_SBB;
  8855. else
  8856. InternalError(2021011002);
  8857. end;
  8858. Taicpu(hp1).ops:=2;
  8859. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8860. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8861. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8862. else
  8863. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8864. Taicpu(hp1).loadconst(0,0);
  8865. Taicpu(hp1).opcode:=carryadd_opcode;
  8866. RemoveCurrentP(p, hp1);
  8867. result:=true;
  8868. exit;
  8869. end
  8870. {
  8871. jcc @@1 setcc tmpreg
  8872. inc/dec/add/sub operand -> (movzx tmpreg)
  8873. @@1: add/sub tmpreg,operand
  8874. While this increases code size slightly, it makes the code much faster if the
  8875. jump is unpredictable
  8876. }
  8877. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8878. begin
  8879. { search for an available register which is volatile }
  8880. for reg in tcpuregisterset do
  8881. begin
  8882. if
  8883. {$if defined(i386) or defined(i8086)}
  8884. { Only use registers whose lowest 8-bits can Be accessed }
  8885. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  8886. {$endif i386 or i8086}
  8887. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  8888. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  8889. { We don't need to check if tmpreg is in hp1 or not, because
  8890. it will be marked as in use at p (if not, this is
  8891. indictive of a compiler bug). }
  8892. then
  8893. begin
  8894. TAsmLabel(symbol).decrefs;
  8895. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  8896. Taicpu(p).clearop(0);
  8897. Taicpu(p).ops:=1;
  8898. Taicpu(p).is_jmp:=false;
  8899. Taicpu(p).opcode:=A_SETcc;
  8900. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8901. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8902. Taicpu(p).loadreg(0,increg);
  8903. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8904. begin
  8905. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8906. R_SUBW:
  8907. begin
  8908. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  8909. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8910. end;
  8911. R_SUBD:
  8912. begin
  8913. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  8914. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8915. end;
  8916. {$ifdef x86_64}
  8917. R_SUBQ:
  8918. begin
  8919. { MOVZX doesn't have a 64-bit variant, because
  8920. the 32-bit version implicitly zeroes the
  8921. upper 32-bits of the destination register }
  8922. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  8923. newreg(R_INTREGISTER,reg,R_SUBD));
  8924. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  8925. end;
  8926. {$endif x86_64}
  8927. else
  8928. Internalerror(2020030601);
  8929. end;
  8930. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8931. asml.InsertAfter(hp2,p);
  8932. end
  8933. else
  8934. tmpreg := increg;
  8935. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  8936. begin
  8937. Taicpu(hp1).ops:=2;
  8938. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  8939. end;
  8940. Taicpu(hp1).loadreg(0,tmpreg);
  8941. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  8942. Result := True;
  8943. { p is no longer a Jcc instruction, so exit }
  8944. Exit;
  8945. end;
  8946. end;
  8947. end;
  8948. end;
  8949. { Detect the following:
  8950. jmp<cond> @Lbl1
  8951. jmp @Lbl2
  8952. ...
  8953. @Lbl1:
  8954. ret
  8955. Change to:
  8956. jmp<inv_cond> @Lbl2
  8957. ret
  8958. }
  8959. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8960. begin
  8961. hp2:=getlabelwithsym(TAsmLabel(symbol));
  8962. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  8963. MatchInstruction(hp2,A_RET,[S_NO]) then
  8964. begin
  8965. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8966. { Change label address to that of the unconditional jump }
  8967. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  8968. TAsmLabel(symbol).DecRefs;
  8969. taicpu(hp1).opcode := A_RET;
  8970. taicpu(hp1).is_jmp := false;
  8971. taicpu(hp1).ops := taicpu(hp2).ops;
  8972. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  8973. case taicpu(hp2).ops of
  8974. 0:
  8975. taicpu(hp1).clearop(0);
  8976. 1:
  8977. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  8978. else
  8979. internalerror(2016041302);
  8980. end;
  8981. end;
  8982. {$ifndef i8086}
  8983. end
  8984. {
  8985. convert
  8986. j<c> .L1
  8987. mov 1,reg
  8988. jmp .L2
  8989. .L1
  8990. mov 0,reg
  8991. .L2
  8992. into
  8993. mov 0,reg
  8994. set<not(c)> reg
  8995. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8996. would destroy the flag contents
  8997. }
  8998. else if MatchInstruction(hp1,A_MOV,[]) and
  8999. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9000. {$ifdef i386}
  9001. (
  9002. { Under i386, ESI, EDI, EBP and ESP
  9003. don't have an 8-bit representation }
  9004. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9005. ) and
  9006. {$endif i386}
  9007. (taicpu(hp1).oper[0]^.val=1) and
  9008. GetNextInstruction(hp1,hp2) and
  9009. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9010. GetNextInstruction(hp2,hp3) and
  9011. { skip align }
  9012. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9013. (hp3.typ=ait_label) and
  9014. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9015. (tai_label(hp3).labsym.getrefs=1) and
  9016. GetNextInstruction(hp3,hp4) and
  9017. MatchInstruction(hp4,A_MOV,[]) and
  9018. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9019. (taicpu(hp4).oper[0]^.val=0) and
  9020. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9021. GetNextInstruction(hp4,hp5) and
  9022. (hp5.typ=ait_label) and
  9023. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9024. (tai_label(hp5).labsym.getrefs=1) then
  9025. begin
  9026. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9027. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9028. { remove last label }
  9029. RemoveInstruction(hp5);
  9030. { remove second label }
  9031. RemoveInstruction(hp3);
  9032. { if align is present remove it }
  9033. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9034. RemoveInstruction(hp3);
  9035. { remove jmp }
  9036. RemoveInstruction(hp2);
  9037. if taicpu(hp1).opsize=S_B then
  9038. RemoveInstruction(hp1)
  9039. else
  9040. taicpu(hp1).loadconst(0,0);
  9041. taicpu(hp4).opcode:=A_SETcc;
  9042. taicpu(hp4).opsize:=S_B;
  9043. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9044. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9045. taicpu(hp4).opercnt:=1;
  9046. taicpu(hp4).ops:=1;
  9047. taicpu(hp4).freeop(1);
  9048. RemoveCurrentP(p);
  9049. Result:=true;
  9050. exit;
  9051. end
  9052. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9053. begin
  9054. { check for
  9055. jCC xxx
  9056. <several movs>
  9057. xxx:
  9058. }
  9059. l:=0;
  9060. while assigned(hp1) and
  9061. CanBeCMOV(hp1) and
  9062. { stop on labels }
  9063. not(hp1.typ=ait_label) do
  9064. begin
  9065. inc(l);
  9066. GetNextInstruction(hp1,hp1);
  9067. end;
  9068. if assigned(hp1) then
  9069. begin
  9070. if FindLabel(tasmlabel(symbol),hp1) then
  9071. begin
  9072. if (l<=4) and (l>0) then
  9073. begin
  9074. condition:=inverse_cond(taicpu(p).condition);
  9075. UpdateUsedRegs(tai(p.next));
  9076. GetNextInstruction(p,hp1);
  9077. repeat
  9078. if not Assigned(hp1) then
  9079. InternalError(2018062900);
  9080. taicpu(hp1).opcode:=A_CMOVcc;
  9081. taicpu(hp1).condition:=condition;
  9082. UpdateUsedRegs(tai(hp1.next));
  9083. GetNextInstruction(hp1,hp1);
  9084. until not(CanBeCMOV(hp1));
  9085. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9086. hp2 := hp1;
  9087. repeat
  9088. if not Assigned(hp2) then
  9089. InternalError(2018062910);
  9090. case hp2.typ of
  9091. ait_label:
  9092. { What we expected - break out of the loop (it won't be a dead label at the top of
  9093. a cluster because that was optimised at an earlier stage) }
  9094. Break;
  9095. ait_align:
  9096. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9097. begin
  9098. hp2 := tai(hp2.Next);
  9099. Continue;
  9100. end;
  9101. else
  9102. begin
  9103. { Might be a comment or temporary allocation entry }
  9104. if not (hp2.typ in SkipInstr) then
  9105. InternalError(2018062911);
  9106. hp2 := tai(hp2.Next);
  9107. Continue;
  9108. end;
  9109. end;
  9110. until False;
  9111. { Now we can safely decrement the reference count }
  9112. tasmlabel(symbol).decrefs;
  9113. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9114. { Remove the original jump }
  9115. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9116. UpdateUsedRegs(tai(hp2.next));
  9117. GetNextInstruction(hp2, p); { Instruction after the label }
  9118. { Remove the label if this is its final reference }
  9119. if (tasmlabel(symbol).getrefs=0) then
  9120. StripLabelFast(hp1);
  9121. if Assigned(p) then
  9122. result:=true;
  9123. exit;
  9124. end;
  9125. end
  9126. else
  9127. begin
  9128. { check further for
  9129. jCC xxx
  9130. <several movs 1>
  9131. jmp yyy
  9132. xxx:
  9133. <several movs 2>
  9134. yyy:
  9135. }
  9136. { hp2 points to jmp yyy }
  9137. hp2:=hp1;
  9138. { skip hp1 to xxx (or an align right before it) }
  9139. GetNextInstruction(hp1, hp1);
  9140. if assigned(hp2) and
  9141. assigned(hp1) and
  9142. (l<=3) and
  9143. (hp2.typ=ait_instruction) and
  9144. (taicpu(hp2).is_jmp) and
  9145. (taicpu(hp2).condition=C_None) and
  9146. { real label and jump, no further references to the
  9147. label are allowed }
  9148. (tasmlabel(symbol).getrefs=1) and
  9149. FindLabel(tasmlabel(symbol),hp1) then
  9150. begin
  9151. l:=0;
  9152. { skip hp1 to <several moves 2> }
  9153. if (hp1.typ = ait_align) then
  9154. GetNextInstruction(hp1, hp1);
  9155. GetNextInstruction(hp1, hpmov2);
  9156. hp1 := hpmov2;
  9157. while assigned(hp1) and
  9158. CanBeCMOV(hp1) do
  9159. begin
  9160. inc(l);
  9161. GetNextInstruction(hp1, hp1);
  9162. end;
  9163. { hp1 points to yyy (or an align right before it) }
  9164. hp3 := hp1;
  9165. if assigned(hp1) and
  9166. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9167. begin
  9168. condition:=inverse_cond(taicpu(p).condition);
  9169. UpdateUsedRegs(tai(p.next));
  9170. GetNextInstruction(p,hp1);
  9171. repeat
  9172. taicpu(hp1).opcode:=A_CMOVcc;
  9173. taicpu(hp1).condition:=condition;
  9174. UpdateUsedRegs(tai(hp1.next));
  9175. GetNextInstruction(hp1,hp1);
  9176. until not(assigned(hp1)) or
  9177. not(CanBeCMOV(hp1));
  9178. condition:=inverse_cond(condition);
  9179. if GetLastInstruction(hpmov2,hp1) then
  9180. UpdateUsedRegs(tai(hp1.next));
  9181. hp1 := hpmov2;
  9182. { hp1 is now at <several movs 2> }
  9183. while Assigned(hp1) and CanBeCMOV(hp1) do
  9184. begin
  9185. taicpu(hp1).opcode:=A_CMOVcc;
  9186. taicpu(hp1).condition:=condition;
  9187. UpdateUsedRegs(tai(hp1.next));
  9188. GetNextInstruction(hp1,hp1);
  9189. end;
  9190. hp1 := p;
  9191. { Get first instruction after label }
  9192. UpdateUsedRegs(tai(hp3.next));
  9193. GetNextInstruction(hp3, p);
  9194. if assigned(p) and (hp3.typ = ait_align) then
  9195. GetNextInstruction(p, p);
  9196. { Don't dereference yet, as doing so will cause
  9197. GetNextInstruction to skip the label and
  9198. optional align marker. [Kit] }
  9199. GetNextInstruction(hp2, hp4);
  9200. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9201. { remove jCC }
  9202. RemoveInstruction(hp1);
  9203. { Now we can safely decrement it }
  9204. tasmlabel(symbol).decrefs;
  9205. { Remove label xxx (it will have a ref of zero due to the initial check }
  9206. StripLabelFast(hp4);
  9207. { remove jmp }
  9208. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9209. RemoveInstruction(hp2);
  9210. { As before, now we can safely decrement it }
  9211. tasmlabel(symbol).decrefs;
  9212. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9213. if tasmlabel(symbol).getrefs = 0 then
  9214. StripLabelFast(hp3);
  9215. if Assigned(p) then
  9216. result:=true;
  9217. exit;
  9218. end;
  9219. end;
  9220. end;
  9221. end;
  9222. {$endif i8086}
  9223. end;
  9224. end;
  9225. end;
  9226. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9227. var
  9228. hp1,hp2,hp3: tai;
  9229. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9230. NewSize: TOpSize;
  9231. NewRegSize: TSubRegister;
  9232. Limit: TCgInt;
  9233. SwapOper: POper;
  9234. begin
  9235. result:=false;
  9236. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9237. GetNextInstruction(p,hp1) and
  9238. (hp1.typ = ait_instruction);
  9239. if reg_and_hp1_is_instr and
  9240. (
  9241. (taicpu(hp1).opcode <> A_LEA) or
  9242. { If the LEA instruction can be converted into an arithmetic instruction,
  9243. it may be possible to then fold it. }
  9244. (
  9245. { If the flags register is in use, don't change the instruction
  9246. to an ADD otherwise this will scramble the flags. [Kit] }
  9247. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9248. ConvertLEA(taicpu(hp1))
  9249. )
  9250. ) and
  9251. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9252. GetNextInstruction(hp1,hp2) and
  9253. MatchInstruction(hp2,A_MOV,[]) and
  9254. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9255. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9256. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9257. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9258. {$ifdef i386}
  9259. { not all registers have byte size sub registers on i386 }
  9260. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9261. {$endif i386}
  9262. (((taicpu(hp1).ops=2) and
  9263. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9264. ((taicpu(hp1).ops=1) and
  9265. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9266. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9267. begin
  9268. { change movsX/movzX reg/ref, reg2
  9269. add/sub/or/... reg3/$const, reg2
  9270. mov reg2 reg/ref
  9271. to add/sub/or/... reg3/$const, reg/ref }
  9272. { by example:
  9273. movswl %si,%eax movswl %si,%eax p
  9274. decl %eax addl %edx,%eax hp1
  9275. movw %ax,%si movw %ax,%si hp2
  9276. ->
  9277. movswl %si,%eax movswl %si,%eax p
  9278. decw %eax addw %edx,%eax hp1
  9279. movw %ax,%si movw %ax,%si hp2
  9280. }
  9281. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9282. {
  9283. ->
  9284. movswl %si,%eax movswl %si,%eax p
  9285. decw %si addw %dx,%si hp1
  9286. movw %ax,%si movw %ax,%si hp2
  9287. }
  9288. case taicpu(hp1).ops of
  9289. 1:
  9290. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9291. 2:
  9292. begin
  9293. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9294. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9295. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9296. end;
  9297. else
  9298. internalerror(2008042702);
  9299. end;
  9300. {
  9301. ->
  9302. decw %si addw %dx,%si p
  9303. }
  9304. DebugMsg(SPeepholeOptimization + 'var3',p);
  9305. RemoveCurrentP(p, hp1);
  9306. RemoveInstruction(hp2);
  9307. Result := True;
  9308. Exit;
  9309. end;
  9310. if reg_and_hp1_is_instr and
  9311. (taicpu(hp1).opcode = A_MOV) and
  9312. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9313. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9314. {$ifdef x86_64}
  9315. { check for implicit extension to 64 bit }
  9316. or
  9317. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9318. (taicpu(hp1).opsize=S_Q) and
  9319. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9320. )
  9321. {$endif x86_64}
  9322. )
  9323. then
  9324. begin
  9325. { change
  9326. movx %reg1,%reg2
  9327. mov %reg2,%reg3
  9328. dealloc %reg2
  9329. into
  9330. movx %reg,%reg3
  9331. }
  9332. TransferUsedRegs(TmpUsedRegs);
  9333. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9334. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9335. begin
  9336. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9337. {$ifdef x86_64}
  9338. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9339. (taicpu(hp1).opsize=S_Q) then
  9340. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9341. else
  9342. {$endif x86_64}
  9343. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9344. RemoveInstruction(hp1);
  9345. Result := True;
  9346. Exit;
  9347. end;
  9348. end;
  9349. if reg_and_hp1_is_instr and
  9350. ((taicpu(hp1).opcode=A_MOV) or
  9351. (taicpu(hp1).opcode=A_ADD) or
  9352. (taicpu(hp1).opcode=A_SUB) or
  9353. (taicpu(hp1).opcode=A_CMP) or
  9354. (taicpu(hp1).opcode=A_OR) or
  9355. (taicpu(hp1).opcode=A_XOR) or
  9356. (taicpu(hp1).opcode=A_AND)
  9357. ) and
  9358. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9359. begin
  9360. AndTest := (taicpu(hp1).opcode=A_AND) and
  9361. GetNextInstruction(hp1, hp2) and
  9362. (hp2.typ = ait_instruction) and
  9363. (
  9364. (
  9365. (taicpu(hp2).opcode=A_TEST) and
  9366. (
  9367. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9368. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9369. (
  9370. { If the AND and TEST instructions share a constant, this is also valid }
  9371. (taicpu(hp1).oper[0]^.typ = top_const) and
  9372. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9373. )
  9374. ) and
  9375. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9376. ) or
  9377. (
  9378. (taicpu(hp2).opcode=A_CMP) and
  9379. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9380. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9381. )
  9382. );
  9383. { change
  9384. movx (oper),%reg2
  9385. and $x,%reg2
  9386. test %reg2,%reg2
  9387. dealloc %reg2
  9388. into
  9389. op %reg1,%reg3
  9390. if the second op accesses only the bits stored in reg1
  9391. }
  9392. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9393. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9394. (taicpu(hp1).oper[0]^.typ = top_const) and
  9395. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9396. AndTest then
  9397. begin
  9398. { Check if the AND constant is in range }
  9399. case taicpu(p).opsize of
  9400. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9401. begin
  9402. NewSize := S_B;
  9403. Limit := $FF;
  9404. end;
  9405. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9406. begin
  9407. NewSize := S_W;
  9408. Limit := $FFFF;
  9409. end;
  9410. {$ifdef x86_64}
  9411. S_LQ:
  9412. begin
  9413. NewSize := S_L;
  9414. Limit := $FFFFFFFF;
  9415. end;
  9416. {$endif x86_64}
  9417. else
  9418. InternalError(2021120303);
  9419. end;
  9420. if (
  9421. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9422. { Check for negative operands }
  9423. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9424. ) and
  9425. GetNextInstruction(hp2,hp3) and
  9426. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9427. (taicpu(hp3).condition in [C_E,C_NE]) then
  9428. begin
  9429. TransferUsedRegs(TmpUsedRegs);
  9430. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9431. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9432. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9433. begin
  9434. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9435. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9436. taicpu(hp1).opcode := A_TEST;
  9437. taicpu(hp1).opsize := NewSize;
  9438. RemoveInstruction(hp2);
  9439. RemoveCurrentP(p, hp1);
  9440. Result:=true;
  9441. exit;
  9442. end;
  9443. end;
  9444. end;
  9445. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9446. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9447. (taicpu(hp1).opsize=S_B)) or
  9448. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9449. (taicpu(hp1).opsize=S_W))
  9450. {$ifdef x86_64}
  9451. or ((taicpu(p).opsize=S_LQ) and
  9452. (taicpu(hp1).opsize=S_L))
  9453. {$endif x86_64}
  9454. ) and
  9455. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9456. begin
  9457. { change
  9458. movx %reg1,%reg2
  9459. op %reg2,%reg3
  9460. dealloc %reg2
  9461. into
  9462. op %reg1,%reg3
  9463. if the second op accesses only the bits stored in reg1
  9464. }
  9465. TransferUsedRegs(TmpUsedRegs);
  9466. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9467. if AndTest then
  9468. begin
  9469. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9470. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9471. end
  9472. else
  9473. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9474. if not RegUsed then
  9475. begin
  9476. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9477. if taicpu(p).oper[0]^.typ=top_reg then
  9478. begin
  9479. case taicpu(hp1).opsize of
  9480. S_B:
  9481. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9482. S_W:
  9483. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9484. S_L:
  9485. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9486. else
  9487. Internalerror(2020102301);
  9488. end;
  9489. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9490. end
  9491. else
  9492. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9493. RemoveCurrentP(p);
  9494. if AndTest then
  9495. RemoveInstruction(hp2);
  9496. result:=true;
  9497. exit;
  9498. end;
  9499. end
  9500. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9501. (
  9502. { Bitwise operations only }
  9503. (taicpu(hp1).opcode=A_AND) or
  9504. (taicpu(hp1).opcode=A_TEST) or
  9505. (
  9506. (taicpu(hp1).oper[0]^.typ = top_const) and
  9507. (
  9508. (taicpu(hp1).opcode=A_OR) or
  9509. (taicpu(hp1).opcode=A_XOR)
  9510. )
  9511. )
  9512. ) and
  9513. (
  9514. (taicpu(hp1).oper[0]^.typ = top_const) or
  9515. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9516. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9517. ) then
  9518. begin
  9519. { change
  9520. movx %reg2,%reg2
  9521. op const,%reg2
  9522. into
  9523. op const,%reg2 (smaller version)
  9524. movx %reg2,%reg2
  9525. also change
  9526. movx %reg1,%reg2
  9527. and/test (oper),%reg2
  9528. dealloc %reg2
  9529. into
  9530. and/test (oper),%reg1
  9531. }
  9532. case taicpu(p).opsize of
  9533. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9534. begin
  9535. NewSize := S_B;
  9536. NewRegSize := R_SUBL;
  9537. Limit := $FF;
  9538. end;
  9539. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9540. begin
  9541. NewSize := S_W;
  9542. NewRegSize := R_SUBW;
  9543. Limit := $FFFF;
  9544. end;
  9545. {$ifdef x86_64}
  9546. S_LQ:
  9547. begin
  9548. NewSize := S_L;
  9549. NewRegSize := R_SUBD;
  9550. Limit := $FFFFFFFF;
  9551. end;
  9552. {$endif x86_64}
  9553. else
  9554. Internalerror(2021120302);
  9555. end;
  9556. TransferUsedRegs(TmpUsedRegs);
  9557. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9558. if AndTest then
  9559. begin
  9560. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9561. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9562. end
  9563. else
  9564. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9565. if
  9566. (
  9567. (taicpu(p).opcode = A_MOVZX) and
  9568. (
  9569. (taicpu(hp1).opcode=A_AND) or
  9570. (taicpu(hp1).opcode=A_TEST)
  9571. ) and
  9572. not (
  9573. { If both are references, then the final instruction will have
  9574. both operands as references, which is not allowed }
  9575. (taicpu(p).oper[0]^.typ = top_ref) and
  9576. (taicpu(hp1).oper[0]^.typ = top_ref)
  9577. ) and
  9578. not RegUsed
  9579. ) or
  9580. (
  9581. (
  9582. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9583. not RegUsed
  9584. ) and
  9585. (taicpu(p).oper[0]^.typ = top_reg) and
  9586. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9587. (taicpu(hp1).oper[0]^.typ = top_const) and
  9588. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9589. ) then
  9590. begin
  9591. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9592. if AndTest and not RegUsed then
  9593. taicpu(hp1).opcode := A_TEST;
  9594. taicpu(hp1).opsize := NewSize;
  9595. case taicpu(hp1).oper[0]^.typ of
  9596. top_reg:
  9597. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9598. top_const:
  9599. { For the AND/TEST case }
  9600. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9601. else
  9602. ;
  9603. end;
  9604. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9605. if (taicpu(hp1).opcode = A_TEST) and (taicpu(hp1).oper[0]^.typ = top_ref) then
  9606. begin
  9607. { For TEST, make sure the reference is the second operand }
  9608. SwapOper := taicpu(hp1).oper[0];
  9609. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9610. taicpu(hp1).oper[1] := SwapOper;
  9611. end;
  9612. if AndTest then
  9613. RemoveInstruction(hp2);
  9614. if RegUsed then
  9615. begin
  9616. AsmL.Remove(p);
  9617. AsmL.InsertAfter(p, hp1);
  9618. p := hp1;
  9619. end
  9620. else
  9621. RemoveCurrentP(p, hp1);
  9622. result:=true;
  9623. exit;
  9624. end;
  9625. end;
  9626. end;
  9627. if reg_and_hp1_is_instr and
  9628. (taicpu(p).oper[0]^.typ = top_reg) and
  9629. (
  9630. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9631. ) and
  9632. (taicpu(hp1).oper[0]^.typ = top_const) and
  9633. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9634. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9635. { Minimum shift value allowed is the bit difference between the sizes }
  9636. (taicpu(hp1).oper[0]^.val >=
  9637. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9638. 8 * (
  9639. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9640. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9641. )
  9642. ) then
  9643. begin
  9644. { For:
  9645. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9646. shl/sal ##, %reg1
  9647. Remove the movsx/movzx instruction if the shift overwrites the
  9648. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9649. }
  9650. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9651. RemoveCurrentP(p, hp1);
  9652. Result := True;
  9653. Exit;
  9654. end
  9655. else if reg_and_hp1_is_instr and
  9656. (taicpu(p).oper[0]^.typ = top_reg) and
  9657. (
  9658. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9659. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9660. ) and
  9661. (taicpu(hp1).oper[0]^.typ = top_const) and
  9662. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9663. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9664. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9665. (taicpu(hp1).oper[0]^.val <
  9666. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9667. 8 * (
  9668. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9669. )
  9670. ) then
  9671. begin
  9672. { For:
  9673. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9674. sar ##, %reg1 shr ##, %reg1
  9675. Move the shift to before the movx instruction if the shift value
  9676. is not too large.
  9677. }
  9678. asml.Remove(hp1);
  9679. asml.InsertBefore(hp1, p);
  9680. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9681. case taicpu(p).opsize of
  9682. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9683. taicpu(hp1).opsize := S_B;
  9684. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9685. taicpu(hp1).opsize := S_W;
  9686. {$ifdef x86_64}
  9687. S_LQ:
  9688. taicpu(hp1).opsize := S_L;
  9689. {$endif}
  9690. else
  9691. InternalError(2020112401);
  9692. end;
  9693. if (taicpu(hp1).opcode = A_SHR) then
  9694. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9695. else
  9696. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9697. Result := True;
  9698. end;
  9699. if reg_and_hp1_is_instr and
  9700. (taicpu(p).oper[0]^.typ = top_reg) and
  9701. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9702. (
  9703. (taicpu(hp1).opcode = taicpu(p).opcode)
  9704. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9705. {$ifdef x86_64}
  9706. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9707. {$endif x86_64}
  9708. ) then
  9709. begin
  9710. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9711. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9712. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9713. begin
  9714. {
  9715. For example:
  9716. movzbw %al,%ax
  9717. movzwl %ax,%eax
  9718. Compress into:
  9719. movzbl %al,%eax
  9720. }
  9721. RegUsed := False;
  9722. case taicpu(p).opsize of
  9723. S_BW:
  9724. case taicpu(hp1).opsize of
  9725. S_WL:
  9726. begin
  9727. taicpu(p).opsize := S_BL;
  9728. RegUsed := True;
  9729. end;
  9730. {$ifdef x86_64}
  9731. S_WQ:
  9732. begin
  9733. if taicpu(p).opcode = A_MOVZX then
  9734. begin
  9735. taicpu(p).opsize := S_BL;
  9736. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9737. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9738. end
  9739. else
  9740. taicpu(p).opsize := S_BQ;
  9741. RegUsed := True;
  9742. end;
  9743. {$endif x86_64}
  9744. else
  9745. ;
  9746. end;
  9747. {$ifdef x86_64}
  9748. S_BL:
  9749. case taicpu(hp1).opsize of
  9750. S_LQ:
  9751. begin
  9752. if taicpu(p).opcode = A_MOVZX then
  9753. begin
  9754. taicpu(p).opsize := S_BL;
  9755. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9756. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9757. end
  9758. else
  9759. taicpu(p).opsize := S_BQ;
  9760. RegUsed := True;
  9761. end;
  9762. else
  9763. ;
  9764. end;
  9765. S_WL:
  9766. case taicpu(hp1).opsize of
  9767. S_LQ:
  9768. begin
  9769. if taicpu(p).opcode = A_MOVZX then
  9770. begin
  9771. taicpu(p).opsize := S_WL;
  9772. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9773. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9774. end
  9775. else
  9776. taicpu(p).opsize := S_WQ;
  9777. RegUsed := True;
  9778. end;
  9779. else
  9780. ;
  9781. end;
  9782. {$endif x86_64}
  9783. else
  9784. ;
  9785. end;
  9786. if RegUsed then
  9787. begin
  9788. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9789. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9790. RemoveInstruction(hp1);
  9791. Result := True;
  9792. Exit;
  9793. end;
  9794. end;
  9795. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9796. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9797. GetNextInstruction(hp1, hp2) and
  9798. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9799. (
  9800. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9801. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9802. {$ifdef x86_64}
  9803. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9804. {$endif x86_64}
  9805. ) and
  9806. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9807. (
  9808. (
  9809. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9810. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9811. ) or
  9812. (
  9813. { Only allow the operands in reverse order for TEST instructions }
  9814. (taicpu(hp2).opcode = A_TEST) and
  9815. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9816. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9817. )
  9818. ) then
  9819. begin
  9820. {
  9821. For example:
  9822. movzbl %al,%eax
  9823. movzbl (ref),%edx
  9824. andl %edx,%eax
  9825. (%edx deallocated)
  9826. Change to:
  9827. andb (ref),%al
  9828. movzbl %al,%eax
  9829. Rules are:
  9830. - First two instructions have the same opcode and opsize
  9831. - First instruction's operands are the same super-register
  9832. - Second instruction operates on a different register
  9833. - Third instruction is AND, OR, XOR or TEST
  9834. - Third instruction's operands are the destination registers of the first two instructions
  9835. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9836. - Second instruction's destination register is deallocated afterwards
  9837. }
  9838. TransferUsedRegs(TmpUsedRegs);
  9839. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9840. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9841. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9842. begin
  9843. case taicpu(p).opsize of
  9844. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9845. NewSize := S_B;
  9846. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9847. NewSize := S_W;
  9848. {$ifdef x86_64}
  9849. S_LQ:
  9850. NewSize := S_L;
  9851. {$endif x86_64}
  9852. else
  9853. InternalError(2021120301);
  9854. end;
  9855. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  9856. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  9857. taicpu(hp2).opsize := NewSize;
  9858. RemoveInstruction(hp1);
  9859. { With TEST, it's best to keep the MOVX instruction at the top }
  9860. if (taicpu(hp2).opcode <> A_TEST) then
  9861. begin
  9862. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  9863. asml.Remove(p);
  9864. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  9865. asml.InsertAfter(p, hp2);
  9866. p := hp2;
  9867. end
  9868. else
  9869. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  9870. Result := True;
  9871. Exit;
  9872. end;
  9873. end;
  9874. end;
  9875. if taicpu(p).opcode=A_MOVZX then
  9876. begin
  9877. { removes superfluous And's after movzx's }
  9878. if reg_and_hp1_is_instr and
  9879. (taicpu(hp1).opcode = A_AND) and
  9880. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9881. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9882. {$ifdef x86_64}
  9883. { check for implicit extension to 64 bit }
  9884. or
  9885. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9886. (taicpu(hp1).opsize=S_Q) and
  9887. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  9888. )
  9889. {$endif x86_64}
  9890. )
  9891. then
  9892. begin
  9893. case taicpu(p).opsize Of
  9894. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9895. if (taicpu(hp1).oper[0]^.val = $ff) then
  9896. begin
  9897. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  9898. RemoveInstruction(hp1);
  9899. Result:=true;
  9900. exit;
  9901. end;
  9902. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9903. if (taicpu(hp1).oper[0]^.val = $ffff) then
  9904. begin
  9905. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  9906. RemoveInstruction(hp1);
  9907. Result:=true;
  9908. exit;
  9909. end;
  9910. {$ifdef x86_64}
  9911. S_LQ:
  9912. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  9913. begin
  9914. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  9915. RemoveInstruction(hp1);
  9916. Result:=true;
  9917. exit;
  9918. end;
  9919. {$endif x86_64}
  9920. else
  9921. ;
  9922. end;
  9923. { we cannot get rid of the and, but can we get rid of the movz ?}
  9924. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  9925. begin
  9926. case taicpu(p).opsize Of
  9927. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9928. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  9929. begin
  9930. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  9931. RemoveCurrentP(p,hp1);
  9932. Result:=true;
  9933. exit;
  9934. end;
  9935. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9936. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  9937. begin
  9938. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  9939. RemoveCurrentP(p,hp1);
  9940. Result:=true;
  9941. exit;
  9942. end;
  9943. {$ifdef x86_64}
  9944. S_LQ:
  9945. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  9946. begin
  9947. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  9948. RemoveCurrentP(p,hp1);
  9949. Result:=true;
  9950. exit;
  9951. end;
  9952. {$endif x86_64}
  9953. else
  9954. ;
  9955. end;
  9956. end;
  9957. end;
  9958. { changes some movzx constructs to faster synonyms (all examples
  9959. are given with eax/ax, but are also valid for other registers)}
  9960. if MatchOpType(taicpu(p),top_reg,top_reg) then
  9961. begin
  9962. case taicpu(p).opsize of
  9963. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  9964. (the machine code is equivalent to movzbl %al,%eax), but the
  9965. code generator still generates that assembler instruction and
  9966. it is silently converted. This should probably be checked.
  9967. [Kit] }
  9968. S_BW:
  9969. begin
  9970. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  9971. (
  9972. not IsMOVZXAcceptable
  9973. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  9974. or (
  9975. (cs_opt_size in current_settings.optimizerswitches) and
  9976. (taicpu(p).oper[1]^.reg = NR_AX)
  9977. )
  9978. ) then
  9979. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  9980. begin
  9981. DebugMsg(SPeepholeOptimization + 'var7',p);
  9982. taicpu(p).opcode := A_AND;
  9983. taicpu(p).changeopsize(S_W);
  9984. taicpu(p).loadConst(0,$ff);
  9985. Result := True;
  9986. end
  9987. else if not IsMOVZXAcceptable and
  9988. GetNextInstruction(p, hp1) and
  9989. (tai(hp1).typ = ait_instruction) and
  9990. (taicpu(hp1).opcode = A_AND) and
  9991. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9992. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9993. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  9994. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  9995. begin
  9996. DebugMsg(SPeepholeOptimization + 'var8',p);
  9997. taicpu(p).opcode := A_MOV;
  9998. taicpu(p).changeopsize(S_W);
  9999. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10000. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10001. Result := True;
  10002. end;
  10003. end;
  10004. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10005. S_BL:
  10006. begin
  10007. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10008. (
  10009. not IsMOVZXAcceptable
  10010. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10011. or (
  10012. (cs_opt_size in current_settings.optimizerswitches) and
  10013. (taicpu(p).oper[1]^.reg = NR_EAX)
  10014. )
  10015. ) then
  10016. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10017. begin
  10018. DebugMsg(SPeepholeOptimization + 'var9',p);
  10019. taicpu(p).opcode := A_AND;
  10020. taicpu(p).changeopsize(S_L);
  10021. taicpu(p).loadConst(0,$ff);
  10022. Result := True;
  10023. end
  10024. else if not IsMOVZXAcceptable and
  10025. GetNextInstruction(p, hp1) and
  10026. (tai(hp1).typ = ait_instruction) and
  10027. (taicpu(hp1).opcode = A_AND) and
  10028. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10029. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10030. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10031. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10032. begin
  10033. DebugMsg(SPeepholeOptimization + 'var10',p);
  10034. taicpu(p).opcode := A_MOV;
  10035. taicpu(p).changeopsize(S_L);
  10036. { do not use R_SUBWHOLE
  10037. as movl %rdx,%eax
  10038. is invalid in assembler PM }
  10039. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10040. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10041. Result := True;
  10042. end;
  10043. end;
  10044. {$endif i8086}
  10045. S_WL:
  10046. if not IsMOVZXAcceptable then
  10047. begin
  10048. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10049. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10050. begin
  10051. DebugMsg(SPeepholeOptimization + 'var11',p);
  10052. taicpu(p).opcode := A_AND;
  10053. taicpu(p).changeopsize(S_L);
  10054. taicpu(p).loadConst(0,$ffff);
  10055. Result := True;
  10056. end
  10057. else if GetNextInstruction(p, hp1) and
  10058. (tai(hp1).typ = ait_instruction) and
  10059. (taicpu(hp1).opcode = A_AND) and
  10060. (taicpu(hp1).oper[0]^.typ = top_const) and
  10061. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10062. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10063. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10064. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10065. begin
  10066. DebugMsg(SPeepholeOptimization + 'var12',p);
  10067. taicpu(p).opcode := A_MOV;
  10068. taicpu(p).changeopsize(S_L);
  10069. { do not use R_SUBWHOLE
  10070. as movl %rdx,%eax
  10071. is invalid in assembler PM }
  10072. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10073. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10074. Result := True;
  10075. end;
  10076. end;
  10077. else
  10078. InternalError(2017050705);
  10079. end;
  10080. end
  10081. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10082. begin
  10083. if GetNextInstruction(p, hp1) and
  10084. (tai(hp1).typ = ait_instruction) and
  10085. (taicpu(hp1).opcode = A_AND) and
  10086. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10087. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10088. begin
  10089. //taicpu(p).opcode := A_MOV;
  10090. case taicpu(p).opsize Of
  10091. S_BL:
  10092. begin
  10093. DebugMsg(SPeepholeOptimization + 'var13',p);
  10094. taicpu(hp1).changeopsize(S_L);
  10095. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10096. end;
  10097. S_WL:
  10098. begin
  10099. DebugMsg(SPeepholeOptimization + 'var14',p);
  10100. taicpu(hp1).changeopsize(S_L);
  10101. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10102. end;
  10103. S_BW:
  10104. begin
  10105. DebugMsg(SPeepholeOptimization + 'var15',p);
  10106. taicpu(hp1).changeopsize(S_W);
  10107. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10108. end;
  10109. else
  10110. Internalerror(2017050704)
  10111. end;
  10112. Result := True;
  10113. end;
  10114. end;
  10115. end;
  10116. end;
  10117. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10118. var
  10119. hp1, hp2 : tai;
  10120. MaskLength : Cardinal;
  10121. MaskedBits : TCgInt;
  10122. ActiveReg : TRegister;
  10123. begin
  10124. Result:=false;
  10125. { There are no optimisations for reference targets }
  10126. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10127. Exit;
  10128. while GetNextInstruction(p, hp1) and
  10129. (hp1.typ = ait_instruction) do
  10130. begin
  10131. if (taicpu(p).oper[0]^.typ = top_const) then
  10132. begin
  10133. case taicpu(hp1).opcode of
  10134. A_AND:
  10135. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10136. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10137. { the second register must contain the first one, so compare their subreg types }
  10138. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10139. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10140. { change
  10141. and const1, reg
  10142. and const2, reg
  10143. to
  10144. and (const1 and const2), reg
  10145. }
  10146. begin
  10147. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10148. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10149. RemoveCurrentP(p, hp1);
  10150. Result:=true;
  10151. exit;
  10152. end;
  10153. A_CMP:
  10154. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10157. { Just check that the condition on the next instruction is compatible }
  10158. GetNextInstruction(hp1, hp2) and
  10159. (hp2.typ = ait_instruction) and
  10160. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10161. then
  10162. { change
  10163. and 2^n, reg
  10164. cmp 2^n, reg
  10165. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10166. to
  10167. and 2^n, reg
  10168. test reg, reg
  10169. j(~c) / set(~c) / cmov(~c)
  10170. }
  10171. begin
  10172. { Keep TEST instruction in, rather than remove it, because
  10173. it may trigger other optimisations such as MovAndTest2Test }
  10174. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10175. taicpu(hp1).opcode := A_TEST;
  10176. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10177. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10178. Result := True;
  10179. Exit;
  10180. end;
  10181. A_MOVZX:
  10182. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10183. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10184. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10185. (
  10186. (
  10187. (taicpu(p).opsize=S_W) and
  10188. (taicpu(hp1).opsize=S_BW)
  10189. ) or
  10190. (
  10191. (taicpu(p).opsize=S_L) and
  10192. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10193. )
  10194. {$ifdef x86_64}
  10195. or
  10196. (
  10197. (taicpu(p).opsize=S_Q) and
  10198. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10199. )
  10200. {$endif x86_64}
  10201. ) then
  10202. begin
  10203. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10204. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10205. ) or
  10206. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10207. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10208. then
  10209. begin
  10210. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10211. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10212. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10213. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10214. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10215. }
  10216. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10217. RemoveInstruction(hp1);
  10218. { See if there are other optimisations possible }
  10219. Continue;
  10220. end;
  10221. end;
  10222. A_SHL:
  10223. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10224. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10225. begin
  10226. {$ifopt R+}
  10227. {$define RANGE_WAS_ON}
  10228. {$R-}
  10229. {$endif}
  10230. { get length of potential and mask }
  10231. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10232. { really a mask? }
  10233. {$ifdef RANGE_WAS_ON}
  10234. {$R+}
  10235. {$endif}
  10236. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10237. { unmasked part shifted out? }
  10238. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10239. begin
  10240. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10241. RemoveCurrentP(p, hp1);
  10242. Result:=true;
  10243. exit;
  10244. end;
  10245. end;
  10246. A_SHR:
  10247. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10248. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10249. (taicpu(hp1).oper[0]^.val <= 63) then
  10250. begin
  10251. { Does SHR combined with the AND cover all the bits?
  10252. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10253. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10254. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10255. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10256. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10257. begin
  10258. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10259. RemoveCurrentP(p, hp1);
  10260. Result := True;
  10261. Exit;
  10262. end;
  10263. end;
  10264. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10265. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10266. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10267. begin
  10268. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10269. (
  10270. (
  10271. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10272. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10273. ) or (
  10274. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10275. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10276. {$ifdef x86_64}
  10277. ) or (
  10278. (taicpu(hp1).opsize = S_LQ) and
  10279. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10280. {$endif x86_64}
  10281. )
  10282. ) then
  10283. begin
  10284. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10285. begin
  10286. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10287. RemoveInstruction(hp1);
  10288. { See if there are other optimisations possible }
  10289. Continue;
  10290. end;
  10291. { The super-registers are the same though.
  10292. Note that this change by itself doesn't improve
  10293. code speed, but it opens up other optimisations. }
  10294. {$ifdef x86_64}
  10295. { Convert 64-bit register to 32-bit }
  10296. case taicpu(hp1).opsize of
  10297. S_BQ:
  10298. begin
  10299. taicpu(hp1).opsize := S_BL;
  10300. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10301. end;
  10302. S_WQ:
  10303. begin
  10304. taicpu(hp1).opsize := S_WL;
  10305. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10306. end
  10307. else
  10308. ;
  10309. end;
  10310. {$endif x86_64}
  10311. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10312. taicpu(hp1).opcode := A_MOVZX;
  10313. { See if there are other optimisations possible }
  10314. Continue;
  10315. end;
  10316. end;
  10317. else
  10318. ;
  10319. end;
  10320. end
  10321. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10322. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10323. begin
  10324. {$ifdef x86_64}
  10325. if (taicpu(p).opsize = S_Q) then
  10326. begin
  10327. { Never necessary }
  10328. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10329. RemoveCurrentP(p, hp1);
  10330. Result := True;
  10331. Exit;
  10332. end;
  10333. {$endif x86_64}
  10334. { Forward check to determine necessity of and %reg,%reg }
  10335. TransferUsedRegs(TmpUsedRegs);
  10336. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10337. { Saves on a bunch of dereferences }
  10338. ActiveReg := taicpu(p).oper[1]^.reg;
  10339. case taicpu(hp1).opcode of
  10340. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10341. if (
  10342. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10343. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10344. ) and
  10345. (
  10346. (taicpu(hp1).opcode <> A_MOV) or
  10347. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10348. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10349. ) and
  10350. not (
  10351. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10352. (taicpu(hp1).opcode = A_MOV) and
  10353. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10354. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10355. ) and
  10356. (
  10357. (
  10358. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10359. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10360. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10361. ) or
  10362. (
  10363. {$ifdef x86_64}
  10364. (
  10365. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10366. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10367. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10368. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10369. ) and
  10370. {$endif x86_64}
  10371. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10372. )
  10373. ) then
  10374. begin
  10375. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10376. RemoveCurrentP(p, hp1);
  10377. Result := True;
  10378. Exit;
  10379. end;
  10380. A_ADD,
  10381. A_AND,
  10382. A_BSF,
  10383. A_BSR,
  10384. A_BTC,
  10385. A_BTR,
  10386. A_BTS,
  10387. A_OR,
  10388. A_SUB,
  10389. A_XOR:
  10390. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10391. if (
  10392. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10393. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10394. ) and
  10395. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10396. begin
  10397. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10398. RemoveCurrentP(p, hp1);
  10399. Result := True;
  10400. Exit;
  10401. end;
  10402. A_CMP,
  10403. A_TEST:
  10404. if (
  10405. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10406. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10407. ) and
  10408. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10409. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10410. begin
  10411. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10412. RemoveCurrentP(p, hp1);
  10413. Result := True;
  10414. Exit;
  10415. end;
  10416. A_BSWAP,
  10417. A_NEG,
  10418. A_NOT:
  10419. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10420. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10421. begin
  10422. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10423. RemoveCurrentP(p, hp1);
  10424. Result := True;
  10425. Exit;
  10426. end;
  10427. else
  10428. ;
  10429. end;
  10430. end;
  10431. if (taicpu(hp1).is_jmp) and
  10432. (taicpu(hp1).opcode<>A_JMP) and
  10433. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10434. begin
  10435. { change
  10436. and x, reg
  10437. jxx
  10438. to
  10439. test x, reg
  10440. jxx
  10441. if reg is deallocated before the
  10442. jump, but only if it's a conditional jump (PFV)
  10443. }
  10444. taicpu(p).opcode := A_TEST;
  10445. Exit;
  10446. end;
  10447. Break;
  10448. end;
  10449. { Lone AND tests }
  10450. if (taicpu(p).oper[0]^.typ = top_const) then
  10451. begin
  10452. {
  10453. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10454. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10455. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10456. }
  10457. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10458. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10459. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10460. begin
  10461. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10462. if taicpu(p).opsize = S_L then
  10463. begin
  10464. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10465. Result := True;
  10466. end;
  10467. end;
  10468. end;
  10469. { Backward check to determine necessity of and %reg,%reg }
  10470. if (taicpu(p).oper[0]^.typ = top_reg) and
  10471. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10472. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10473. GetLastInstruction(p, hp2) and
  10474. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10475. { Check size of adjacent instruction to determine if the AND is
  10476. effectively a null operation }
  10477. (
  10478. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10479. { Note: Don't include S_Q }
  10480. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10481. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10482. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10483. ) then
  10484. begin
  10485. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10486. { If GetNextInstruction returned False, hp1 will be nil }
  10487. RemoveCurrentP(p, hp1);
  10488. Result := True;
  10489. Exit;
  10490. end;
  10491. end;
  10492. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10493. var
  10494. hp1: tai; NewRef: TReference;
  10495. { This entire nested function is used in an if-statement below, but we
  10496. want to avoid all the used reg transfers and GetNextInstruction calls
  10497. until we really have to check }
  10498. function MemRegisterNotUsedLater: Boolean; inline;
  10499. var
  10500. hp2: tai;
  10501. begin
  10502. TransferUsedRegs(TmpUsedRegs);
  10503. hp2 := p;
  10504. repeat
  10505. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10506. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10507. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10508. end;
  10509. begin
  10510. Result := False;
  10511. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10512. Exit;
  10513. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10514. begin
  10515. { Change:
  10516. add %reg2,%reg1
  10517. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10518. To:
  10519. mov/s/z #(%reg1,%reg2),%reg1
  10520. }
  10521. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10522. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10523. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10524. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10525. (
  10526. (
  10527. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10528. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10529. { r/esp cannot be an index }
  10530. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10531. ) or (
  10532. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10533. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10534. )
  10535. ) and (
  10536. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10537. (
  10538. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10539. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10540. MemRegisterNotUsedLater
  10541. )
  10542. ) then
  10543. begin
  10544. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10545. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10546. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10547. RemoveCurrentp(p, hp1);
  10548. Result := True;
  10549. Exit;
  10550. end;
  10551. { Change:
  10552. addl/q $x,%reg1
  10553. movl/q %reg1,%reg2
  10554. To:
  10555. leal/q $x(%reg1),%reg2
  10556. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10557. Breaks the dependency chain.
  10558. }
  10559. if MatchOpType(taicpu(p),top_const,top_reg) and
  10560. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10561. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10562. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10563. (
  10564. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10565. not (cs_opt_size in current_settings.optimizerswitches) or
  10566. (
  10567. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10568. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10569. )
  10570. ) then
  10571. begin
  10572. { Change the MOV instruction to a LEA instruction, and update the
  10573. first operand }
  10574. reference_reset(NewRef, 1, []);
  10575. NewRef.base := taicpu(p).oper[1]^.reg;
  10576. NewRef.scalefactor := 1;
  10577. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10578. taicpu(hp1).opcode := A_LEA;
  10579. taicpu(hp1).loadref(0, NewRef);
  10580. TransferUsedRegs(TmpUsedRegs);
  10581. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10582. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10583. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10584. begin
  10585. { Move what is now the LEA instruction to before the SUB instruction }
  10586. Asml.Remove(hp1);
  10587. Asml.InsertBefore(hp1, p);
  10588. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10589. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10590. p := hp1;
  10591. end
  10592. else
  10593. begin
  10594. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10595. RemoveCurrentP(p, hp1);
  10596. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10597. end;
  10598. Result := True;
  10599. end;
  10600. end;
  10601. end;
  10602. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10603. var
  10604. SubReg: TSubRegister;
  10605. begin
  10606. Result:=false;
  10607. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10608. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10609. with taicpu(p).oper[0]^.ref^ do
  10610. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10611. begin
  10612. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10613. begin
  10614. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10615. taicpu(p).opcode := A_ADD;
  10616. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10617. Result := True;
  10618. end
  10619. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10620. begin
  10621. if (base <> NR_NO) then
  10622. begin
  10623. if (scalefactor <= 1) then
  10624. begin
  10625. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10626. taicpu(p).opcode := A_ADD;
  10627. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10628. Result := True;
  10629. end;
  10630. end
  10631. else
  10632. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10633. if (scalefactor in [2, 4, 8]) then
  10634. begin
  10635. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10636. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10637. taicpu(p).opcode := A_SHL;
  10638. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10639. Result := True;
  10640. end;
  10641. end;
  10642. end;
  10643. end;
  10644. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10645. var
  10646. hp1: tai; NewRef: TReference;
  10647. begin
  10648. { Change:
  10649. subl/q $x,%reg1
  10650. movl/q %reg1,%reg2
  10651. To:
  10652. leal/q $-x(%reg1),%reg2
  10653. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10654. Breaks the dependency chain and potentially permits the removal of
  10655. a CMP instruction if one follows.
  10656. }
  10657. Result := False;
  10658. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10659. MatchOpType(taicpu(p),top_const,top_reg) and
  10660. GetNextInstruction(p, hp1) and
  10661. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10662. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10663. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10664. (
  10665. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10666. not (cs_opt_size in current_settings.optimizerswitches) or
  10667. (
  10668. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10669. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10670. )
  10671. ) then
  10672. begin
  10673. { Change the MOV instruction to a LEA instruction, and update the
  10674. first operand }
  10675. reference_reset(NewRef, 1, []);
  10676. NewRef.base := taicpu(p).oper[1]^.reg;
  10677. NewRef.scalefactor := 1;
  10678. NewRef.offset := -taicpu(p).oper[0]^.val;
  10679. taicpu(hp1).opcode := A_LEA;
  10680. taicpu(hp1).loadref(0, NewRef);
  10681. TransferUsedRegs(TmpUsedRegs);
  10682. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10683. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10684. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10685. begin
  10686. { Move what is now the LEA instruction to before the SUB instruction }
  10687. Asml.Remove(hp1);
  10688. Asml.InsertBefore(hp1, p);
  10689. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10690. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10691. p := hp1;
  10692. end
  10693. else
  10694. begin
  10695. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10696. RemoveCurrentP(p, hp1);
  10697. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10698. end;
  10699. Result := True;
  10700. end;
  10701. end;
  10702. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10703. begin
  10704. { we can skip all instructions not messing with the stack pointer }
  10705. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10706. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10707. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10708. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10709. ({(taicpu(hp1).ops=0) or }
  10710. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10711. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10712. ) and }
  10713. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10714. )
  10715. ) do
  10716. GetNextInstruction(hp1,hp1);
  10717. Result:=assigned(hp1);
  10718. end;
  10719. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10720. var
  10721. hp1, hp2, hp3, hp4, hp5: tai;
  10722. begin
  10723. Result:=false;
  10724. hp5:=nil;
  10725. { replace
  10726. leal(q) x(<stackpointer>),<stackpointer>
  10727. call procname
  10728. leal(q) -x(<stackpointer>),<stackpointer>
  10729. ret
  10730. by
  10731. jmp procname
  10732. but do it only on level 4 because it destroys stack back traces
  10733. }
  10734. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10735. MatchOpType(taicpu(p),top_ref,top_reg) and
  10736. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10737. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10738. { the -8 or -24 are not required, but bail out early if possible,
  10739. higher values are unlikely }
  10740. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10741. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10742. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10743. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10744. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10745. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10746. GetNextInstruction(p, hp1) and
  10747. { Take a copy of hp1 }
  10748. SetAndTest(hp1, hp4) and
  10749. { trick to skip label }
  10750. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10751. SkipSimpleInstructions(hp1) and
  10752. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10753. GetNextInstruction(hp1, hp2) and
  10754. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10755. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10756. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10757. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10758. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10759. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10760. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10761. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10762. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10763. GetNextInstruction(hp2, hp3) and
  10764. { trick to skip label }
  10765. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10766. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10767. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10768. SetAndTest(hp3,hp5) and
  10769. GetNextInstruction(hp3,hp3) and
  10770. MatchInstruction(hp3,A_RET,[S_NO])
  10771. )
  10772. ) and
  10773. (taicpu(hp3).ops=0) then
  10774. begin
  10775. taicpu(hp1).opcode := A_JMP;
  10776. taicpu(hp1).is_jmp := true;
  10777. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10778. RemoveCurrentP(p, hp4);
  10779. RemoveInstruction(hp2);
  10780. RemoveInstruction(hp3);
  10781. if Assigned(hp5) then
  10782. begin
  10783. AsmL.Remove(hp5);
  10784. ASmL.InsertBefore(hp5,hp1)
  10785. end;
  10786. Result:=true;
  10787. end;
  10788. end;
  10789. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10790. {$ifdef x86_64}
  10791. var
  10792. hp1, hp2, hp3, hp4, hp5: tai;
  10793. {$endif x86_64}
  10794. begin
  10795. Result:=false;
  10796. {$ifdef x86_64}
  10797. hp5:=nil;
  10798. { replace
  10799. push %rax
  10800. call procname
  10801. pop %rcx
  10802. ret
  10803. by
  10804. jmp procname
  10805. but do it only on level 4 because it destroys stack back traces
  10806. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10807. for all supported calling conventions
  10808. }
  10809. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10810. MatchOpType(taicpu(p),top_reg) and
  10811. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10812. GetNextInstruction(p, hp1) and
  10813. { Take a copy of hp1 }
  10814. SetAndTest(hp1, hp4) and
  10815. { trick to skip label }
  10816. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10817. SkipSimpleInstructions(hp1) and
  10818. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10819. GetNextInstruction(hp1, hp2) and
  10820. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10821. MatchOpType(taicpu(hp2),top_reg) and
  10822. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10823. GetNextInstruction(hp2, hp3) and
  10824. { trick to skip label }
  10825. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10826. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10827. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10828. SetAndTest(hp3,hp5) and
  10829. GetNextInstruction(hp3,hp3) and
  10830. MatchInstruction(hp3,A_RET,[S_NO])
  10831. )
  10832. ) and
  10833. (taicpu(hp3).ops=0) then
  10834. begin
  10835. taicpu(hp1).opcode := A_JMP;
  10836. taicpu(hp1).is_jmp := true;
  10837. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10838. RemoveCurrentP(p, hp4);
  10839. RemoveInstruction(hp2);
  10840. RemoveInstruction(hp3);
  10841. if Assigned(hp5) then
  10842. begin
  10843. AsmL.Remove(hp5);
  10844. ASmL.InsertBefore(hp5,hp1)
  10845. end;
  10846. Result:=true;
  10847. end;
  10848. {$endif x86_64}
  10849. end;
  10850. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  10851. var
  10852. Value, RegName: string;
  10853. begin
  10854. Result:=false;
  10855. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  10856. begin
  10857. case taicpu(p).oper[0]^.val of
  10858. 0:
  10859. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  10860. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10861. begin
  10862. { change "mov $0,%reg" into "xor %reg,%reg" }
  10863. taicpu(p).opcode := A_XOR;
  10864. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  10865. Result := True;
  10866. {$ifdef x86_64}
  10867. end
  10868. else if (taicpu(p).opsize = S_Q) then
  10869. begin
  10870. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10871. { The actual optimization }
  10872. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10873. taicpu(p).changeopsize(S_L);
  10874. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10875. Result := True;
  10876. end;
  10877. $1..$FFFFFFFF:
  10878. begin
  10879. { Code size reduction by J. Gareth "Kit" Moreton }
  10880. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  10881. case taicpu(p).opsize of
  10882. S_Q:
  10883. begin
  10884. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10885. Value := debug_tostr(taicpu(p).oper[0]^.val);
  10886. { The actual optimization }
  10887. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10888. taicpu(p).changeopsize(S_L);
  10889. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10890. Result := True;
  10891. end;
  10892. else
  10893. { Do nothing };
  10894. end;
  10895. {$endif x86_64}
  10896. end;
  10897. -1:
  10898. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  10899. if (cs_opt_size in current_settings.optimizerswitches) and
  10900. (taicpu(p).opsize <> S_B) and
  10901. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10902. begin
  10903. { change "mov $-1,%reg" into "or $-1,%reg" }
  10904. { NOTES:
  10905. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  10906. - This operation creates a false dependency on the register, so only do it when optimising for size
  10907. - 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
  10908. }
  10909. taicpu(p).opcode := A_OR;
  10910. Result := True;
  10911. end;
  10912. else
  10913. { Do nothing };
  10914. end;
  10915. end;
  10916. end;
  10917. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  10918. var
  10919. hp1: tai;
  10920. begin
  10921. { Detect:
  10922. andw x, %ax (0 <= x < $8000)
  10923. ...
  10924. movzwl %ax,%eax
  10925. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  10926. }
  10927. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  10928. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  10929. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  10930. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  10931. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  10932. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  10933. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  10934. begin
  10935. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  10936. taicpu(hp1).opcode := A_CWDE;
  10937. taicpu(hp1).clearop(0);
  10938. taicpu(hp1).clearop(1);
  10939. taicpu(hp1).ops := 0;
  10940. { A change was made, but not with p, so move forward 1 }
  10941. p := tai(p.Next);
  10942. Result := True;
  10943. end;
  10944. end;
  10945. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  10946. begin
  10947. Result := False;
  10948. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  10949. Exit;
  10950. { Convert:
  10951. movswl %ax,%eax -> cwtl
  10952. movslq %eax,%rax -> cdqe
  10953. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  10954. refer to the same opcode and depends only on the assembler's
  10955. current operand-size attribute. [Kit]
  10956. }
  10957. with taicpu(p) do
  10958. case opsize of
  10959. S_WL:
  10960. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  10961. begin
  10962. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  10963. opcode := A_CWDE;
  10964. clearop(0);
  10965. clearop(1);
  10966. ops := 0;
  10967. Result := True;
  10968. end;
  10969. {$ifdef x86_64}
  10970. S_LQ:
  10971. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  10972. begin
  10973. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  10974. opcode := A_CDQE;
  10975. clearop(0);
  10976. clearop(1);
  10977. ops := 0;
  10978. Result := True;
  10979. end;
  10980. {$endif x86_64}
  10981. else
  10982. ;
  10983. end;
  10984. end;
  10985. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  10986. var
  10987. hp1: tai;
  10988. begin
  10989. { Detect:
  10990. shr x, %ax (x > 0)
  10991. ...
  10992. movzwl %ax,%eax
  10993. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  10994. }
  10995. Result := False;
  10996. if MatchOpType(taicpu(p), top_const, top_reg) and
  10997. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  10998. (taicpu(p).oper[0]^.val > 0) and
  10999. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11000. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11001. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11002. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11003. begin
  11004. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11005. taicpu(hp1).opcode := A_CWDE;
  11006. taicpu(hp1).clearop(0);
  11007. taicpu(hp1).clearop(1);
  11008. taicpu(hp1).ops := 0;
  11009. { A change was made, but not with p, so move forward 1 }
  11010. p := tai(p.Next);
  11011. Result := True;
  11012. end;
  11013. end;
  11014. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11015. var
  11016. hp1, hp2: tai;
  11017. Opposite, SecondOpposite: TAsmOp;
  11018. NewCond: TAsmCond;
  11019. begin
  11020. Result := False;
  11021. { Change:
  11022. add/sub 128,(dest)
  11023. To:
  11024. sub/add -128,(dest)
  11025. This generaally takes fewer bytes to encode because -128 can be stored
  11026. in a signed byte, whereas +128 cannot.
  11027. }
  11028. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11029. begin
  11030. if taicpu(p).opcode = A_ADD then
  11031. Opposite := A_SUB
  11032. else
  11033. Opposite := A_ADD;
  11034. { Be careful if the flags are in use, because the CF flag inverts
  11035. when changing from ADD to SUB and vice versa }
  11036. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11037. GetNextInstruction(p, hp1) then
  11038. begin
  11039. TransferUsedRegs(TmpUsedRegs);
  11040. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11041. hp2 := hp1;
  11042. { Scan ahead to check if everything's safe }
  11043. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11044. begin
  11045. if (hp1.typ <> ait_instruction) then
  11046. { Probably unsafe since the flags are still in use }
  11047. Exit;
  11048. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11049. { Stop searching at an unconditional jump }
  11050. Break;
  11051. if not
  11052. (
  11053. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11054. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11055. ) and
  11056. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11057. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11058. Exit;
  11059. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11060. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11061. { Move to the next instruction }
  11062. GetNextInstruction(hp1, hp1);
  11063. end;
  11064. while Assigned(hp2) and (hp2 <> hp1) do
  11065. begin
  11066. NewCond := C_None;
  11067. case taicpu(hp2).condition of
  11068. C_A, C_NBE:
  11069. NewCond := C_BE;
  11070. C_B, C_C, C_NAE:
  11071. NewCond := C_AE;
  11072. C_AE, C_NB, C_NC:
  11073. NewCond := C_B;
  11074. C_BE, C_NA:
  11075. NewCond := C_A;
  11076. else
  11077. { No change needed };
  11078. end;
  11079. if NewCond <> C_None then
  11080. begin
  11081. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11082. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11083. taicpu(hp2).condition := NewCond;
  11084. end
  11085. else
  11086. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11087. begin
  11088. { Because of the flipping of the carry bit, to ensure
  11089. the operation remains equivalent, ADC becomes SBB
  11090. and vice versa, and the constant is not-inverted.
  11091. If multiple ADCs or SBBs appear in a row, each one
  11092. changed causes the carry bit to invert, so they all
  11093. need to be flipped }
  11094. if taicpu(hp2).opcode = A_ADC then
  11095. SecondOpposite := A_SBB
  11096. else
  11097. SecondOpposite := A_ADC;
  11098. if taicpu(hp2).oper[0]^.typ <> top_const then
  11099. { Should have broken out of this optimisation already }
  11100. InternalError(2021112901);
  11101. 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]^) + ' -> ' +
  11102. 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);
  11103. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11104. taicpu(hp2).opcode := SecondOpposite;
  11105. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11106. end;
  11107. { Move to the next instruction }
  11108. GetNextInstruction(hp2, hp2);
  11109. end;
  11110. if (hp2 <> hp1) then
  11111. InternalError(2021111501);
  11112. end;
  11113. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11114. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11115. taicpu(p).opcode := Opposite;
  11116. taicpu(p).oper[0]^.val := -128;
  11117. { No further optimisations can be made on this instruction, so move
  11118. onto the next one to save time }
  11119. p := tai(p.Next);
  11120. UpdateUsedRegs(p);
  11121. Result := True;
  11122. Exit;
  11123. end;
  11124. { Detect:
  11125. add/sub %reg2,(dest)
  11126. add/sub x, (dest)
  11127. (dest can be a register or a reference)
  11128. Swap the instructions to minimise a pipeline stall. This reverses the
  11129. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11130. optimisations could be made.
  11131. }
  11132. if (taicpu(p).oper[0]^.typ = top_reg) and
  11133. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11134. (
  11135. (
  11136. (taicpu(p).oper[1]^.typ = top_reg) and
  11137. { We can try searching further ahead if we're writing to a register }
  11138. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11139. ) or
  11140. (
  11141. (taicpu(p).oper[1]^.typ = top_ref) and
  11142. GetNextInstruction(p, hp1)
  11143. )
  11144. ) and
  11145. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11146. (taicpu(hp1).oper[0]^.typ = top_const) and
  11147. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11148. begin
  11149. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11150. TransferUsedRegs(TmpUsedRegs);
  11151. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11152. hp2 := p;
  11153. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11154. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11155. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11156. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11157. begin
  11158. asml.remove(hp1);
  11159. asml.InsertBefore(hp1, p);
  11160. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11161. Result := True;
  11162. end;
  11163. end;
  11164. end;
  11165. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11166. begin
  11167. Result:=false;
  11168. { change "cmp $0, %reg" to "test %reg, %reg" }
  11169. if MatchOpType(taicpu(p),top_const,top_reg) and
  11170. (taicpu(p).oper[0]^.val = 0) then
  11171. begin
  11172. taicpu(p).opcode := A_TEST;
  11173. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11174. Result:=true;
  11175. end;
  11176. end;
  11177. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11178. var
  11179. IsTestConstX : Boolean;
  11180. hp1,hp2 : tai;
  11181. begin
  11182. Result:=false;
  11183. { removes the line marked with (x) from the sequence
  11184. and/or/xor/add/sub/... $x, %y
  11185. test/or %y, %y | test $-1, %y (x)
  11186. j(n)z _Label
  11187. as the first instruction already adjusts the ZF
  11188. %y operand may also be a reference }
  11189. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11190. MatchOperand(taicpu(p).oper[0]^,-1);
  11191. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11192. GetLastInstruction(p, hp1) and
  11193. (tai(hp1).typ = ait_instruction) and
  11194. GetNextInstruction(p,hp2) and
  11195. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11196. case taicpu(hp1).opcode Of
  11197. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  11198. begin
  11199. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11200. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11201. { and in case of carry for A(E)/B(E)/C/NC }
  11202. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11203. ((taicpu(hp1).opcode <> A_ADD) and
  11204. (taicpu(hp1).opcode <> A_SUB))) then
  11205. begin
  11206. RemoveCurrentP(p, hp2);
  11207. Result:=true;
  11208. Exit;
  11209. end;
  11210. end;
  11211. A_SHL, A_SAL, A_SHR, A_SAR:
  11212. begin
  11213. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11214. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11215. { therefore, it's only safe to do this optimization for }
  11216. { shifts by a (nonzero) constant }
  11217. (taicpu(hp1).oper[0]^.typ = top_const) and
  11218. (taicpu(hp1).oper[0]^.val <> 0) and
  11219. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11220. { and in case of carry for A(E)/B(E)/C/NC }
  11221. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11222. begin
  11223. RemoveCurrentP(p, hp2);
  11224. Result:=true;
  11225. Exit;
  11226. end;
  11227. end;
  11228. A_DEC, A_INC, A_NEG:
  11229. begin
  11230. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11231. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11232. { and in case of carry for A(E)/B(E)/C/NC }
  11233. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11234. begin
  11235. RemoveCurrentP(p, hp2);
  11236. Result:=true;
  11237. Exit;
  11238. end;
  11239. end
  11240. else
  11241. ;
  11242. end; { case }
  11243. { change "test $-1,%reg" into "test %reg,%reg" }
  11244. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11245. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11246. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11247. if MatchInstruction(p, A_OR, []) and
  11248. { Can only match if they're both registers }
  11249. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11250. begin
  11251. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11252. taicpu(p).opcode := A_TEST;
  11253. { No need to set Result to True, as we've done all the optimisations we can }
  11254. end;
  11255. end;
  11256. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11257. var
  11258. hp1,hp3 : tai;
  11259. {$ifndef x86_64}
  11260. hp2 : taicpu;
  11261. {$endif x86_64}
  11262. begin
  11263. Result:=false;
  11264. hp3:=nil;
  11265. {$ifndef x86_64}
  11266. { don't do this on modern CPUs, this really hurts them due to
  11267. broken call/ret pairing }
  11268. if (current_settings.optimizecputype < cpu_Pentium2) and
  11269. not(cs_create_pic in current_settings.moduleswitches) and
  11270. GetNextInstruction(p, hp1) and
  11271. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11272. MatchOpType(taicpu(hp1),top_ref) and
  11273. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11274. begin
  11275. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11276. InsertLLItem(p.previous, p, hp2);
  11277. taicpu(p).opcode := A_JMP;
  11278. taicpu(p).is_jmp := true;
  11279. RemoveInstruction(hp1);
  11280. Result:=true;
  11281. end
  11282. else
  11283. {$endif x86_64}
  11284. { replace
  11285. call procname
  11286. ret
  11287. by
  11288. jmp procname
  11289. but do it only on level 4 because it destroys stack back traces
  11290. else if the subroutine is marked as no return, remove the ret
  11291. }
  11292. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11293. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11294. GetNextInstruction(p, hp1) and
  11295. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11296. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11297. SetAndTest(hp1,hp3) and
  11298. GetNextInstruction(hp1,hp1) and
  11299. MatchInstruction(hp1,A_RET,[S_NO])
  11300. )
  11301. ) and
  11302. (taicpu(hp1).ops=0) then
  11303. begin
  11304. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11305. { we might destroy stack alignment here if we do not do a call }
  11306. (target_info.stackalign<=sizeof(SizeUInt)) then
  11307. begin
  11308. taicpu(p).opcode := A_JMP;
  11309. taicpu(p).is_jmp := true;
  11310. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11311. end
  11312. else
  11313. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11314. RemoveInstruction(hp1);
  11315. if Assigned(hp3) then
  11316. begin
  11317. AsmL.Remove(hp3);
  11318. AsmL.InsertBefore(hp3,p)
  11319. end;
  11320. Result:=true;
  11321. end;
  11322. end;
  11323. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11324. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11325. begin
  11326. case OpSize of
  11327. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11328. Result := (Val <= $FF) and (Val >= -128);
  11329. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11330. Result := (Val <= $FFFF) and (Val >= -32768);
  11331. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11332. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11333. else
  11334. Result := True;
  11335. end;
  11336. end;
  11337. var
  11338. hp1, hp2 : tai;
  11339. SizeChange: Boolean;
  11340. PreMessage: string;
  11341. begin
  11342. Result := False;
  11343. if (taicpu(p).oper[0]^.typ = top_reg) and
  11344. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11345. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11346. begin
  11347. { Change (using movzbl %al,%eax as an example):
  11348. movzbl %al, %eax movzbl %al, %eax
  11349. cmpl x, %eax testl %eax,%eax
  11350. To:
  11351. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11352. movzbl %al, %eax movzbl %al, %eax
  11353. Smaller instruction and minimises pipeline stall as the CPU
  11354. doesn't have to wait for the register to get zero-extended. [Kit]
  11355. Also allow if the smaller of the two registers is being checked,
  11356. as this still removes the false dependency.
  11357. }
  11358. if
  11359. (
  11360. (
  11361. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11362. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11363. ) or (
  11364. { If MatchOperand returns True, they must both be registers }
  11365. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11366. )
  11367. ) and
  11368. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11369. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11370. begin
  11371. 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);
  11372. asml.Remove(hp1);
  11373. asml.InsertBefore(hp1, p);
  11374. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11375. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11376. begin
  11377. taicpu(hp1).opcode := A_TEST;
  11378. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11379. end;
  11380. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11381. case taicpu(p).opsize of
  11382. S_BW, S_BL:
  11383. begin
  11384. SizeChange := taicpu(hp1).opsize <> S_B;
  11385. taicpu(hp1).changeopsize(S_B);
  11386. end;
  11387. S_WL:
  11388. begin
  11389. SizeChange := taicpu(hp1).opsize <> S_W;
  11390. taicpu(hp1).changeopsize(S_W);
  11391. end
  11392. else
  11393. InternalError(2020112701);
  11394. end;
  11395. UpdateUsedRegs(tai(p.Next));
  11396. { Check if the register is used aferwards - if not, we can
  11397. remove the movzx instruction completely }
  11398. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11399. begin
  11400. { Hp1 is a better position than p for debugging purposes }
  11401. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11402. RemoveCurrentp(p, hp1);
  11403. Result := True;
  11404. end;
  11405. if SizeChange then
  11406. DebugMsg(SPeepholeOptimization + PreMessage +
  11407. 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)
  11408. else
  11409. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11410. Exit;
  11411. end;
  11412. { Change (using movzwl %ax,%eax as an example):
  11413. movzwl %ax, %eax
  11414. movb %al, (dest) (Register is smaller than read register in movz)
  11415. To:
  11416. movb %al, (dest) (Move one back to avoid a false dependency)
  11417. movzwl %ax, %eax
  11418. }
  11419. if (taicpu(hp1).opcode = A_MOV) and
  11420. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11421. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11422. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11423. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11424. begin
  11425. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11426. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11427. asml.Remove(hp1);
  11428. asml.InsertBefore(hp1, p);
  11429. if taicpu(hp1).oper[1]^.typ = top_reg then
  11430. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11431. { Check if the register is used aferwards - if not, we can
  11432. remove the movzx instruction completely }
  11433. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11434. begin
  11435. { Hp1 is a better position than p for debugging purposes }
  11436. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11437. RemoveCurrentp(p, hp1);
  11438. Result := True;
  11439. end;
  11440. Exit;
  11441. end;
  11442. end;
  11443. end;
  11444. {$ifdef x86_64}
  11445. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11446. var
  11447. PreMessage, RegName: string;
  11448. begin
  11449. { Code size reduction by J. Gareth "Kit" Moreton }
  11450. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11451. as this removes the REX prefix }
  11452. Result := False;
  11453. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11454. Exit;
  11455. if taicpu(p).oper[0]^.typ <> top_reg then
  11456. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11457. InternalError(2018011500);
  11458. case taicpu(p).opsize of
  11459. S_Q:
  11460. begin
  11461. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11462. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11463. { The actual optimization }
  11464. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11465. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11466. taicpu(p).changeopsize(S_L);
  11467. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11468. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11469. end;
  11470. else
  11471. ;
  11472. end;
  11473. end;
  11474. {$endif}
  11475. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11476. var
  11477. XReg: TRegister;
  11478. begin
  11479. Result := False;
  11480. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11481. Smaller encoding and slightly faster on some platforms (also works for
  11482. ZMM-sized registers) }
  11483. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11484. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11485. begin
  11486. XReg := taicpu(p).oper[0]^.reg;
  11487. if (taicpu(p).oper[1]^.reg = XReg) then
  11488. begin
  11489. taicpu(p).changeopsize(S_XMM);
  11490. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11491. if (cs_opt_size in current_settings.optimizerswitches) then
  11492. begin
  11493. { Change input registers to %xmm0 to reduce size. Note that
  11494. there's a risk of a false dependency doing this, so only
  11495. optimise for size here }
  11496. XReg := NR_XMM0;
  11497. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11498. end
  11499. else
  11500. begin
  11501. setsubreg(XReg, R_SUBMMX);
  11502. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11503. end;
  11504. taicpu(p).oper[0]^.reg := XReg;
  11505. taicpu(p).oper[1]^.reg := XReg;
  11506. Result := True;
  11507. end;
  11508. end;
  11509. end;
  11510. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11511. var
  11512. OperIdx: Integer;
  11513. begin
  11514. for OperIdx := 0 to p.ops - 1 do
  11515. if p.oper[OperIdx]^.typ = top_ref then
  11516. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11517. end;
  11518. end.