aoptx86.pas 693 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2037. begin
  2038. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2039. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2040. begin
  2041. { vmova* reg1,reg2
  2042. vmova* reg2,reg3
  2043. dealloc reg2
  2044. =>
  2045. vmova* reg1,reg3 }
  2046. TransferUsedRegs(TmpUsedRegs);
  2047. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2048. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2049. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2050. begin
  2051. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2052. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2053. RemoveInstruction(hp1);
  2054. result:=true;
  2055. exit;
  2056. end;
  2057. { special case:
  2058. vmova* reg1,<op>
  2059. vmova* <op>,reg1
  2060. =>
  2061. vmova* reg1,<op> }
  2062. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2063. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2064. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2065. ) then
  2066. begin
  2067. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2068. RemoveInstruction(hp1);
  2069. result:=true;
  2070. exit;
  2071. end
  2072. end
  2073. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2074. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2075. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2076. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2077. ) and
  2078. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2079. begin
  2080. { vmova* reg1,reg2
  2081. vmovs* reg2,<op>
  2082. dealloc reg2
  2083. =>
  2084. vmovs* reg1,reg3 }
  2085. TransferUsedRegs(TmpUsedRegs);
  2086. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2087. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2088. begin
  2089. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2090. taicpu(p).opcode:=taicpu(hp1).opcode;
  2091. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2092. RemoveInstruction(hp1);
  2093. result:=true;
  2094. exit;
  2095. end
  2096. end;
  2097. end;
  2098. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2099. begin
  2100. if MatchInstruction(hp1,[A_VFMADDPD,
  2101. A_VFMADD132PD,
  2102. A_VFMADD132PS,
  2103. A_VFMADD132SD,
  2104. A_VFMADD132SS,
  2105. A_VFMADD213PD,
  2106. A_VFMADD213PS,
  2107. A_VFMADD213SD,
  2108. A_VFMADD213SS,
  2109. A_VFMADD231PD,
  2110. A_VFMADD231PS,
  2111. A_VFMADD231SD,
  2112. A_VFMADD231SS,
  2113. A_VFMADDSUB132PD,
  2114. A_VFMADDSUB132PS,
  2115. A_VFMADDSUB213PD,
  2116. A_VFMADDSUB213PS,
  2117. A_VFMADDSUB231PD,
  2118. A_VFMADDSUB231PS,
  2119. A_VFMSUB132PD,
  2120. A_VFMSUB132PS,
  2121. A_VFMSUB132SD,
  2122. A_VFMSUB132SS,
  2123. A_VFMSUB213PD,
  2124. A_VFMSUB213PS,
  2125. A_VFMSUB213SD,
  2126. A_VFMSUB213SS,
  2127. A_VFMSUB231PD,
  2128. A_VFMSUB231PS,
  2129. A_VFMSUB231SD,
  2130. A_VFMSUB231SS,
  2131. A_VFMSUBADD132PD,
  2132. A_VFMSUBADD132PS,
  2133. A_VFMSUBADD213PD,
  2134. A_VFMSUBADD213PS,
  2135. A_VFMSUBADD231PD,
  2136. A_VFMSUBADD231PS,
  2137. A_VFNMADD132PD,
  2138. A_VFNMADD132PS,
  2139. A_VFNMADD132SD,
  2140. A_VFNMADD132SS,
  2141. A_VFNMADD213PD,
  2142. A_VFNMADD213PS,
  2143. A_VFNMADD213SD,
  2144. A_VFNMADD213SS,
  2145. A_VFNMADD231PD,
  2146. A_VFNMADD231PS,
  2147. A_VFNMADD231SD,
  2148. A_VFNMADD231SS,
  2149. A_VFNMSUB132PD,
  2150. A_VFNMSUB132PS,
  2151. A_VFNMSUB132SD,
  2152. A_VFNMSUB132SS,
  2153. A_VFNMSUB213PD,
  2154. A_VFNMSUB213PS,
  2155. A_VFNMSUB213SD,
  2156. A_VFNMSUB213SS,
  2157. A_VFNMSUB231PD,
  2158. A_VFNMSUB231PS,
  2159. A_VFNMSUB231SD,
  2160. A_VFNMSUB231SS],[S_NO]) and
  2161. { we mix single and double opperations here because we assume that the compiler
  2162. generates vmovapd only after double operations and vmovaps only after single operations }
  2163. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2164. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2165. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2166. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2170. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2171. begin
  2172. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2173. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2174. RemoveCurrentP(p)
  2175. else
  2176. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2177. RemoveInstruction(hp2);
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_MOVAPS) and
  2182. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2183. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2184. ((taicpu(p).opcode=A_MOVAPD) and
  2185. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2186. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2187. ) and
  2188. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2189. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2190. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2191. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2192. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2193. { change
  2194. movapX reg,reg2
  2195. addsX/subsX/... reg3, reg2
  2196. movapX reg2,reg
  2197. to
  2198. addsX/subsX/... reg3,reg
  2199. }
  2200. begin
  2201. TransferUsedRegs(TmpUsedRegs);
  2202. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2203. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2204. begin
  2205. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2206. debug_op2str(taicpu(p).opcode)+' '+
  2207. debug_op2str(taicpu(hp1).opcode)+' '+
  2208. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2209. { we cannot eliminate the first move if
  2210. the operations uses the same register for source and dest }
  2211. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2212. { Remember that hp1 is not necessarily the immediate
  2213. next instruction }
  2214. RemoveCurrentP(p);
  2215. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2216. RemoveInstruction(hp2);
  2217. result:=true;
  2218. end;
  2219. end
  2220. else if (hp1.typ = ait_instruction) and
  2221. (((taicpu(p).opcode=A_VMOVAPD) and
  2222. (taicpu(hp1).opcode=A_VCOMISD)) or
  2223. ((taicpu(p).opcode=A_VMOVAPS) and
  2224. ((taicpu(hp1).opcode=A_VCOMISS))
  2225. )
  2226. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { change
  2228. movapX reg,reg1
  2229. vcomisX reg1,reg1
  2230. to
  2231. vcomisX reg,reg
  2232. }
  2233. begin
  2234. TransferUsedRegs(TmpUsedRegs);
  2235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2236. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2237. begin
  2238. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2239. debug_op2str(taicpu(p).opcode)+' '+
  2240. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2241. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2242. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2243. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2244. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2245. RemoveCurrentP(p);
  2246. result:=true;
  2247. exit;
  2248. end;
  2249. end
  2250. end;
  2251. end;
  2252. end;
  2253. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2254. var
  2255. hp1 : tai;
  2256. begin
  2257. result:=false;
  2258. { replace
  2259. V<Op>X %mreg1,%mreg2,%mreg3
  2260. VMovX %mreg3,%mreg4
  2261. dealloc %mreg3
  2262. by
  2263. V<Op>X %mreg1,%mreg2,%mreg4
  2264. ?
  2265. }
  2266. if GetNextInstruction(p,hp1) and
  2267. { we mix single and double operations here because we assume that the compiler
  2268. generates vmovapd only after double operations and vmovaps only after single operations }
  2269. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2270. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2271. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2272. begin
  2273. TransferUsedRegs(TmpUsedRegs);
  2274. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2275. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2276. begin
  2277. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2278. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2279. RemoveInstruction(hp1);
  2280. result:=true;
  2281. end;
  2282. end;
  2283. end;
  2284. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2285. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2286. begin
  2287. Result := False;
  2288. { For safety reasons, only check for exact register matches }
  2289. { Check base register }
  2290. if (ref.base = AOldReg) then
  2291. begin
  2292. ref.base := ANewReg;
  2293. Result := True;
  2294. end;
  2295. { Check index register }
  2296. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2297. begin
  2298. ref.index := ANewReg;
  2299. Result := True;
  2300. end;
  2301. end;
  2302. { Replaces all references to AOldReg in an operand to ANewReg }
  2303. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2304. var
  2305. OldSupReg, NewSupReg: TSuperRegister;
  2306. OldSubReg, NewSubReg: TSubRegister;
  2307. OldRegType: TRegisterType;
  2308. ThisOper: POper;
  2309. begin
  2310. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2311. Result := False;
  2312. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2313. InternalError(2020011801);
  2314. OldSupReg := getsupreg(AOldReg);
  2315. OldSubReg := getsubreg(AOldReg);
  2316. OldRegType := getregtype(AOldReg);
  2317. NewSupReg := getsupreg(ANewReg);
  2318. NewSubReg := getsubreg(ANewReg);
  2319. if OldRegType <> getregtype(ANewReg) then
  2320. InternalError(2020011802);
  2321. if OldSubReg <> NewSubReg then
  2322. InternalError(2020011803);
  2323. case ThisOper^.typ of
  2324. top_reg:
  2325. if (
  2326. (ThisOper^.reg = AOldReg) or
  2327. (
  2328. (OldRegType = R_INTREGISTER) and
  2329. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2330. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2331. (
  2332. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2333. {$ifndef x86_64}
  2334. and (
  2335. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2336. don't have an 8-bit representation }
  2337. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2338. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2339. )
  2340. {$endif x86_64}
  2341. )
  2342. )
  2343. ) then
  2344. begin
  2345. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2346. Result := True;
  2347. end;
  2348. top_ref:
  2349. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2350. Result := True;
  2351. else
  2352. ;
  2353. end;
  2354. end;
  2355. { Replaces all references to AOldReg in an instruction to ANewReg }
  2356. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2357. const
  2358. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2359. var
  2360. OperIdx: Integer;
  2361. begin
  2362. Result := False;
  2363. for OperIdx := 0 to p.ops - 1 do
  2364. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2365. begin
  2366. { The shift and rotate instructions can only use CL }
  2367. if not (
  2368. (OperIdx = 0) and
  2369. { This second condition just helps to avoid unnecessarily
  2370. calling MatchInstruction for 10 different opcodes }
  2371. (p.oper[0]^.reg = NR_CL) and
  2372. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2373. ) then
  2374. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2375. end
  2376. else if p.oper[OperIdx]^.typ = top_ref then
  2377. { It's okay to replace registers in references that get written to }
  2378. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2379. end;
  2380. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2381. begin
  2382. Result :=
  2383. (ref^.index = NR_NO) and
  2384. (
  2385. {$ifdef x86_64}
  2386. (
  2387. (ref^.base = NR_RIP) and
  2388. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2389. ) or
  2390. {$endif x86_64}
  2391. (ref^.refaddr = addr_full) or
  2392. (ref^.base = NR_STACK_POINTER_REG) or
  2393. (ref^.base = current_procinfo.framepointer)
  2394. );
  2395. end;
  2396. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2397. var
  2398. l: asizeint;
  2399. begin
  2400. Result := False;
  2401. { Should have been checked previously }
  2402. if p.opcode <> A_LEA then
  2403. InternalError(2020072501);
  2404. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2405. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2406. not(cs_opt_size in current_settings.optimizerswitches) then
  2407. exit;
  2408. with p.oper[0]^.ref^ do
  2409. begin
  2410. if (base <> p.oper[1]^.reg) or
  2411. (index <> NR_NO) or
  2412. assigned(symbol) then
  2413. exit;
  2414. l:=offset;
  2415. if (l=1) and UseIncDec then
  2416. begin
  2417. p.opcode:=A_INC;
  2418. p.loadreg(0,p.oper[1]^.reg);
  2419. p.ops:=1;
  2420. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2421. end
  2422. else if (l=-1) and UseIncDec then
  2423. begin
  2424. p.opcode:=A_DEC;
  2425. p.loadreg(0,p.oper[1]^.reg);
  2426. p.ops:=1;
  2427. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2428. end
  2429. else
  2430. begin
  2431. if (l<0) and (l<>-2147483648) then
  2432. begin
  2433. p.opcode:=A_SUB;
  2434. p.loadConst(0,-l);
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2436. end
  2437. else
  2438. begin
  2439. p.opcode:=A_ADD;
  2440. p.loadConst(0,l);
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2442. end;
  2443. end;
  2444. end;
  2445. Result := True;
  2446. end;
  2447. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2448. var
  2449. CurrentReg, ReplaceReg: TRegister;
  2450. begin
  2451. Result := False;
  2452. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2453. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2454. case hp.opcode of
  2455. A_FSTSW, A_FNSTSW,
  2456. A_IN, A_INS, A_OUT, A_OUTS,
  2457. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2458. { These routines have explicit operands, but they are restricted in
  2459. what they can be (e.g. IN and OUT can only read from AL, AX or
  2460. EAX. }
  2461. Exit;
  2462. A_IMUL:
  2463. begin
  2464. { The 1-operand version writes to implicit registers
  2465. The 2-operand version reads from the first operator, and reads
  2466. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2467. the 3-operand version reads from a register that it doesn't write to
  2468. }
  2469. case hp.ops of
  2470. 1:
  2471. if (
  2472. (
  2473. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2474. ) or
  2475. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2476. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2477. begin
  2478. Result := True;
  2479. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2480. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2481. end;
  2482. 2:
  2483. { Only modify the first parameter }
  2484. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2485. begin
  2486. Result := True;
  2487. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2488. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2489. end;
  2490. 3:
  2491. { Only modify the second parameter }
  2492. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2493. begin
  2494. Result := True;
  2495. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2496. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2497. end;
  2498. else
  2499. InternalError(2020012901);
  2500. end;
  2501. end;
  2502. else
  2503. if (hp.ops > 0) and
  2504. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. end;
  2511. end;
  2512. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2513. var
  2514. hp2: tai;
  2515. p_SourceReg, p_TargetReg: TRegister;
  2516. begin
  2517. Result := False;
  2518. { Backward optimisation. If we have:
  2519. func. %reg1,%reg2
  2520. mov %reg2,%reg3
  2521. (dealloc %reg2)
  2522. Change to:
  2523. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2524. Perform similar optimisations with 1, 3 and 4-operand instructions
  2525. that only have one output.
  2526. }
  2527. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2528. begin
  2529. p_SourceReg := taicpu(p).oper[0]^.reg;
  2530. p_TargetReg := taicpu(p).oper[1]^.reg;
  2531. TransferUsedRegs(TmpUsedRegs);
  2532. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2533. GetLastInstruction(p, hp2) and
  2534. (hp2.typ = ait_instruction) and
  2535. { Have to make sure it's an instruction that only reads from
  2536. the first operands and only writes (not reads or modifies) to
  2537. the last one; in essence, a pure function such as BSR, POPCNT
  2538. or ANDN }
  2539. (
  2540. (
  2541. (taicpu(hp2).ops = 1) and
  2542. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2543. ) or
  2544. (
  2545. (taicpu(hp2).ops = 2) and
  2546. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2547. ) or
  2548. (
  2549. (taicpu(hp2).ops = 3) and
  2550. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2551. ) or
  2552. (
  2553. (taicpu(hp2).ops = 4) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2555. )
  2556. ) and
  2557. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2558. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2559. begin
  2560. case taicpu(hp2).opcode of
  2561. A_FSTSW, A_FNSTSW,
  2562. A_IN, A_INS, A_OUT, A_OUTS,
  2563. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2564. { These routines have explicit operands, but they are restricted in
  2565. what they can be (e.g. IN and OUT can only read from AL, AX or
  2566. EAX. }
  2567. ;
  2568. else
  2569. begin
  2570. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2571. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2572. if not RegInInstruction(p_TargetReg, hp2) then
  2573. begin
  2574. { Since we're allocating from an earlier point, we
  2575. need to remove the register from the tracking }
  2576. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2577. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2578. end;
  2579. RemoveCurrentp(p, hp1);
  2580. { If the Func was another MOV instruction, we might get
  2581. "mov %reg,%reg" that doesn't get removed in Pass 2
  2582. otherwise, so deal with it here (also do something
  2583. similar with lea (%reg),%reg}
  2584. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2585. begin
  2586. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2587. if p = hp2 then
  2588. RemoveCurrentp(p)
  2589. else
  2590. RemoveInstruction(hp2);
  2591. end;
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. end;
  2596. end;
  2597. end;
  2598. end;
  2599. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2600. var
  2601. hp1, hp2, hp3: tai;
  2602. DoOptimisation, TempBool: Boolean;
  2603. {$ifdef x86_64}
  2604. NewConst: TCGInt;
  2605. {$endif x86_64}
  2606. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2607. begin
  2608. if taicpu(hp1).opcode = signed_movop then
  2609. begin
  2610. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2611. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2612. end
  2613. else
  2614. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2615. end;
  2616. function TryConstMerge(var p1, p2: tai): Boolean;
  2617. var
  2618. ThisRef: TReference;
  2619. begin
  2620. Result := False;
  2621. ThisRef := taicpu(p2).oper[1]^.ref^;
  2622. { Only permit writes to the stack, since we can guarantee alignment with that }
  2623. if (ThisRef.index = NR_NO) and
  2624. (
  2625. (ThisRef.base = NR_STACK_POINTER_REG) or
  2626. (ThisRef.base = current_procinfo.framepointer)
  2627. ) then
  2628. begin
  2629. case taicpu(p).opsize of
  2630. S_B:
  2631. begin
  2632. { Word writes must be on a 2-byte boundary }
  2633. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2634. begin
  2635. { Reduce offset of second reference to see if it is sequential with the first }
  2636. Dec(ThisRef.offset, 1);
  2637. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2638. begin
  2639. { Make sure the constants aren't represented as a
  2640. negative number, as these won't merge properly }
  2641. taicpu(p1).opsize := S_W;
  2642. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2643. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2644. RemoveInstruction(p2);
  2645. Result := True;
  2646. end;
  2647. end;
  2648. end;
  2649. S_W:
  2650. begin
  2651. { Longword writes must be on a 4-byte boundary }
  2652. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2653. begin
  2654. { Reduce offset of second reference to see if it is sequential with the first }
  2655. Dec(ThisRef.offset, 2);
  2656. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2657. begin
  2658. { Make sure the constants aren't represented as a
  2659. negative number, as these won't merge properly }
  2660. taicpu(p1).opsize := S_L;
  2661. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2662. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2663. RemoveInstruction(p2);
  2664. Result := True;
  2665. end;
  2666. end;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_L:
  2670. begin
  2671. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2672. see if the constants can be encoded this way. }
  2673. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2674. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2675. { Quadword writes must be on an 8-byte boundary }
  2676. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2677. begin
  2678. { Reduce offset of second reference to see if it is sequential with the first }
  2679. Dec(ThisRef.offset, 4);
  2680. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2681. begin
  2682. { Make sure the constants aren't represented as a
  2683. negative number, as these won't merge properly }
  2684. taicpu(p1).opsize := S_Q;
  2685. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2686. taicpu(p1).oper[0]^.val := NewConst;
  2687. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2688. RemoveInstruction(p2);
  2689. Result := True;
  2690. end;
  2691. end;
  2692. end;
  2693. {$endif x86_64}
  2694. else
  2695. ;
  2696. end;
  2697. end;
  2698. end;
  2699. var
  2700. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2701. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2702. NewSize: topsize; NewOffset: asizeint;
  2703. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2704. SourceRef, TargetRef: TReference;
  2705. MovAligned, MovUnaligned: TAsmOp;
  2706. ThisRef: TReference;
  2707. JumpTracking: TLinkedList;
  2708. begin
  2709. Result:=false;
  2710. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2711. { remove mov reg1,reg1? }
  2712. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2713. then
  2714. begin
  2715. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2716. { take care of the register (de)allocs following p }
  2717. RemoveCurrentP(p, hp1);
  2718. Result:=true;
  2719. exit;
  2720. end;
  2721. { All the next optimisations require a next instruction }
  2722. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2723. Exit;
  2724. { Prevent compiler warnings }
  2725. p_TargetReg := NR_NO;
  2726. if taicpu(p).oper[1]^.typ = top_reg then
  2727. begin
  2728. { Saves on a large number of dereferences }
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. { Look for:
  2731. mov %reg1,%reg2
  2732. ??? %reg2,r/m
  2733. Change to:
  2734. mov %reg1,%reg2
  2735. ??? %reg1,r/m
  2736. }
  2737. if taicpu(p).oper[0]^.typ = top_reg then
  2738. begin
  2739. if RegReadByInstruction(p_TargetReg, hp1) and
  2740. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2741. begin
  2742. { A change has occurred, just not in p }
  2743. Result := True;
  2744. TransferUsedRegs(TmpUsedRegs);
  2745. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2746. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2747. { Just in case something didn't get modified (e.g. an
  2748. implicit register) }
  2749. not RegReadByInstruction(p_TargetReg, hp1) then
  2750. begin
  2751. { We can remove the original MOV }
  2752. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2753. RemoveCurrentp(p, hp1);
  2754. { UsedRegs got updated by RemoveCurrentp }
  2755. Result := True;
  2756. Exit;
  2757. end;
  2758. { If we know a MOV instruction has become a null operation, we might as well
  2759. get rid of it now to save time. }
  2760. if (taicpu(hp1).opcode = A_MOV) and
  2761. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2762. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2763. { Just being a register is enough to confirm it's a null operation }
  2764. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2765. begin
  2766. Result := True;
  2767. { Speed-up to reduce a pipeline stall... if we had something like...
  2768. movl %eax,%edx
  2769. movw %dx,%ax
  2770. ... the second instruction would change to movw %ax,%ax, but
  2771. given that it is now %ax that's active rather than %eax,
  2772. penalties might occur due to a partial register write, so instead,
  2773. change it to a MOVZX instruction when optimising for speed.
  2774. }
  2775. if not (cs_opt_size in current_settings.optimizerswitches) and
  2776. IsMOVZXAcceptable and
  2777. (taicpu(hp1).opsize < taicpu(p).opsize)
  2778. {$ifdef x86_64}
  2779. { operations already implicitly set the upper 64 bits to zero }
  2780. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2781. {$endif x86_64}
  2782. then
  2783. begin
  2784. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2785. case taicpu(p).opsize of
  2786. S_W:
  2787. if taicpu(hp1).opsize = S_B then
  2788. taicpu(hp1).opsize := S_BL
  2789. else
  2790. InternalError(2020012911);
  2791. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2792. case taicpu(hp1).opsize of
  2793. S_B:
  2794. taicpu(hp1).opsize := S_BL;
  2795. S_W:
  2796. taicpu(hp1).opsize := S_WL;
  2797. else
  2798. InternalError(2020012912);
  2799. end;
  2800. else
  2801. InternalError(2020012910);
  2802. end;
  2803. taicpu(hp1).opcode := A_MOVZX;
  2804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2805. end
  2806. else
  2807. begin
  2808. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2809. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2810. RemoveInstruction(hp1);
  2811. { The instruction after what was hp1 is now the immediate next instruction,
  2812. so we can continue to make optimisations if it's present }
  2813. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2814. Exit;
  2815. hp1 := hp2;
  2816. end;
  2817. end;
  2818. end;
  2819. end;
  2820. end;
  2821. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2822. overwrites the original destination register. e.g.
  2823. movl ###,%reg2d
  2824. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2825. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2826. }
  2827. if (taicpu(p).oper[1]^.typ = top_reg) and
  2828. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2829. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2830. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2831. begin
  2832. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2833. begin
  2834. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2835. case taicpu(p).oper[0]^.typ of
  2836. top_const:
  2837. { We have something like:
  2838. movb $x, %regb
  2839. movzbl %regb,%regd
  2840. Change to:
  2841. movl $x, %regd
  2842. }
  2843. begin
  2844. case taicpu(hp1).opsize of
  2845. S_BW:
  2846. begin
  2847. convert_mov_value(A_MOVSX, $FF);
  2848. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2849. taicpu(p).opsize := S_W;
  2850. end;
  2851. S_BL:
  2852. begin
  2853. convert_mov_value(A_MOVSX, $FF);
  2854. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2855. taicpu(p).opsize := S_L;
  2856. end;
  2857. S_WL:
  2858. begin
  2859. convert_mov_value(A_MOVSX, $FFFF);
  2860. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2861. taicpu(p).opsize := S_L;
  2862. end;
  2863. {$ifdef x86_64}
  2864. S_BQ:
  2865. begin
  2866. convert_mov_value(A_MOVSX, $FF);
  2867. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2868. taicpu(p).opsize := S_Q;
  2869. end;
  2870. S_WQ:
  2871. begin
  2872. convert_mov_value(A_MOVSX, $FFFF);
  2873. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2874. taicpu(p).opsize := S_Q;
  2875. end;
  2876. S_LQ:
  2877. begin
  2878. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2879. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2880. taicpu(p).opsize := S_Q;
  2881. end;
  2882. {$endif x86_64}
  2883. else
  2884. { If hp1 was a MOV instruction, it should have been
  2885. optimised already }
  2886. InternalError(2020021001);
  2887. end;
  2888. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2889. RemoveInstruction(hp1);
  2890. Result := True;
  2891. Exit;
  2892. end;
  2893. top_ref:
  2894. begin
  2895. { We have something like:
  2896. movb mem, %regb
  2897. movzbl %regb,%regd
  2898. Change to:
  2899. movzbl mem, %regd
  2900. }
  2901. ThisRef := taicpu(p).oper[0]^.ref^;
  2902. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2903. begin
  2904. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2905. taicpu(hp1).loadref(0, ThisRef);
  2906. { Make sure any registers in the references are properly tracked }
  2907. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2908. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2909. if (ThisRef.index <> NR_NO) then
  2910. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2911. RemoveCurrentP(p, hp1);
  2912. Result := True;
  2913. Exit;
  2914. end;
  2915. end;
  2916. else
  2917. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2918. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2919. Exit;
  2920. end;
  2921. end
  2922. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2923. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2924. optimised }
  2925. else
  2926. begin
  2927. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2928. RemoveCurrentP(p, hp1);
  2929. Result := True;
  2930. Exit;
  2931. end;
  2932. end;
  2933. if (taicpu(hp1).opcode = A_AND) and
  2934. (taicpu(p).oper[1]^.typ = top_reg) and
  2935. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2936. begin
  2937. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2938. begin
  2939. case taicpu(p).opsize of
  2940. S_L:
  2941. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2942. begin
  2943. { Optimize out:
  2944. mov x, %reg
  2945. and ffffffffh, %reg
  2946. }
  2947. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2948. RemoveInstruction(hp1);
  2949. Result:=true;
  2950. exit;
  2951. end;
  2952. S_Q: { TODO: Confirm if this is even possible }
  2953. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2954. begin
  2955. { Optimize out:
  2956. mov x, %reg
  2957. and ffffffffffffffffh, %reg
  2958. }
  2959. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2960. RemoveInstruction(hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. else
  2965. ;
  2966. end;
  2967. if (
  2968. (taicpu(p).oper[0]^.typ=top_reg) or
  2969. (
  2970. (taicpu(p).oper[0]^.typ=top_ref) and
  2971. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2972. )
  2973. ) and
  2974. GetNextInstruction(hp1,hp2) and
  2975. MatchInstruction(hp2,A_TEST,[]) and
  2976. (
  2977. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2978. (
  2979. { If the register being tested is smaller than the one
  2980. that received a bitwise AND, permit it if the constant
  2981. fits into the smaller size }
  2982. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2983. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2984. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2985. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2986. (
  2987. (
  2988. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2989. (taicpu(hp1).oper[0]^.val <= $FF)
  2990. ) or
  2991. (
  2992. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2993. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2994. {$ifdef x86_64}
  2995. ) or
  2996. (
  2997. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2998. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2999. {$endif x86_64}
  3000. )
  3001. )
  3002. )
  3003. ) and
  3004. (
  3005. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3006. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3007. ) and
  3008. GetNextInstruction(hp2,hp3) and
  3009. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3010. (taicpu(hp3).condition in [C_E,C_NE]) then
  3011. begin
  3012. TransferUsedRegs(TmpUsedRegs);
  3013. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3015. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3016. begin
  3017. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3018. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3019. taicpu(hp1).opcode:=A_TEST;
  3020. { Shrink the TEST instruction down to the smallest possible size }
  3021. case taicpu(hp1).oper[0]^.val of
  3022. 0..255:
  3023. if (taicpu(hp1).opsize <> S_B)
  3024. {$ifndef x86_64}
  3025. and (
  3026. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3027. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3028. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3029. )
  3030. {$endif x86_64}
  3031. then
  3032. begin
  3033. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3034. { Only print debug message if the TEST instruction
  3035. is a different size before and after }
  3036. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3037. taicpu(hp1).opsize := S_B;
  3038. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3039. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3040. end;
  3041. 256..65535:
  3042. if (taicpu(hp1).opsize <> S_W) then
  3043. begin
  3044. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3045. { Only print debug message if the TEST instruction
  3046. is a different size before and after }
  3047. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3048. taicpu(hp1).opsize := S_W;
  3049. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3050. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3051. end;
  3052. {$ifdef x86_64}
  3053. 65536..$7FFFFFFF:
  3054. if (taicpu(hp1).opsize <> S_L) then
  3055. begin
  3056. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3057. { Only print debug message if the TEST instruction
  3058. is a different size before and after }
  3059. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3060. taicpu(hp1).opsize := S_L;
  3061. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3062. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3063. end;
  3064. {$endif x86_64}
  3065. else
  3066. ;
  3067. end;
  3068. RemoveInstruction(hp2);
  3069. RemoveCurrentP(p, hp1);
  3070. Result:=true;
  3071. exit;
  3072. end;
  3073. end;
  3074. end
  3075. else if IsMOVZXAcceptable and
  3076. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3077. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3078. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3079. then
  3080. begin
  3081. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3082. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3083. case taicpu(p).opsize of
  3084. S_B:
  3085. if (taicpu(hp1).oper[0]^.val = $ff) then
  3086. begin
  3087. { Convert:
  3088. movb x, %regl movb x, %regl
  3089. andw ffh, %regw andl ffh, %regd
  3090. To:
  3091. movzbw x, %regd movzbl x, %regd
  3092. (Identical registers, just different sizes)
  3093. }
  3094. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3095. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3096. case taicpu(hp1).opsize of
  3097. S_W: NewSize := S_BW;
  3098. S_L: NewSize := S_BL;
  3099. {$ifdef x86_64}
  3100. S_Q: NewSize := S_BQ;
  3101. {$endif x86_64}
  3102. else
  3103. InternalError(2018011510);
  3104. end;
  3105. end
  3106. else
  3107. NewSize := S_NO;
  3108. S_W:
  3109. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3110. begin
  3111. { Convert:
  3112. movw x, %regw
  3113. andl ffffh, %regd
  3114. To:
  3115. movzwl x, %regd
  3116. (Identical registers, just different sizes)
  3117. }
  3118. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3119. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3120. case taicpu(hp1).opsize of
  3121. S_L: NewSize := S_WL;
  3122. {$ifdef x86_64}
  3123. S_Q: NewSize := S_WQ;
  3124. {$endif x86_64}
  3125. else
  3126. InternalError(2018011511);
  3127. end;
  3128. end
  3129. else
  3130. NewSize := S_NO;
  3131. else
  3132. NewSize := S_NO;
  3133. end;
  3134. if NewSize <> S_NO then
  3135. begin
  3136. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3137. { The actual optimization }
  3138. taicpu(p).opcode := A_MOVZX;
  3139. taicpu(p).changeopsize(NewSize);
  3140. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3141. { Safeguard if "and" is followed by a conditional command }
  3142. TransferUsedRegs(TmpUsedRegs);
  3143. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3144. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3145. begin
  3146. { At this point, the "and" command is effectively equivalent to
  3147. "test %reg,%reg". This will be handled separately by the
  3148. Peephole Optimizer. [Kit] }
  3149. DebugMsg(SPeepholeOptimization + PreMessage +
  3150. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3151. end
  3152. else
  3153. begin
  3154. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3155. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3156. RemoveInstruction(hp1);
  3157. end;
  3158. Result := True;
  3159. Exit;
  3160. end;
  3161. end;
  3162. end;
  3163. if (taicpu(hp1).opcode = A_OR) and
  3164. (taicpu(p).oper[1]^.typ = top_reg) and
  3165. MatchOperand(taicpu(p).oper[0]^, 0) and
  3166. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3167. begin
  3168. { mov 0, %reg
  3169. or ###,%reg
  3170. Change to (only if the flags are not used):
  3171. mov ###,%reg
  3172. }
  3173. TransferUsedRegs(TmpUsedRegs);
  3174. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3175. DoOptimisation := True;
  3176. { Even if the flags are used, we might be able to do the optimisation
  3177. if the conditions are predictable }
  3178. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3179. begin
  3180. { Only perform if ### = %reg (the same register) or equal to 0,
  3181. so %reg is guaranteed to still have a value of zero }
  3182. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3183. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3184. begin
  3185. hp2 := hp1;
  3186. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3187. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3188. GetNextInstruction(hp2, hp3) do
  3189. begin
  3190. { Don't continue modifying if the flags state is getting changed }
  3191. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3192. Break;
  3193. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3194. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3195. begin
  3196. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3197. begin
  3198. { Condition is always true }
  3199. case taicpu(hp3).opcode of
  3200. A_Jcc:
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3203. { Check for jump shortcuts before we destroy the condition }
  3204. DoJumpOptimizations(hp3, TempBool);
  3205. MakeUnconditional(taicpu(hp3));
  3206. Result := True;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3211. taicpu(hp3).opcode := A_MOV;
  3212. taicpu(hp3).condition := C_None;
  3213. Result := True;
  3214. end;
  3215. A_SETcc:
  3216. begin
  3217. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3218. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3219. taicpu(hp3).opcode := A_MOV;
  3220. taicpu(hp3).ops := 2;
  3221. taicpu(hp3).condition := C_None;
  3222. taicpu(hp3).opsize := S_B;
  3223. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3224. taicpu(hp3).loadconst(0, 1);
  3225. Result := True;
  3226. end;
  3227. else
  3228. InternalError(2021090701);
  3229. end;
  3230. end
  3231. 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
  3232. begin
  3233. { Condition is always false }
  3234. case taicpu(hp3).opcode of
  3235. A_Jcc:
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3238. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3239. RemoveInstruction(hp3);
  3240. Result := True;
  3241. { Since hp3 was deleted, hp2 must not be updated }
  3242. Continue;
  3243. end;
  3244. A_CMOVcc:
  3245. begin
  3246. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3247. RemoveInstruction(hp3);
  3248. Result := True;
  3249. { Since hp3 was deleted, hp2 must not be updated }
  3250. Continue;
  3251. end;
  3252. A_SETcc:
  3253. begin
  3254. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3256. taicpu(hp3).opcode := A_MOV;
  3257. taicpu(hp3).ops := 2;
  3258. taicpu(hp3).condition := C_None;
  3259. taicpu(hp3).opsize := S_B;
  3260. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3261. taicpu(hp3).loadconst(0, 0);
  3262. Result := True;
  3263. end;
  3264. else
  3265. InternalError(2021090702);
  3266. end;
  3267. end
  3268. else
  3269. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3270. DoOptimisation := False;
  3271. end;
  3272. hp2 := hp3;
  3273. end;
  3274. { Flags are still in use - don't optimise }
  3275. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3276. DoOptimisation := False;
  3277. end
  3278. else
  3279. DoOptimisation := False;
  3280. end;
  3281. if DoOptimisation then
  3282. begin
  3283. {$ifdef x86_64}
  3284. { OR only supports 32-bit sign-extended constants for 64-bit
  3285. instructions, so compensate for this if the constant is
  3286. encoded as a value greater than or equal to 2^31 }
  3287. if (taicpu(hp1).opsize = S_Q) and
  3288. (taicpu(hp1).oper[0]^.typ = top_const) and
  3289. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3290. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3291. {$endif x86_64}
  3292. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3293. taicpu(hp1).opcode := A_MOV;
  3294. RemoveCurrentP(p, hp1);
  3295. Result := True;
  3296. Exit;
  3297. end;
  3298. end;
  3299. { Next instruction is also a MOV ? }
  3300. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3301. begin
  3302. if MatchOpType(taicpu(p), top_const, top_ref) and
  3303. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3304. TryConstMerge(p, hp1) then
  3305. begin
  3306. Result := True;
  3307. { In case we have four byte writes in a row, check for 2 more
  3308. right now so we don't have to wait for another iteration of
  3309. pass 1
  3310. }
  3311. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3312. case taicpu(p).opsize of
  3313. S_W:
  3314. begin
  3315. if GetNextInstruction(p, hp1) and
  3316. MatchInstruction(hp1, A_MOV, [S_B]) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2, A_MOV, [S_B]) and
  3320. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3321. { Try to merge the two bytes }
  3322. TryConstMerge(hp1, hp2) then
  3323. { Now try to merge the two words (hp2 will get deleted) }
  3324. TryConstMerge(p, hp1);
  3325. end;
  3326. S_L:
  3327. begin
  3328. { Though this only really benefits x86_64 and not i386, it
  3329. gets a potential optimisation done faster and hence
  3330. reduces the number of times OptPass1MOV is entered }
  3331. if GetNextInstruction(p, hp1) and
  3332. MatchInstruction(hp1, A_MOV, [S_W]) and
  3333. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3334. GetNextInstruction(hp1, hp2) and
  3335. MatchInstruction(hp2, A_MOV, [S_W]) and
  3336. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3337. { Try to merge the two words }
  3338. TryConstMerge(hp1, hp2) then
  3339. { This will always fail on i386, so don't bother
  3340. calling it unless we're doing x86_64 }
  3341. {$ifdef x86_64}
  3342. { Now try to merge the two longwords (hp2 will get deleted) }
  3343. TryConstMerge(p, hp1)
  3344. {$endif x86_64}
  3345. ;
  3346. end;
  3347. else
  3348. ;
  3349. end;
  3350. Exit;
  3351. end;
  3352. if (taicpu(p).oper[1]^.typ = top_reg) and
  3353. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3354. begin
  3355. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3356. TransferUsedRegs(TmpUsedRegs);
  3357. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3358. { we have
  3359. mov x, %treg
  3360. mov %treg, y
  3361. }
  3362. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3363. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3364. { we've got
  3365. mov x, %treg
  3366. mov %treg, y
  3367. with %treg is not used after }
  3368. case taicpu(p).oper[0]^.typ Of
  3369. { top_reg is covered by DeepMOVOpt }
  3370. top_const:
  3371. begin
  3372. { change
  3373. mov const, %treg
  3374. mov %treg, y
  3375. to
  3376. mov const, y
  3377. }
  3378. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3379. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3380. begin
  3381. if taicpu(hp1).oper[1]^.typ=top_reg then
  3382. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3383. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3385. RemoveInstruction(hp1);
  3386. Result:=true;
  3387. Exit;
  3388. end;
  3389. end;
  3390. top_ref:
  3391. case taicpu(hp1).oper[1]^.typ of
  3392. top_reg:
  3393. begin
  3394. { change
  3395. mov mem, %treg
  3396. mov %treg, %reg
  3397. to
  3398. mov mem, %reg"
  3399. }
  3400. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3401. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3402. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3403. RemoveInstruction(hp1);
  3404. Result:=true;
  3405. Exit;
  3406. end;
  3407. top_ref:
  3408. begin
  3409. {$ifdef x86_64}
  3410. { Look for the following to simplify:
  3411. mov x(mem1), %reg
  3412. mov %reg, y(mem2)
  3413. mov x+8(mem1), %reg
  3414. mov %reg, y+8(mem2)
  3415. Change to:
  3416. movdqu x(mem1), %xmmreg
  3417. movdqu %xmmreg, y(mem2)
  3418. ...but only as long as the memory blocks don't overlap
  3419. }
  3420. SourceRef := taicpu(p).oper[0]^.ref^;
  3421. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3422. if (taicpu(p).opsize = S_Q) and
  3423. GetNextInstruction(hp1, hp2) and
  3424. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3425. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3426. begin
  3427. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3428. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3429. Inc(SourceRef.offset, 8);
  3430. if UseAVX then
  3431. begin
  3432. MovAligned := A_VMOVDQA;
  3433. MovUnaligned := A_VMOVDQU;
  3434. end
  3435. else
  3436. begin
  3437. MovAligned := A_MOVDQA;
  3438. MovUnaligned := A_MOVDQU;
  3439. end;
  3440. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3441. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3442. begin
  3443. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3444. Inc(TargetRef.offset, 8);
  3445. if GetNextInstruction(hp2, hp3) and
  3446. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3447. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3448. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3449. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3450. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3451. begin
  3452. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3453. if NewMMReg <> NR_NO then
  3454. begin
  3455. { Remember that the offsets are 8 ahead }
  3456. if ((SourceRef.offset mod 16) = 8) and
  3457. (
  3458. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3459. (SourceRef.base = current_procinfo.framepointer) or
  3460. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3461. ) then
  3462. taicpu(p).opcode := MovAligned
  3463. else
  3464. taicpu(p).opcode := MovUnaligned;
  3465. taicpu(p).opsize := S_XMM;
  3466. taicpu(p).oper[1]^.reg := NewMMReg;
  3467. if ((TargetRef.offset mod 16) = 8) and
  3468. (
  3469. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3470. (TargetRef.base = current_procinfo.framepointer) or
  3471. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3472. ) then
  3473. taicpu(hp1).opcode := MovAligned
  3474. else
  3475. taicpu(hp1).opcode := MovUnaligned;
  3476. taicpu(hp1).opsize := S_XMM;
  3477. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3478. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3479. RemoveInstruction(hp2);
  3480. RemoveInstruction(hp3);
  3481. Result := True;
  3482. Exit;
  3483. end;
  3484. end;
  3485. end
  3486. else
  3487. begin
  3488. { See if the next references are 8 less rather than 8 greater }
  3489. Dec(SourceRef.offset, 16); { -8 the other way }
  3490. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3491. begin
  3492. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3493. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3494. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3495. GetNextInstruction(hp2, hp3) and
  3496. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3497. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3498. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3499. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3500. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3501. begin
  3502. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3503. if NewMMReg <> NR_NO then
  3504. begin
  3505. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3506. if ((SourceRef.offset mod 16) = 0) and
  3507. (
  3508. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3509. (SourceRef.base = current_procinfo.framepointer) or
  3510. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3511. ) then
  3512. taicpu(hp2).opcode := MovAligned
  3513. else
  3514. taicpu(hp2).opcode := MovUnaligned;
  3515. taicpu(hp2).opsize := S_XMM;
  3516. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3517. if ((TargetRef.offset mod 16) = 0) and
  3518. (
  3519. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3520. (TargetRef.base = current_procinfo.framepointer) or
  3521. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3522. ) then
  3523. taicpu(hp3).opcode := MovAligned
  3524. else
  3525. taicpu(hp3).opcode := MovUnaligned;
  3526. taicpu(hp3).opsize := S_XMM;
  3527. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3528. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3529. RemoveInstruction(hp1);
  3530. RemoveCurrentP(p, hp2);
  3531. Result := True;
  3532. Exit;
  3533. end;
  3534. end;
  3535. end;
  3536. end;
  3537. end;
  3538. {$endif x86_64}
  3539. end;
  3540. else
  3541. { The write target should be a reg or a ref }
  3542. InternalError(2021091601);
  3543. end;
  3544. else
  3545. ;
  3546. end
  3547. else
  3548. { %treg is used afterwards, but all eventualities
  3549. other than the first MOV instruction being a constant
  3550. are covered by DeepMOVOpt, so only check for that }
  3551. if (taicpu(p).oper[0]^.typ = top_const) and
  3552. (
  3553. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3554. not (cs_opt_size in current_settings.optimizerswitches) or
  3555. (taicpu(hp1).opsize = S_B)
  3556. ) and
  3557. (
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3559. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3560. ) then
  3561. begin
  3562. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3563. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3564. end;
  3565. end;
  3566. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3567. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3568. { mov reg1, mem1 or mov mem1, reg1
  3569. mov mem2, reg2 mov reg2, mem2}
  3570. begin
  3571. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3572. { mov reg1, mem1 or mov mem1, reg1
  3573. mov mem2, reg1 mov reg2, mem1}
  3574. begin
  3575. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3576. { Removes the second statement from
  3577. mov reg1, mem1/reg2
  3578. mov mem1/reg2, reg1 }
  3579. begin
  3580. if taicpu(p).oper[0]^.typ=top_reg then
  3581. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3582. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3583. RemoveInstruction(hp1);
  3584. Result:=true;
  3585. exit;
  3586. end
  3587. else
  3588. begin
  3589. TransferUsedRegs(TmpUsedRegs);
  3590. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3591. if (taicpu(p).oper[1]^.typ = top_ref) and
  3592. { mov reg1, mem1
  3593. mov mem2, reg1 }
  3594. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3595. GetNextInstruction(hp1, hp2) and
  3596. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3597. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3598. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3599. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3600. { change to
  3601. mov reg1, mem1 mov reg1, mem1
  3602. mov mem2, reg1 cmp reg1, mem2
  3603. cmp mem1, reg1
  3604. }
  3605. begin
  3606. RemoveInstruction(hp2);
  3607. taicpu(hp1).opcode := A_CMP;
  3608. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3609. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3610. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3611. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3612. end;
  3613. end;
  3614. end
  3615. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3616. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3617. begin
  3618. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3619. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3621. end
  3622. else
  3623. begin
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. if GetNextInstruction(hp1, hp2) and
  3626. MatchOpType(taicpu(p),top_ref,top_reg) and
  3627. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3628. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3629. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3630. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3631. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3632. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3633. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3634. { mov mem1, %reg1
  3635. mov %reg1, mem2
  3636. mov mem2, reg2
  3637. to:
  3638. mov mem1, reg2
  3639. mov reg2, mem2}
  3640. begin
  3641. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3642. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3643. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3644. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3645. RemoveInstruction(hp2);
  3646. Result := True;
  3647. end
  3648. {$ifdef i386}
  3649. { this is enabled for i386 only, as the rules to create the reg sets below
  3650. are too complicated for x86-64, so this makes this code too error prone
  3651. on x86-64
  3652. }
  3653. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3654. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3655. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3656. { mov mem1, reg1 mov mem1, reg1
  3657. mov reg1, mem2 mov reg1, mem2
  3658. mov mem2, reg2 mov mem2, reg1
  3659. to: to:
  3660. mov mem1, reg1 mov mem1, reg1
  3661. mov mem1, reg2 mov reg1, mem2
  3662. mov reg1, mem2
  3663. or (if mem1 depends on reg1
  3664. and/or if mem2 depends on reg2)
  3665. to:
  3666. mov mem1, reg1
  3667. mov reg1, mem2
  3668. mov reg1, reg2
  3669. }
  3670. begin
  3671. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3672. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3673. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3674. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3675. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3676. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3677. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3678. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3679. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3680. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3681. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3682. end
  3683. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3684. begin
  3685. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3686. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3687. end
  3688. else
  3689. begin
  3690. RemoveInstruction(hp2);
  3691. end
  3692. {$endif i386}
  3693. ;
  3694. end;
  3695. end
  3696. { movl [mem1],reg1
  3697. movl [mem1],reg2
  3698. to
  3699. movl [mem1],reg1
  3700. movl reg1,reg2
  3701. }
  3702. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3703. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3704. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3705. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3706. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3707. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3708. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3709. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3710. begin
  3711. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3712. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3713. end;
  3714. { movl const1,[mem1]
  3715. movl [mem1],reg1
  3716. to
  3717. movl const1,reg1
  3718. movl reg1,[mem1]
  3719. }
  3720. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3721. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3722. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3723. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3724. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3725. begin
  3726. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3727. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3728. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3729. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3730. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3731. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3732. Result:=true;
  3733. exit;
  3734. end;
  3735. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3736. { Change:
  3737. movl %reg1,%reg2
  3738. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3739. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3740. To:
  3741. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3742. movl x(%reg1),%reg1
  3743. movl %reg1,%regX
  3744. }
  3745. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3746. begin
  3747. p_SourceReg := taicpu(p).oper[0]^.reg;
  3748. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3749. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3750. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3751. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3752. GetNextInstruction(hp1, hp2) and
  3753. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3754. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3755. begin
  3756. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3757. if RegInRef(p_TargetReg, SourceRef) and
  3758. { If %reg1 also appears in the second reference, then it will
  3759. not refer to the same memory block as the first reference }
  3760. not RegInRef(p_SourceReg, SourceRef) then
  3761. begin
  3762. { Check to see if the references match if %reg2 is changed to %reg1 }
  3763. if SourceRef.base = p_TargetReg then
  3764. SourceRef.base := p_SourceReg;
  3765. if SourceRef.index = p_TargetReg then
  3766. SourceRef.index := p_SourceReg;
  3767. { RefsEqual also checks to ensure both references are non-volatile }
  3768. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3769. begin
  3770. taicpu(hp2).loadreg(0, p_SourceReg);
  3771. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3772. Result := True;
  3773. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3774. begin
  3775. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3776. RemoveCurrentP(p, hp1);
  3777. Exit;
  3778. end
  3779. else
  3780. begin
  3781. { Check to see if %reg2 is no longer in use }
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3785. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3786. begin
  3787. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3788. RemoveCurrentP(p, hp1);
  3789. Exit;
  3790. end;
  3791. end;
  3792. { If we reach this point, p and hp1 weren't actually modified,
  3793. so we can do a bit more work on this pass }
  3794. end;
  3795. end;
  3796. end;
  3797. end;
  3798. end;
  3799. {$ifdef x86_64}
  3800. { Change:
  3801. movl %reg1l,%reg2l
  3802. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3803. To:
  3804. movl %reg1l,%reg2l
  3805. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3806. If %reg1 = %reg3, convert to:
  3807. movl %reg1l,%reg2l
  3808. andl %reg1l,%reg1l
  3809. }
  3810. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3811. MatchOpType(taicpu(p), top_reg, top_reg) and
  3812. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3813. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3814. begin
  3815. TransferUsedRegs(TmpUsedRegs);
  3816. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3817. taicpu(hp1).opsize := S_L;
  3818. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3819. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3820. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3821. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3822. begin
  3823. { %reg1 = %reg3 }
  3824. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3825. taicpu(hp1).opcode := A_AND;
  3826. end
  3827. else
  3828. begin
  3829. { %reg1 <> %reg3 }
  3830. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3831. end;
  3832. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3833. begin
  3834. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3835. RemoveCurrentP(p, hp1);
  3836. Result := True;
  3837. Exit;
  3838. end
  3839. else
  3840. begin
  3841. { Initial instruction wasn't actually changed }
  3842. Include(OptsToCheck, aoc_ForceNewIteration);
  3843. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3844. appears below since %reg1 has technically changed }
  3845. if taicpu(hp1).opcode = A_AND then
  3846. Exit;
  3847. end;
  3848. end;
  3849. {$endif x86_64}
  3850. { search further than the next instruction for a mov (as long as it's not a jump) }
  3851. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3852. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3853. (taicpu(p).oper[1]^.typ = top_reg) and
  3854. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3855. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3856. begin
  3857. { we work with hp2 here, so hp1 can be still used later on when
  3858. checking for GetNextInstruction_p }
  3859. hp3 := hp1;
  3860. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3861. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3862. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3863. TransferUsedRegs(TmpUsedRegs);
  3864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3865. if NotFirstIteration then
  3866. JumpTracking := TLinkedList.Create
  3867. else
  3868. JumpTracking := nil;
  3869. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3870. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3871. (hp2.typ=ait_instruction) do
  3872. begin
  3873. case taicpu(hp2).opcode of
  3874. A_POP:
  3875. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3876. begin
  3877. if not CrossJump and
  3878. not RegUsedBetween(p_TargetReg, p, hp2) then
  3879. begin
  3880. { We can remove the original MOV since the register
  3881. wasn't used between it and its popping from the stack }
  3882. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3883. RemoveCurrentp(p, hp1);
  3884. Result := True;
  3885. JumpTracking.Free;
  3886. Exit;
  3887. end;
  3888. { Can't go any further }
  3889. Break;
  3890. end;
  3891. A_MOV:
  3892. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3893. ((taicpu(p).oper[0]^.typ=top_const) or
  3894. ((taicpu(p).oper[0]^.typ=top_reg) and
  3895. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3896. )
  3897. ) then
  3898. begin
  3899. { we have
  3900. mov x, %treg
  3901. mov %treg, y
  3902. }
  3903. { We don't need to call UpdateUsedRegs for every instruction between
  3904. p and hp2 because the register we're concerned about will not
  3905. become deallocated (otherwise GetNextInstructionUsingReg would
  3906. have stopped at an earlier instruction). [Kit] }
  3907. TempRegUsed :=
  3908. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3909. RegReadByInstruction(p_TargetReg, hp3) or
  3910. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3911. case taicpu(p).oper[0]^.typ Of
  3912. top_reg:
  3913. begin
  3914. { change
  3915. mov %reg, %treg
  3916. mov %treg, y
  3917. to
  3918. mov %reg, y
  3919. }
  3920. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3921. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3922. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3923. begin
  3924. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3925. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3926. if TempRegUsed then
  3927. begin
  3928. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3929. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3930. { Set the start of the next GetNextInstructionUsingRegCond search
  3931. to start at the entry right before hp2 (which is about to be removed) }
  3932. hp3 := tai(hp2.Previous);
  3933. RemoveInstruction(hp2);
  3934. Include(OptsToCheck, aoc_ForceNewIteration);
  3935. { See if there's more we can optimise }
  3936. Continue;
  3937. end
  3938. else
  3939. begin
  3940. RemoveInstruction(hp2);
  3941. { We can remove the original MOV too }
  3942. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3943. RemoveCurrentP(p, hp1);
  3944. Result:=true;
  3945. JumpTracking.Free;
  3946. Exit;
  3947. end;
  3948. end
  3949. else
  3950. begin
  3951. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3952. taicpu(hp2).loadReg(0, p_SourceReg);
  3953. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3954. { Check to see if the register also appears in the reference }
  3955. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3956. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3957. { Don't remove the first instruction if the temporary register is in use }
  3958. if not TempRegUsed and
  3959. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3960. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3961. begin
  3962. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3963. RemoveCurrentP(p, hp1);
  3964. Result:=true;
  3965. JumpTracking.Free;
  3966. Exit;
  3967. end;
  3968. { No need to set Result to True here. If there's another instruction later
  3969. on that can be optimised, it will be detected when the main Pass 1 loop
  3970. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3971. end;
  3972. end;
  3973. top_const:
  3974. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3975. begin
  3976. { change
  3977. mov const, %treg
  3978. mov %treg, y
  3979. to
  3980. mov const, y
  3981. }
  3982. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3983. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3984. begin
  3985. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3986. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3987. if TempRegUsed then
  3988. begin
  3989. { Don't remove the first instruction if the temporary register is in use }
  3990. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3991. { No need to set Result to True. If there's another instruction later on
  3992. that can be optimised, it will be detected when the main Pass 1 loop
  3993. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3994. end
  3995. else
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3998. RemoveCurrentP(p, hp1);
  3999. Result:=true;
  4000. Exit;
  4001. end;
  4002. end;
  4003. end;
  4004. else
  4005. Internalerror(2019103001);
  4006. end;
  4007. end
  4008. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4009. begin
  4010. if not CrossJump and
  4011. not RegUsedBetween(p_TargetReg, p, hp2) and
  4012. not RegReadByInstruction(p_TargetReg, hp2) then
  4013. begin
  4014. { Register is not used before it is overwritten }
  4015. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4016. RemoveCurrentp(p, hp1);
  4017. Result := True;
  4018. Exit;
  4019. end;
  4020. if (taicpu(p).oper[0]^.typ = top_const) and
  4021. (taicpu(hp2).oper[0]^.typ = top_const) then
  4022. begin
  4023. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4024. begin
  4025. { Same value - register hasn't changed }
  4026. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4027. RemoveInstruction(hp2);
  4028. Include(OptsToCheck, aoc_ForceNewIteration);
  4029. { See if there's more we can optimise }
  4030. Continue;
  4031. end;
  4032. end;
  4033. {$ifdef x86_64}
  4034. end
  4035. { Change:
  4036. movl %reg1l,%reg2l
  4037. ...
  4038. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4039. To:
  4040. movl %reg1l,%reg2l
  4041. ...
  4042. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4043. If %reg1 = %reg3, convert to:
  4044. movl %reg1l,%reg2l
  4045. ...
  4046. andl %reg1l,%reg1l
  4047. }
  4048. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4049. (taicpu(p).oper[0]^.typ = top_reg) and
  4050. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4051. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4052. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4053. begin
  4054. TempRegUsed :=
  4055. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4056. RegReadByInstruction(p_TargetReg, hp3) or
  4057. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4058. taicpu(hp2).opsize := S_L;
  4059. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4060. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4062. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4063. begin
  4064. { %reg1 = %reg3 }
  4065. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4066. taicpu(hp2).opcode := A_AND;
  4067. end
  4068. else
  4069. begin
  4070. { %reg1 <> %reg3 }
  4071. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4072. end;
  4073. if not TempRegUsed then
  4074. begin
  4075. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4076. RemoveCurrentP(p, hp1);
  4077. Result := True;
  4078. Exit;
  4079. end
  4080. else
  4081. begin
  4082. { Initial instruction wasn't actually changed }
  4083. Include(OptsToCheck, aoc_ForceNewIteration);
  4084. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4085. appears below since %reg1 has technically changed }
  4086. if taicpu(hp2).opcode = A_AND then
  4087. Break;
  4088. end;
  4089. {$endif x86_64}
  4090. end;
  4091. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4092. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4093. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4094. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4095. begin
  4096. {
  4097. Change from:
  4098. mov ###, %reg
  4099. ...
  4100. movs/z %reg,%reg (Same register, just different sizes)
  4101. To:
  4102. movs/z ###, %reg (Longer version)
  4103. ...
  4104. (remove)
  4105. }
  4106. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4107. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4108. { Keep the first instruction as mov if ### is a constant }
  4109. if taicpu(p).oper[0]^.typ = top_const then
  4110. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4111. else
  4112. begin
  4113. taicpu(p).opcode := taicpu(hp2).opcode;
  4114. taicpu(p).opsize := taicpu(hp2).opsize;
  4115. end;
  4116. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4117. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4118. RemoveInstruction(hp2);
  4119. Result := True;
  4120. JumpTracking.Free;
  4121. Exit;
  4122. end;
  4123. else
  4124. { Move down to the if-block below };
  4125. end;
  4126. { Also catches MOV/S/Z instructions that aren't modified }
  4127. if taicpu(p).oper[0]^.typ = top_reg then
  4128. begin
  4129. p_SourceReg := taicpu(p).oper[0]^.reg;
  4130. if
  4131. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4132. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4133. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4134. begin
  4135. Result := True;
  4136. { Just in case something didn't get modified (e.g. an
  4137. implicit register). Also, if it does read from this
  4138. register, then there's no longer an advantage to
  4139. changing the register on subsequent instructions.}
  4140. if not RegReadByInstruction(p_TargetReg, hp2) then
  4141. begin
  4142. { If a conditional jump was crossed, do not delete
  4143. the original MOV no matter what }
  4144. if not CrossJump and
  4145. { RegEndOfLife returns True if the register is
  4146. deallocated before the next instruction or has
  4147. been loaded with a new value }
  4148. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4149. begin
  4150. { We can remove the original MOV }
  4151. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4152. RemoveCurrentp(p, hp1);
  4153. JumpTracking.Free;
  4154. Result := True;
  4155. Exit;
  4156. end;
  4157. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4158. begin
  4159. { See if there's more we can optimise }
  4160. hp3 := hp2;
  4161. Continue;
  4162. end;
  4163. end;
  4164. end;
  4165. end;
  4166. { Break out of the while loop under normal circumstances }
  4167. Break;
  4168. end;
  4169. JumpTracking.Free;
  4170. end;
  4171. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4172. (taicpu(p).oper[1]^.typ = top_reg) and
  4173. (taicpu(p).opsize = S_L) and
  4174. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4175. (hp2.typ = ait_instruction) and
  4176. (taicpu(hp2).opcode = A_AND) and
  4177. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4178. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4179. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4180. ) then
  4181. begin
  4182. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4183. begin
  4184. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4185. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4186. begin
  4187. { Optimize out:
  4188. mov x, %reg
  4189. and ffffffffh, %reg
  4190. }
  4191. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4192. RemoveInstruction(hp2);
  4193. Result:=true;
  4194. exit;
  4195. end;
  4196. end;
  4197. end;
  4198. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4199. x >= RetOffset) as it doesn't do anything (it writes either to a
  4200. parameter or to the temporary storage room for the function
  4201. result)
  4202. }
  4203. if IsExitCode(hp1) and
  4204. (taicpu(p).oper[1]^.typ = top_ref) and
  4205. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4206. (
  4207. (
  4208. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4209. not (
  4210. assigned(current_procinfo.procdef.funcretsym) and
  4211. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4212. )
  4213. ) or
  4214. { Also discard writes to the stack that are below the base pointer,
  4215. as this is temporary storage rather than a function result on the
  4216. stack, say. }
  4217. (
  4218. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4219. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4220. )
  4221. ) then
  4222. begin
  4223. RemoveCurrentp(p, hp1);
  4224. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4225. RemoveLastDeallocForFuncRes(p);
  4226. Result:=true;
  4227. exit;
  4228. end;
  4229. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4230. begin
  4231. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4232. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4233. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4234. begin
  4235. { change
  4236. mov reg1, mem1
  4237. test/cmp x, mem1
  4238. to
  4239. mov reg1, mem1
  4240. test/cmp x, reg1
  4241. }
  4242. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4243. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if DoMovCmpMemOpt(p, hp1) then
  4249. begin
  4250. Result := True;
  4251. Exit;
  4252. end;
  4253. end;
  4254. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4255. { If the flags register is in use, don't change the instruction to an
  4256. ADD otherwise this will scramble the flags. [Kit] }
  4257. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4258. begin
  4259. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4260. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4261. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4262. ) or
  4263. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4264. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4265. )
  4266. ) then
  4267. { mov reg1,ref
  4268. lea reg2,[reg1,reg2]
  4269. to
  4270. add reg2,ref}
  4271. begin
  4272. TransferUsedRegs(TmpUsedRegs);
  4273. { reg1 may not be used afterwards }
  4274. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4275. begin
  4276. Taicpu(hp1).opcode:=A_ADD;
  4277. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4278. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4279. RemoveCurrentp(p, hp1);
  4280. result:=true;
  4281. exit;
  4282. end;
  4283. end;
  4284. { If the LEA instruction can be converted into an arithmetic instruction,
  4285. it may be possible to then fold it in the next optimisation, otherwise
  4286. there's nothing more that can be optimised here. }
  4287. if not ConvertLEA(taicpu(hp1)) then
  4288. Exit;
  4289. end;
  4290. if (taicpu(p).oper[1]^.typ = top_reg) and
  4291. (hp1.typ = ait_instruction) and
  4292. GetNextInstruction(hp1, hp2) and
  4293. MatchInstruction(hp2,A_MOV,[]) and
  4294. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4295. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4296. (
  4297. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4298. {$ifdef x86_64}
  4299. or
  4300. (
  4301. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4302. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4303. )
  4304. {$endif x86_64}
  4305. ) then
  4306. begin
  4307. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4308. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4309. { change movsX/movzX reg/ref, reg2
  4310. add/sub/or/... reg3/$const, reg2
  4311. mov reg2 reg/ref
  4312. dealloc reg2
  4313. to
  4314. add/sub/or/... reg3/$const, reg/ref }
  4315. begin
  4316. TransferUsedRegs(TmpUsedRegs);
  4317. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4318. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4319. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4320. begin
  4321. { by example:
  4322. movswl %si,%eax movswl %si,%eax p
  4323. decl %eax addl %edx,%eax hp1
  4324. movw %ax,%si movw %ax,%si hp2
  4325. ->
  4326. movswl %si,%eax movswl %si,%eax p
  4327. decw %eax addw %edx,%eax hp1
  4328. movw %ax,%si movw %ax,%si hp2
  4329. }
  4330. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4331. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4332. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4333. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4334. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4335. {
  4336. ->
  4337. movswl %si,%eax movswl %si,%eax p
  4338. decw %si addw %dx,%si hp1
  4339. movw %ax,%si movw %ax,%si hp2
  4340. }
  4341. case taicpu(hp1).ops of
  4342. 1:
  4343. begin
  4344. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4345. if taicpu(hp1).oper[0]^.typ=top_reg then
  4346. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4347. end;
  4348. 2:
  4349. begin
  4350. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4351. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4352. (taicpu(hp1).opcode<>A_SHL) and
  4353. (taicpu(hp1).opcode<>A_SHR) and
  4354. (taicpu(hp1).opcode<>A_SAR) then
  4355. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4356. end;
  4357. else
  4358. internalerror(2008042701);
  4359. end;
  4360. {
  4361. ->
  4362. decw %si addw %dx,%si p
  4363. }
  4364. RemoveInstruction(hp2);
  4365. RemoveCurrentP(p, hp1);
  4366. Result:=True;
  4367. Exit;
  4368. end;
  4369. end;
  4370. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4371. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4372. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4373. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4374. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4375. )
  4376. {$ifdef i386}
  4377. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4378. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4379. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4380. {$endif i386}
  4381. then
  4382. { change movsX/movzX reg/ref, reg2
  4383. add/sub/or/... regX/$const, reg2
  4384. mov reg2, reg3
  4385. dealloc reg2
  4386. to
  4387. movsX/movzX reg/ref, reg3
  4388. add/sub/or/... reg3/$const, reg3
  4389. }
  4390. begin
  4391. TransferUsedRegs(TmpUsedRegs);
  4392. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4394. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4395. begin
  4396. { by example:
  4397. movswl %si,%eax movswl %si,%eax p
  4398. decl %eax addl %edx,%eax hp1
  4399. movw %ax,%si movw %ax,%si hp2
  4400. ->
  4401. movswl %si,%eax movswl %si,%eax p
  4402. decw %eax addw %edx,%eax hp1
  4403. movw %ax,%si movw %ax,%si hp2
  4404. }
  4405. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4406. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4407. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4408. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4409. { limit size of constants as well to avoid assembler errors, but
  4410. check opsize to avoid overflow when left shifting the 1 }
  4411. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4412. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4413. {$ifdef x86_64}
  4414. { Be careful of, for example:
  4415. movl %reg1,%reg2
  4416. addl %reg3,%reg2
  4417. movq %reg2,%reg4
  4418. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4419. }
  4420. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4421. begin
  4422. taicpu(hp2).changeopsize(S_L);
  4423. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4424. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4425. end;
  4426. {$endif x86_64}
  4427. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4428. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4429. if taicpu(p).oper[0]^.typ=top_reg then
  4430. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4431. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4432. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4433. {
  4434. ->
  4435. movswl %si,%eax movswl %si,%eax p
  4436. decw %si addw %dx,%si hp1
  4437. movw %ax,%si movw %ax,%si hp2
  4438. }
  4439. case taicpu(hp1).ops of
  4440. 1:
  4441. begin
  4442. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4443. if taicpu(hp1).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. 2:
  4447. begin
  4448. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4449. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4450. (taicpu(hp1).opcode<>A_SHL) and
  4451. (taicpu(hp1).opcode<>A_SHR) and
  4452. (taicpu(hp1).opcode<>A_SAR) then
  4453. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4454. end;
  4455. else
  4456. internalerror(2018111801);
  4457. end;
  4458. {
  4459. ->
  4460. decw %si addw %dx,%si p
  4461. }
  4462. RemoveInstruction(hp2);
  4463. end;
  4464. end;
  4465. end;
  4466. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4467. GetNextInstruction(hp1, hp2) and
  4468. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4469. MatchOperand(Taicpu(p).oper[0]^,0) and
  4470. (Taicpu(p).oper[1]^.typ = top_reg) and
  4471. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4472. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4473. { mov reg1,0
  4474. bts reg1,operand1 --> mov reg1,operand2
  4475. or reg1,operand2 bts reg1,operand1}
  4476. begin
  4477. Taicpu(hp2).opcode:=A_MOV;
  4478. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4479. asml.remove(hp1);
  4480. insertllitem(hp2,hp2.next,hp1);
  4481. RemoveCurrentp(p, hp1);
  4482. Result:=true;
  4483. exit;
  4484. end;
  4485. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4487. GetNextInstruction(hp1, hp2) and
  4488. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4489. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4490. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4491. { change
  4492. mov reg1,reg2
  4493. sub reg3,reg2
  4494. cmp reg3,reg1
  4495. into
  4496. mov reg1,reg2
  4497. sub reg3,reg2
  4498. }
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4501. RemoveInstruction(hp2);
  4502. Result:=true;
  4503. exit;
  4504. end;
  4505. {
  4506. mov ref,reg0
  4507. <op> reg0,reg1
  4508. dealloc reg0
  4509. to
  4510. <op> ref,reg1
  4511. }
  4512. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4513. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4514. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4515. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4516. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4517. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4518. begin
  4519. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4520. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4521. RemoveCurrentp(p, hp1);
  4522. Result:=true;
  4523. exit;
  4524. end;
  4525. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4526. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4527. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4528. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4529. begin
  4530. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4531. {$ifdef x86_64}
  4532. { Convert:
  4533. movq x(ref),%reg64
  4534. shrq y,%reg64
  4535. To:
  4536. movl x+4(ref),%reg32
  4537. shrl y-32,%reg32 (Remove if y = 32)
  4538. }
  4539. if (taicpu(p).opsize = S_Q) and
  4540. (taicpu(hp1).opcode = A_SHR) and
  4541. (taicpu(hp1).oper[0]^.val >= 32) then
  4542. begin
  4543. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4544. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4545. { Convert to 32-bit }
  4546. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4547. taicpu(p).opsize := S_L;
  4548. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4549. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4550. if (taicpu(hp1).oper[0]^.val = 32) then
  4551. begin
  4552. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4553. RemoveInstruction(hp1);
  4554. end
  4555. else
  4556. begin
  4557. { This will potentially open up more arithmetic operations since
  4558. the peephole optimizer now has a big hint that only the lower
  4559. 32 bits are currently in use (and opcodes are smaller in size) }
  4560. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4561. taicpu(hp1).opsize := S_L;
  4562. Dec(taicpu(hp1).oper[0]^.val, 32);
  4563. DebugMsg(SPeepholeOptimization + PreMessage +
  4564. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4565. end;
  4566. Result := True;
  4567. Exit;
  4568. end;
  4569. {$endif x86_64}
  4570. { Convert:
  4571. movl x(ref),%reg
  4572. shrl $24,%reg
  4573. To:
  4574. movzbl x+3(ref),%reg
  4575. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4576. Also accept sar instead of shr, but convert to movsx instead of movzx
  4577. }
  4578. if taicpu(hp1).opcode = A_SHR then
  4579. MovUnaligned := A_MOVZX
  4580. else
  4581. MovUnaligned := A_MOVSX;
  4582. NewSize := S_NO;
  4583. NewOffset := 0;
  4584. case taicpu(p).opsize of
  4585. S_B:
  4586. { No valid combinations };
  4587. S_W:
  4588. if (taicpu(hp1).oper[0]^.val = 8) then
  4589. begin
  4590. NewSize := S_BW;
  4591. NewOffset := 1;
  4592. end;
  4593. S_L:
  4594. case taicpu(hp1).oper[0]^.val of
  4595. 16:
  4596. begin
  4597. NewSize := S_WL;
  4598. NewOffset := 2;
  4599. end;
  4600. 24:
  4601. begin
  4602. NewSize := S_BL;
  4603. NewOffset := 3;
  4604. end;
  4605. else
  4606. ;
  4607. end;
  4608. {$ifdef x86_64}
  4609. S_Q:
  4610. case taicpu(hp1).oper[0]^.val of
  4611. 32:
  4612. begin
  4613. if taicpu(hp1).opcode = A_SAR then
  4614. begin
  4615. { 32-bit to 64-bit is a distinct instruction }
  4616. MovUnaligned := A_MOVSXD;
  4617. NewSize := S_LQ;
  4618. NewOffset := 4;
  4619. end
  4620. else
  4621. { Should have been handled by MovShr2Mov above }
  4622. InternalError(2022081811);
  4623. end;
  4624. 48:
  4625. begin
  4626. NewSize := S_WQ;
  4627. NewOffset := 6;
  4628. end;
  4629. 56:
  4630. begin
  4631. NewSize := S_BQ;
  4632. NewOffset := 7;
  4633. end;
  4634. else
  4635. ;
  4636. end;
  4637. {$endif x86_64}
  4638. else
  4639. InternalError(2022081810);
  4640. end;
  4641. if (NewSize <> S_NO) and
  4642. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4643. begin
  4644. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4645. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4646. debug_op2str(MovUnaligned);
  4647. {$ifdef x86_64}
  4648. if MovUnaligned <> A_MOVSXD then
  4649. { Don't add size suffix for MOVSXD }
  4650. {$endif x86_64}
  4651. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4652. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4653. taicpu(p).opcode := MovUnaligned;
  4654. taicpu(p).opsize := NewSize;
  4655. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4656. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4657. RemoveInstruction(hp1);
  4658. Result := True;
  4659. Exit;
  4660. end;
  4661. end;
  4662. { Backward optimisation shared with OptPass2MOV }
  4663. if FuncMov2Func(p, hp1) then
  4664. begin
  4665. Result := True;
  4666. Exit;
  4667. end;
  4668. end;
  4669. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4670. var
  4671. hp1 : tai;
  4672. begin
  4673. Result:=false;
  4674. if taicpu(p).ops <> 2 then
  4675. exit;
  4676. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4677. GetNextInstruction(p,hp1) then
  4678. begin
  4679. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4680. (taicpu(hp1).ops = 2) then
  4681. begin
  4682. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4683. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4684. { movXX reg1, mem1 or movXX mem1, reg1
  4685. movXX mem2, reg2 movXX reg2, mem2}
  4686. begin
  4687. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4688. { movXX reg1, mem1 or movXX mem1, reg1
  4689. movXX mem2, reg1 movXX reg2, mem1}
  4690. begin
  4691. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4692. begin
  4693. { Removes the second statement from
  4694. movXX reg1, mem1/reg2
  4695. movXX mem1/reg2, reg1
  4696. }
  4697. if taicpu(p).oper[0]^.typ=top_reg then
  4698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4699. { Removes the second statement from
  4700. movXX mem1/reg1, reg2
  4701. movXX reg2, mem1/reg1
  4702. }
  4703. if (taicpu(p).oper[1]^.typ=top_reg) and
  4704. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4705. begin
  4706. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4707. RemoveInstruction(hp1);
  4708. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4709. Result:=true;
  4710. exit;
  4711. end
  4712. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4713. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4716. RemoveInstruction(hp1);
  4717. Result:=true;
  4718. exit;
  4719. end;
  4720. end
  4721. end;
  4722. end;
  4723. end;
  4724. end;
  4725. end;
  4726. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4727. var
  4728. hp1 : tai;
  4729. begin
  4730. result:=false;
  4731. { replace
  4732. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4733. MovX %mreg2,%mreg1
  4734. dealloc %mreg2
  4735. by
  4736. <Op>X %mreg2,%mreg1
  4737. ?
  4738. }
  4739. if GetNextInstruction(p,hp1) and
  4740. { we mix single and double opperations here because we assume that the compiler
  4741. generates vmovapd only after double operations and vmovaps only after single operations }
  4742. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4745. (taicpu(p).oper[0]^.typ=top_reg) then
  4746. begin
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4750. begin
  4751. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4753. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4754. RemoveInstruction(hp1);
  4755. result:=true;
  4756. end;
  4757. end;
  4758. end;
  4759. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4760. var
  4761. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4762. JumpLabel, JumpLabel_dist: TAsmLabel;
  4763. FirstValue, SecondValue: TCGInt;
  4764. TempBool: Boolean;
  4765. begin
  4766. Result := False;
  4767. if (taicpu(p).oper[0]^.typ = top_const) and
  4768. (taicpu(p).oper[0]^.val <> -1) then
  4769. begin
  4770. { Convert unsigned maximum constants to -1 to aid optimisation }
  4771. case taicpu(p).opsize of
  4772. S_B:
  4773. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4774. begin
  4775. taicpu(p).oper[0]^.val := -1;
  4776. Result := True;
  4777. Exit;
  4778. end;
  4779. S_W:
  4780. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4781. begin
  4782. taicpu(p).oper[0]^.val := -1;
  4783. Result := True;
  4784. Exit;
  4785. end;
  4786. S_L:
  4787. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. {$ifdef x86_64}
  4794. S_Q:
  4795. { Storing anything greater than $7FFFFFFF is not possible so do
  4796. nothing };
  4797. {$endif x86_64}
  4798. else
  4799. InternalError(2021121001);
  4800. end;
  4801. end;
  4802. if GetNextInstruction(p, hp1) and
  4803. TrySwapMovCmp(p, hp1) then
  4804. begin
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. if MatchInstruction(hp1, A_Jcc, []) then
  4809. begin
  4810. TempBool := True;
  4811. if DoJumpOptimizations(hp1, TempBool) or
  4812. not TempBool then
  4813. begin
  4814. Result := True;
  4815. if Assigned(hp1) then
  4816. begin
  4817. if (hp1.typ in [ait_align]) then
  4818. SkipAligns(hp1, hp1);
  4819. { CollapseZeroDistJump will be set to the label after the
  4820. jump if it optimises, whether or not it's live or dead }
  4821. if (hp1.typ in [ait_label]) and
  4822. not (tai_label(hp1).labsym.is_used) then
  4823. GetNextInstruction(hp1, hp1);
  4824. end;
  4825. TransferUsedRegs(TmpUsedRegs);
  4826. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4827. if not Assigned(hp1) or
  4828. (
  4829. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4830. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4831. ) then
  4832. begin
  4833. { No more conditional jumps; conditional statement is no longer required }
  4834. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4835. RemoveCurrentP(p);
  4836. end;
  4837. Exit;
  4838. end;
  4839. end;
  4840. { Search for:
  4841. test $x,(reg/ref)
  4842. jne @lbl1
  4843. ...
  4844. test $y,(reg/ref) (same register or reference)
  4845. jne @lbl1
  4846. Change to:
  4847. test $(x or y),(reg/ref)
  4848. jne @lbl1
  4849. (Note, this doesn't work with je instead of jne)
  4850. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4851. Also search for:
  4852. test $x,(reg/ref)
  4853. je @lbl1
  4854. ...
  4855. test $y,(reg/ref)
  4856. je/jne @lbl2
  4857. If (x or y) = x, then the second jump is deterministic
  4858. }
  4859. if (
  4860. (
  4861. (taicpu(p).oper[0]^.typ = top_const) or
  4862. (
  4863. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4864. (taicpu(p).oper[0]^.typ = top_reg) and
  4865. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4866. )
  4867. ) and
  4868. MatchInstruction(hp1, A_JCC, [])
  4869. ) then
  4870. begin
  4871. if (taicpu(p).oper[0]^.typ = top_reg) and
  4872. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4873. FirstValue := -1
  4874. else
  4875. FirstValue := taicpu(p).oper[0]^.val;
  4876. { If we have several test/jne's in a row, it might be the case that
  4877. the second label doesn't go to the same location, but the one
  4878. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4879. so accommodate for this with a while loop.
  4880. }
  4881. hp1_last := hp1;
  4882. while (
  4883. (
  4884. (taicpu(p).oper[1]^.typ = top_reg) and
  4885. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4886. ) or GetNextInstruction(hp1_last, p_dist)
  4887. ) and (p_dist.typ = ait_instruction) do
  4888. begin
  4889. if (
  4890. (
  4891. (taicpu(p_dist).opcode = A_TEST) and
  4892. (
  4893. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4894. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4895. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4896. )
  4897. ) or
  4898. (
  4899. { cmp 0,%reg = test %reg,%reg }
  4900. (taicpu(p_dist).opcode = A_CMP) and
  4901. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4902. )
  4903. ) and
  4904. { Make sure the destination operands are actually the same }
  4905. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4906. GetNextInstruction(p_dist, hp1_dist) and
  4907. MatchInstruction(hp1_dist, A_JCC, []) then
  4908. begin
  4909. if
  4910. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4911. (
  4912. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4913. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4914. ) then
  4915. SecondValue := -1
  4916. else
  4917. SecondValue := taicpu(p_dist).oper[0]^.val;
  4918. { If both of the TEST constants are identical, delete the
  4919. second TEST that is unnecessary (be careful though, just
  4920. in case the flags are modified in between) }
  4921. if (FirstValue = SecondValue) then
  4922. begin
  4923. { We have to check the entire range }
  4924. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4925. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4926. begin
  4927. { Since the second jump's condition is a subset of the first, we
  4928. know it will never branch because the first jump dominates it.
  4929. Get it out of the way now rather than wait for the jump
  4930. optimisations for a speed boost. }
  4931. if IsJumpToLabel(taicpu(hp1_dist)) then
  4932. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4933. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4934. RemoveInstruction(hp1_dist);
  4935. Result := True;
  4936. end
  4937. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4938. begin
  4939. { If the inverse of the first condition is a subset of the second,
  4940. the second one will definitely branch if the first one doesn't }
  4941. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4942. { We can remove the TEST instruction too }
  4943. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4944. RemoveInstruction(p_dist);
  4945. MakeUnconditional(taicpu(hp1_dist));
  4946. RemoveDeadCodeAfterJump(hp1_dist);
  4947. { Since the jump is now unconditional, we can't
  4948. continue any further with this particular
  4949. optimisation. The original TEST is still intact
  4950. though, so there might be something else we can
  4951. do }
  4952. Include(OptsToCheck, aoc_ForceNewIteration);
  4953. Break;
  4954. end;
  4955. if Result or
  4956. { If a jump wasn't removed or made unconditional, only
  4957. remove the identical TEST instruction if the flags
  4958. weren't modified }
  4959. TempBool then
  4960. begin
  4961. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4962. RemoveInstruction(p_dist);
  4963. { If the jump was removed or made unconditional, we
  4964. don't need to allocate NR_DEFAULTFLAGS over the
  4965. entire range }
  4966. if not Result then
  4967. begin
  4968. { Mark the flags as 'in use' over the entire range }
  4969. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4970. { Speed gain - continue search from the Jcc instruction }
  4971. hp1_last := hp1_dist;
  4972. { Only the TEST instruction was removed, and the
  4973. original was unchanged, so we can safely do
  4974. another iteration of the while loop }
  4975. Include(OptsToCheck, aoc_ForceNewIteration);
  4976. Continue;
  4977. end;
  4978. Exit;
  4979. end;
  4980. end;
  4981. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4982. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4983. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4984. then the second jump will never branch, so it can also be
  4985. removed regardless of where it goes }
  4986. (
  4987. (FirstValue = -1) or
  4988. (SecondValue = -1) or
  4989. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4990. ) then
  4991. begin
  4992. { Same jump location... can be a register since nothing's changed }
  4993. { If any of the entries are equivalent to test %reg,%reg, then the
  4994. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4995. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4996. if IsJumpToLabel(taicpu(hp1_dist)) then
  4997. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4998. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4999. RemoveInstruction(hp1_dist);
  5000. { Only remove the second test if no jumps or other conditional instructions follow }
  5001. TransferUsedRegs(TmpUsedRegs);
  5002. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5003. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5004. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  5005. RemoveInstruction(p_dist);
  5006. Result := True;
  5007. Exit;
  5008. end;
  5009. end;
  5010. if { If -O2 and under, it may stop on any old instruction }
  5011. (cs_opt_level3 in current_settings.optimizerswitches) and
  5012. (taicpu(p).oper[1]^.typ = top_reg) and
  5013. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5014. begin
  5015. hp1_last := p_dist;
  5016. Continue;
  5017. end;
  5018. Break;
  5019. end;
  5020. end;
  5021. { Search for:
  5022. test %reg,%reg
  5023. j(c1) @lbl1
  5024. ...
  5025. @lbl:
  5026. test %reg,%reg (same register)
  5027. j(c2) @lbl2
  5028. If c2 is a subset of c1, change to:
  5029. test %reg,%reg
  5030. j(c1) @lbl2
  5031. (@lbl1 may become a dead label as a result)
  5032. }
  5033. if (taicpu(p).oper[1]^.typ = top_reg) and
  5034. (taicpu(p).oper[0]^.typ = top_reg) and
  5035. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5036. MatchInstruction(hp1, A_JCC, []) and
  5037. IsJumpToLabel(taicpu(hp1)) then
  5038. begin
  5039. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5040. p_label := nil;
  5041. if Assigned(JumpLabel) then
  5042. p_label := getlabelwithsym(JumpLabel);
  5043. if Assigned(p_label) and
  5044. GetNextInstruction(p_label, p_dist) and
  5045. MatchInstruction(p_dist, A_TEST, []) and
  5046. { It's fine if the second test uses smaller sub-registers }
  5047. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5048. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5049. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5050. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5051. GetNextInstruction(p_dist, hp1_dist) and
  5052. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5053. begin
  5054. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5055. if JumpLabel = JumpLabel_dist then
  5056. { This is an infinite loop }
  5057. Exit;
  5058. { Best optimisation when the first condition is a subset (or equal) of the second }
  5059. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5060. begin
  5061. { Any registers used here will already be allocated }
  5062. if Assigned(JumpLabel) then
  5063. JumpLabel.DecRefs;
  5064. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5065. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5066. Result := True;
  5067. Exit;
  5068. end;
  5069. end;
  5070. end;
  5071. end;
  5072. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5073. var
  5074. hp1, hp2: tai;
  5075. ActiveReg: TRegister;
  5076. OldOffset: asizeint;
  5077. ThisConst: TCGInt;
  5078. function RegDeallocated: Boolean;
  5079. begin
  5080. TransferUsedRegs(TmpUsedRegs);
  5081. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5082. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5083. end;
  5084. begin
  5085. result:=false;
  5086. hp1 := nil;
  5087. { replace
  5088. addX const,%reg1
  5089. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5090. dealloc %reg1
  5091. by
  5092. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5093. }
  5094. if MatchOpType(taicpu(p),top_const,top_reg) then
  5095. begin
  5096. ActiveReg := taicpu(p).oper[1]^.reg;
  5097. { Ensures the entire register was updated }
  5098. if (taicpu(p).opsize >= S_L) and
  5099. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5100. MatchInstruction(hp1,A_LEA,[]) and
  5101. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5102. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5103. (
  5104. { Cover the case where the register in the reference is also the destination register }
  5105. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5106. (
  5107. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5108. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5109. RegDeallocated
  5110. )
  5111. ) then
  5112. begin
  5113. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5114. {$push}
  5115. {$R-}{$Q-}
  5116. { Explicitly disable overflow checking for these offset calculation
  5117. as those do not matter for the final result }
  5118. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5119. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5120. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5121. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5122. {$pop}
  5123. {$ifdef x86_64}
  5124. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5125. begin
  5126. { Overflow; abort }
  5127. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5128. end
  5129. else
  5130. {$endif x86_64}
  5131. begin
  5132. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5133. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5134. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5135. RemoveCurrentP(p, hp1)
  5136. else
  5137. RemoveCurrentP(p);
  5138. result:=true;
  5139. Exit;
  5140. end;
  5141. end;
  5142. if (
  5143. { Save calling GetNextInstructionUsingReg again }
  5144. Assigned(hp1) or
  5145. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5146. ) and
  5147. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5148. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5149. begin
  5150. if taicpu(hp1).oper[0]^.typ = top_const then
  5151. begin
  5152. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5153. if taicpu(hp1).opcode = A_ADD then
  5154. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5155. else
  5156. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5157. Result := True;
  5158. { Handle any overflows }
  5159. case taicpu(p).opsize of
  5160. S_B:
  5161. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5162. S_W:
  5163. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5164. S_L:
  5165. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5166. {$ifdef x86_64}
  5167. S_Q:
  5168. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5169. { Overflow; abort }
  5170. Result := False
  5171. else
  5172. taicpu(p).oper[0]^.val := ThisConst;
  5173. {$endif x86_64}
  5174. else
  5175. InternalError(2021102610);
  5176. end;
  5177. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5178. if Result then
  5179. begin
  5180. if (taicpu(p).oper[0]^.val < 0) and
  5181. (
  5182. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5183. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5184. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5185. ) then
  5186. begin
  5187. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5188. taicpu(p).opcode := A_SUB;
  5189. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5190. end
  5191. else
  5192. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5193. RemoveInstruction(hp1);
  5194. end;
  5195. end
  5196. else
  5197. begin
  5198. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5199. TransferUsedRegs(TmpUsedRegs);
  5200. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5201. hp2 := p;
  5202. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5203. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5204. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5205. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5206. begin
  5207. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5208. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5209. Asml.Remove(p);
  5210. Asml.InsertAfter(p, hp1);
  5211. p := hp1;
  5212. Result := True;
  5213. Exit;
  5214. end;
  5215. end;
  5216. end;
  5217. if DoArithCombineOpt(p) then
  5218. Result:=true;
  5219. end;
  5220. end;
  5221. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5222. var
  5223. hp1, hp2: tai;
  5224. ref: Integer;
  5225. saveref: treference;
  5226. offsetcalc: Int64;
  5227. TempReg: TRegister;
  5228. Multiple: TCGInt;
  5229. Adjacent, IntermediateRegDiscarded: Boolean;
  5230. begin
  5231. Result:=false;
  5232. { play save and throw an error if LEA uses a seg register prefix,
  5233. this is most likely an error somewhere else }
  5234. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5235. internalerror(2022022001);
  5236. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5237. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5238. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5239. (
  5240. { do not mess with leas accessing the stack pointer
  5241. unless it's a null operation }
  5242. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5243. (
  5244. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5245. (taicpu(p).oper[0]^.ref^.offset = 0)
  5246. )
  5247. ) and
  5248. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5249. begin
  5250. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5251. begin
  5252. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5253. begin
  5254. taicpu(p).opcode := A_MOV;
  5255. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5256. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5257. end
  5258. else
  5259. begin
  5260. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5261. RemoveCurrentP(p);
  5262. end;
  5263. Result:=true;
  5264. exit;
  5265. end
  5266. else if (
  5267. { continue to use lea to adjust the stack pointer,
  5268. it is the recommended way, but only if not optimizing for size }
  5269. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5270. (cs_opt_size in current_settings.optimizerswitches)
  5271. ) and
  5272. { If the flags register is in use, don't change the instruction
  5273. to an ADD otherwise this will scramble the flags. [Kit] }
  5274. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5275. ConvertLEA(taicpu(p)) then
  5276. begin
  5277. Result:=true;
  5278. exit;
  5279. end;
  5280. end;
  5281. { Don't optimise if the stack or frame pointer is the destination register }
  5282. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5283. Exit;
  5284. if GetNextInstruction(p,hp1) and
  5285. (hp1.typ=ait_instruction) then
  5286. begin
  5287. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5288. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5289. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5290. begin
  5291. TransferUsedRegs(TmpUsedRegs);
  5292. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5293. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5294. begin
  5295. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5296. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5297. RemoveInstruction(hp1);
  5298. result:=true;
  5299. exit;
  5300. end;
  5301. end;
  5302. { changes
  5303. lea <ref1>, reg1
  5304. <op> ...,<ref. with reg1>,...
  5305. to
  5306. <op> ...,<ref1>,... }
  5307. { find a reference which uses reg1 }
  5308. 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
  5309. ref:=0
  5310. 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
  5311. ref:=1
  5312. else
  5313. ref:=-1;
  5314. if (ref<>-1) and
  5315. { reg1 must be either the base or the index }
  5316. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5317. begin
  5318. { reg1 can be removed from the reference }
  5319. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5320. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5321. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5322. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5323. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5324. else
  5325. Internalerror(2019111201);
  5326. { check if the can insert all data of the lea into the second instruction }
  5327. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5328. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5329. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5330. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5331. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5332. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5333. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5334. {$ifdef x86_64}
  5335. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5336. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5337. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5338. )
  5339. {$endif x86_64}
  5340. then
  5341. begin
  5342. { reg1 might not used by the second instruction after it is remove from the reference }
  5343. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5344. begin
  5345. TransferUsedRegs(TmpUsedRegs);
  5346. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5347. { reg1 is not updated so it might not be used afterwards }
  5348. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5349. begin
  5350. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5351. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5352. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5353. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5354. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5355. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5356. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5357. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5358. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5359. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5360. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5361. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5362. RemoveCurrentP(p, hp1);
  5363. result:=true;
  5364. exit;
  5365. end
  5366. end;
  5367. end;
  5368. { recover }
  5369. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5370. end;
  5371. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5372. if Adjacent or
  5373. { Check further ahead (up to 2 instructions ahead for -O2) }
  5374. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5375. begin
  5376. { Check common LEA/LEA conditions }
  5377. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5378. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5379. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5380. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5381. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5382. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5383. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5384. (
  5385. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5386. calling it (since it calls GetNextInstruction) }
  5387. Adjacent or
  5388. (
  5389. (
  5390. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5391. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5392. ) and (
  5393. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5394. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5395. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5396. )
  5397. )
  5398. ) then
  5399. begin
  5400. TransferUsedRegs(TmpUsedRegs);
  5401. hp2 := p;
  5402. repeat
  5403. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5404. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5405. IntermediateRegDiscarded :=
  5406. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5407. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5408. { changes
  5409. lea offset1(regX,scale), reg1
  5410. lea offset2(reg1,reg1), reg2
  5411. to
  5412. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5413. and
  5414. lea offset1(regX,scale1), reg1
  5415. lea offset2(reg1,scale2), reg2
  5416. to
  5417. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5418. and
  5419. lea offset1(regX,scale1), reg1
  5420. lea offset2(reg3,reg1,scale2), reg2
  5421. to
  5422. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5423. ... so long as the final scale does not exceed 8
  5424. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5425. }
  5426. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5427. (
  5428. { Don't optimise if size is a concern and the intermediate register remains in use }
  5429. IntermediateRegDiscarded or
  5430. not (cs_opt_size in current_settings.optimizerswitches)
  5431. ) and
  5432. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5433. (
  5434. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5435. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5436. ) and (
  5437. (
  5438. { lea (reg1,scale2), reg2 variant }
  5439. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5440. (
  5441. Adjacent or
  5442. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5443. ) and
  5444. (
  5445. (
  5446. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5447. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5448. ) or (
  5449. { lea (regX,regX), reg1 variant }
  5450. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5451. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5452. )
  5453. )
  5454. ) or (
  5455. { lea (reg1,reg1), reg1 variant }
  5456. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5457. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5458. )
  5459. ) then
  5460. begin
  5461. { Make everything homogeneous to make calculations easier }
  5462. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5463. begin
  5464. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5465. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5466. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5467. else
  5468. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5469. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5470. end;
  5471. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5472. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5473. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5474. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5475. begin
  5476. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5477. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5478. begin
  5479. { Put the register to change in the index register }
  5480. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5481. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5482. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5483. end;
  5484. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5485. begin
  5486. { Just to prevent miscalculations }
  5487. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5488. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5489. else
  5490. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5491. end
  5492. else
  5493. begin
  5494. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5495. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5496. end;
  5497. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5498. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5499. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5500. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5501. if IntermediateRegDiscarded then
  5502. begin
  5503. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5504. RemoveCurrentP(p);
  5505. end
  5506. else
  5507. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5508. result:=true;
  5509. exit;
  5510. end;
  5511. end;
  5512. { changes
  5513. lea offset1(regX), reg1
  5514. lea offset2(reg1), reg2
  5515. to
  5516. lea offset1+offset2(regX), reg2 }
  5517. if (
  5518. { Don't optimise if size is a concern and the intermediate register remains in use }
  5519. IntermediateRegDiscarded or
  5520. not (cs_opt_size in current_settings.optimizerswitches)
  5521. ) and
  5522. (
  5523. (
  5524. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5525. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5526. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5527. ) or (
  5528. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5529. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5530. (
  5531. (
  5532. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5533. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5534. ) or (
  5535. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5536. (
  5537. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5538. (
  5539. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5540. (
  5541. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5542. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5543. )
  5544. )
  5545. )
  5546. )
  5547. )
  5548. )
  5549. ) then
  5550. begin
  5551. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5552. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5553. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5554. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5555. begin
  5556. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5557. begin
  5558. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5559. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5560. { if the register is used as index and base, we have to increase for base as well
  5561. and adapt base }
  5562. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5563. begin
  5564. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5565. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5566. end;
  5567. end
  5568. else
  5569. begin
  5570. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5571. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5572. end;
  5573. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5574. begin
  5575. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5576. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5577. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5578. end;
  5579. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5580. if IntermediateRegDiscarded then
  5581. begin
  5582. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5583. RemoveCurrentP(p);
  5584. end
  5585. else
  5586. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5587. result:=true;
  5588. exit;
  5589. end;
  5590. end;
  5591. end;
  5592. { Change:
  5593. leal/q $x(%reg1),%reg2
  5594. ...
  5595. shll/q $y,%reg2
  5596. To:
  5597. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5598. }
  5599. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5600. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5601. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5602. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5603. (taicpu(hp1).oper[0]^.val <= 3) then
  5604. begin
  5605. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5606. TransferUsedRegs(TmpUsedRegs);
  5607. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5608. if
  5609. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5610. (this works even if scalefactor is zero) }
  5611. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5612. { Ensure offset doesn't go out of bounds }
  5613. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5614. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5615. (
  5616. (
  5617. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5618. (
  5619. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5620. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5621. (
  5622. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5623. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5624. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5625. )
  5626. )
  5627. ) or (
  5628. (
  5629. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5630. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5631. ) and
  5632. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5633. )
  5634. ) then
  5635. begin
  5636. repeat
  5637. with taicpu(p).oper[0]^.ref^ do
  5638. begin
  5639. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5640. if index = base then
  5641. begin
  5642. if Multiple > 4 then
  5643. { Optimisation will no longer work because resultant
  5644. scale factor will exceed 8 }
  5645. Break;
  5646. base := NR_NO;
  5647. scalefactor := 2;
  5648. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5649. end
  5650. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5651. begin
  5652. { Scale factor only works on the index register }
  5653. index := base;
  5654. base := NR_NO;
  5655. end;
  5656. { For safety }
  5657. if scalefactor <= 1 then
  5658. begin
  5659. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5660. scalefactor := Multiple;
  5661. end
  5662. else
  5663. begin
  5664. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5665. scalefactor := scalefactor * Multiple;
  5666. end;
  5667. offset := offset * Multiple;
  5668. end;
  5669. RemoveInstruction(hp1);
  5670. Result := True;
  5671. Exit;
  5672. { This repeat..until loop exists for the benefit of Break }
  5673. until True;
  5674. end;
  5675. end;
  5676. end;
  5677. end;
  5678. end;
  5679. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5680. var
  5681. hp1 : tai;
  5682. SubInstr: Boolean;
  5683. ThisConst: TCGInt;
  5684. const
  5685. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5686. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5687. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5688. begin
  5689. Result := False;
  5690. if taicpu(p).oper[0]^.typ <> top_const then
  5691. { Should have been confirmed before calling }
  5692. InternalError(2021102601);
  5693. SubInstr := (taicpu(p).opcode = A_SUB);
  5694. if GetLastInstruction(p, hp1) and
  5695. (hp1.typ = ait_instruction) and
  5696. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5697. begin
  5698. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5699. { Bad size }
  5700. InternalError(2022042001);
  5701. case taicpu(hp1).opcode Of
  5702. A_INC:
  5703. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5704. begin
  5705. if SubInstr then
  5706. ThisConst := taicpu(p).oper[0]^.val - 1
  5707. else
  5708. ThisConst := taicpu(p).oper[0]^.val + 1;
  5709. end
  5710. else
  5711. Exit;
  5712. A_DEC:
  5713. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5714. begin
  5715. if SubInstr then
  5716. ThisConst := taicpu(p).oper[0]^.val + 1
  5717. else
  5718. ThisConst := taicpu(p).oper[0]^.val - 1;
  5719. end
  5720. else
  5721. Exit;
  5722. A_SUB:
  5723. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5724. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5725. begin
  5726. if SubInstr then
  5727. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5728. else
  5729. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5730. end
  5731. else
  5732. Exit;
  5733. A_ADD:
  5734. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5735. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5736. begin
  5737. if SubInstr then
  5738. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5739. else
  5740. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5741. end
  5742. else
  5743. Exit;
  5744. else
  5745. Exit;
  5746. end;
  5747. { Check that the values are in range }
  5748. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5749. { Overflow; abort }
  5750. Exit;
  5751. if (ThisConst = 0) then
  5752. begin
  5753. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5754. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5755. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5756. RemoveInstruction(hp1);
  5757. hp1 := tai(p.next);
  5758. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5759. if not GetLastInstruction(hp1, p) then
  5760. p := hp1;
  5761. end
  5762. else
  5763. begin
  5764. if taicpu(hp1).opercnt=1 then
  5765. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5766. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5767. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5768. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5769. else
  5770. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5771. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5772. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5773. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5774. RemoveInstruction(hp1);
  5775. taicpu(p).loadconst(0, ThisConst);
  5776. end;
  5777. Result := True;
  5778. end;
  5779. end;
  5780. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5781. begin
  5782. Result := False;
  5783. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5784. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5785. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5786. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5787. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5788. (
  5789. (
  5790. (taicpu(hp1).opcode = A_TEST)
  5791. ) or (
  5792. (taicpu(hp1).opcode = A_CMP) and
  5793. { A sanity check more than anything }
  5794. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5795. )
  5796. ) then
  5797. begin
  5798. { change
  5799. mov mem, %reg
  5800. ...
  5801. cmp/test x, %reg / test %reg,%reg
  5802. (reg deallocated)
  5803. to
  5804. cmp/test x, mem / cmp 0, mem
  5805. }
  5806. TransferUsedRegs(TmpUsedRegs);
  5807. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5808. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5809. begin
  5810. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5811. if (taicpu(hp1).opcode = A_TEST) and
  5812. (
  5813. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5814. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5815. ) then
  5816. begin
  5817. taicpu(hp1).opcode := A_CMP;
  5818. taicpu(hp1).loadconst(0, 0);
  5819. end;
  5820. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5821. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5822. RemoveCurrentP(p);
  5823. if (p <> hp1) then
  5824. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5825. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5826. { Make sure the flags are allocated across the CMP instruction }
  5827. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5828. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5829. Result := True;
  5830. Exit;
  5831. end;
  5832. end;
  5833. end;
  5834. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5835. var
  5836. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5837. ThisReg, SecondReg: TRegister;
  5838. JumpLoc: TAsmLabel;
  5839. NewSize: TOpSize;
  5840. begin
  5841. Result := False;
  5842. {
  5843. Convert:
  5844. j<c> .L1
  5845. .L2:
  5846. mov 1,reg
  5847. jmp .L3 (or ret, although it might not be a RET yet)
  5848. .L1:
  5849. mov 0,reg
  5850. jmp .L3 (or ret)
  5851. ( As long as .L3 <> .L1 or .L2)
  5852. To:
  5853. mov 0,reg
  5854. set<not(c)> reg
  5855. jmp .L3 (or ret)
  5856. .L2:
  5857. mov 1,reg
  5858. jmp .L3 (or ret)
  5859. .L1:
  5860. mov 0,reg
  5861. jmp .L3 (or ret)
  5862. }
  5863. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5864. Exit;
  5865. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5866. if GetNextInstruction(hp_label, hp2) and
  5867. MatchInstruction(hp2,A_MOV,[]) and
  5868. (taicpu(hp2).oper[0]^.typ = top_const) and
  5869. (
  5870. (
  5871. (taicpu(hp2).oper[1]^.typ = top_reg)
  5872. {$ifdef i386}
  5873. { Under i386, ESI, EDI, EBP and ESP
  5874. don't have an 8-bit representation }
  5875. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5876. {$endif i386}
  5877. ) or (
  5878. {$ifdef i386}
  5879. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5880. {$endif i386}
  5881. (taicpu(hp2).opsize = S_B)
  5882. )
  5883. ) and
  5884. GetNextInstruction(hp2, hp3) and
  5885. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5886. (
  5887. (taicpu(hp3).opcode=A_RET) or
  5888. (
  5889. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5890. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5891. )
  5892. ) and
  5893. GetNextInstruction(hp3, hp4) and
  5894. SkipAligns(hp4, hp4) and
  5895. (hp4.typ=ait_label) and
  5896. (tai_label(hp4).labsym=JumpLoc) and
  5897. (
  5898. not (cs_opt_size in current_settings.optimizerswitches) or
  5899. { If the initial jump is the label's only reference, then it will
  5900. become a dead label if the other conditions are met and hence
  5901. remove at least 2 instructions, including a jump }
  5902. (JumpLoc.getrefs = 1)
  5903. ) and
  5904. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5905. that will be optimised out }
  5906. GetNextInstruction(hp4, hp5) and
  5907. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5908. (taicpu(hp5).oper[0]^.typ = top_const) and
  5909. (
  5910. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5911. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5912. ) and
  5913. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5914. GetNextInstruction(hp5,hp6) and
  5915. (
  5916. (hp6.typ<>ait_label) or
  5917. SkipLabels(hp6, hp6)
  5918. ) and
  5919. (hp6.typ=ait_instruction) then
  5920. begin
  5921. { First, let's look at the two jumps that are hp3 and hp6 }
  5922. if not
  5923. (
  5924. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5925. (
  5926. (taicpu(hp6).opcode=A_RET) or
  5927. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5928. )
  5929. ) then
  5930. { If condition is False, then the JMP/RET instructions matched conventionally }
  5931. begin
  5932. { See if one of the jumps can be instantly converted into a RET }
  5933. if (taicpu(hp3).opcode=A_JMP) then
  5934. begin
  5935. { Reuse hp5 }
  5936. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5937. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5938. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5939. Exit;
  5940. if MatchInstruction(hp5, A_RET, []) then
  5941. begin
  5942. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5943. ConvertJumpToRET(hp3, hp5);
  5944. Result := True;
  5945. end
  5946. else
  5947. Exit;
  5948. end;
  5949. if (taicpu(hp6).opcode=A_JMP) then
  5950. begin
  5951. { Reuse hp5 }
  5952. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5953. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5954. Exit;
  5955. if MatchInstruction(hp5, A_RET, []) then
  5956. begin
  5957. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5958. ConvertJumpToRET(hp6, hp5);
  5959. Result := True;
  5960. end
  5961. else
  5962. Exit;
  5963. end;
  5964. if not
  5965. (
  5966. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5967. (
  5968. (taicpu(hp6).opcode=A_RET) or
  5969. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5970. )
  5971. ) then
  5972. { Still doesn't match }
  5973. Exit;
  5974. end;
  5975. if (taicpu(hp2).oper[0]^.val = 1) then
  5976. begin
  5977. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5978. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5979. end
  5980. else
  5981. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5982. if taicpu(hp2).opsize=S_B then
  5983. begin
  5984. if taicpu(hp2).oper[1]^.typ = top_reg then
  5985. begin
  5986. SecondReg := taicpu(hp2).oper[1]^.reg;
  5987. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5988. end
  5989. else
  5990. begin
  5991. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5992. SecondReg := NR_NO;
  5993. end;
  5994. hp_pos := p;
  5995. hp_allocstart := hp4;
  5996. end
  5997. else
  5998. begin
  5999. { Will be a register because the size can't be S_B otherwise }
  6000. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6001. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6002. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6003. if (cs_opt_size in current_settings.optimizerswitches) then
  6004. begin
  6005. { Favour using MOVZX when optimising for size }
  6006. case taicpu(hp2).opsize of
  6007. S_W:
  6008. NewSize := S_BW;
  6009. S_L:
  6010. NewSize := S_BL;
  6011. {$ifdef x86_64}
  6012. S_Q:
  6013. begin
  6014. NewSize := S_BL;
  6015. { Will implicitly zero-extend to 64-bit }
  6016. setsubreg(SecondReg, R_SUBD);
  6017. end;
  6018. {$endif x86_64}
  6019. else
  6020. InternalError(2022101301);
  6021. end;
  6022. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6023. { Inserting it right before p will guarantee that the flags are also tracked }
  6024. Asml.InsertBefore(hp5, p);
  6025. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6026. hp_pos := hp5;
  6027. hp_allocstart := hp4;
  6028. end
  6029. else
  6030. begin
  6031. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6032. { Inserting it right before p will guarantee that the flags are also tracked }
  6033. Asml.InsertBefore(hp5, p);
  6034. hp_pos := p;
  6035. hp_allocstart := hp5;
  6036. end;
  6037. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6038. end;
  6039. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6040. taicpu(hp4).condition := taicpu(p).condition;
  6041. asml.InsertBefore(hp4, hp_pos);
  6042. if taicpu(hp3).is_jmp then
  6043. begin
  6044. JumpLoc.decrefs;
  6045. MakeUnconditional(taicpu(p));
  6046. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6047. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6048. end
  6049. else
  6050. ConvertJumpToRET(p, hp3);
  6051. if SecondReg <> NR_NO then
  6052. { Ensure the destination register is allocated over this region }
  6053. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6054. if (JumpLoc.getrefs = 0) then
  6055. RemoveDeadCodeAfterJump(hp3);
  6056. Result:=true;
  6057. exit;
  6058. end;
  6059. end;
  6060. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6061. var
  6062. hp1, hp2: tai;
  6063. ActiveReg: TRegister;
  6064. OldOffset: asizeint;
  6065. ThisConst: TCGInt;
  6066. function RegDeallocated: Boolean;
  6067. begin
  6068. TransferUsedRegs(TmpUsedRegs);
  6069. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6070. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6071. end;
  6072. begin
  6073. Result:=false;
  6074. hp1 := nil;
  6075. { replace
  6076. subX const,%reg1
  6077. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6078. dealloc %reg1
  6079. by
  6080. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6081. }
  6082. if MatchOpType(taicpu(p),top_const,top_reg) then
  6083. begin
  6084. ActiveReg := taicpu(p).oper[1]^.reg;
  6085. { Ensures the entire register was updated }
  6086. if (taicpu(p).opsize >= S_L) and
  6087. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6088. MatchInstruction(hp1,A_LEA,[]) and
  6089. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6090. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6091. (
  6092. { Cover the case where the register in the reference is also the destination register }
  6093. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6094. (
  6095. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6096. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6097. RegDeallocated
  6098. )
  6099. ) then
  6100. begin
  6101. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6102. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6103. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6104. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6105. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6106. {$ifdef x86_64}
  6107. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6108. begin
  6109. { Overflow; abort }
  6110. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6111. end
  6112. else
  6113. {$endif x86_64}
  6114. begin
  6115. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6116. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6117. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6118. RemoveCurrentP(p, hp1)
  6119. else
  6120. RemoveCurrentP(p);
  6121. result:=true;
  6122. Exit;
  6123. end;
  6124. end;
  6125. if (
  6126. { Save calling GetNextInstructionUsingReg again }
  6127. Assigned(hp1) or
  6128. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6129. ) and
  6130. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6131. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6132. begin
  6133. if taicpu(hp1).oper[0]^.typ = top_const then
  6134. begin
  6135. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6136. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6137. Result := True;
  6138. { Handle any overflows }
  6139. case taicpu(p).opsize of
  6140. S_B:
  6141. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6142. S_W:
  6143. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6144. S_L:
  6145. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6146. {$ifdef x86_64}
  6147. S_Q:
  6148. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6149. { Overflow; abort }
  6150. Result := False
  6151. else
  6152. taicpu(p).oper[0]^.val := ThisConst;
  6153. {$endif x86_64}
  6154. else
  6155. InternalError(2021102611);
  6156. end;
  6157. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6158. if Result then
  6159. begin
  6160. if (taicpu(p).oper[0]^.val < 0) and
  6161. (
  6162. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6163. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6164. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6165. ) then
  6166. begin
  6167. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6168. taicpu(p).opcode := A_SUB;
  6169. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6170. end
  6171. else
  6172. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6173. RemoveInstruction(hp1);
  6174. end;
  6175. end
  6176. else
  6177. begin
  6178. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6179. TransferUsedRegs(TmpUsedRegs);
  6180. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6181. hp2 := p;
  6182. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6183. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6184. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6185. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6186. begin
  6187. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6188. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6189. Asml.Remove(p);
  6190. Asml.InsertAfter(p, hp1);
  6191. p := hp1;
  6192. Result := True;
  6193. Exit;
  6194. end;
  6195. end;
  6196. end;
  6197. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6198. { * change "sub/add const1, reg" or "dec reg" followed by
  6199. "sub const2, reg" to one "sub ..., reg" }
  6200. {$ifdef i386}
  6201. if (taicpu(p).oper[0]^.val = 2) and
  6202. (ActiveReg = NR_ESP) and
  6203. { Don't do the sub/push optimization if the sub }
  6204. { comes from setting up the stack frame (JM) }
  6205. (not(GetLastInstruction(p,hp1)) or
  6206. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6207. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6208. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6209. begin
  6210. hp1 := tai(p.next);
  6211. while Assigned(hp1) and
  6212. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6213. not RegReadByInstruction(NR_ESP,hp1) and
  6214. not RegModifiedByInstruction(NR_ESP,hp1) do
  6215. hp1 := tai(hp1.next);
  6216. if Assigned(hp1) and
  6217. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6218. begin
  6219. taicpu(hp1).changeopsize(S_L);
  6220. if taicpu(hp1).oper[0]^.typ=top_reg then
  6221. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6222. hp1 := tai(p.next);
  6223. RemoveCurrentp(p, hp1);
  6224. Result:=true;
  6225. exit;
  6226. end;
  6227. end;
  6228. {$endif i386}
  6229. if DoArithCombineOpt(p) then
  6230. Result:=true;
  6231. end;
  6232. end;
  6233. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6234. var
  6235. TmpBool1,TmpBool2 : Boolean;
  6236. tmpref : treference;
  6237. hp1,hp2: tai;
  6238. mask, shiftval: tcgint;
  6239. begin
  6240. Result:=false;
  6241. { All these optimisations work on "shl/sal const,%reg" }
  6242. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6243. Exit;
  6244. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6245. (taicpu(p).oper[0]^.val <= 3) then
  6246. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6247. begin
  6248. { should we check the next instruction? }
  6249. TmpBool1 := True;
  6250. { have we found an add/sub which could be
  6251. integrated in the lea? }
  6252. TmpBool2 := False;
  6253. reference_reset(tmpref,2,[]);
  6254. TmpRef.index := taicpu(p).oper[1]^.reg;
  6255. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6256. while TmpBool1 and
  6257. GetNextInstruction(p, hp1) and
  6258. (tai(hp1).typ = ait_instruction) and
  6259. ((((taicpu(hp1).opcode = A_ADD) or
  6260. (taicpu(hp1).opcode = A_SUB)) and
  6261. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6262. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6263. (((taicpu(hp1).opcode = A_INC) or
  6264. (taicpu(hp1).opcode = A_DEC)) and
  6265. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6266. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6267. ((taicpu(hp1).opcode = A_LEA) and
  6268. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6269. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6270. (not GetNextInstruction(hp1,hp2) or
  6271. not instrReadsFlags(hp2)) Do
  6272. begin
  6273. TmpBool1 := False;
  6274. if taicpu(hp1).opcode=A_LEA then
  6275. begin
  6276. if (TmpRef.base = NR_NO) and
  6277. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6278. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6279. { Segment register isn't a concern here }
  6280. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6281. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6282. begin
  6283. TmpBool1 := True;
  6284. TmpBool2 := True;
  6285. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6286. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6287. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6288. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6289. RemoveInstruction(hp1);
  6290. end
  6291. end
  6292. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6293. begin
  6294. TmpBool1 := True;
  6295. TmpBool2 := True;
  6296. case taicpu(hp1).opcode of
  6297. A_ADD:
  6298. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6299. A_SUB:
  6300. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6301. else
  6302. internalerror(2019050536);
  6303. end;
  6304. RemoveInstruction(hp1);
  6305. end
  6306. else
  6307. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6308. (((taicpu(hp1).opcode = A_ADD) and
  6309. (TmpRef.base = NR_NO)) or
  6310. (taicpu(hp1).opcode = A_INC) or
  6311. (taicpu(hp1).opcode = A_DEC)) then
  6312. begin
  6313. TmpBool1 := True;
  6314. TmpBool2 := True;
  6315. case taicpu(hp1).opcode of
  6316. A_ADD:
  6317. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6318. A_INC:
  6319. inc(TmpRef.offset);
  6320. A_DEC:
  6321. dec(TmpRef.offset);
  6322. else
  6323. internalerror(2019050535);
  6324. end;
  6325. RemoveInstruction(hp1);
  6326. end;
  6327. end;
  6328. if TmpBool2
  6329. {$ifndef x86_64}
  6330. or
  6331. ((current_settings.optimizecputype < cpu_Pentium2) and
  6332. (taicpu(p).oper[0]^.val <= 3) and
  6333. not(cs_opt_size in current_settings.optimizerswitches))
  6334. {$endif x86_64}
  6335. then
  6336. begin
  6337. if not(TmpBool2) and
  6338. (taicpu(p).oper[0]^.val=1) then
  6339. begin
  6340. taicpu(p).opcode := A_ADD;
  6341. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6342. end
  6343. else
  6344. begin
  6345. taicpu(p).opcode := A_LEA;
  6346. taicpu(p).loadref(0, TmpRef);
  6347. end;
  6348. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6349. Result := True;
  6350. end;
  6351. end
  6352. {$ifndef x86_64}
  6353. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6354. begin
  6355. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6356. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6357. (unlike shl, which is only Tairable in the U pipe) }
  6358. if taicpu(p).oper[0]^.val=1 then
  6359. begin
  6360. taicpu(p).opcode := A_ADD;
  6361. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6362. Result := True;
  6363. end
  6364. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6365. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6366. else if (taicpu(p).opsize = S_L) and
  6367. (taicpu(p).oper[0]^.val<= 3) then
  6368. begin
  6369. reference_reset(tmpref,2,[]);
  6370. TmpRef.index := taicpu(p).oper[1]^.reg;
  6371. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6372. taicpu(p).opcode := A_LEA;
  6373. taicpu(p).loadref(0, TmpRef);
  6374. Result := True;
  6375. end;
  6376. end
  6377. {$endif x86_64}
  6378. else if
  6379. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6380. (
  6381. (
  6382. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6383. SetAndTest(hp1, hp2)
  6384. {$ifdef x86_64}
  6385. ) or
  6386. (
  6387. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6388. GetNextInstruction(hp1, hp2) and
  6389. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6390. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6391. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6392. {$endif x86_64}
  6393. )
  6394. ) and
  6395. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6396. begin
  6397. { Change:
  6398. shl x, %reg1
  6399. mov -(1<<x), %reg2
  6400. and %reg2, %reg1
  6401. Or:
  6402. shl x, %reg1
  6403. and -(1<<x), %reg1
  6404. To just:
  6405. shl x, %reg1
  6406. Since the and operation only zeroes bits that are already zero from the shl operation
  6407. }
  6408. case taicpu(p).oper[0]^.val of
  6409. 8:
  6410. mask:=$FFFFFFFFFFFFFF00;
  6411. 16:
  6412. mask:=$FFFFFFFFFFFF0000;
  6413. 32:
  6414. mask:=$FFFFFFFF00000000;
  6415. 63:
  6416. { Constant pre-calculated to prevent overflow errors with Int64 }
  6417. mask:=$8000000000000000;
  6418. else
  6419. begin
  6420. if taicpu(p).oper[0]^.val >= 64 then
  6421. { Shouldn't happen realistically, since the register
  6422. is guaranteed to be set to zero at this point }
  6423. mask := 0
  6424. else
  6425. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6426. end;
  6427. end;
  6428. if taicpu(hp1).oper[0]^.val = mask then
  6429. begin
  6430. { Everything checks out, perform the optimisation, as long as
  6431. the FLAGS register isn't being used}
  6432. TransferUsedRegs(TmpUsedRegs);
  6433. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6434. {$ifdef x86_64}
  6435. if (hp1 <> hp2) then
  6436. begin
  6437. { "shl/mov/and" version }
  6438. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6439. { Don't do the optimisation if the FLAGS register is in use }
  6440. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6441. begin
  6442. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6443. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6444. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6445. begin
  6446. RemoveInstruction(hp1);
  6447. Result := True;
  6448. end;
  6449. { Only set Result to True if the 'mov' instruction was removed }
  6450. RemoveInstruction(hp2);
  6451. end;
  6452. end
  6453. else
  6454. {$endif x86_64}
  6455. begin
  6456. { "shl/and" version }
  6457. { Don't do the optimisation if the FLAGS register is in use }
  6458. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6459. begin
  6460. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6461. RemoveInstruction(hp1);
  6462. Result := True;
  6463. end;
  6464. end;
  6465. Exit;
  6466. end
  6467. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6468. begin
  6469. { Even if the mask doesn't allow for its removal, we might be
  6470. able to optimise the mask for the "shl/and" version, which
  6471. may permit other peephole optimisations }
  6472. {$ifdef DEBUG_AOPTCPU}
  6473. mask := taicpu(hp1).oper[0]^.val and mask;
  6474. if taicpu(hp1).oper[0]^.val <> mask then
  6475. begin
  6476. DebugMsg(
  6477. SPeepholeOptimization +
  6478. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6479. ' to $' + debug_tostr(mask) +
  6480. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6481. taicpu(hp1).oper[0]^.val := mask;
  6482. end;
  6483. {$else DEBUG_AOPTCPU}
  6484. { If debugging is off, just set the operand even if it's the same }
  6485. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6486. {$endif DEBUG_AOPTCPU}
  6487. end;
  6488. end;
  6489. {
  6490. change
  6491. shl/sal const,reg
  6492. <op> ...(...,reg,1),...
  6493. into
  6494. <op> ...(...,reg,1 shl const),...
  6495. if const in 1..3
  6496. }
  6497. if MatchOpType(taicpu(p), top_const, top_reg) and
  6498. (taicpu(p).oper[0]^.val in [1..3]) and
  6499. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6500. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6501. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6502. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6503. MatchOpType(taicpu(hp1),top_ref))
  6504. ) and
  6505. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6506. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6507. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6508. begin
  6509. TransferUsedRegs(TmpUsedRegs);
  6510. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6511. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6512. begin
  6513. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6514. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6515. RemoveCurrentP(p);
  6516. Result:=true;
  6517. exit;
  6518. end;
  6519. end;
  6520. if MatchOpType(taicpu(p), top_const, top_reg) and
  6521. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6522. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6523. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6524. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6525. begin
  6526. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6527. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6528. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6529. {$ifdef x86_64}
  6530. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6531. {$endif x86_64}
  6532. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6533. begin
  6534. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6535. taicpu(hp1).opcode:=A_MOV;
  6536. taicpu(hp1).oper[0]^.val:=0;
  6537. end
  6538. else
  6539. begin
  6540. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6541. taicpu(hp1).oper[0]^.val:=shiftval;
  6542. end;
  6543. RemoveCurrentP(p);
  6544. Result:=true;
  6545. exit;
  6546. end;
  6547. end;
  6548. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6549. begin
  6550. case shr_size of
  6551. S_B:
  6552. { No valid combinations }
  6553. Result := False;
  6554. S_W:
  6555. Result := (Shift >= 8) and (movz_size = S_BW);
  6556. S_L:
  6557. Result :=
  6558. (Shift >= 24) { Any opsize is valid for this shift } or
  6559. ((Shift >= 16) and (movz_size = S_WL));
  6560. {$ifdef x86_64}
  6561. S_Q:
  6562. Result :=
  6563. (Shift >= 56) { Any opsize is valid for this shift } or
  6564. ((Shift >= 48) and (movz_size = S_WL));
  6565. {$endif x86_64}
  6566. else
  6567. InternalError(2022081510);
  6568. end;
  6569. end;
  6570. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6571. var
  6572. hp1, hp2: tai;
  6573. Shift: TCGInt;
  6574. LimitSize: Topsize;
  6575. DoNotMerge: Boolean;
  6576. begin
  6577. Result := False;
  6578. { All these optimisations work on "shr const,%reg" }
  6579. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6580. Exit;
  6581. DoNotMerge := False;
  6582. Shift := taicpu(p).oper[0]^.val;
  6583. LimitSize := taicpu(p).opsize;
  6584. hp1 := p;
  6585. repeat
  6586. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6587. Exit;
  6588. case taicpu(hp1).opcode of
  6589. A_TEST, A_CMP, A_Jcc:
  6590. { Skip over conditional jumps and relevant comparisons }
  6591. Continue;
  6592. A_MOVZX:
  6593. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6594. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6595. begin
  6596. { Since the original register is being read as is, subsequent
  6597. SHRs must not be merged at this point }
  6598. DoNotMerge := True;
  6599. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6600. begin
  6601. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6602. begin
  6603. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6604. taicpu(hp1).opcode := A_MOV;
  6605. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6606. case taicpu(hp1).opsize of
  6607. S_BW:
  6608. taicpu(hp1).opsize := S_W;
  6609. S_BL, S_WL:
  6610. taicpu(hp1).opsize := S_L;
  6611. else
  6612. InternalError(2022081503);
  6613. end;
  6614. { p itself hasn't changed, so no need to set Result to True }
  6615. Include(OptsToCheck, aoc_ForceNewIteration);
  6616. { See if there's anything afterwards that can be
  6617. optimised, since the input register hasn't changed }
  6618. Continue;
  6619. end;
  6620. { NOTE: If the MOVZX instruction reads and writes the same
  6621. register, defer this to the post-peephole optimisation stage }
  6622. Exit;
  6623. end;
  6624. end;
  6625. A_SHL, A_SAL, A_SHR:
  6626. if (taicpu(hp1).opsize <= LimitSize) and
  6627. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6628. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6629. begin
  6630. { Make sure the sizes don't exceed the register size limit
  6631. (measured by the shift value falling below the limit) }
  6632. if taicpu(hp1).opsize < LimitSize then
  6633. LimitSize := taicpu(hp1).opsize;
  6634. if taicpu(hp1).opcode = A_SHR then
  6635. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6636. else
  6637. begin
  6638. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6639. DoNotMerge := True;
  6640. end;
  6641. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6642. Exit;
  6643. { Since we've established that the combined shift is within
  6644. limits, we can actually combine the adjacent SHR
  6645. instructions even if they're different sizes }
  6646. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6647. begin
  6648. hp2 := tai(hp1.Previous);
  6649. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6650. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6651. RemoveInstruction(hp1);
  6652. hp1 := hp2;
  6653. { Though p has changed, only the constant has, and its
  6654. effects can still be detected on the next iteration of
  6655. the repeat..until loop }
  6656. Include(OptsToCheck, aoc_ForceNewIteration);
  6657. end;
  6658. { Move onto the next instruction }
  6659. Continue;
  6660. end;
  6661. else
  6662. ;
  6663. end;
  6664. Break;
  6665. until False;
  6666. end;
  6667. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6668. var
  6669. CurrentRef: TReference;
  6670. FullReg: TRegister;
  6671. hp1, hp2: tai;
  6672. begin
  6673. Result := False;
  6674. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6675. Exit;
  6676. { We assume you've checked if the operand is actually a reference by
  6677. this point. If it isn't, you'll most likely get an access violation }
  6678. CurrentRef := first_mov.oper[1]^.ref^;
  6679. { Memory must be aligned }
  6680. if (CurrentRef.offset mod 4) <> 0 then
  6681. Exit;
  6682. Inc(CurrentRef.offset);
  6683. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6684. if MatchOperand(second_mov.oper[0]^, 0) and
  6685. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6686. GetNextInstruction(second_mov, hp1) and
  6687. (hp1.typ = ait_instruction) and
  6688. (taicpu(hp1).opcode = A_MOV) and
  6689. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6690. (taicpu(hp1).oper[0]^.val = 0) then
  6691. begin
  6692. Inc(CurrentRef.offset);
  6693. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6694. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6695. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6696. begin
  6697. case taicpu(hp1).opsize of
  6698. S_B:
  6699. if GetNextInstruction(hp1, hp2) and
  6700. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6701. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6702. (taicpu(hp2).oper[0]^.val = 0) then
  6703. begin
  6704. Inc(CurrentRef.offset);
  6705. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6706. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6707. (taicpu(hp2).opsize = S_B) then
  6708. begin
  6709. RemoveInstruction(hp1);
  6710. RemoveInstruction(hp2);
  6711. first_mov.opsize := S_L;
  6712. if first_mov.oper[0]^.typ = top_reg then
  6713. begin
  6714. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6715. { Reuse second_mov as a MOVZX instruction }
  6716. second_mov.opcode := A_MOVZX;
  6717. second_mov.opsize := S_BL;
  6718. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6719. second_mov.loadreg(1, FullReg);
  6720. first_mov.oper[0]^.reg := FullReg;
  6721. asml.Remove(second_mov);
  6722. asml.InsertBefore(second_mov, first_mov);
  6723. end
  6724. else
  6725. { It's a value }
  6726. begin
  6727. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6728. RemoveInstruction(second_mov);
  6729. end;
  6730. Result := True;
  6731. Exit;
  6732. end;
  6733. end;
  6734. S_W:
  6735. begin
  6736. RemoveInstruction(hp1);
  6737. first_mov.opsize := S_L;
  6738. if first_mov.oper[0]^.typ = top_reg then
  6739. begin
  6740. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6741. { Reuse second_mov as a MOVZX instruction }
  6742. second_mov.opcode := A_MOVZX;
  6743. second_mov.opsize := S_BL;
  6744. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6745. second_mov.loadreg(1, FullReg);
  6746. first_mov.oper[0]^.reg := FullReg;
  6747. asml.Remove(second_mov);
  6748. asml.InsertBefore(second_mov, first_mov);
  6749. end
  6750. else
  6751. { It's a value }
  6752. begin
  6753. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6754. RemoveInstruction(second_mov);
  6755. end;
  6756. Result := True;
  6757. Exit;
  6758. end;
  6759. else
  6760. ;
  6761. end;
  6762. end;
  6763. end;
  6764. end;
  6765. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6766. { returns true if a "continue" should be done after this optimization }
  6767. var
  6768. hp1, hp2, hp3: tai;
  6769. begin
  6770. Result := false;
  6771. hp3 := nil;
  6772. if MatchOpType(taicpu(p),top_ref) and
  6773. GetNextInstruction(p, hp1) and
  6774. (hp1.typ = ait_instruction) and
  6775. (((taicpu(hp1).opcode = A_FLD) and
  6776. (taicpu(p).opcode = A_FSTP)) or
  6777. ((taicpu(p).opcode = A_FISTP) and
  6778. (taicpu(hp1).opcode = A_FILD))) and
  6779. MatchOpType(taicpu(hp1),top_ref) and
  6780. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6781. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6782. begin
  6783. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6784. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6785. GetNextInstruction(hp1, hp2) and
  6786. (((hp2.typ = ait_instruction) and
  6787. IsExitCode(hp2) and
  6788. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6789. not(assigned(current_procinfo.procdef.funcretsym) and
  6790. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6791. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6792. { fstp <temp>
  6793. fld <temp>
  6794. <dealloc> <temp>
  6795. }
  6796. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6797. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6798. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6799. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6800. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6801. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6802. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6803. )
  6804. )
  6805. ) then
  6806. begin
  6807. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6808. RemoveInstruction(hp1);
  6809. RemoveCurrentP(p, hp2);
  6810. { first case: exit code }
  6811. if hp2.typ = ait_instruction then
  6812. RemoveLastDeallocForFuncRes(p);
  6813. Result := true;
  6814. end
  6815. else
  6816. { we can do this only in fast math mode as fstp is rounding ...
  6817. ... still disabled as it breaks the compiler and/or rtl }
  6818. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6819. { ... or if another fstp equal to the first one follows }
  6820. GetNextInstruction(hp1,hp2) and
  6821. (hp2.typ = ait_instruction) and
  6822. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6823. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6824. begin
  6825. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6826. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6827. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6828. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6829. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6830. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6831. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6832. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6833. ) then
  6834. begin
  6835. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6836. RemoveCurrentP(p,hp2);
  6837. RemoveInstruction(hp1);
  6838. Result := true;
  6839. end
  6840. else if { fst can't store an extended/comp value }
  6841. (taicpu(p).opsize <> S_FX) and
  6842. (taicpu(p).opsize <> S_IQ) then
  6843. begin
  6844. if (taicpu(p).opcode = A_FSTP) then
  6845. taicpu(p).opcode := A_FST
  6846. else
  6847. taicpu(p).opcode := A_FIST;
  6848. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6849. RemoveInstruction(hp1);
  6850. Result := true;
  6851. end;
  6852. end;
  6853. end;
  6854. end;
  6855. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6856. var
  6857. hp1, hp2, hp3: tai;
  6858. begin
  6859. result:=false;
  6860. if MatchOpType(taicpu(p),top_reg) and
  6861. GetNextInstruction(p, hp1) and
  6862. (hp1.typ = Ait_Instruction) and
  6863. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6864. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6865. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6866. { change to
  6867. fld reg fxxx reg,st
  6868. fxxxp st, st1 (hp1)
  6869. Remark: non commutative operations must be reversed!
  6870. }
  6871. begin
  6872. case taicpu(hp1).opcode Of
  6873. A_FMULP,A_FADDP,
  6874. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6875. begin
  6876. case taicpu(hp1).opcode Of
  6877. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6878. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6879. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6880. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6881. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6882. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6883. else
  6884. internalerror(2019050534);
  6885. end;
  6886. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6887. taicpu(hp1).oper[1]^.reg := NR_ST;
  6888. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6889. RemoveCurrentP(p, hp1);
  6890. Result:=true;
  6891. exit;
  6892. end;
  6893. else
  6894. ;
  6895. end;
  6896. end
  6897. else
  6898. if MatchOpType(taicpu(p),top_ref) and
  6899. GetNextInstruction(p, hp2) and
  6900. (hp2.typ = Ait_Instruction) and
  6901. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6902. (taicpu(p).opsize in [S_FS, S_FL]) and
  6903. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6904. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6905. if GetLastInstruction(p, hp1) and
  6906. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6907. MatchOpType(taicpu(hp1),top_ref) and
  6908. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6909. if ((taicpu(hp2).opcode = A_FMULP) or
  6910. (taicpu(hp2).opcode = A_FADDP)) then
  6911. { change to
  6912. fld/fst mem1 (hp1) fld/fst mem1
  6913. fld mem1 (p) fadd/
  6914. faddp/ fmul st, st
  6915. fmulp st, st1 (hp2) }
  6916. begin
  6917. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6918. RemoveCurrentP(p, hp1);
  6919. if (taicpu(hp2).opcode = A_FADDP) then
  6920. taicpu(hp2).opcode := A_FADD
  6921. else
  6922. taicpu(hp2).opcode := A_FMUL;
  6923. taicpu(hp2).oper[1]^.reg := NR_ST;
  6924. end
  6925. else
  6926. { change to
  6927. fld/fst mem1 (hp1) fld/fst mem1
  6928. fld mem1 (p) fld st
  6929. }
  6930. begin
  6931. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6932. taicpu(p).changeopsize(S_FL);
  6933. taicpu(p).loadreg(0,NR_ST);
  6934. end
  6935. else
  6936. begin
  6937. case taicpu(hp2).opcode Of
  6938. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6939. { change to
  6940. fld/fst mem1 (hp1) fld/fst mem1
  6941. fld mem2 (p) fxxx mem2
  6942. fxxxp st, st1 (hp2) }
  6943. begin
  6944. case taicpu(hp2).opcode Of
  6945. A_FADDP: taicpu(p).opcode := A_FADD;
  6946. A_FMULP: taicpu(p).opcode := A_FMUL;
  6947. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6948. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6949. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6950. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6951. else
  6952. internalerror(2019050533);
  6953. end;
  6954. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6955. RemoveInstruction(hp2);
  6956. end
  6957. else
  6958. ;
  6959. end
  6960. end
  6961. end;
  6962. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6963. begin
  6964. Result := condition_in(cond1, cond2) or
  6965. { Not strictly subsets due to the actual flags checked, but because we're
  6966. comparing integers, E is a subset of AE and GE and their aliases }
  6967. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6968. end;
  6969. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6970. var
  6971. v: TCGInt;
  6972. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6973. FirstMatch, TempBool: Boolean;
  6974. NewReg: TRegister;
  6975. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6976. begin
  6977. Result:=false;
  6978. { All these optimisations need a next instruction }
  6979. if not GetNextInstruction(p, hp1) then
  6980. Exit;
  6981. { Search for:
  6982. cmp ###,###
  6983. j(c1) @lbl1
  6984. ...
  6985. @lbl:
  6986. cmp ###,### (same comparison as above)
  6987. j(c2) @lbl2
  6988. If c1 is a subset of c2, change to:
  6989. cmp ###,###
  6990. j(c1) @lbl2
  6991. (@lbl1 may become a dead label as a result)
  6992. }
  6993. { Also handle cases where there are multiple jumps in a row }
  6994. p_jump := hp1;
  6995. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6996. begin
  6997. if IsJumpToLabel(taicpu(p_jump)) then
  6998. begin
  6999. { Do jump optimisations first in case the condition becomes
  7000. unnecessary }
  7001. TempBool := True;
  7002. if DoJumpOptimizations(p_jump, TempBool) or
  7003. not TempBool then
  7004. begin
  7005. if Assigned(p_jump) then
  7006. begin
  7007. hp1 := p_jump;
  7008. if (p_jump.typ in [ait_align]) then
  7009. SkipAligns(p_jump, p_jump);
  7010. { CollapseZeroDistJump will be set to the label after the
  7011. jump if it optimises, whether or not it's live or dead }
  7012. if (p_jump.typ in [ait_label]) and
  7013. not (tai_label(p_jump).labsym.is_used) then
  7014. GetNextInstruction(p_jump, p_jump);
  7015. end;
  7016. TransferUsedRegs(TmpUsedRegs);
  7017. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7018. if not Assigned(p_jump) or
  7019. (
  7020. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7021. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7022. ) then
  7023. begin
  7024. { No more conditional jumps; conditional statement is no longer required }
  7025. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7026. RemoveCurrentP(p);
  7027. Result := True;
  7028. Exit;
  7029. end;
  7030. hp1 := p_jump;
  7031. Include(OptsToCheck, aoc_ForceNewIteration);
  7032. Continue;
  7033. end;
  7034. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7035. if GetNextInstruction(p_jump, hp2) and
  7036. (
  7037. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7038. not TempBool
  7039. ) then
  7040. begin
  7041. hp1 := p_jump;
  7042. Include(OptsToCheck, aoc_ForceNewIteration);
  7043. Continue;
  7044. end;
  7045. p_label := nil;
  7046. if Assigned(JumpLabel) then
  7047. p_label := getlabelwithsym(JumpLabel);
  7048. if Assigned(p_label) and
  7049. GetNextInstruction(p_label, p_dist) and
  7050. MatchInstruction(p_dist, A_CMP, []) and
  7051. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7052. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7053. GetNextInstruction(p_dist, hp1_dist) and
  7054. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7055. begin
  7056. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7057. if JumpLabel = JumpLabel_dist then
  7058. { This is an infinite loop }
  7059. Exit;
  7060. { Best optimisation when the first condition is a subset (or equal) of the second }
  7061. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7062. begin
  7063. { Any registers used here will already be allocated }
  7064. if Assigned(JumpLabel) then
  7065. JumpLabel.DecRefs;
  7066. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7067. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7068. Result := True;
  7069. { Don't exit yet. Since p and p_jump haven't actually been
  7070. removed, we can check for more on this iteration }
  7071. end
  7072. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7073. GetNextInstruction(hp1_dist, hp1_label) and
  7074. SkipAligns(hp1_label, hp1_label) and
  7075. (hp1_label.typ = ait_label) then
  7076. begin
  7077. JumpLabel_far := tai_label(hp1_label).labsym;
  7078. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7079. { This is an infinite loop }
  7080. Exit;
  7081. if Assigned(JumpLabel_far) then
  7082. begin
  7083. { In this situation, if the first jump branches, the second one will never,
  7084. branch so change the destination label to after the second jump }
  7085. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7086. if Assigned(JumpLabel) then
  7087. JumpLabel.DecRefs;
  7088. JumpLabel_far.IncRefs;
  7089. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7090. Result := True;
  7091. { Don't exit yet. Since p and p_jump haven't actually been
  7092. removed, we can check for more on this iteration }
  7093. Continue;
  7094. end;
  7095. end;
  7096. end;
  7097. end;
  7098. { Search for:
  7099. cmp ###,###
  7100. j(c1) @lbl1
  7101. cmp ###,### (same as first)
  7102. Remove second cmp
  7103. }
  7104. if GetNextInstruction(p_jump, hp2) and
  7105. (
  7106. (
  7107. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7108. (
  7109. (
  7110. MatchOpType(taicpu(p), top_const, top_reg) and
  7111. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7112. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7113. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7114. ) or (
  7115. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7116. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7117. )
  7118. )
  7119. ) or (
  7120. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7121. MatchOperand(taicpu(p).oper[0]^, 0) and
  7122. (taicpu(p).oper[1]^.typ = top_reg) and
  7123. MatchInstruction(hp2, A_TEST, []) and
  7124. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7125. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7126. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7127. )
  7128. ) then
  7129. begin
  7130. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7131. RemoveInstruction(hp2);
  7132. Result := True;
  7133. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7134. end;
  7135. GetNextInstruction(p_jump, p_jump);
  7136. end;
  7137. if (
  7138. { Don't call GetNextInstruction again if we already have it }
  7139. (hp1 = p_jump) or
  7140. GetNextInstruction(p, hp1)
  7141. ) and
  7142. MatchInstruction(hp1, A_Jcc, []) and
  7143. IsJumpToLabel(taicpu(hp1)) and
  7144. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7145. GetNextInstruction(hp1, hp2) then
  7146. begin
  7147. {
  7148. cmp x, y (or "cmp y, x")
  7149. je @lbl
  7150. mov x, y
  7151. @lbl:
  7152. (x and y can be constants, registers or references)
  7153. Change to:
  7154. mov x, y (x and y will always be equal in the end)
  7155. @lbl: (may beceome a dead label)
  7156. Also:
  7157. cmp x, y (or "cmp y, x")
  7158. jne @lbl
  7159. mov x, y
  7160. @lbl:
  7161. (x and y can be constants, registers or references)
  7162. Change to:
  7163. Absolutely nothing! (Except @lbl if it's still live)
  7164. }
  7165. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7166. (
  7167. (
  7168. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7169. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7170. ) or (
  7171. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7172. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7173. )
  7174. ) and
  7175. GetNextInstruction(hp2, hp1_label) and
  7176. SkipAligns(hp1_label, hp1_label) and
  7177. (hp1_label.typ = ait_label) and
  7178. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7179. begin
  7180. tai_label(hp1_label).labsym.DecRefs;
  7181. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7182. begin
  7183. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7184. RemoveInstruction(hp2);
  7185. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7186. end
  7187. else
  7188. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7189. RemoveInstruction(hp1);
  7190. RemoveCurrentp(p, hp2);
  7191. Result := True;
  7192. Exit;
  7193. end;
  7194. {
  7195. Try to optimise the following:
  7196. cmp $x,### ($x and $y can be registers or constants)
  7197. je @lbl1 (only reference)
  7198. cmp $y,### (### are identical)
  7199. @Lbl:
  7200. sete %reg1
  7201. Change to:
  7202. cmp $x,###
  7203. sete %reg2 (allocate new %reg2)
  7204. cmp $y,###
  7205. sete %reg1
  7206. orb %reg2,%reg1
  7207. (dealloc %reg2)
  7208. This adds an instruction (so don't perform under -Os), but it removes
  7209. a conditional branch.
  7210. }
  7211. if not (cs_opt_size in current_settings.optimizerswitches) and
  7212. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7213. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7214. { The first operand of CMP instructions can only be a register or
  7215. immediate anyway, so no need to check }
  7216. GetNextInstruction(hp2, p_label) and
  7217. (p_label.typ = ait_label) and
  7218. (tai_label(p_label).labsym.getrefs = 1) and
  7219. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7220. GetNextInstruction(p_label, p_dist) and
  7221. MatchInstruction(p_dist, A_SETcc, []) and
  7222. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7223. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7224. begin
  7225. TransferUsedRegs(TmpUsedRegs);
  7226. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7227. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7228. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7229. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7230. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7231. { Get the instruction after the SETcc instruction so we can
  7232. allocate a new register over the entire range }
  7233. GetNextInstruction(p_dist, hp1_dist) then
  7234. begin
  7235. { Register can appear in p if it's not used afterwards, so only
  7236. allocate between hp1 and hp1_dist }
  7237. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7238. if NewReg <> NR_NO then
  7239. begin
  7240. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7241. { Change the jump instruction into a SETcc instruction }
  7242. taicpu(hp1).opcode := A_SETcc;
  7243. taicpu(hp1).opsize := S_B;
  7244. taicpu(hp1).loadreg(0, NewReg);
  7245. { This is now a dead label }
  7246. tai_label(p_label).labsym.decrefs;
  7247. { Prefer adding before the next instruction so the FLAGS
  7248. register is deallicated first }
  7249. AsmL.InsertBefore(
  7250. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7251. hp1_dist
  7252. );
  7253. Result := True;
  7254. { Don't exit yet, as p wasn't changed and hp1, while
  7255. modified, is still intact and might be optimised by the
  7256. SETcc optimisation below }
  7257. end;
  7258. end;
  7259. end;
  7260. end;
  7261. if taicpu(p).oper[0]^.typ = top_const then
  7262. begin
  7263. if (taicpu(p).oper[0]^.val = 0) and
  7264. (taicpu(p).oper[1]^.typ = top_reg) and
  7265. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7266. begin
  7267. hp2 := p;
  7268. FirstMatch := True;
  7269. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7270. anything meaningful once it's converted to "test %reg,%reg";
  7271. additionally, some jumps will always (or never) branch, so
  7272. evaluate every jump immediately following the
  7273. comparison, optimising the conditions if possible.
  7274. Similarly with SETcc... those that are always set to 0 or 1
  7275. are changed to MOV instructions }
  7276. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7277. (
  7278. GetNextInstruction(hp2, hp1) and
  7279. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7280. ) do
  7281. begin
  7282. FirstMatch := False;
  7283. case taicpu(hp1).condition of
  7284. C_B, C_C, C_NAE, C_O:
  7285. { For B/NAE:
  7286. Will never branch since an unsigned integer can never be below zero
  7287. For C/O:
  7288. Result cannot overflow because 0 is being subtracted
  7289. }
  7290. begin
  7291. if taicpu(hp1).opcode = A_Jcc then
  7292. begin
  7293. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7294. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7295. RemoveInstruction(hp1);
  7296. { Since hp1 was deleted, hp2 must not be updated }
  7297. Continue;
  7298. end
  7299. else
  7300. begin
  7301. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7302. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7303. taicpu(hp1).opcode := A_MOV;
  7304. taicpu(hp1).ops := 2;
  7305. taicpu(hp1).condition := C_None;
  7306. taicpu(hp1).opsize := S_B;
  7307. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7308. taicpu(hp1).loadconst(0, 0);
  7309. end;
  7310. end;
  7311. C_BE, C_NA:
  7312. begin
  7313. { Will only branch if equal to zero }
  7314. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7315. taicpu(hp1).condition := C_E;
  7316. end;
  7317. C_A, C_NBE:
  7318. begin
  7319. { Will only branch if not equal to zero }
  7320. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7321. taicpu(hp1).condition := C_NE;
  7322. end;
  7323. C_AE, C_NB, C_NC, C_NO:
  7324. begin
  7325. { Will always branch }
  7326. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7327. if taicpu(hp1).opcode = A_Jcc then
  7328. begin
  7329. MakeUnconditional(taicpu(hp1));
  7330. { Any jumps/set that follow will now be dead code }
  7331. RemoveDeadCodeAfterJump(taicpu(hp1));
  7332. Break;
  7333. end
  7334. else
  7335. begin
  7336. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7337. taicpu(hp1).opcode := A_MOV;
  7338. taicpu(hp1).ops := 2;
  7339. taicpu(hp1).condition := C_None;
  7340. taicpu(hp1).opsize := S_B;
  7341. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7342. taicpu(hp1).loadconst(0, 1);
  7343. end;
  7344. end;
  7345. C_None:
  7346. InternalError(2020012201);
  7347. C_P, C_PE, C_NP, C_PO:
  7348. { We can't handle parity checks and they should never be generated
  7349. after a general-purpose CMP (it's used in some floating-point
  7350. comparisons that don't use CMP) }
  7351. InternalError(2020012202);
  7352. else
  7353. { Zero/Equality, Sign, their complements and all of the
  7354. signed comparisons do not need to be converted };
  7355. end;
  7356. hp2 := hp1;
  7357. end;
  7358. { Convert the instruction to a TEST }
  7359. taicpu(p).opcode := A_TEST;
  7360. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7361. Result := True;
  7362. Exit;
  7363. end
  7364. else if (taicpu(p).oper[0]^.val = 1) and
  7365. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7366. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7367. begin
  7368. { Convert; To:
  7369. cmp $1,r/m cmp $0,r/m
  7370. jl @lbl jle @lbl
  7371. (Also do inverted conditions)
  7372. }
  7373. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7374. taicpu(p).oper[0]^.val := 0;
  7375. if taicpu(hp1).condition in [C_L, C_NGE] then
  7376. taicpu(hp1).condition := C_LE
  7377. else
  7378. taicpu(hp1).condition := C_NLE;
  7379. { If the instruction is now "cmp $0,%reg", convert it to a
  7380. TEST (and effectively do the work of the "cmp $0,%reg" in
  7381. the block above)
  7382. }
  7383. if (taicpu(p).oper[1]^.typ = top_reg) then
  7384. begin
  7385. taicpu(p).opcode := A_TEST;
  7386. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7387. end;
  7388. Result := True;
  7389. Exit;
  7390. end
  7391. else if (taicpu(p).oper[1]^.typ = top_reg)
  7392. {$ifdef x86_64}
  7393. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7394. {$endif x86_64}
  7395. then
  7396. begin
  7397. { cmp register,$8000 neg register
  7398. je target --> jo target
  7399. .... only if register is deallocated before jump.}
  7400. case Taicpu(p).opsize of
  7401. S_B: v:=$80;
  7402. S_W: v:=$8000;
  7403. S_L: v:=qword($80000000);
  7404. else
  7405. internalerror(2013112905);
  7406. end;
  7407. if (taicpu(p).oper[0]^.val=v) and
  7408. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7409. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7410. begin
  7411. TransferUsedRegs(TmpUsedRegs);
  7412. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7413. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7414. begin
  7415. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7416. Taicpu(p).opcode:=A_NEG;
  7417. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7418. Taicpu(p).clearop(1);
  7419. Taicpu(p).ops:=1;
  7420. if Taicpu(hp1).condition=C_E then
  7421. Taicpu(hp1).condition:=C_O
  7422. else
  7423. Taicpu(hp1).condition:=C_NO;
  7424. Result:=true;
  7425. exit;
  7426. end;
  7427. end;
  7428. end;
  7429. end;
  7430. if TrySwapMovCmp(p, hp1) then
  7431. begin
  7432. Result := True;
  7433. Exit;
  7434. end;
  7435. end;
  7436. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7437. var
  7438. hp1: tai;
  7439. begin
  7440. {
  7441. remove the second (v)pxor from
  7442. pxor reg,reg
  7443. ...
  7444. pxor reg,reg
  7445. }
  7446. Result:=false;
  7447. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7448. MatchOpType(taicpu(p),top_reg,top_reg) and
  7449. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7450. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7451. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7452. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7453. begin
  7454. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7455. RemoveInstruction(hp1);
  7456. Result:=true;
  7457. Exit;
  7458. end
  7459. {
  7460. replace
  7461. pxor reg1,reg1
  7462. movapd/s reg1,reg2
  7463. dealloc reg1
  7464. by
  7465. pxor reg2,reg2
  7466. }
  7467. else if GetNextInstruction(p,hp1) and
  7468. { we mix single and double opperations here because we assume that the compiler
  7469. generates vmovapd only after double operations and vmovaps only after single operations }
  7470. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7471. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7472. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7473. (taicpu(p).oper[0]^.typ=top_reg) then
  7474. begin
  7475. TransferUsedRegs(TmpUsedRegs);
  7476. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7477. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7478. begin
  7479. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7480. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7481. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7482. RemoveInstruction(hp1);
  7483. result:=true;
  7484. end;
  7485. end;
  7486. end;
  7487. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7488. var
  7489. hp1: tai;
  7490. begin
  7491. {
  7492. remove the second (v)pxor from
  7493. (v)pxor reg,reg
  7494. ...
  7495. (v)pxor reg,reg
  7496. }
  7497. Result:=false;
  7498. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7499. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7500. begin
  7501. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7502. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7503. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7504. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7505. begin
  7506. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7507. RemoveInstruction(hp1);
  7508. Result:=true;
  7509. Exit;
  7510. end;
  7511. {$ifdef x86_64}
  7512. {
  7513. replace
  7514. vpxor reg1,reg1,reg1
  7515. vmov reg,mem
  7516. by
  7517. movq $0,mem
  7518. }
  7519. if GetNextInstruction(p,hp1) and
  7520. MatchInstruction(hp1,A_VMOVSD,[]) and
  7521. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7522. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7523. begin
  7524. TransferUsedRegs(TmpUsedRegs);
  7525. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7526. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7527. begin
  7528. taicpu(hp1).loadconst(0,0);
  7529. taicpu(hp1).opcode:=A_MOV;
  7530. taicpu(hp1).opsize:=S_Q;
  7531. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7532. RemoveCurrentP(p);
  7533. result:=true;
  7534. Exit;
  7535. end;
  7536. end;
  7537. {$endif x86_64}
  7538. end
  7539. {
  7540. replace
  7541. vpxor reg1,reg1,reg2
  7542. by
  7543. vpxor reg2,reg2,reg2
  7544. to avoid unncessary data dependencies
  7545. }
  7546. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7547. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7548. begin
  7549. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7550. { avoid unncessary data dependency }
  7551. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7552. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7553. result:=true;
  7554. exit;
  7555. end;
  7556. Result:=OptPass1VOP(p);
  7557. end;
  7558. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7559. var
  7560. hp1 : tai;
  7561. begin
  7562. result:=false;
  7563. { replace
  7564. IMul const,%mreg1,%mreg2
  7565. Mov %reg2,%mreg3
  7566. dealloc %mreg3
  7567. by
  7568. Imul const,%mreg1,%mreg23
  7569. }
  7570. if (taicpu(p).ops=3) and
  7571. GetNextInstruction(p,hp1) and
  7572. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7573. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7574. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7575. begin
  7576. TransferUsedRegs(TmpUsedRegs);
  7577. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7578. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7579. begin
  7580. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7581. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7582. RemoveInstruction(hp1);
  7583. result:=true;
  7584. end;
  7585. end;
  7586. end;
  7587. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7588. var
  7589. hp1 : tai;
  7590. begin
  7591. result:=false;
  7592. { replace
  7593. IMul %reg0,%reg1,%reg2
  7594. Mov %reg2,%reg3
  7595. dealloc %reg2
  7596. by
  7597. Imul %reg0,%reg1,%reg3
  7598. }
  7599. if GetNextInstruction(p,hp1) and
  7600. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7601. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7602. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7603. begin
  7604. TransferUsedRegs(TmpUsedRegs);
  7605. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7606. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7607. begin
  7608. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7609. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7610. RemoveInstruction(hp1);
  7611. result:=true;
  7612. end;
  7613. end;
  7614. end;
  7615. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7616. var
  7617. hp1: tai;
  7618. begin
  7619. Result:=false;
  7620. { get rid of
  7621. (v)cvtss2sd reg0,<reg1,>reg2
  7622. (v)cvtss2sd reg2,<reg2,>reg0
  7623. }
  7624. if GetNextInstruction(p,hp1) and
  7625. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7626. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7627. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7628. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7629. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7630. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7631. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7632. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7633. )
  7634. ) then
  7635. begin
  7636. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7637. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7638. begin
  7639. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7640. RemoveCurrentP(p);
  7641. RemoveInstruction(hp1);
  7642. end
  7643. else
  7644. begin
  7645. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7646. if taicpu(hp1).opcode=A_CVTSD2SS then
  7647. begin
  7648. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7649. taicpu(p).opcode:=A_MOVAPS;
  7650. end
  7651. else
  7652. begin
  7653. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7654. taicpu(p).opcode:=A_VMOVAPS;
  7655. end;
  7656. taicpu(p).ops:=2;
  7657. RemoveInstruction(hp1);
  7658. end;
  7659. Result:=true;
  7660. Exit;
  7661. end;
  7662. end;
  7663. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7664. var
  7665. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7666. ThisReg: TRegister;
  7667. begin
  7668. Result := False;
  7669. if not GetNextInstruction(p,hp1) then
  7670. Exit;
  7671. {
  7672. convert
  7673. j<c> .L1
  7674. mov 1,reg
  7675. jmp .L2
  7676. .L1
  7677. mov 0,reg
  7678. .L2
  7679. into
  7680. mov 0,reg
  7681. set<not(c)> reg
  7682. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7683. would destroy the flag contents
  7684. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7685. executed at the same time as a previous comparison.
  7686. set<not(c)> reg
  7687. movzx reg, reg
  7688. }
  7689. if MatchInstruction(hp1,A_MOV,[]) and
  7690. (taicpu(hp1).oper[0]^.typ = top_const) and
  7691. (
  7692. (
  7693. (taicpu(hp1).oper[1]^.typ = top_reg)
  7694. {$ifdef i386}
  7695. { Under i386, ESI, EDI, EBP and ESP
  7696. don't have an 8-bit representation }
  7697. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7698. {$endif i386}
  7699. ) or (
  7700. {$ifdef i386}
  7701. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7702. {$endif i386}
  7703. (taicpu(hp1).opsize = S_B)
  7704. )
  7705. ) and
  7706. GetNextInstruction(hp1,hp2) and
  7707. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7708. GetNextInstruction(hp2,hp3) and
  7709. SkipAligns(hp3, hp3) and
  7710. (hp3.typ=ait_label) and
  7711. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7712. GetNextInstruction(hp3,hp4) and
  7713. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7714. (taicpu(hp4).oper[0]^.typ = top_const) and
  7715. (
  7716. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7717. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7718. ) and
  7719. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7720. GetNextInstruction(hp4,hp5) and
  7721. SkipAligns(hp5, hp5) and
  7722. (hp5.typ=ait_label) and
  7723. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7724. begin
  7725. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7726. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7727. tai_label(hp3).labsym.DecRefs;
  7728. { If this isn't the only reference to the middle label, we can
  7729. still make a saving - only that the first jump and everything
  7730. that follows will remain. }
  7731. if (tai_label(hp3).labsym.getrefs = 0) then
  7732. begin
  7733. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7734. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7735. else
  7736. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7737. { remove jump, first label and second MOV (also catching any aligns) }
  7738. repeat
  7739. if not GetNextInstruction(hp2, hp3) then
  7740. InternalError(2021040810);
  7741. RemoveInstruction(hp2);
  7742. hp2 := hp3;
  7743. until hp2 = hp5;
  7744. { Don't decrement reference count before the removal loop
  7745. above, otherwise GetNextInstruction won't stop on the
  7746. the label }
  7747. tai_label(hp5).labsym.DecRefs;
  7748. end
  7749. else
  7750. begin
  7751. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7752. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7753. else
  7754. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7755. end;
  7756. taicpu(p).opcode:=A_SETcc;
  7757. taicpu(p).opsize:=S_B;
  7758. taicpu(p).is_jmp:=False;
  7759. if taicpu(hp1).opsize=S_B then
  7760. begin
  7761. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7762. if taicpu(hp1).oper[1]^.typ = top_reg then
  7763. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7764. RemoveInstruction(hp1);
  7765. end
  7766. else
  7767. begin
  7768. { Will be a register because the size can't be S_B otherwise }
  7769. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7770. taicpu(p).loadreg(0, ThisReg);
  7771. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7772. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7773. begin
  7774. case taicpu(hp1).opsize of
  7775. S_W:
  7776. taicpu(hp1).opsize := S_BW;
  7777. S_L:
  7778. taicpu(hp1).opsize := S_BL;
  7779. {$ifdef x86_64}
  7780. S_Q:
  7781. begin
  7782. taicpu(hp1).opsize := S_BL;
  7783. { Change the destination register to 32-bit }
  7784. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7785. end;
  7786. {$endif x86_64}
  7787. else
  7788. InternalError(2021040820);
  7789. end;
  7790. taicpu(hp1).opcode := A_MOVZX;
  7791. taicpu(hp1).loadreg(0, ThisReg);
  7792. end
  7793. else
  7794. begin
  7795. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7796. { hp1 is already a MOV instruction with the correct register }
  7797. taicpu(hp1).loadconst(0, 0);
  7798. { Inserting it right before p will guarantee that the flags are also tracked }
  7799. asml.Remove(hp1);
  7800. asml.InsertBefore(hp1, p);
  7801. end;
  7802. end;
  7803. Result:=true;
  7804. exit;
  7805. end
  7806. else if (hp1.typ = ait_label) then
  7807. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7808. end;
  7809. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7810. var
  7811. hp1, hp2, hp3: tai;
  7812. SourceRef, TargetRef: TReference;
  7813. CurrentReg: TRegister;
  7814. begin
  7815. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7816. if not UseAVX then
  7817. InternalError(2021100501);
  7818. Result := False;
  7819. { Look for the following to simplify:
  7820. vmovdqa/u x(mem1), %xmmreg
  7821. vmovdqa/u %xmmreg, y(mem2)
  7822. vmovdqa/u x+16(mem1), %xmmreg
  7823. vmovdqa/u %xmmreg, y+16(mem2)
  7824. Change to:
  7825. vmovdqa/u x(mem1), %ymmreg
  7826. vmovdqa/u %ymmreg, y(mem2)
  7827. vpxor %ymmreg, %ymmreg, %ymmreg
  7828. ( The VPXOR instruction is to zero the upper half, thus removing the
  7829. need to call the potentially expensive VZEROUPPER instruction. Other
  7830. peephole optimisations can remove VPXOR if it's unnecessary )
  7831. }
  7832. TransferUsedRegs(TmpUsedRegs);
  7833. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7834. { NOTE: In the optimisations below, if the references dictate that an
  7835. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7836. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7837. if (taicpu(p).opsize = S_XMM) and
  7838. MatchOpType(taicpu(p), top_ref, top_reg) and
  7839. GetNextInstruction(p, hp1) and
  7840. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7841. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7842. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7843. begin
  7844. SourceRef := taicpu(p).oper[0]^.ref^;
  7845. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7846. if GetNextInstruction(hp1, hp2) and
  7847. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7848. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7849. begin
  7850. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7852. Inc(SourceRef.offset, 16);
  7853. { Reuse the register in the first block move }
  7854. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7855. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7856. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7857. begin
  7858. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7859. Inc(TargetRef.offset, 16);
  7860. if GetNextInstruction(hp2, hp3) and
  7861. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7862. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7863. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7864. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7865. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7866. begin
  7867. { Update the register tracking to the new size }
  7868. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7869. { Remember that the offsets are 16 ahead }
  7870. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7871. if not (
  7872. ((SourceRef.offset mod 32) = 16) and
  7873. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7874. ) then
  7875. taicpu(p).opcode := A_VMOVDQU;
  7876. taicpu(p).opsize := S_YMM;
  7877. taicpu(p).oper[1]^.reg := CurrentReg;
  7878. if not (
  7879. ((TargetRef.offset mod 32) = 16) and
  7880. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7881. ) then
  7882. taicpu(hp1).opcode := A_VMOVDQU;
  7883. taicpu(hp1).opsize := S_YMM;
  7884. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7885. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7886. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7887. if (pi_uses_ymm in current_procinfo.flags) then
  7888. RemoveInstruction(hp2)
  7889. else
  7890. begin
  7891. taicpu(hp2).opcode := A_VPXOR;
  7892. taicpu(hp2).opsize := S_YMM;
  7893. taicpu(hp2).loadreg(0, CurrentReg);
  7894. taicpu(hp2).loadreg(1, CurrentReg);
  7895. taicpu(hp2).loadreg(2, CurrentReg);
  7896. taicpu(hp2).ops := 3;
  7897. end;
  7898. RemoveInstruction(hp3);
  7899. Result := True;
  7900. Exit;
  7901. end;
  7902. end
  7903. else
  7904. begin
  7905. { See if the next references are 16 less rather than 16 greater }
  7906. Dec(SourceRef.offset, 32); { -16 the other way }
  7907. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7908. begin
  7909. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7910. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7911. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7912. GetNextInstruction(hp2, hp3) and
  7913. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7914. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7915. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7916. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7917. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7918. begin
  7919. { Update the register tracking to the new size }
  7920. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7921. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7922. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7923. if not(
  7924. ((SourceRef.offset mod 32) = 0) and
  7925. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7926. ) then
  7927. taicpu(hp2).opcode := A_VMOVDQU;
  7928. taicpu(hp2).opsize := S_YMM;
  7929. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7930. if not (
  7931. ((TargetRef.offset mod 32) = 0) and
  7932. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7933. ) then
  7934. taicpu(hp3).opcode := A_VMOVDQU;
  7935. taicpu(hp3).opsize := S_YMM;
  7936. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7937. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7938. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7939. if (pi_uses_ymm in current_procinfo.flags) then
  7940. RemoveInstruction(hp1)
  7941. else
  7942. begin
  7943. taicpu(hp1).opcode := A_VPXOR;
  7944. taicpu(hp1).opsize := S_YMM;
  7945. taicpu(hp1).loadreg(0, CurrentReg);
  7946. taicpu(hp1).loadreg(1, CurrentReg);
  7947. taicpu(hp1).loadreg(2, CurrentReg);
  7948. taicpu(hp1).ops := 3;
  7949. Asml.Remove(hp1);
  7950. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7951. end;
  7952. RemoveCurrentP(p, hp2);
  7953. Result := True;
  7954. Exit;
  7955. end;
  7956. end;
  7957. end;
  7958. end;
  7959. end;
  7960. end;
  7961. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7962. var
  7963. hp2, hp3, first_assignment: tai;
  7964. IncCount, OperIdx: Integer;
  7965. OrigLabel: TAsmLabel;
  7966. begin
  7967. Count := 0;
  7968. Result := False;
  7969. first_assignment := nil;
  7970. if (LoopCount >= 20) then
  7971. begin
  7972. { Guard against infinite loops }
  7973. Exit;
  7974. end;
  7975. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7976. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7977. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7978. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7979. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7980. Exit;
  7981. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7982. {
  7983. change
  7984. jmp .L1
  7985. ...
  7986. .L1:
  7987. mov ##, ## ( multiple movs possible )
  7988. jmp/ret
  7989. into
  7990. mov ##, ##
  7991. jmp/ret
  7992. }
  7993. if not Assigned(hp1) then
  7994. begin
  7995. hp1 := GetLabelWithSym(OrigLabel);
  7996. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7997. Exit;
  7998. end;
  7999. hp2 := hp1;
  8000. while Assigned(hp2) do
  8001. begin
  8002. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8003. SkipLabels(hp2,hp2);
  8004. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8005. Break;
  8006. case taicpu(hp2).opcode of
  8007. A_MOVSD:
  8008. begin
  8009. if taicpu(hp2).ops = 0 then
  8010. { Wrong MOVSD }
  8011. Break;
  8012. Inc(Count);
  8013. if Count >= 5 then
  8014. { Too many to be worthwhile }
  8015. Break;
  8016. GetNextInstruction(hp2, hp2);
  8017. Continue;
  8018. end;
  8019. A_MOV,
  8020. A_MOVD,
  8021. A_MOVQ,
  8022. A_MOVSX,
  8023. {$ifdef x86_64}
  8024. A_MOVSXD,
  8025. {$endif x86_64}
  8026. A_MOVZX,
  8027. A_MOVAPS,
  8028. A_MOVUPS,
  8029. A_MOVSS,
  8030. A_MOVAPD,
  8031. A_MOVUPD,
  8032. A_MOVDQA,
  8033. A_MOVDQU,
  8034. A_VMOVSS,
  8035. A_VMOVAPS,
  8036. A_VMOVUPS,
  8037. A_VMOVSD,
  8038. A_VMOVAPD,
  8039. A_VMOVUPD,
  8040. A_VMOVDQA,
  8041. A_VMOVDQU:
  8042. begin
  8043. Inc(Count);
  8044. if Count >= 5 then
  8045. { Too many to be worthwhile }
  8046. Break;
  8047. GetNextInstruction(hp2, hp2);
  8048. Continue;
  8049. end;
  8050. A_JMP:
  8051. begin
  8052. { Guard against infinite loops }
  8053. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8054. Exit;
  8055. { Analyse this jump first in case it also duplicates assignments }
  8056. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8057. begin
  8058. { Something did change! }
  8059. Result := True;
  8060. Inc(Count, IncCount);
  8061. if Count >= 5 then
  8062. begin
  8063. { Too many to be worthwhile }
  8064. Exit;
  8065. end;
  8066. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8067. Break;
  8068. end;
  8069. Result := True;
  8070. Break;
  8071. end;
  8072. A_RET:
  8073. begin
  8074. Result := True;
  8075. Break;
  8076. end;
  8077. else
  8078. Break;
  8079. end;
  8080. end;
  8081. if Result then
  8082. begin
  8083. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8084. if Count = 0 then
  8085. begin
  8086. Result := False;
  8087. Exit;
  8088. end;
  8089. hp3 := p;
  8090. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8091. while True do
  8092. begin
  8093. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8094. SkipLabels(hp1,hp1);
  8095. if (hp1.typ <> ait_instruction) then
  8096. InternalError(2021040720);
  8097. case taicpu(hp1).opcode of
  8098. A_JMP:
  8099. begin
  8100. { Change the original jump to the new destination }
  8101. OrigLabel.decrefs;
  8102. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8103. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8104. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8105. if not Assigned(first_assignment) then
  8106. InternalError(2021040810)
  8107. else
  8108. p := first_assignment;
  8109. Exit;
  8110. end;
  8111. A_RET:
  8112. begin
  8113. { Now change the jump into a RET instruction }
  8114. ConvertJumpToRET(p, hp1);
  8115. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8116. if not Assigned(first_assignment) then
  8117. InternalError(2021040811)
  8118. else
  8119. p := first_assignment;
  8120. Exit;
  8121. end;
  8122. else
  8123. begin
  8124. { Duplicate the MOV instruction }
  8125. hp3:=tai(hp1.getcopy);
  8126. if first_assignment = nil then
  8127. first_assignment := hp3;
  8128. asml.InsertBefore(hp3, p);
  8129. { Make sure the compiler knows about any final registers written here }
  8130. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8131. with taicpu(hp3).oper[OperIdx]^ do
  8132. begin
  8133. case typ of
  8134. top_ref:
  8135. begin
  8136. if (ref^.base <> NR_NO) and
  8137. (getsupreg(ref^.base) <> RS_ESP) and
  8138. (getsupreg(ref^.base) <> RS_EBP)
  8139. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8140. then
  8141. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8142. if (ref^.index <> NR_NO) and
  8143. (getsupreg(ref^.index) <> RS_ESP) and
  8144. (getsupreg(ref^.index) <> RS_EBP)
  8145. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8146. (ref^.index <> ref^.base) then
  8147. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8148. end;
  8149. top_reg:
  8150. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8151. else
  8152. ;
  8153. end;
  8154. end;
  8155. end;
  8156. end;
  8157. if not GetNextInstruction(hp1, hp1) then
  8158. { Should have dropped out earlier }
  8159. InternalError(2021040710);
  8160. end;
  8161. end;
  8162. end;
  8163. const
  8164. WriteOp: array[0..3] of set of TInsChange = (
  8165. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8166. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8167. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8168. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8169. RegWriteFlags: array[0..7] of set of TInsChange = (
  8170. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8171. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8172. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8173. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8174. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8175. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8176. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8177. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8178. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8179. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8180. var
  8181. hp2: tai;
  8182. X: Integer;
  8183. begin
  8184. { If we have something like:
  8185. op ###,###
  8186. mov ###,###
  8187. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8188. interfere in regards to what they write to.
  8189. NOTE: p must be a 2-operand instruction
  8190. }
  8191. Result := False;
  8192. if (hp1.typ <> ait_instruction) or
  8193. taicpu(hp1).is_jmp or
  8194. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8195. Exit;
  8196. { NOP is a pipeline fence, likely marking the beginning of the function
  8197. epilogue, so drop out. Similarly, drop out if POP or RET are
  8198. encountered }
  8199. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8200. Exit;
  8201. if (taicpu(hp1).opcode = A_MOVSD) and
  8202. (taicpu(hp1).ops = 0) then
  8203. { Wrong MOVSD }
  8204. Exit;
  8205. { Check for writes to specific registers first }
  8206. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8207. for X := 0 to 7 do
  8208. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8209. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8210. Exit;
  8211. for X := 0 to taicpu(hp1).ops - 1 do
  8212. begin
  8213. { Check to see if this operand writes to something }
  8214. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8215. { And matches something in the CMP/TEST instruction }
  8216. (
  8217. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8218. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8219. (
  8220. { If it's a register, make sure the register written to doesn't
  8221. appear in the cmp instruction as part of a reference }
  8222. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8223. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8224. )
  8225. ) then
  8226. Exit;
  8227. end;
  8228. { Check p to make sure it doesn't write to something that affects hp1 }
  8229. { Check for writes to specific registers first }
  8230. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8231. for X := 0 to 7 do
  8232. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8233. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8234. Exit;
  8235. for X := 0 to taicpu(p).ops - 1 do
  8236. begin
  8237. { Check to see if this operand writes to something }
  8238. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8239. { And matches something in hp1 }
  8240. (taicpu(p).oper[X]^.typ = top_reg) and
  8241. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8242. Exit;
  8243. end;
  8244. { The instruction can be safely moved }
  8245. asml.Remove(hp1);
  8246. { Try to insert after the last instructions where the FLAGS register is not
  8247. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8248. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8249. asml.InsertBefore(hp1, hp2)
  8250. { Failing that, try to insert after the last instructions where the
  8251. FLAGS register is not yet in use }
  8252. else if GetLastInstruction(p, hp2) and
  8253. (
  8254. (hp2.typ <> ait_instruction) or
  8255. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8256. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8257. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8258. ) then
  8259. asml.InsertAfter(hp1, hp2)
  8260. else
  8261. { Note, if p.Previous is nil (even if it should logically never be the
  8262. case), FindRegAllocBackward immediately exits with False and so we
  8263. safely land here (we can't just pass p because FindRegAllocBackward
  8264. immediately exits on an instruction). [Kit] }
  8265. asml.InsertBefore(hp1, p);
  8266. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8267. { We can't trust UsedRegs because we're looking backwards, although we
  8268. know the registers are allocated after p at the very least, so manually
  8269. create tai_regalloc objects if needed }
  8270. for X := 0 to taicpu(hp1).ops - 1 do
  8271. case taicpu(hp1).oper[X]^.typ of
  8272. top_reg:
  8273. begin
  8274. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8275. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8276. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8277. end;
  8278. top_ref:
  8279. begin
  8280. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8281. begin
  8282. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8283. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8284. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8285. end;
  8286. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8287. begin
  8288. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8289. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8290. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8291. end;
  8292. end;
  8293. else
  8294. ;
  8295. end;
  8296. Result := True;
  8297. end;
  8298. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8299. var
  8300. hp2: tai;
  8301. X: Integer;
  8302. begin
  8303. { If we have something like:
  8304. cmp ###,%reg1
  8305. mov 0,%reg2
  8306. And no modified registers are shared, move the instruction to before
  8307. the comparison as this means it can be optimised without worrying
  8308. about the FLAGS register. (CMP/MOV is generated by
  8309. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8310. As long as the second instruction doesn't use the flags or one of the
  8311. registers used by CMP or TEST (also check any references that use the
  8312. registers), then it can be moved prior to the comparison.
  8313. }
  8314. Result := False;
  8315. if not TrySwapMovOp(p, hp1) then
  8316. Exit;
  8317. if taicpu(hp1).opcode = A_LEA then
  8318. { The flags will be overwritten by the CMP/TEST instruction }
  8319. ConvertLEA(taicpu(hp1));
  8320. Result := True;
  8321. { Can we move it one further back? }
  8322. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8323. { Check to see if CMP/TEST is a comparison against zero }
  8324. (
  8325. (
  8326. (taicpu(p).opcode = A_CMP) and
  8327. MatchOperand(taicpu(p).oper[0]^, 0)
  8328. ) or
  8329. (
  8330. (taicpu(p).opcode = A_TEST) and
  8331. (
  8332. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8333. MatchOperand(taicpu(p).oper[0]^, -1)
  8334. )
  8335. )
  8336. ) and
  8337. { These instructions set the zero flag if the result is zero }
  8338. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8339. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8340. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8341. TrySwapMovOp(hp2, hp1);
  8342. end;
  8343. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8344. function IsXCHGAcceptable: Boolean; inline;
  8345. begin
  8346. { Always accept if optimising for size }
  8347. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8348. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8349. than 3, so it becomes a saving compared to three MOVs with two of
  8350. them able to execute simultaneously. [Kit] }
  8351. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8352. end;
  8353. var
  8354. NewRef: TReference;
  8355. hp1, hp2, hp3, hp4: Tai;
  8356. {$ifndef x86_64}
  8357. OperIdx: Integer;
  8358. {$endif x86_64}
  8359. NewInstr : Taicpu;
  8360. NewAligh : Tai_align;
  8361. DestLabel: TAsmLabel;
  8362. TempTracking: TAllUsedRegs;
  8363. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8364. var
  8365. NextInstr: tai;
  8366. begin
  8367. Result := False;
  8368. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8369. if not GetNextInstruction(InputInstr, NextInstr) or
  8370. (
  8371. { The FLAGS register isn't always tracked properly, so do not
  8372. perform this optimisation if a conditional statement follows }
  8373. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8374. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8375. ) then
  8376. begin
  8377. reference_reset(NewRef, 1, []);
  8378. NewRef.base := taicpu(p).oper[0]^.reg;
  8379. NewRef.scalefactor := 1;
  8380. if taicpu(InputInstr).opcode = A_ADD then
  8381. begin
  8382. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8383. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8384. end
  8385. else
  8386. begin
  8387. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8388. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8389. end;
  8390. taicpu(p).opcode := A_LEA;
  8391. taicpu(p).loadref(0, NewRef);
  8392. RemoveInstruction(InputInstr);
  8393. Result := True;
  8394. end;
  8395. end;
  8396. begin
  8397. Result:=false;
  8398. { This optimisation adds an instruction, so only do it for speed }
  8399. if not (cs_opt_size in current_settings.optimizerswitches) and
  8400. MatchOpType(taicpu(p), top_const, top_reg) and
  8401. (taicpu(p).oper[0]^.val = 0) then
  8402. begin
  8403. { To avoid compiler warning }
  8404. DestLabel := nil;
  8405. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8406. InternalError(2021040750);
  8407. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8408. Exit;
  8409. case hp1.typ of
  8410. ait_align,
  8411. ait_label:
  8412. begin
  8413. { Change:
  8414. mov $0,%reg mov $0,%reg
  8415. @Lbl1: @Lbl1:
  8416. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8417. je @Lbl2 jne @Lbl2
  8418. To: To:
  8419. mov $0,%reg mov $0,%reg
  8420. jmp @Lbl2 jmp @Lbl3
  8421. (align) (align)
  8422. @Lbl1: @Lbl1:
  8423. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8424. je @Lbl2 je @Lbl2
  8425. @Lbl3: <-- Only if label exists
  8426. (Not if it's optimised for size)
  8427. }
  8428. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8429. Exit;
  8430. if (hp2.typ = ait_instruction) and
  8431. (
  8432. { Register sizes must exactly match }
  8433. (
  8434. (taicpu(hp2).opcode = A_CMP) and
  8435. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8436. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8437. ) or (
  8438. (taicpu(hp2).opcode = A_TEST) and
  8439. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8440. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8441. )
  8442. ) and GetNextInstruction(hp2, hp3) and
  8443. (hp3.typ = ait_instruction) and
  8444. (taicpu(hp3).opcode = A_JCC) and
  8445. (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
  8446. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8447. begin
  8448. { Check condition of jump }
  8449. { Always true? }
  8450. if condition_in(C_E, taicpu(hp3).condition) then
  8451. begin
  8452. { Copy label symbol and obtain matching label entry for the
  8453. conditional jump, as this will be our destination}
  8454. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8455. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8456. Result := True;
  8457. end
  8458. { Always false? }
  8459. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8460. begin
  8461. { This is only worth it if there's a jump to take }
  8462. case hp2.typ of
  8463. ait_instruction:
  8464. begin
  8465. if taicpu(hp2).opcode = A_JMP then
  8466. begin
  8467. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8468. { An unconditional jump follows the conditional jump which will always be false,
  8469. so use this jump's destination for the new jump }
  8470. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8471. Result := True;
  8472. end
  8473. else if taicpu(hp2).opcode = A_JCC then
  8474. begin
  8475. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8476. if condition_in(C_E, taicpu(hp2).condition) then
  8477. begin
  8478. { A second conditional jump follows the conditional jump which will always be false,
  8479. while the second jump is always True, so use this jump's destination for the new jump }
  8480. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8481. Result := True;
  8482. end;
  8483. { Don't risk it if the jump isn't always true (Result remains False) }
  8484. end;
  8485. end;
  8486. else
  8487. { If anything else don't optimise };
  8488. end;
  8489. end;
  8490. if Result then
  8491. begin
  8492. { Just so we have something to insert as a paremeter}
  8493. reference_reset(NewRef, 1, []);
  8494. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8495. { Now actually load the correct parameter (this also
  8496. increases the reference count) }
  8497. NewInstr.loadsymbol(0, DestLabel, 0);
  8498. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8499. begin
  8500. { Get instruction before original label (may not be p under -O3) }
  8501. if not GetLastInstruction(hp1, hp2) then
  8502. { Shouldn't fail here }
  8503. InternalError(2021040701);
  8504. { Before the aligns too }
  8505. while (hp2.typ = ait_align) do
  8506. if not GetLastInstruction(hp2, hp2) then
  8507. { Shouldn't fail here }
  8508. InternalError(2021040702);
  8509. end
  8510. else
  8511. hp2 := p;
  8512. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8513. AsmL.InsertAfter(NewInstr, hp2);
  8514. { Add new alignment field }
  8515. (* AsmL.InsertAfter(
  8516. cai_align.create_max(
  8517. current_settings.alignment.jumpalign,
  8518. current_settings.alignment.jumpalignskipmax
  8519. ),
  8520. NewInstr
  8521. ); *)
  8522. end;
  8523. Exit;
  8524. end;
  8525. end;
  8526. else
  8527. ;
  8528. end;
  8529. end;
  8530. if not GetNextInstruction(p, hp1) then
  8531. Exit;
  8532. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8533. and DoMovCmpMemOpt(p, hp1) then
  8534. begin
  8535. Result := True;
  8536. Exit;
  8537. end
  8538. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8539. begin
  8540. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8541. further, but we can't just put this jump optimisation in pass 1
  8542. because it tends to perform worse when conditional jumps are
  8543. nearby (e.g. when converting CMOV instructions). [Kit] }
  8544. CopyUsedRegs(TempTracking);
  8545. UpdateUsedRegs(tai(p.Next));
  8546. if OptPass2JMP(hp1) then
  8547. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8548. Result := OptPass1MOV(p);
  8549. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8550. returned True and the instruction is still a MOV, thus checking
  8551. the optimisations below }
  8552. { If OptPass2JMP returned False, no optimisations were done to
  8553. the jump and there are no further optimisations that can be done
  8554. to the MOV instruction on this pass }
  8555. { Restore register state }
  8556. RestoreUsedRegs(TempTracking);
  8557. ReleaseUsedRegs(TempTracking);
  8558. end
  8559. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8560. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8561. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8562. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8563. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8564. begin
  8565. { Change:
  8566. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8567. addl/q $x,%reg2 subl/q $x,%reg2
  8568. To:
  8569. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8570. }
  8571. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8572. { be lazy, checking separately for sub would be slightly better }
  8573. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8574. begin
  8575. TransferUsedRegs(TmpUsedRegs);
  8576. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8577. if TryMovArith2Lea(hp1) then
  8578. begin
  8579. Result := True;
  8580. Exit;
  8581. end
  8582. end
  8583. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8584. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8585. { Same as above, but also adds or subtracts to %reg2 in between.
  8586. It's still valid as long as the flags aren't in use }
  8587. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8588. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8589. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8590. { be lazy, checking separately for sub would be slightly better }
  8591. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8592. begin
  8593. TransferUsedRegs(TmpUsedRegs);
  8594. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8595. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8596. if TryMovArith2Lea(hp2) then
  8597. begin
  8598. Result := True;
  8599. Exit;
  8600. end;
  8601. end;
  8602. end
  8603. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8604. {$ifdef x86_64}
  8605. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8606. {$else x86_64}
  8607. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8608. {$endif x86_64}
  8609. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8610. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8611. { mov reg1, reg2 mov reg1, reg2
  8612. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8613. begin
  8614. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8615. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8616. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8617. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8618. TransferUsedRegs(TmpUsedRegs);
  8619. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8620. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8621. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8622. then
  8623. begin
  8624. RemoveCurrentP(p, hp1);
  8625. Result:=true;
  8626. end;
  8627. exit;
  8628. end
  8629. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8630. IsXCHGAcceptable and
  8631. { XCHG doesn't support 8-byte registers }
  8632. (taicpu(p).opsize <> S_B) and
  8633. MatchInstruction(hp1, A_MOV, []) and
  8634. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8635. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8636. GetNextInstruction(hp1, hp2) and
  8637. MatchInstruction(hp2, A_MOV, []) and
  8638. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8639. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8640. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8641. begin
  8642. { mov %reg1,%reg2
  8643. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8644. mov %reg2,%reg3
  8645. (%reg2 not used afterwards)
  8646. Note that xchg takes 3 cycles to execute, and generally mov's take
  8647. only one cycle apiece, but the first two mov's can be executed in
  8648. parallel, only taking 2 cycles overall. Older processors should
  8649. therefore only optimise for size. [Kit]
  8650. }
  8651. TransferUsedRegs(TmpUsedRegs);
  8652. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8653. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8654. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8655. begin
  8656. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8657. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8658. taicpu(hp1).opcode := A_XCHG;
  8659. RemoveCurrentP(p, hp1);
  8660. RemoveInstruction(hp2);
  8661. Result := True;
  8662. Exit;
  8663. end;
  8664. end
  8665. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8666. MatchInstruction(hp1, A_SAR, []) then
  8667. begin
  8668. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8669. begin
  8670. { the use of %edx also covers the opsize being S_L }
  8671. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8672. begin
  8673. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8674. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8675. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8676. begin
  8677. { Change:
  8678. movl %eax,%edx
  8679. sarl $31,%edx
  8680. To:
  8681. cltd
  8682. }
  8683. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8684. RemoveInstruction(hp1);
  8685. taicpu(p).opcode := A_CDQ;
  8686. taicpu(p).opsize := S_NO;
  8687. taicpu(p).clearop(1);
  8688. taicpu(p).clearop(0);
  8689. taicpu(p).ops:=0;
  8690. Result := True;
  8691. end
  8692. else if (cs_opt_size in current_settings.optimizerswitches) and
  8693. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8694. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8695. begin
  8696. { Change:
  8697. movl %edx,%eax
  8698. sarl $31,%edx
  8699. To:
  8700. movl %edx,%eax
  8701. cltd
  8702. Note that this creates a dependency between the two instructions,
  8703. so only perform if optimising for size.
  8704. }
  8705. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8706. taicpu(hp1).opcode := A_CDQ;
  8707. taicpu(hp1).opsize := S_NO;
  8708. taicpu(hp1).clearop(1);
  8709. taicpu(hp1).clearop(0);
  8710. taicpu(hp1).ops:=0;
  8711. end;
  8712. {$ifndef x86_64}
  8713. end
  8714. { Don't bother if CMOV is supported, because a more optimal
  8715. sequence would have been generated for the Abs() intrinsic }
  8716. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8717. { the use of %eax also covers the opsize being S_L }
  8718. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8719. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8720. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8721. GetNextInstruction(hp1, hp2) and
  8722. MatchInstruction(hp2, A_XOR, [S_L]) and
  8723. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8724. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8725. GetNextInstruction(hp2, hp3) and
  8726. MatchInstruction(hp3, A_SUB, [S_L]) and
  8727. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8728. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8729. begin
  8730. { Change:
  8731. movl %eax,%edx
  8732. sarl $31,%eax
  8733. xorl %eax,%edx
  8734. subl %eax,%edx
  8735. (Instruction that uses %edx)
  8736. (%eax deallocated)
  8737. (%edx deallocated)
  8738. To:
  8739. cltd
  8740. xorl %edx,%eax <-- Note the registers have swapped
  8741. subl %edx,%eax
  8742. (Instruction that uses %eax) <-- %eax rather than %edx
  8743. }
  8744. TransferUsedRegs(TmpUsedRegs);
  8745. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8746. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8747. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8748. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8749. begin
  8750. if GetNextInstruction(hp3, hp4) and
  8751. not RegModifiedByInstruction(NR_EDX, hp4) and
  8752. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8753. begin
  8754. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8755. taicpu(p).opcode := A_CDQ;
  8756. taicpu(p).clearop(1);
  8757. taicpu(p).clearop(0);
  8758. taicpu(p).ops:=0;
  8759. RemoveInstruction(hp1);
  8760. taicpu(hp2).loadreg(0, NR_EDX);
  8761. taicpu(hp2).loadreg(1, NR_EAX);
  8762. taicpu(hp3).loadreg(0, NR_EDX);
  8763. taicpu(hp3).loadreg(1, NR_EAX);
  8764. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8765. { Convert references in the following instruction (hp4) from %edx to %eax }
  8766. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8767. with taicpu(hp4).oper[OperIdx]^ do
  8768. case typ of
  8769. top_reg:
  8770. if getsupreg(reg) = RS_EDX then
  8771. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8772. top_ref:
  8773. begin
  8774. if getsupreg(reg) = RS_EDX then
  8775. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8776. if getsupreg(reg) = RS_EDX then
  8777. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8778. end;
  8779. else
  8780. ;
  8781. end;
  8782. end;
  8783. end;
  8784. {$else x86_64}
  8785. end;
  8786. end
  8787. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8788. { the use of %rdx also covers the opsize being S_Q }
  8789. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8790. begin
  8791. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8792. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8793. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8794. begin
  8795. { Change:
  8796. movq %rax,%rdx
  8797. sarq $63,%rdx
  8798. To:
  8799. cqto
  8800. }
  8801. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8802. RemoveInstruction(hp1);
  8803. taicpu(p).opcode := A_CQO;
  8804. taicpu(p).opsize := S_NO;
  8805. taicpu(p).clearop(1);
  8806. taicpu(p).clearop(0);
  8807. taicpu(p).ops:=0;
  8808. Result := True;
  8809. end
  8810. else if (cs_opt_size in current_settings.optimizerswitches) and
  8811. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8812. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8813. begin
  8814. { Change:
  8815. movq %rdx,%rax
  8816. sarq $63,%rdx
  8817. To:
  8818. movq %rdx,%rax
  8819. cqto
  8820. Note that this creates a dependency between the two instructions,
  8821. so only perform if optimising for size.
  8822. }
  8823. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8824. taicpu(hp1).opcode := A_CQO;
  8825. taicpu(hp1).opsize := S_NO;
  8826. taicpu(hp1).clearop(1);
  8827. taicpu(hp1).clearop(0);
  8828. taicpu(hp1).ops:=0;
  8829. {$endif x86_64}
  8830. end;
  8831. end;
  8832. end
  8833. else if MatchInstruction(hp1, A_MOV, []) and
  8834. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8835. { Though "GetNextInstruction" could be factored out, along with
  8836. the instructions that depend on hp2, it is an expensive call that
  8837. should be delayed for as long as possible, hence we do cheaper
  8838. checks first that are likely to be False. [Kit] }
  8839. begin
  8840. if (
  8841. (
  8842. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8843. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8844. (
  8845. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8846. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8847. )
  8848. ) or
  8849. (
  8850. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8851. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8852. (
  8853. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8854. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8855. )
  8856. )
  8857. ) and
  8858. GetNextInstruction(hp1, hp2) and
  8859. MatchInstruction(hp2, A_SAR, []) and
  8860. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8861. begin
  8862. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8863. begin
  8864. { Change:
  8865. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8866. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8867. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8868. To:
  8869. movl r/m,%eax <- Note the change in register
  8870. cltd
  8871. }
  8872. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8873. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8874. taicpu(p).loadreg(1, NR_EAX);
  8875. taicpu(hp1).opcode := A_CDQ;
  8876. taicpu(hp1).clearop(1);
  8877. taicpu(hp1).clearop(0);
  8878. taicpu(hp1).ops:=0;
  8879. RemoveInstruction(hp2);
  8880. (*
  8881. {$ifdef x86_64}
  8882. end
  8883. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8884. { This code sequence does not get generated - however it might become useful
  8885. if and when 128-bit signed integer types make an appearance, so the code
  8886. is kept here for when it is eventually needed. [Kit] }
  8887. (
  8888. (
  8889. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8890. (
  8891. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8892. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8893. )
  8894. ) or
  8895. (
  8896. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8897. (
  8898. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8899. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8900. )
  8901. )
  8902. ) and
  8903. GetNextInstruction(hp1, hp2) and
  8904. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8905. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8906. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8907. begin
  8908. { Change:
  8909. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8910. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8911. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8912. To:
  8913. movq r/m,%rax <- Note the change in register
  8914. cqto
  8915. }
  8916. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8917. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8918. taicpu(p).loadreg(1, NR_RAX);
  8919. taicpu(hp1).opcode := A_CQO;
  8920. taicpu(hp1).clearop(1);
  8921. taicpu(hp1).clearop(0);
  8922. taicpu(hp1).ops:=0;
  8923. RemoveInstruction(hp2);
  8924. {$endif x86_64}
  8925. *)
  8926. end;
  8927. end;
  8928. {$ifdef x86_64}
  8929. end
  8930. else if (taicpu(p).opsize = S_L) and
  8931. (taicpu(p).oper[1]^.typ = top_reg) and
  8932. (
  8933. MatchInstruction(hp1, A_MOV,[]) and
  8934. (taicpu(hp1).opsize = S_L) and
  8935. (taicpu(hp1).oper[1]^.typ = top_reg)
  8936. ) and (
  8937. GetNextInstruction(hp1, hp2) and
  8938. (tai(hp2).typ=ait_instruction) and
  8939. (taicpu(hp2).opsize = S_Q) and
  8940. (
  8941. (
  8942. MatchInstruction(hp2, A_ADD,[]) and
  8943. (taicpu(hp2).opsize = S_Q) and
  8944. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8945. (
  8946. (
  8947. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8948. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8949. ) or (
  8950. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8951. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8952. )
  8953. )
  8954. ) or (
  8955. MatchInstruction(hp2, A_LEA,[]) and
  8956. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8957. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8958. (
  8959. (
  8960. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8961. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8962. ) or (
  8963. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8964. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8965. )
  8966. ) and (
  8967. (
  8968. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8969. ) or (
  8970. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8971. )
  8972. )
  8973. )
  8974. )
  8975. ) and (
  8976. GetNextInstruction(hp2, hp3) and
  8977. MatchInstruction(hp3, A_SHR,[]) and
  8978. (taicpu(hp3).opsize = S_Q) and
  8979. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8980. (taicpu(hp3).oper[0]^.val = 1) and
  8981. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8982. ) then
  8983. begin
  8984. { Change movl x, reg1d movl x, reg1d
  8985. movl y, reg2d movl y, reg2d
  8986. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8987. shrq $1, reg1q shrq $1, reg1q
  8988. ( reg1d and reg2d can be switched around in the first two instructions )
  8989. To movl x, reg1d
  8990. addl y, reg1d
  8991. rcrl $1, reg1d
  8992. This corresponds to the common expression (x + y) shr 1, where
  8993. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8994. smaller code, but won't account for x + y causing an overflow). [Kit]
  8995. }
  8996. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8997. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8998. { Change first MOV command to have the same register as the final output }
  8999. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9000. else
  9001. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9002. { Change second MOV command to an ADD command. This is easier than
  9003. converting the existing command because it means we don't have to
  9004. touch 'y', which might be a complicated reference, and also the
  9005. fact that the third command might either be ADD or LEA. [Kit] }
  9006. taicpu(hp1).opcode := A_ADD;
  9007. { Delete old ADD/LEA instruction }
  9008. RemoveInstruction(hp2);
  9009. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9010. taicpu(hp3).opcode := A_RCR;
  9011. taicpu(hp3).changeopsize(S_L);
  9012. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9013. {$endif x86_64}
  9014. end;
  9015. if FuncMov2Func(p, hp1) then
  9016. begin
  9017. Result := True;
  9018. Exit;
  9019. end;
  9020. end;
  9021. {$push}
  9022. {$q-}{$r-}
  9023. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9024. var
  9025. ThisReg: TRegister;
  9026. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9027. TargetSubReg: TSubRegister;
  9028. hp1, hp2: tai;
  9029. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9030. { Store list of found instructions so we don't have to call
  9031. GetNextInstructionUsingReg multiple times }
  9032. InstrList: array of taicpu;
  9033. InstrMax, Index: Integer;
  9034. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9035. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9036. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9037. WorkingValue: TCgInt;
  9038. PreMessage: string;
  9039. { Data flow analysis }
  9040. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9041. BitwiseOnly, OrXorUsed,
  9042. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9043. function CheckOverflowConditions: Boolean;
  9044. begin
  9045. Result := True;
  9046. if (TestValSignedMax > SignedUpperLimit) then
  9047. UpperSignedOverflow := True;
  9048. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9049. LowerSignedOverflow := True;
  9050. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9051. LowerUnsignedOverflow := True;
  9052. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9053. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9054. begin
  9055. { Absolute overflow }
  9056. Result := False;
  9057. Exit;
  9058. end;
  9059. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9060. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9061. ShiftDownOverflow := True;
  9062. if (TestValMin < 0) or (TestValMax < 0) then
  9063. begin
  9064. LowerUnsignedOverflow := True;
  9065. UpperUnsignedOverflow := True;
  9066. end;
  9067. end;
  9068. function AdjustInitialLoadAndSize: Boolean;
  9069. begin
  9070. Result := False;
  9071. if not p_removed then
  9072. begin
  9073. if TargetSize = MinSize then
  9074. begin
  9075. { Convert the input MOVZX to a MOV }
  9076. if (taicpu(p).oper[0]^.typ = top_reg) and
  9077. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9078. begin
  9079. { Or remove it completely! }
  9080. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9081. RemoveCurrentP(p);
  9082. p_removed := True;
  9083. end
  9084. else
  9085. begin
  9086. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9087. taicpu(p).opcode := A_MOV;
  9088. taicpu(p).oper[1]^.reg := ThisReg;
  9089. taicpu(p).opsize := TargetSize;
  9090. end;
  9091. Result := True;
  9092. end
  9093. else if TargetSize <> MaxSize then
  9094. begin
  9095. case MaxSize of
  9096. S_L:
  9097. if TargetSize = S_W then
  9098. begin
  9099. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9100. taicpu(p).opsize := S_BW;
  9101. taicpu(p).oper[1]^.reg := ThisReg;
  9102. Result := True;
  9103. end
  9104. else
  9105. InternalError(2020112341);
  9106. S_W:
  9107. if TargetSize = S_L then
  9108. begin
  9109. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9110. taicpu(p).opsize := S_BL;
  9111. taicpu(p).oper[1]^.reg := ThisReg;
  9112. Result := True;
  9113. end
  9114. else
  9115. InternalError(2020112342);
  9116. else
  9117. ;
  9118. end;
  9119. end
  9120. else if not hp1_removed and not RegInUse then
  9121. begin
  9122. { If we have something like:
  9123. movzbl (oper),%regd
  9124. add x, %regd
  9125. movzbl %regb, %regd
  9126. We can reduce the register size to the input of the final
  9127. movzbl instruction. Overflows won't have any effect.
  9128. }
  9129. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9130. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9131. begin
  9132. TargetSize := S_B;
  9133. setsubreg(ThisReg, R_SUBL);
  9134. Result := True;
  9135. end
  9136. else if (taicpu(p).opsize = S_WL) and
  9137. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9138. begin
  9139. TargetSize := S_W;
  9140. setsubreg(ThisReg, R_SUBW);
  9141. Result := True;
  9142. end;
  9143. if Result then
  9144. begin
  9145. { Convert the input MOVZX to a MOV }
  9146. if (taicpu(p).oper[0]^.typ = top_reg) and
  9147. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9148. begin
  9149. { Or remove it completely! }
  9150. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9151. RemoveCurrentP(p);
  9152. p_removed := True;
  9153. end
  9154. else
  9155. begin
  9156. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9157. taicpu(p).opcode := A_MOV;
  9158. taicpu(p).oper[1]^.reg := ThisReg;
  9159. taicpu(p).opsize := TargetSize;
  9160. end;
  9161. end;
  9162. end;
  9163. end;
  9164. end;
  9165. procedure AdjustFinalLoad;
  9166. begin
  9167. if not LowerUnsignedOverflow then
  9168. begin
  9169. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9170. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9171. begin
  9172. { Convert the output MOVZX to a MOV }
  9173. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9174. begin
  9175. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9176. if (MinSize = S_B) or
  9177. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9178. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9179. begin
  9180. { Remove it completely! }
  9181. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9182. { Be careful; if p = hp1 and p was also removed, p
  9183. will become a dangling pointer }
  9184. if p = hp1 then
  9185. begin
  9186. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9187. p_removed := True;
  9188. end
  9189. else
  9190. RemoveInstruction(hp1);
  9191. hp1_removed := True;
  9192. end;
  9193. end
  9194. else
  9195. begin
  9196. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9197. taicpu(hp1).opcode := A_MOV;
  9198. taicpu(hp1).oper[0]^.reg := ThisReg;
  9199. taicpu(hp1).opsize := TargetSize;
  9200. end;
  9201. end
  9202. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9203. begin
  9204. { Need to change the size of the output }
  9205. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9206. taicpu(hp1).oper[0]^.reg := ThisReg;
  9207. taicpu(hp1).opsize := S_BL;
  9208. end;
  9209. end;
  9210. end;
  9211. function CompressInstructions: Boolean;
  9212. var
  9213. LocalIndex: Integer;
  9214. begin
  9215. Result := False;
  9216. { The objective here is to try to find a combination that
  9217. removes one of the MOV/Z instructions. }
  9218. if (
  9219. (taicpu(p).oper[0]^.typ <> top_reg) or
  9220. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9221. ) and
  9222. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9223. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9224. begin
  9225. { Make a preference to remove the second MOVZX instruction }
  9226. case taicpu(hp1).opsize of
  9227. S_BL, S_WL:
  9228. begin
  9229. TargetSize := S_L;
  9230. TargetSubReg := R_SUBD;
  9231. end;
  9232. S_BW:
  9233. begin
  9234. TargetSize := S_W;
  9235. TargetSubReg := R_SUBW;
  9236. end;
  9237. else
  9238. InternalError(2020112302);
  9239. end;
  9240. end
  9241. else
  9242. begin
  9243. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9244. begin
  9245. { Exceeded lower bound but not upper bound }
  9246. TargetSize := MaxSize;
  9247. end
  9248. else if not LowerUnsignedOverflow then
  9249. begin
  9250. { Size didn't exceed lower bound }
  9251. TargetSize := MinSize;
  9252. end
  9253. else
  9254. Exit;
  9255. end;
  9256. case TargetSize of
  9257. S_B:
  9258. TargetSubReg := R_SUBL;
  9259. S_W:
  9260. TargetSubReg := R_SUBW;
  9261. S_L:
  9262. TargetSubReg := R_SUBD;
  9263. else
  9264. InternalError(2020112350);
  9265. end;
  9266. { Update the register to its new size }
  9267. setsubreg(ThisReg, TargetSubReg);
  9268. RegInUse := False;
  9269. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9270. begin
  9271. { Check to see if the active register is used afterwards;
  9272. if not, we can change it and make a saving. }
  9273. TransferUsedRegs(TmpUsedRegs);
  9274. { The target register may be marked as in use to cross
  9275. a jump to a distant label, so exclude it }
  9276. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9277. hp2 := p;
  9278. repeat
  9279. { Explicitly check for the excluded register (don't include the first
  9280. instruction as it may be reading from here }
  9281. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9282. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9283. begin
  9284. RegInUse := True;
  9285. Break;
  9286. end;
  9287. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9288. if not GetNextInstruction(hp2, hp2) then
  9289. InternalError(2020112340);
  9290. until (hp2 = hp1);
  9291. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9292. { We might still be able to get away with this }
  9293. RegInUse := not
  9294. (
  9295. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9296. (hp2.typ = ait_instruction) and
  9297. (
  9298. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9299. instruction that doesn't actually contain ThisReg }
  9300. (cs_opt_level3 in current_settings.optimizerswitches) or
  9301. RegInInstruction(ThisReg, hp2)
  9302. ) and
  9303. RegLoadedWithNewValue(ThisReg, hp2)
  9304. );
  9305. if not RegInUse then
  9306. begin
  9307. { Force the register size to the same as this instruction so it can be removed}
  9308. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9309. begin
  9310. TargetSize := S_L;
  9311. TargetSubReg := R_SUBD;
  9312. end
  9313. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9314. begin
  9315. TargetSize := S_W;
  9316. TargetSubReg := R_SUBW;
  9317. end;
  9318. ThisReg := taicpu(hp1).oper[1]^.reg;
  9319. setsubreg(ThisReg, TargetSubReg);
  9320. RegChanged := True;
  9321. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9322. TransferUsedRegs(TmpUsedRegs);
  9323. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9324. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9325. if p = hp1 then
  9326. begin
  9327. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9328. p_removed := True;
  9329. end
  9330. else
  9331. RemoveInstruction(hp1);
  9332. hp1_removed := True;
  9333. { Instruction will become "mov %reg,%reg" }
  9334. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9335. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9336. begin
  9337. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9338. RemoveCurrentP(p);
  9339. p_removed := True;
  9340. end
  9341. else
  9342. taicpu(p).oper[1]^.reg := ThisReg;
  9343. Result := True;
  9344. end
  9345. else
  9346. begin
  9347. if TargetSize <> MaxSize then
  9348. begin
  9349. { Since the register is in use, we have to force it to
  9350. MaxSize otherwise part of it may become undefined later on }
  9351. TargetSize := MaxSize;
  9352. case TargetSize of
  9353. S_B:
  9354. TargetSubReg := R_SUBL;
  9355. S_W:
  9356. TargetSubReg := R_SUBW;
  9357. S_L:
  9358. TargetSubReg := R_SUBD;
  9359. else
  9360. InternalError(2020112351);
  9361. end;
  9362. setsubreg(ThisReg, TargetSubReg);
  9363. end;
  9364. AdjustFinalLoad;
  9365. end;
  9366. end
  9367. else
  9368. AdjustFinalLoad;
  9369. Result := AdjustInitialLoadAndSize or Result;
  9370. { Now go through every instruction we found and change the
  9371. size. If TargetSize = MaxSize, then almost no changes are
  9372. needed and Result can remain False if it hasn't been set
  9373. yet.
  9374. If RegChanged is True, then the register requires changing
  9375. and so the point about TargetSize = MaxSize doesn't apply. }
  9376. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9377. begin
  9378. for LocalIndex := 0 to InstrMax do
  9379. begin
  9380. { If p_removed is true, then the original MOV/Z was removed
  9381. and removing the AND instruction may not be safe if it
  9382. appears first }
  9383. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9384. InternalError(2020112310);
  9385. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9386. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9387. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9388. InstrList[LocalIndex].opsize := TargetSize;
  9389. end;
  9390. Result := True;
  9391. end;
  9392. end;
  9393. begin
  9394. Result := False;
  9395. p_removed := False;
  9396. hp1_removed := False;
  9397. ThisReg := taicpu(p).oper[1]^.reg;
  9398. { Check for:
  9399. movs/z ###,%ecx (or %cx or %rcx)
  9400. ...
  9401. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9402. (dealloc %ecx)
  9403. Change to:
  9404. mov ###,%cl (if ### = %cl, then remove completely)
  9405. ...
  9406. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9407. }
  9408. if (getsupreg(ThisReg) = RS_ECX) and
  9409. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9410. (hp1.typ = ait_instruction) and
  9411. (
  9412. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9413. instruction that doesn't actually contain ECX }
  9414. (cs_opt_level3 in current_settings.optimizerswitches) or
  9415. RegInInstruction(NR_ECX, hp1) or
  9416. (
  9417. { It's common for the shift/rotate's read/write register to be
  9418. initialised in between, so under -O2 and under, search ahead
  9419. one more instruction
  9420. }
  9421. GetNextInstruction(hp1, hp1) and
  9422. (hp1.typ = ait_instruction) and
  9423. RegInInstruction(NR_ECX, hp1)
  9424. )
  9425. ) and
  9426. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9427. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9428. begin
  9429. TransferUsedRegs(TmpUsedRegs);
  9430. hp2 := p;
  9431. repeat
  9432. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9433. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9434. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9435. begin
  9436. case taicpu(p).opsize of
  9437. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9438. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9439. begin
  9440. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9441. RemoveCurrentP(p);
  9442. end
  9443. else
  9444. begin
  9445. taicpu(p).opcode := A_MOV;
  9446. taicpu(p).opsize := S_B;
  9447. taicpu(p).oper[1]^.reg := NR_CL;
  9448. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9449. end;
  9450. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9451. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9452. begin
  9453. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9454. RemoveCurrentP(p);
  9455. end
  9456. else
  9457. begin
  9458. taicpu(p).opcode := A_MOV;
  9459. taicpu(p).opsize := S_W;
  9460. taicpu(p).oper[1]^.reg := NR_CX;
  9461. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9462. end;
  9463. {$ifdef x86_64}
  9464. S_LQ:
  9465. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9466. begin
  9467. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9468. RemoveCurrentP(p);
  9469. end
  9470. else
  9471. begin
  9472. taicpu(p).opcode := A_MOV;
  9473. taicpu(p).opsize := S_L;
  9474. taicpu(p).oper[1]^.reg := NR_ECX;
  9475. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9476. end;
  9477. {$endif x86_64}
  9478. else
  9479. InternalError(2021120401);
  9480. end;
  9481. Result := True;
  9482. Exit;
  9483. end;
  9484. end;
  9485. { This is anything but quick! }
  9486. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9487. Exit;
  9488. SetLength(InstrList, 0);
  9489. InstrMax := -1;
  9490. case taicpu(p).opsize of
  9491. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9492. begin
  9493. {$if defined(i386) or defined(i8086)}
  9494. { If the target size is 8-bit, make sure we can actually encode it }
  9495. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9496. Exit;
  9497. {$endif i386 or i8086}
  9498. LowerLimit := $FF;
  9499. SignedLowerLimit := $7F;
  9500. SignedLowerLimitBottom := -128;
  9501. MinSize := S_B;
  9502. if taicpu(p).opsize = S_BW then
  9503. begin
  9504. MaxSize := S_W;
  9505. UpperLimit := $FFFF;
  9506. SignedUpperLimit := $7FFF;
  9507. SignedUpperLimitBottom := -32768;
  9508. end
  9509. else
  9510. begin
  9511. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9512. MaxSize := S_L;
  9513. UpperLimit := $FFFFFFFF;
  9514. SignedUpperLimit := $7FFFFFFF;
  9515. SignedUpperLimitBottom := -2147483648;
  9516. end;
  9517. end;
  9518. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9519. begin
  9520. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9521. LowerLimit := $FFFF;
  9522. SignedLowerLimit := $7FFF;
  9523. SignedLowerLimitBottom := -32768;
  9524. UpperLimit := $FFFFFFFF;
  9525. SignedUpperLimit := $7FFFFFFF;
  9526. SignedUpperLimitBottom := -2147483648;
  9527. MinSize := S_W;
  9528. MaxSize := S_L;
  9529. end;
  9530. {$ifdef x86_64}
  9531. S_LQ:
  9532. begin
  9533. { Both the lower and upper limits are set to 32-bit. If a limit
  9534. is breached, then optimisation is impossible }
  9535. LowerLimit := $FFFFFFFF;
  9536. SignedLowerLimit := $7FFFFFFF;
  9537. SignedLowerLimitBottom := -2147483648;
  9538. UpperLimit := $FFFFFFFF;
  9539. SignedUpperLimit := $7FFFFFFF;
  9540. SignedUpperLimitBottom := -2147483648;
  9541. MinSize := S_L;
  9542. MaxSize := S_L;
  9543. end;
  9544. {$endif x86_64}
  9545. else
  9546. InternalError(2020112301);
  9547. end;
  9548. TestValMin := 0;
  9549. TestValMax := LowerLimit;
  9550. TestValSignedMax := SignedLowerLimit;
  9551. TryShiftDownLimit := LowerLimit;
  9552. TryShiftDown := S_NO;
  9553. ShiftDownOverflow := False;
  9554. RegChanged := False;
  9555. BitwiseOnly := True;
  9556. OrXorUsed := False;
  9557. UpperSignedOverflow := False;
  9558. LowerSignedOverflow := False;
  9559. UpperUnsignedOverflow := False;
  9560. LowerUnsignedOverflow := False;
  9561. hp1 := p;
  9562. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9563. (hp1.typ = ait_instruction) and
  9564. (
  9565. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9566. instruction that doesn't actually contain ThisReg }
  9567. (cs_opt_level3 in current_settings.optimizerswitches) or
  9568. { This allows this Movx optimisation to work through the SETcc instructions
  9569. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9570. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9571. skip over these SETcc instructions). }
  9572. (taicpu(hp1).opcode = A_SETcc) or
  9573. RegInInstruction(ThisReg, hp1)
  9574. ) do
  9575. begin
  9576. case taicpu(hp1).opcode of
  9577. A_INC,A_DEC:
  9578. begin
  9579. { Has to be an exact match on the register }
  9580. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9581. Break;
  9582. if taicpu(hp1).opcode = A_INC then
  9583. begin
  9584. Inc(TestValMin);
  9585. Inc(TestValMax);
  9586. Inc(TestValSignedMax);
  9587. end
  9588. else
  9589. begin
  9590. Dec(TestValMin);
  9591. Dec(TestValMax);
  9592. Dec(TestValSignedMax);
  9593. end;
  9594. end;
  9595. A_TEST, A_CMP:
  9596. begin
  9597. if (
  9598. { Too high a risk of non-linear behaviour that breaks DFA
  9599. here, unless it's cmp $0,%reg, which is equivalent to
  9600. test %reg,%reg }
  9601. OrXorUsed and
  9602. (taicpu(hp1).opcode = A_CMP) and
  9603. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9604. ) or
  9605. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9606. { Has to be an exact match on the register }
  9607. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9608. (
  9609. { Permit "test %reg,%reg" }
  9610. (taicpu(hp1).opcode = A_TEST) and
  9611. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9612. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9613. ) or
  9614. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9615. { Make sure the comparison value is not smaller than the
  9616. smallest allowed signed value for the minimum size (e.g.
  9617. -128 for 8-bit) }
  9618. not (
  9619. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9620. { Is it in the negative range? }
  9621. (
  9622. (taicpu(hp1).oper[0]^.val < 0) and
  9623. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9624. )
  9625. ) then
  9626. Break;
  9627. { Check to see if the active register is used afterwards }
  9628. TransferUsedRegs(TmpUsedRegs);
  9629. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9630. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9631. begin
  9632. { Make sure the comparison or any previous instructions
  9633. hasn't pushed the test values outside of the range of
  9634. MinSize }
  9635. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9636. begin
  9637. { Exceeded lower bound but not upper bound }
  9638. Exit;
  9639. end
  9640. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9641. begin
  9642. { Size didn't exceed lower bound }
  9643. TargetSize := MinSize;
  9644. end
  9645. else
  9646. Break;
  9647. case TargetSize of
  9648. S_B:
  9649. TargetSubReg := R_SUBL;
  9650. S_W:
  9651. TargetSubReg := R_SUBW;
  9652. S_L:
  9653. TargetSubReg := R_SUBD;
  9654. else
  9655. InternalError(2021051002);
  9656. end;
  9657. if TargetSize <> MaxSize then
  9658. begin
  9659. { Update the register to its new size }
  9660. setsubreg(ThisReg, TargetSubReg);
  9661. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9662. taicpu(hp1).oper[1]^.reg := ThisReg;
  9663. taicpu(hp1).opsize := TargetSize;
  9664. { Convert the input MOVZX to a MOV if necessary }
  9665. AdjustInitialLoadAndSize;
  9666. if (InstrMax >= 0) then
  9667. begin
  9668. for Index := 0 to InstrMax do
  9669. begin
  9670. { If p_removed is true, then the original MOV/Z was removed
  9671. and removing the AND instruction may not be safe if it
  9672. appears first }
  9673. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9674. InternalError(2020112311);
  9675. if InstrList[Index].oper[0]^.typ = top_reg then
  9676. InstrList[Index].oper[0]^.reg := ThisReg;
  9677. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9678. InstrList[Index].opsize := MinSize;
  9679. end;
  9680. end;
  9681. Result := True;
  9682. end;
  9683. Exit;
  9684. end;
  9685. end;
  9686. A_SETcc:
  9687. begin
  9688. { This allows this Movx optimisation to work through the SETcc instructions
  9689. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9690. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9691. skip over these SETcc instructions). }
  9692. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9693. { Of course, break out if the current register is used }
  9694. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9695. Break
  9696. else
  9697. { We must use Continue so the instruction doesn't get added
  9698. to InstrList }
  9699. Continue;
  9700. end;
  9701. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9702. begin
  9703. if
  9704. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9705. { Has to be an exact match on the register }
  9706. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9707. (
  9708. (
  9709. (taicpu(hp1).oper[0]^.typ = top_const) and
  9710. (
  9711. (
  9712. (taicpu(hp1).opcode = A_SHL) and
  9713. (
  9714. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9715. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9716. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9717. )
  9718. ) or (
  9719. (taicpu(hp1).opcode <> A_SHL) and
  9720. (
  9721. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9722. { Is it in the negative range? }
  9723. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9724. )
  9725. )
  9726. )
  9727. ) or (
  9728. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9729. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9730. )
  9731. ) then
  9732. Break;
  9733. { Only process OR and XOR if there are only bitwise operations,
  9734. since otherwise they can too easily fool the data flow
  9735. analysis (they can cause non-linear behaviour) }
  9736. case taicpu(hp1).opcode of
  9737. A_ADD:
  9738. begin
  9739. if OrXorUsed then
  9740. { Too high a risk of non-linear behaviour that breaks DFA here }
  9741. Break
  9742. else
  9743. BitwiseOnly := False;
  9744. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9745. begin
  9746. TestValMin := TestValMin * 2;
  9747. TestValMax := TestValMax * 2;
  9748. TestValSignedMax := TestValSignedMax * 2;
  9749. end
  9750. else
  9751. begin
  9752. WorkingValue := taicpu(hp1).oper[0]^.val;
  9753. TestValMin := TestValMin + WorkingValue;
  9754. TestValMax := TestValMax + WorkingValue;
  9755. TestValSignedMax := TestValSignedMax + WorkingValue;
  9756. end;
  9757. end;
  9758. A_SUB:
  9759. begin
  9760. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9761. begin
  9762. TestValMin := 0;
  9763. TestValMax := 0;
  9764. TestValSignedMax := 0;
  9765. end
  9766. else
  9767. begin
  9768. if OrXorUsed then
  9769. { Too high a risk of non-linear behaviour that breaks DFA here }
  9770. Break
  9771. else
  9772. BitwiseOnly := False;
  9773. WorkingValue := taicpu(hp1).oper[0]^.val;
  9774. TestValMin := TestValMin - WorkingValue;
  9775. TestValMax := TestValMax - WorkingValue;
  9776. TestValSignedMax := TestValSignedMax - WorkingValue;
  9777. end;
  9778. end;
  9779. A_AND:
  9780. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9781. begin
  9782. { we might be able to go smaller if AND appears first }
  9783. if InstrMax = -1 then
  9784. case MinSize of
  9785. S_B:
  9786. ;
  9787. S_W:
  9788. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9789. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9790. begin
  9791. TryShiftDown := S_B;
  9792. TryShiftDownLimit := $FF;
  9793. end;
  9794. S_L:
  9795. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9796. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9797. begin
  9798. TryShiftDown := S_B;
  9799. TryShiftDownLimit := $FF;
  9800. end
  9801. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9802. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9803. begin
  9804. TryShiftDown := S_W;
  9805. TryShiftDownLimit := $FFFF;
  9806. end;
  9807. else
  9808. InternalError(2020112320);
  9809. end;
  9810. WorkingValue := taicpu(hp1).oper[0]^.val;
  9811. TestValMin := TestValMin and WorkingValue;
  9812. TestValMax := TestValMax and WorkingValue;
  9813. TestValSignedMax := TestValSignedMax and WorkingValue;
  9814. end;
  9815. A_OR:
  9816. begin
  9817. if not BitwiseOnly then
  9818. Break;
  9819. OrXorUsed := True;
  9820. WorkingValue := taicpu(hp1).oper[0]^.val;
  9821. TestValMin := TestValMin or WorkingValue;
  9822. TestValMax := TestValMax or WorkingValue;
  9823. TestValSignedMax := TestValSignedMax or WorkingValue;
  9824. end;
  9825. A_XOR:
  9826. begin
  9827. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9828. begin
  9829. TestValMin := 0;
  9830. TestValMax := 0;
  9831. TestValSignedMax := 0;
  9832. end
  9833. else
  9834. begin
  9835. if not BitwiseOnly then
  9836. Break;
  9837. OrXorUsed := True;
  9838. WorkingValue := taicpu(hp1).oper[0]^.val;
  9839. TestValMin := TestValMin xor WorkingValue;
  9840. TestValMax := TestValMax xor WorkingValue;
  9841. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9842. end;
  9843. end;
  9844. A_SHL:
  9845. begin
  9846. BitwiseOnly := False;
  9847. WorkingValue := taicpu(hp1).oper[0]^.val;
  9848. TestValMin := TestValMin shl WorkingValue;
  9849. TestValMax := TestValMax shl WorkingValue;
  9850. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9851. end;
  9852. A_SHR,
  9853. { The first instruction was MOVZX, so the value won't be negative }
  9854. A_SAR:
  9855. begin
  9856. if InstrMax <> -1 then
  9857. BitwiseOnly := False
  9858. else
  9859. { we might be able to go smaller if SHR appears first }
  9860. case MinSize of
  9861. S_B:
  9862. ;
  9863. S_W:
  9864. if (taicpu(hp1).oper[0]^.val >= 8) then
  9865. begin
  9866. TryShiftDown := S_B;
  9867. TryShiftDownLimit := $FF;
  9868. TryShiftDownSignedLimit := $7F;
  9869. TryShiftDownSignedLimitLower := -128;
  9870. end;
  9871. S_L:
  9872. if (taicpu(hp1).oper[0]^.val >= 24) then
  9873. begin
  9874. TryShiftDown := S_B;
  9875. TryShiftDownLimit := $FF;
  9876. TryShiftDownSignedLimit := $7F;
  9877. TryShiftDownSignedLimitLower := -128;
  9878. end
  9879. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9880. begin
  9881. TryShiftDown := S_W;
  9882. TryShiftDownLimit := $FFFF;
  9883. TryShiftDownSignedLimit := $7FFF;
  9884. TryShiftDownSignedLimitLower := -32768;
  9885. end;
  9886. else
  9887. InternalError(2020112321);
  9888. end;
  9889. WorkingValue := taicpu(hp1).oper[0]^.val;
  9890. if taicpu(hp1).opcode = A_SAR then
  9891. begin
  9892. TestValMin := SarInt64(TestValMin, WorkingValue);
  9893. TestValMax := SarInt64(TestValMax, WorkingValue);
  9894. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9895. end
  9896. else
  9897. begin
  9898. TestValMin := TestValMin shr WorkingValue;
  9899. TestValMax := TestValMax shr WorkingValue;
  9900. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9901. end;
  9902. end;
  9903. else
  9904. InternalError(2020112303);
  9905. end;
  9906. end;
  9907. (*
  9908. A_IMUL:
  9909. case taicpu(hp1).ops of
  9910. 2:
  9911. begin
  9912. if not MatchOpType(hp1, top_reg, top_reg) or
  9913. { Has to be an exact match on the register }
  9914. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9915. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9916. Break;
  9917. TestValMin := TestValMin * TestValMin;
  9918. TestValMax := TestValMax * TestValMax;
  9919. TestValSignedMax := TestValSignedMax * TestValMax;
  9920. end;
  9921. 3:
  9922. begin
  9923. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9924. { Has to be an exact match on the register }
  9925. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9926. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9927. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9928. { Is it in the negative range? }
  9929. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9930. Break;
  9931. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9932. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9933. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9934. end;
  9935. else
  9936. Break;
  9937. end;
  9938. A_IDIV:
  9939. case taicpu(hp1).ops of
  9940. 3:
  9941. begin
  9942. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9943. { Has to be an exact match on the register }
  9944. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9945. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9946. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9947. { Is it in the negative range? }
  9948. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9949. Break;
  9950. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9951. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9952. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9953. end;
  9954. else
  9955. Break;
  9956. end;
  9957. *)
  9958. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9959. begin
  9960. { If there are no instructions in between, then we might be able to make a saving }
  9961. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9962. Break;
  9963. { We have something like:
  9964. movzbw %dl,%dx
  9965. ...
  9966. movswl %dx,%edx
  9967. Change the latter to a zero-extension then enter the
  9968. A_MOVZX case branch.
  9969. }
  9970. {$ifdef x86_64}
  9971. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9972. begin
  9973. { this becomes a zero extension from 32-bit to 64-bit, but
  9974. the upper 32 bits are already zero, so just delete the
  9975. instruction }
  9976. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9977. RemoveInstruction(hp1);
  9978. Result := True;
  9979. Exit;
  9980. end
  9981. else
  9982. {$endif x86_64}
  9983. begin
  9984. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9985. taicpu(hp1).opcode := A_MOVZX;
  9986. {$ifdef x86_64}
  9987. case taicpu(hp1).opsize of
  9988. S_BQ:
  9989. begin
  9990. taicpu(hp1).opsize := S_BL;
  9991. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9992. end;
  9993. S_WQ:
  9994. begin
  9995. taicpu(hp1).opsize := S_WL;
  9996. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9997. end;
  9998. S_LQ:
  9999. begin
  10000. taicpu(hp1).opcode := A_MOV;
  10001. taicpu(hp1).opsize := S_L;
  10002. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10003. { In this instance, we need to break out because the
  10004. instruction is no longer MOVZX or MOVSXD }
  10005. Result := True;
  10006. Exit;
  10007. end;
  10008. else
  10009. ;
  10010. end;
  10011. {$endif x86_64}
  10012. Result := CompressInstructions;
  10013. Exit;
  10014. end;
  10015. end;
  10016. A_MOVZX:
  10017. begin
  10018. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10019. Break;
  10020. if (InstrMax = -1) then
  10021. begin
  10022. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10023. begin
  10024. { Optimise around i40003 }
  10025. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10026. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10027. {$ifndef x86_64}
  10028. and (
  10029. (taicpu(p).oper[0]^.typ <> top_reg) or
  10030. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10031. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10032. )
  10033. {$endif not x86_64}
  10034. then
  10035. begin
  10036. if (taicpu(p).oper[0]^.typ = top_reg) then
  10037. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10038. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10039. taicpu(p).opsize := S_BL;
  10040. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10041. RemoveInstruction(hp1);
  10042. Result := True;
  10043. Exit;
  10044. end;
  10045. end
  10046. else
  10047. begin
  10048. { Will return false if the second parameter isn't ThisReg
  10049. (can happen on -O2 and under) }
  10050. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10051. begin
  10052. { The two MOVZX instructions are adjacent, so remove the first one }
  10053. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10054. RemoveCurrentP(p);
  10055. Result := True;
  10056. Exit;
  10057. end;
  10058. Break;
  10059. end;
  10060. end;
  10061. Result := CompressInstructions;
  10062. Exit;
  10063. end;
  10064. else
  10065. { This includes ADC, SBB and IDIV }
  10066. Break;
  10067. end;
  10068. if not CheckOverflowConditions then
  10069. Break;
  10070. { Contains highest index (so instruction count - 1) }
  10071. Inc(InstrMax);
  10072. if InstrMax > High(InstrList) then
  10073. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10074. InstrList[InstrMax] := taicpu(hp1);
  10075. end;
  10076. end;
  10077. {$pop}
  10078. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10079. var
  10080. hp1 : tai;
  10081. begin
  10082. Result:=false;
  10083. if (taicpu(p).ops >= 2) and
  10084. ((taicpu(p).oper[0]^.typ = top_const) or
  10085. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10086. (taicpu(p).oper[1]^.typ = top_reg) and
  10087. ((taicpu(p).ops = 2) or
  10088. ((taicpu(p).oper[2]^.typ = top_reg) and
  10089. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10090. GetLastInstruction(p,hp1) and
  10091. MatchInstruction(hp1,A_MOV,[]) and
  10092. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10093. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10094. begin
  10095. TransferUsedRegs(TmpUsedRegs);
  10096. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10097. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10098. { change
  10099. mov reg1,reg2
  10100. imul y,reg2 to imul y,reg1,reg2 }
  10101. begin
  10102. taicpu(p).ops := 3;
  10103. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10104. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10105. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10106. RemoveInstruction(hp1);
  10107. result:=true;
  10108. end;
  10109. end;
  10110. end;
  10111. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10112. var
  10113. ThisLabel: TAsmLabel;
  10114. begin
  10115. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10116. ThisLabel.decrefs;
  10117. taicpu(p).condition := C_None;
  10118. taicpu(p).opcode := A_RET;
  10119. taicpu(p).is_jmp := false;
  10120. taicpu(p).ops := taicpu(ret_p).ops;
  10121. case taicpu(ret_p).ops of
  10122. 0:
  10123. taicpu(p).clearop(0);
  10124. 1:
  10125. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10126. else
  10127. internalerror(2016041301);
  10128. end;
  10129. { If the original label is now dead, it might turn out that the label
  10130. immediately follows p. As a result, everything beyond it, which will
  10131. be just some final register configuration and a RET instruction, is
  10132. now dead code. [Kit] }
  10133. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10134. running RemoveDeadCodeAfterJump for each RET instruction, because
  10135. this optimisation rarely happens and most RETs appear at the end of
  10136. routines where there is nothing that can be stripped. [Kit] }
  10137. if not ThisLabel.is_used then
  10138. RemoveDeadCodeAfterJump(p);
  10139. end;
  10140. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10141. var
  10142. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10143. Unconditional, PotentialModified: Boolean;
  10144. OperPtr: POper;
  10145. NewRef: TReference;
  10146. InstrList: array of taicpu;
  10147. InstrMax, Index: Integer;
  10148. const
  10149. {$ifdef DEBUG_AOPTCPU}
  10150. SNoFlags: shortstring = ' so the flags aren''t modified';
  10151. {$else DEBUG_AOPTCPU}
  10152. SNoFlags = '';
  10153. {$endif DEBUG_AOPTCPU}
  10154. begin
  10155. Result:=false;
  10156. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10157. begin
  10158. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10159. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10160. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10161. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10162. GetNextInstruction(hp1, hp2) and
  10163. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10164. { Change from: To:
  10165. set(C) %reg j(~C) label
  10166. test %reg,%reg/cmp $0,%reg
  10167. je label
  10168. set(C) %reg j(C) label
  10169. test %reg,%reg/cmp $0,%reg
  10170. jne label
  10171. (Also do something similar with sete/setne instead of je/jne)
  10172. }
  10173. begin
  10174. { Before we do anything else, we need to check the instructions
  10175. in between SETcc and TEST to make sure they don't modify the
  10176. FLAGS register - if -O2 or under, there won't be any
  10177. instructions between SET and TEST }
  10178. TransferUsedRegs(TmpUsedRegs);
  10179. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10180. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10181. begin
  10182. next := p;
  10183. SetLength(InstrList, 0);
  10184. InstrMax := -1;
  10185. PotentialModified := False;
  10186. { Make a note of every instruction that modifies the FLAGS
  10187. register }
  10188. while GetNextInstruction(next, next) and (next <> hp1) do
  10189. begin
  10190. if next.typ <> ait_instruction then
  10191. { GetNextInstructionUsingReg should have returned False }
  10192. InternalError(2021051701);
  10193. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10194. begin
  10195. case taicpu(next).opcode of
  10196. A_SETcc,
  10197. A_CMOVcc,
  10198. A_Jcc:
  10199. begin
  10200. if PotentialModified then
  10201. { Not safe because the flags were modified earlier }
  10202. Exit
  10203. else
  10204. { Condition is the same as the initial SETcc, so this is safe
  10205. (don't add to instruction list though) }
  10206. Continue;
  10207. end;
  10208. A_ADD:
  10209. begin
  10210. if (taicpu(next).opsize = S_B) or
  10211. { LEA doesn't support 8-bit operands }
  10212. (taicpu(next).oper[1]^.typ <> top_reg) or
  10213. { Must write to a register }
  10214. (taicpu(next).oper[0]^.typ = top_ref) then
  10215. { Require a constant or a register }
  10216. Exit;
  10217. PotentialModified := True;
  10218. end;
  10219. A_SUB:
  10220. begin
  10221. if (taicpu(next).opsize = S_B) or
  10222. { LEA doesn't support 8-bit operands }
  10223. (taicpu(next).oper[1]^.typ <> top_reg) or
  10224. { Must write to a register }
  10225. (taicpu(next).oper[0]^.typ <> top_const) or
  10226. (taicpu(next).oper[0]^.val = $80000000) then
  10227. { Can't subtract a register with LEA - also
  10228. check that the value isn't -2^31, as this
  10229. can't be negated }
  10230. Exit;
  10231. PotentialModified := True;
  10232. end;
  10233. A_SAL,
  10234. A_SHL:
  10235. begin
  10236. if (taicpu(next).opsize = S_B) or
  10237. { LEA doesn't support 8-bit operands }
  10238. (taicpu(next).oper[1]^.typ <> top_reg) or
  10239. { Must write to a register }
  10240. (taicpu(next).oper[0]^.typ <> top_const) or
  10241. (taicpu(next).oper[0]^.val < 0) or
  10242. (taicpu(next).oper[0]^.val > 3) then
  10243. Exit;
  10244. PotentialModified := True;
  10245. end;
  10246. A_IMUL:
  10247. begin
  10248. if (taicpu(next).ops <> 3) or
  10249. (taicpu(next).oper[1]^.typ <> top_reg) or
  10250. { Must write to a register }
  10251. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10252. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10253. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10254. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10255. Exit
  10256. else
  10257. PotentialModified := True;
  10258. end;
  10259. else
  10260. { Don't know how to change this, so abort }
  10261. Exit;
  10262. end;
  10263. { Contains highest index (so instruction count - 1) }
  10264. Inc(InstrMax);
  10265. if InstrMax > High(InstrList) then
  10266. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10267. InstrList[InstrMax] := taicpu(next);
  10268. end;
  10269. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10270. end;
  10271. if not Assigned(next) or (next <> hp1) then
  10272. { It should be equal to hp1 }
  10273. InternalError(2021051702);
  10274. { Cycle through each instruction and check to see if we can
  10275. change them to versions that don't modify the flags }
  10276. if (InstrMax >= 0) then
  10277. begin
  10278. for Index := 0 to InstrMax do
  10279. case InstrList[Index].opcode of
  10280. A_ADD:
  10281. begin
  10282. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10283. InstrList[Index].opcode := A_LEA;
  10284. reference_reset(NewRef, 1, []);
  10285. NewRef.base := InstrList[Index].oper[1]^.reg;
  10286. if InstrList[Index].oper[0]^.typ = top_reg then
  10287. begin
  10288. NewRef.index := InstrList[Index].oper[0]^.reg;
  10289. NewRef.scalefactor := 1;
  10290. end
  10291. else
  10292. NewRef.offset := InstrList[Index].oper[0]^.val;
  10293. InstrList[Index].loadref(0, NewRef);
  10294. end;
  10295. A_SUB:
  10296. begin
  10297. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10298. InstrList[Index].opcode := A_LEA;
  10299. reference_reset(NewRef, 1, []);
  10300. NewRef.base := InstrList[Index].oper[1]^.reg;
  10301. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10302. InstrList[Index].loadref(0, NewRef);
  10303. end;
  10304. A_SHL,
  10305. A_SAL:
  10306. begin
  10307. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10308. InstrList[Index].opcode := A_LEA;
  10309. reference_reset(NewRef, 1, []);
  10310. NewRef.index := InstrList[Index].oper[1]^.reg;
  10311. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10312. InstrList[Index].loadref(0, NewRef);
  10313. end;
  10314. A_IMUL:
  10315. begin
  10316. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10317. InstrList[Index].opcode := A_LEA;
  10318. reference_reset(NewRef, 1, []);
  10319. NewRef.index := InstrList[Index].oper[1]^.reg;
  10320. case InstrList[Index].oper[0]^.val of
  10321. 2, 4, 8:
  10322. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10323. else {3, 5 and 9}
  10324. begin
  10325. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10326. NewRef.base := InstrList[Index].oper[1]^.reg;
  10327. end;
  10328. end;
  10329. InstrList[Index].loadref(0, NewRef);
  10330. end;
  10331. else
  10332. InternalError(2021051710);
  10333. end;
  10334. end;
  10335. { Mark the FLAGS register as used across this whole block }
  10336. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10337. end;
  10338. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10339. JumpC := taicpu(hp2).condition;
  10340. Unconditional := False;
  10341. if conditions_equal(JumpC, C_E) then
  10342. SetC := inverse_cond(taicpu(p).condition)
  10343. else if conditions_equal(JumpC, C_NE) then
  10344. SetC := taicpu(p).condition
  10345. else
  10346. { We've got something weird here (and inefficent) }
  10347. begin
  10348. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10349. SetC := C_NONE;
  10350. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10351. if condition_in(C_AE, JumpC) then
  10352. Unconditional := True
  10353. else
  10354. { Not sure what to do with this jump - drop out }
  10355. Exit;
  10356. end;
  10357. RemoveInstruction(hp1);
  10358. if Unconditional then
  10359. MakeUnconditional(taicpu(hp2))
  10360. else
  10361. begin
  10362. if SetC = C_NONE then
  10363. InternalError(2018061402);
  10364. taicpu(hp2).SetCondition(SetC);
  10365. end;
  10366. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10367. TmpUsedRegs }
  10368. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10369. begin
  10370. RemoveCurrentp(p, hp2);
  10371. if taicpu(hp2).opcode = A_SETcc then
  10372. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10373. else
  10374. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10375. end
  10376. else
  10377. if taicpu(hp2).opcode = A_SETcc then
  10378. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10379. else
  10380. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10381. Result := True;
  10382. end
  10383. else if
  10384. { Make sure the instructions are adjacent }
  10385. (
  10386. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10387. GetNextInstruction(p, hp1)
  10388. ) and
  10389. MatchInstruction(hp1, A_MOV, [S_B]) and
  10390. { Writing to memory is allowed }
  10391. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10392. begin
  10393. {
  10394. Watch out for sequences such as:
  10395. set(c)b %regb
  10396. movb %regb,(ref)
  10397. movb $0,1(ref)
  10398. movb $0,2(ref)
  10399. movb $0,3(ref)
  10400. Much more efficient to turn it into:
  10401. movl $0,%regl
  10402. set(c)b %regb
  10403. movl %regl,(ref)
  10404. Or:
  10405. set(c)b %regb
  10406. movzbl %regb,%regl
  10407. movl %regl,(ref)
  10408. }
  10409. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10410. GetNextInstruction(hp1, hp2) and
  10411. MatchInstruction(hp2, A_MOV, [S_B]) and
  10412. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10413. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10414. begin
  10415. { Don't do anything else except set Result to True }
  10416. end
  10417. else
  10418. begin
  10419. if taicpu(p).oper[0]^.typ = top_reg then
  10420. begin
  10421. TransferUsedRegs(TmpUsedRegs);
  10422. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10423. end;
  10424. { If it's not a register, it's a memory address }
  10425. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10426. begin
  10427. { Even if the register is still in use, we can minimise the
  10428. pipeline stall by changing the MOV into another SETcc. }
  10429. taicpu(hp1).opcode := A_SETcc;
  10430. taicpu(hp1).condition := taicpu(p).condition;
  10431. if taicpu(hp1).oper[1]^.typ = top_ref then
  10432. begin
  10433. { Swapping the operand pointers like this is probably a
  10434. bit naughty, but it is far faster than using loadoper
  10435. to transfer the reference from oper[1] to oper[0] if
  10436. you take into account the extra procedure calls and
  10437. the memory allocation and deallocation required }
  10438. OperPtr := taicpu(hp1).oper[1];
  10439. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10440. taicpu(hp1).oper[0] := OperPtr;
  10441. end
  10442. else
  10443. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10444. taicpu(hp1).clearop(1);
  10445. taicpu(hp1).ops := 1;
  10446. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10447. end
  10448. else
  10449. begin
  10450. if taicpu(hp1).oper[1]^.typ = top_reg then
  10451. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10452. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10453. RemoveInstruction(hp1);
  10454. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10455. end
  10456. end;
  10457. Result := True;
  10458. end;
  10459. end;
  10460. end;
  10461. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10462. var
  10463. hp1: tai;
  10464. Count: Integer;
  10465. OrigLabel: TAsmLabel;
  10466. begin
  10467. result := False;
  10468. { Sometimes, the optimisations below can permit this }
  10469. RemoveDeadCodeAfterJump(p);
  10470. 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
  10471. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10472. begin
  10473. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10474. { Also a side-effect of optimisations }
  10475. if CollapseZeroDistJump(p, OrigLabel) then
  10476. begin
  10477. Result := True;
  10478. Exit;
  10479. end;
  10480. hp1 := GetLabelWithSym(OrigLabel);
  10481. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10482. begin
  10483. if taicpu(hp1).opcode = A_RET then
  10484. begin
  10485. {
  10486. change
  10487. jmp .L1
  10488. ...
  10489. .L1:
  10490. ret
  10491. into
  10492. ret
  10493. }
  10494. begin
  10495. ConvertJumpToRET(p, hp1);
  10496. result:=true;
  10497. end;
  10498. end
  10499. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10500. not (cs_opt_size in current_settings.optimizerswitches) and
  10501. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10502. begin
  10503. Result := True;
  10504. Exit;
  10505. end;
  10506. end;
  10507. end;
  10508. end;
  10509. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10510. begin
  10511. Result := assigned(p) and
  10512. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10513. (taicpu(p).oper[1]^.typ = top_reg) and
  10514. (
  10515. (taicpu(p).oper[0]^.typ = top_reg) or
  10516. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10517. it is not expected that this can cause a seg. violation }
  10518. (
  10519. (taicpu(p).oper[0]^.typ = top_ref) and
  10520. { TODO: Can we detect which references become constants at this
  10521. stage so we don't have to do a blanket ban? }
  10522. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10523. (
  10524. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10525. (
  10526. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10527. not RefModified and
  10528. { If the reference also appears in the condition, then we know it's safe, otherwise
  10529. any kind of access violation would have occurred already }
  10530. Assigned(cond_p) and
  10531. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10532. (cond_p.typ = ait_instruction) and
  10533. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10534. { Just consider 2-operand comparison instructions for now to be safe }
  10535. (taicpu(cond_p).ops = 2) and
  10536. (
  10537. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10538. (
  10539. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10540. { Don't risk identical registers but different offsets, as we may have constructs
  10541. such as buffer streams with things like length fields that indicate whether
  10542. any more data follows. And there are probably some contrived examples where
  10543. writing to offsets behind the one being read also lead to access violations }
  10544. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10545. (
  10546. { Check that we're not modifying a register that appears in the reference }
  10547. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10548. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10549. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10550. )
  10551. )
  10552. )
  10553. )
  10554. )
  10555. )
  10556. );
  10557. end;
  10558. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10559. begin
  10560. { Update integer registers, ignoring deallocations }
  10561. repeat
  10562. while assigned(p) and
  10563. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10564. (p.typ = ait_label) or
  10565. ((p.typ = ait_marker) and
  10566. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10567. p := tai(p.next);
  10568. while assigned(p) and
  10569. (p.typ=ait_RegAlloc) Do
  10570. begin
  10571. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10572. begin
  10573. case tai_regalloc(p).ratype of
  10574. ra_alloc :
  10575. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10576. else
  10577. ;
  10578. end;
  10579. end;
  10580. p := tai(p.next);
  10581. end;
  10582. until not(assigned(p)) or
  10583. (not(p.typ in SkipInstr) and
  10584. not((p.typ = ait_label) and
  10585. labelCanBeSkipped(tai_label(p))));
  10586. end;
  10587. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10588. var
  10589. hp1,hp2: tai;
  10590. carryadd_opcode : TAsmOp;
  10591. symbol: TAsmSymbol;
  10592. increg, tmpreg: TRegister;
  10593. RefModified: Boolean;
  10594. {$ifndef i8086}
  10595. { Code and variables specific to CMOV optimisations }
  10596. hp3,hp4,hp5,
  10597. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10598. l, c, w, x : Longint;
  10599. condition, second_condition : TAsmCond;
  10600. FoundMatchingJump, RegMatch: Boolean;
  10601. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10602. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10603. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10604. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10605. new register to store the constant }
  10606. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10607. var
  10608. RegSize: TSubRegister;
  10609. CurrentVal: TCGInt;
  10610. NewReg: TRegister;
  10611. X: ShortInt;
  10612. begin
  10613. Result := False;
  10614. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10615. Exit;
  10616. if StoredCount >= MAX_CMOV_REGISTERS then
  10617. { Arrays are full }
  10618. Exit;
  10619. { Remember that CMOV can't encode 8-bit registers }
  10620. case taicpu(p).opsize of
  10621. S_W:
  10622. RegSize := R_SUBW;
  10623. S_L:
  10624. RegSize := R_SUBD;
  10625. S_Q:
  10626. RegSize := R_SUBQ;
  10627. else
  10628. InternalError(2021100401);
  10629. end;
  10630. { See if the value has already been reserved for another CMOV instruction }
  10631. CurrentVal := taicpu(p).oper[0]^.val;
  10632. for X := 0 to StoredCount - 1 do
  10633. if ConstVals[X] = CurrentVal then
  10634. begin
  10635. ConstRegs[StoredCount] := ConstRegs[X];
  10636. ConstVals[StoredCount] := CurrentVal;
  10637. Result := True;
  10638. Inc(StoredCount);
  10639. { Don't increase CMOVCount this time, since we're re-using a register }
  10640. Exit;
  10641. end;
  10642. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10643. if NewReg = NR_NO then
  10644. { No free registers }
  10645. Exit;
  10646. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10647. up vying for the same register }
  10648. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10649. ConstRegs[StoredCount] := NewReg;
  10650. ConstVals[StoredCount] := CurrentVal;
  10651. Inc(StoredCount);
  10652. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10653. MOV required adds complexity and will cause diminishing returns
  10654. sooner than normal. This is more of an approximate weighting than
  10655. anything else. }
  10656. Inc(CMOVCount);
  10657. Result := True;
  10658. end;
  10659. {$endif i8086}
  10660. begin
  10661. result:=false;
  10662. if GetNextInstruction(p,hp1) then
  10663. begin
  10664. if (hp1.typ=ait_label) then
  10665. begin
  10666. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10667. Exit;
  10668. end
  10669. else if (hp1.typ<>ait_instruction) then
  10670. Exit;
  10671. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10672. if (
  10673. (
  10674. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10675. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10676. (Taicpu(hp1).oper[0]^.val=1)
  10677. ) or
  10678. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10679. ) and
  10680. GetNextInstruction(hp1,hp2) and
  10681. SkipAligns(hp2, hp2) and
  10682. (hp2.typ = ait_label) and
  10683. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10684. { jb @@1 cmc
  10685. inc/dec operand --> adc/sbb operand,0
  10686. @@1:
  10687. ... and ...
  10688. jnb @@1
  10689. inc/dec operand --> adc/sbb operand,0
  10690. @@1: }
  10691. begin
  10692. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10693. begin
  10694. case taicpu(hp1).opcode of
  10695. A_INC,
  10696. A_ADD:
  10697. carryadd_opcode:=A_ADC;
  10698. A_DEC,
  10699. A_SUB:
  10700. carryadd_opcode:=A_SBB;
  10701. else
  10702. InternalError(2021011001);
  10703. end;
  10704. Taicpu(p).clearop(0);
  10705. Taicpu(p).ops:=0;
  10706. Taicpu(p).is_jmp:=false;
  10707. Taicpu(p).opcode:=A_CMC;
  10708. Taicpu(p).condition:=C_NONE;
  10709. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10710. Taicpu(hp1).ops:=2;
  10711. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10712. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10713. else
  10714. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10715. Taicpu(hp1).loadconst(0,0);
  10716. Taicpu(hp1).opcode:=carryadd_opcode;
  10717. result:=true;
  10718. exit;
  10719. end
  10720. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10721. begin
  10722. case taicpu(hp1).opcode of
  10723. A_INC,
  10724. A_ADD:
  10725. carryadd_opcode:=A_ADC;
  10726. A_DEC,
  10727. A_SUB:
  10728. carryadd_opcode:=A_SBB;
  10729. else
  10730. InternalError(2021011002);
  10731. end;
  10732. Taicpu(hp1).ops:=2;
  10733. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10734. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10735. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10736. else
  10737. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10738. Taicpu(hp1).loadconst(0,0);
  10739. Taicpu(hp1).opcode:=carryadd_opcode;
  10740. RemoveCurrentP(p, hp1);
  10741. result:=true;
  10742. exit;
  10743. end
  10744. {
  10745. jcc @@1 setcc tmpreg
  10746. inc/dec/add/sub operand -> (movzx tmpreg)
  10747. @@1: add/sub tmpreg,operand
  10748. While this increases code size slightly, it makes the code much faster if the
  10749. jump is unpredictable
  10750. }
  10751. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10752. begin
  10753. { search for an available register which is volatile }
  10754. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10755. if increg <> NR_NO then
  10756. begin
  10757. { We don't need to check if tmpreg is in hp1 or not, because
  10758. it will be marked as in use at p (if not, this is
  10759. indictive of a compiler bug). }
  10760. TAsmLabel(symbol).decrefs;
  10761. Taicpu(p).clearop(0);
  10762. Taicpu(p).ops:=1;
  10763. Taicpu(p).is_jmp:=false;
  10764. Taicpu(p).opcode:=A_SETcc;
  10765. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10766. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10767. Taicpu(p).loadreg(0,increg);
  10768. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10769. begin
  10770. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10771. R_SUBW:
  10772. begin
  10773. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10774. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10775. end;
  10776. R_SUBD:
  10777. begin
  10778. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10779. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10780. end;
  10781. {$ifdef x86_64}
  10782. R_SUBQ:
  10783. begin
  10784. { MOVZX doesn't have a 64-bit variant, because
  10785. the 32-bit version implicitly zeroes the
  10786. upper 32-bits of the destination register }
  10787. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10788. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10789. setsubreg(tmpreg, R_SUBQ);
  10790. end;
  10791. {$endif x86_64}
  10792. else
  10793. Internalerror(2020030601);
  10794. end;
  10795. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10796. asml.InsertAfter(hp2,p);
  10797. end
  10798. else
  10799. tmpreg := increg;
  10800. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10801. begin
  10802. Taicpu(hp1).ops:=2;
  10803. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10804. end;
  10805. Taicpu(hp1).loadreg(0,tmpreg);
  10806. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10807. Result := True;
  10808. { p is no longer a Jcc instruction, so exit }
  10809. Exit;
  10810. end;
  10811. end;
  10812. end;
  10813. { Detect the following:
  10814. jmp<cond> @Lbl1
  10815. jmp @Lbl2
  10816. ...
  10817. @Lbl1:
  10818. ret
  10819. Change to:
  10820. jmp<inv_cond> @Lbl2
  10821. ret
  10822. }
  10823. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10824. begin
  10825. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10826. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10827. MatchInstruction(hp2,A_RET,[S_NO]) then
  10828. begin
  10829. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10830. { Change label address to that of the unconditional jump }
  10831. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10832. TAsmLabel(symbol).DecRefs;
  10833. taicpu(hp1).opcode := A_RET;
  10834. taicpu(hp1).is_jmp := false;
  10835. taicpu(hp1).ops := taicpu(hp2).ops;
  10836. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10837. case taicpu(hp2).ops of
  10838. 0:
  10839. taicpu(hp1).clearop(0);
  10840. 1:
  10841. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10842. else
  10843. internalerror(2016041302);
  10844. end;
  10845. end;
  10846. {$ifndef i8086}
  10847. end
  10848. {
  10849. convert
  10850. j<c> .L1
  10851. mov 1,reg
  10852. jmp .L2
  10853. .L1
  10854. mov 0,reg
  10855. .L2
  10856. into
  10857. mov 0,reg
  10858. set<not(c)> reg
  10859. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10860. would destroy the flag contents
  10861. }
  10862. else if MatchInstruction(hp1,A_MOV,[]) and
  10863. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10864. {$ifdef i386}
  10865. (
  10866. { Under i386, ESI, EDI, EBP and ESP
  10867. don't have an 8-bit representation }
  10868. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10869. ) and
  10870. {$endif i386}
  10871. (taicpu(hp1).oper[0]^.val=1) and
  10872. GetNextInstruction(hp1,hp2) and
  10873. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10874. GetNextInstruction(hp2,hp3) and
  10875. { skip align }
  10876. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10877. (hp3.typ=ait_label) and
  10878. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10879. (tai_label(hp3).labsym.getrefs=1) and
  10880. GetNextInstruction(hp3,hp4) and
  10881. MatchInstruction(hp4,A_MOV,[]) and
  10882. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10883. (taicpu(hp4).oper[0]^.val=0) and
  10884. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10885. GetNextInstruction(hp4,hp5) and
  10886. (hp5.typ=ait_label) and
  10887. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10888. (tai_label(hp5).labsym.getrefs=1) then
  10889. begin
  10890. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10891. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10892. { remove last label }
  10893. RemoveInstruction(hp5);
  10894. { remove second label }
  10895. RemoveInstruction(hp3);
  10896. { if align is present remove it }
  10897. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10898. RemoveInstruction(hp3);
  10899. { remove jmp }
  10900. RemoveInstruction(hp2);
  10901. if taicpu(hp1).opsize=S_B then
  10902. RemoveInstruction(hp1)
  10903. else
  10904. taicpu(hp1).loadconst(0,0);
  10905. taicpu(hp4).opcode:=A_SETcc;
  10906. taicpu(hp4).opsize:=S_B;
  10907. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10908. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10909. taicpu(hp4).opercnt:=1;
  10910. taicpu(hp4).ops:=1;
  10911. taicpu(hp4).freeop(1);
  10912. RemoveCurrentP(p);
  10913. Result:=true;
  10914. exit;
  10915. end
  10916. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10917. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10918. begin
  10919. { check for
  10920. jCC xxx
  10921. <several movs>
  10922. xxx:
  10923. Also spot:
  10924. Jcc xxx
  10925. <several movs>
  10926. jmp xxx
  10927. Change to:
  10928. <several cmovs with inverted condition>
  10929. jmp xxx (only for the 2nd case)
  10930. }
  10931. hp2 := p;
  10932. hp_lblxxx := hp1;
  10933. hp_flagalloc := nil;
  10934. hp_stop := nil;
  10935. FoundMatchingJump := False;
  10936. { Remember the first instruction in the first block of MOVs }
  10937. hpmov1 := hp1;
  10938. TransferUsedRegs(TmpUsedRegs);
  10939. while assigned(hp_lblxxx) and
  10940. { stop on labels }
  10941. (hp_lblxxx.typ <> ait_label) do
  10942. begin
  10943. { Keep track of all integer registers that are used }
  10944. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10945. if hp_lblxxx.typ = ait_instruction then
  10946. begin
  10947. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10948. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10949. begin
  10950. hp_stop := hp_lblxxx;
  10951. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10952. begin
  10953. { We found Jcc xxx; <several movs>; Jmp xxx }
  10954. FoundMatchingJump := True;
  10955. Break;
  10956. end;
  10957. { If it's not the jump we're looking for, it's
  10958. possibly the "if..else" variant }
  10959. end
  10960. { Check to see if we have a valid MOV instruction instead }
  10961. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10962. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10963. Break
  10964. else
  10965. { This will be a valid MOV }
  10966. hp_stop := hp_lblxxx;
  10967. end;
  10968. hp2 := hp_lblxxx;
  10969. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10970. end;
  10971. { Just make sure the last MOV is included if there's no jump }
  10972. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10973. hp_stop := hp_lblxxx;
  10974. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10975. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10976. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10977. jmp yyy; xxx:; movs; yyy:" variation }
  10978. if assigned(hp_lblxxx) and
  10979. (
  10980. { If we found JMP xxx, we don't actually need a label
  10981. (hp_lblxxx is the JMP instruction instead) }
  10982. FoundMatchingJump or
  10983. { Make sure we actually have the right label }
  10984. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10985. ) then
  10986. begin
  10987. { Use TmpUsedRegs to track registers that we reserve }
  10988. { When allocating temporary registers, try to look one
  10989. instruction back, as defining them before a CMP or TEST
  10990. instruction will be faster, and also avoid picking a
  10991. register that was only just deallocated }
  10992. if GetLastInstruction(p, hp_prev) and
  10993. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  10994. begin
  10995. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10996. for l := 0 to 1 do
  10997. with taicpu(hp_prev).oper[l]^ do
  10998. case typ of
  10999. top_reg:
  11000. if getregtype(reg) = R_INTREGISTER then
  11001. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11002. top_ref:
  11003. begin
  11004. if
  11005. {$ifdef x86_64}
  11006. (ref^.base <> NR_RIP) and
  11007. {$endif x86_64}
  11008. (ref^.base <> NR_NO) then
  11009. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11010. if (ref^.index <> NR_NO) then
  11011. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11012. end
  11013. else
  11014. ;
  11015. end;
  11016. { When inserting instructions before hp_prev, try to insert
  11017. them before the allocation of the FLAGS register }
  11018. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11019. { If not found, set it equal to hp_prev so it's something sensible }
  11020. hp_flagalloc := hp_prev;
  11021. hp_prev2 := nil;
  11022. { When dealing with a comparison against zero, take
  11023. note of the instruction before it to see if we can
  11024. move instructions further back in order to benefit
  11025. PostPeepholeOptTestOr.
  11026. }
  11027. if (
  11028. (
  11029. (taicpu(hp_prev).opcode = A_CMP) and
  11030. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11031. ) or
  11032. (
  11033. (taicpu(hp_prev).opcode = A_TEST) and
  11034. (
  11035. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11036. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11037. )
  11038. )
  11039. ) and
  11040. GetLastInstruction(hp_prev, hp_prev2) then
  11041. begin
  11042. if (hp_prev2.typ = ait_instruction) and
  11043. { These instructions set the zero flag if the result is zero }
  11044. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11045. begin
  11046. { Also mark all the registers in this previous instruction
  11047. as 'in use', even if they've just been deallocated }
  11048. for l := 0 to 1 do
  11049. with taicpu(hp_prev2).oper[l]^ do
  11050. case typ of
  11051. top_reg:
  11052. if getregtype(reg) = R_INTREGISTER then
  11053. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11054. top_ref:
  11055. begin
  11056. if
  11057. {$ifdef x86_64}
  11058. (ref^.base <> NR_RIP) and
  11059. {$endif x86_64}
  11060. (ref^.base <> NR_NO) then
  11061. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11062. if (ref^.index <> NR_NO) then
  11063. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11064. end
  11065. else
  11066. ;
  11067. end;
  11068. end
  11069. else
  11070. { Unsuitable instruction }
  11071. hp_prev2 := nil;
  11072. end;
  11073. end
  11074. else
  11075. begin
  11076. hp_prev := p;
  11077. { When inserting instructions before hp_prev, try to insert
  11078. them before the allocation of the FLAGS register }
  11079. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11080. { If not found, set it equal to p so it's something sensible }
  11081. hp_flagalloc := p;
  11082. hp_prev2 := nil;
  11083. end;
  11084. l := 0;
  11085. c := 0;
  11086. { Initialise RegWrites, ConstRegs and ConstVals }
  11087. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11088. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11089. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11090. RefModified := False;
  11091. while assigned(hp1) and
  11092. { Stop on the label we found }
  11093. (hp1 <> hp_lblxxx) do
  11094. begin
  11095. case hp1.typ of
  11096. ait_instruction:
  11097. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11098. begin
  11099. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11100. begin
  11101. Inc(l);
  11102. { MOV instruction will be writing to a register }
  11103. if Assigned(hp_prev) and
  11104. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11105. (hp_prev.typ = ait_instruction) and
  11106. (taicpu(hp_prev).ops = 2) and
  11107. (
  11108. (
  11109. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11110. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11111. ) or
  11112. (
  11113. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11114. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11115. )
  11116. ) then
  11117. { It is no longer safe to use the reference in the condition.
  11118. this prevents problems such as:
  11119. mov (%reg),%reg
  11120. mov (%reg),...
  11121. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11122. (fixes #40165)
  11123. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11124. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11125. }
  11126. RefModified := True;
  11127. end
  11128. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11129. { CMOV with constants grows the code size }
  11130. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11131. begin
  11132. { Register was reserved by TryCMOVConst and
  11133. stored on ConstRegs[c] }
  11134. end
  11135. else
  11136. Break;
  11137. end
  11138. else
  11139. Break;
  11140. else
  11141. ;
  11142. end;
  11143. GetNextInstruction(hp1,hp1);
  11144. end;
  11145. if (hp1 = hp_lblxxx) then
  11146. begin
  11147. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11148. begin
  11149. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11150. TmpUsedRegs[R_INTREGISTER].Clear;
  11151. x := 0;
  11152. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11153. condition := inverse_cond(taicpu(p).condition);
  11154. UpdateUsedRegs(tai(p.next));
  11155. hp1 := hpmov1;
  11156. repeat
  11157. if not Assigned(hp1) then
  11158. InternalError(2018062900);
  11159. if (hp1.typ = ait_instruction) then
  11160. begin
  11161. { Extra safeguard }
  11162. if (taicpu(hp1).opcode <> A_MOV) then
  11163. InternalError(2018062901);
  11164. if taicpu(hp1).oper[0]^.typ = top_const then
  11165. begin
  11166. if x >= MAX_CMOV_REGISTERS then
  11167. InternalError(2021100410);
  11168. { If it's in TmpUsedRegs, then this register
  11169. is being used more than once and hence has
  11170. already had its value defined (it gets
  11171. added to UsedRegs through AllocRegBetween
  11172. below) }
  11173. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11174. begin
  11175. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11176. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11177. asml.InsertBefore(hp_new, hp_flagalloc);
  11178. if Assigned(hp_prev2) then
  11179. TrySwapMovOp(hp_prev2, hp_new);
  11180. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11181. end
  11182. else
  11183. { We just need an instruction between hp_prev and hp1
  11184. where we know the register is marked as in use }
  11185. hp_new := hpmov1;
  11186. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11187. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11188. Inc(x);
  11189. end;
  11190. taicpu(hp1).opcode := A_CMOVcc;
  11191. taicpu(hp1).condition := condition;
  11192. end;
  11193. UpdateUsedRegs(tai(hp1.next));
  11194. GetNextInstruction(hp1, hp1);
  11195. until (hp1 = hp_lblxxx);
  11196. hp2 := hp_lblxxx;
  11197. repeat
  11198. if not Assigned(hp2) then
  11199. InternalError(2018062910);
  11200. case hp2.typ of
  11201. ait_label:
  11202. { What we expected - break out of the loop (it won't be a dead label at the top of
  11203. a cluster because that was optimised at an earlier stage) }
  11204. Break;
  11205. ait_align:
  11206. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11207. begin
  11208. hp2 := tai(hp2.Next);
  11209. Continue;
  11210. end;
  11211. ait_instruction:
  11212. begin
  11213. if taicpu(hp2).opcode<>A_JMP then
  11214. InternalError(2018062912);
  11215. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11216. Break;
  11217. end
  11218. else
  11219. begin
  11220. { Might be a comment or temporary allocation entry }
  11221. if not (hp2.typ in SkipInstr) then
  11222. InternalError(2018062911);
  11223. hp2 := tai(hp2.Next);
  11224. Continue;
  11225. end;
  11226. end;
  11227. until False;
  11228. { Now we can safely decrement the reference count }
  11229. tasmlabel(symbol).decrefs;
  11230. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11231. { Remove the original jump }
  11232. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11233. if hp2.typ=ait_instruction then
  11234. begin
  11235. p := hp2;
  11236. Result := True;
  11237. end
  11238. else
  11239. begin
  11240. UpdateUsedRegs(tai(hp2.next));
  11241. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11242. { Remove the label if this is its final reference }
  11243. if (tasmlabel(symbol).getrefs=0) then
  11244. begin
  11245. { Make sure the aligns get stripped too }
  11246. hp1 := tai(hp_lblxxx.Previous);
  11247. while Assigned(hp1) and (hp1.typ = ait_align) do
  11248. begin
  11249. hp_lblxxx := hp1;
  11250. hp1 := tai(hp_lblxxx.Previous);
  11251. end;
  11252. StripLabelFast(hp_lblxxx);
  11253. end;
  11254. end;
  11255. Exit;
  11256. end;
  11257. end
  11258. else if assigned(hp_lblxxx) and
  11259. { check further for
  11260. jCC xxx
  11261. <several movs 1>
  11262. jmp yyy
  11263. xxx:
  11264. <several movs 2>
  11265. yyy:
  11266. }
  11267. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11268. { hp1 should be pointing to jmp yyy }
  11269. MatchInstruction(hp1, A_JMP, []) and
  11270. { real label and jump, no further references to the
  11271. label are allowed }
  11272. (TAsmLabel(symbol).getrefs=1) and
  11273. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11274. begin
  11275. hp_jump := hp1;
  11276. { Don't set c to zero }
  11277. l := 0;
  11278. w := 0;
  11279. GetNextInstruction(hp_lblxxx, hpmov2);
  11280. hp2 := hp_lblxxx;
  11281. hp_lblyyy := hpmov2;
  11282. while assigned(hp_lblyyy) and
  11283. { stop on labels }
  11284. (hp_lblyyy.typ <> ait_label) do
  11285. begin
  11286. { Keep track of all integer registers that are used }
  11287. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11288. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11289. Break;
  11290. hp2 := hp_lblyyy;
  11291. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11292. end;
  11293. { Analyse the second batch of MOVs to see if the setup is valid }
  11294. RefModified := False;
  11295. hp1 := hpmov2;
  11296. while assigned(hp1) and
  11297. (hp1 <> hp_lblyyy) do
  11298. begin
  11299. case hp1.typ of
  11300. ait_instruction:
  11301. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11302. begin
  11303. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11304. begin
  11305. Inc(l);
  11306. { MOV instruction will be writing to a register }
  11307. if Assigned(hp_prev) and
  11308. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11309. (hp_prev.typ = ait_instruction) and
  11310. (taicpu(hp_prev).ops = 2) and
  11311. (
  11312. (
  11313. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11314. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11315. ) or
  11316. (
  11317. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11318. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11319. )
  11320. ) then
  11321. { It is no longer safe to use the reference in the condition.
  11322. this prevents problems such as:
  11323. mov (%reg),%reg
  11324. mov (%reg),...
  11325. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11326. (fixes #40165)
  11327. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11328. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11329. }
  11330. RefModified := True;
  11331. end
  11332. else if not (cs_opt_size in current_settings.optimizerswitches)
  11333. { CMOV with constants grows the code size }
  11334. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11335. begin
  11336. { Register was reserved by TryCMOVConst and
  11337. stored on ConstRegs[c] }
  11338. end
  11339. else
  11340. Break;
  11341. end
  11342. else
  11343. Break;
  11344. else
  11345. ;
  11346. end;
  11347. GetNextInstruction(hp1,hp1);
  11348. end;
  11349. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11350. TmpUsedRegs[R_INTREGISTER].Clear;
  11351. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11352. (hp1 = hp_lblyyy) and
  11353. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11354. begin
  11355. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11356. second_condition := taicpu(p).condition;
  11357. condition := inverse_cond(taicpu(p).condition);
  11358. UpdateUsedRegs(tai(p.next));
  11359. { Scan through the first set of MOVs to update UsedRegs,
  11360. but don't process them yet }
  11361. hp1 := hpmov1;
  11362. repeat
  11363. if not Assigned(hp1) then
  11364. InternalError(2018062901);
  11365. UpdateUsedRegs(tai(hp1.next));
  11366. GetNextInstruction(hp1, hp1);
  11367. until (hp1 = hp_lblxxx);
  11368. UpdateUsedRegs(tai(hp_lblxxx.next));
  11369. { Process the second set of MOVs first,
  11370. because if a destination register is
  11371. shared between the first and second MOV
  11372. sets, it is more efficient to turn the
  11373. first one into a MOV instruction and place
  11374. it before the CMP if possible, but we
  11375. won't know which registers are shared
  11376. until we've processed at least one list,
  11377. so we might as well make it the second
  11378. one since that won't be modified again. }
  11379. hp1 := hpmov2;
  11380. repeat
  11381. if not Assigned(hp1) then
  11382. InternalError(2018062902);
  11383. if (hp1.typ = ait_instruction) then
  11384. begin
  11385. { Extra safeguard }
  11386. if (taicpu(hp1).opcode <> A_MOV) then
  11387. InternalError(2018062903);
  11388. if taicpu(hp1).oper[0]^.typ = top_const then
  11389. begin
  11390. RegMatch := False;
  11391. for x := 0 to c - 1 do
  11392. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11393. begin
  11394. RegMatch := True;
  11395. { If it's in TmpUsedRegs, then this register
  11396. is being used more than once and hence has
  11397. already had its value defined (it gets
  11398. added to UsedRegs through AllocRegBetween
  11399. below) }
  11400. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11401. begin
  11402. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11403. asml.InsertBefore(hp_new, hp_flagalloc);
  11404. if Assigned(hp_prev2) then
  11405. TrySwapMovOp(hp_prev2, hp_new);
  11406. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11407. end
  11408. else
  11409. { We just need an instruction between hp_prev and hp1
  11410. where we know the register is marked as in use }
  11411. hp_new := hpmov2;
  11412. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11413. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11414. Break;
  11415. end;
  11416. if not RegMatch then
  11417. InternalError(2021100411);
  11418. end;
  11419. taicpu(hp1).opcode := A_CMOVcc;
  11420. taicpu(hp1).condition := second_condition;
  11421. { Store these writes to search for
  11422. duplicates later on }
  11423. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11424. Inc(w);
  11425. end;
  11426. UpdateUsedRegs(tai(hp1.next));
  11427. GetNextInstruction(hp1, hp1);
  11428. until (hp1 = hp_lblyyy);
  11429. { Now do the first set of MOVs }
  11430. hp1 := hpmov1;
  11431. repeat
  11432. if not Assigned(hp1) then
  11433. InternalError(2018062904);
  11434. if (hp1.typ = ait_instruction) then
  11435. begin
  11436. RegMatch := False;
  11437. { Extra safeguard }
  11438. if (taicpu(hp1).opcode <> A_MOV) then
  11439. InternalError(2018062905);
  11440. { Search through the RegWrites list to see
  11441. if there are any opposing CMOV pairs that
  11442. write to the same register }
  11443. for x := 0 to w - 1 do
  11444. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11445. begin
  11446. { We have a match. Keep this as a MOV }
  11447. { Move ahead in preparation }
  11448. GetNextInstruction(hp1, hp1);
  11449. RegMatch := True;
  11450. Break;
  11451. end;
  11452. if RegMatch then
  11453. Continue;
  11454. if taicpu(hp1).oper[0]^.typ = top_const then
  11455. begin
  11456. RegMatch := False;
  11457. for x := 0 to c - 1 do
  11458. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11459. begin
  11460. RegMatch := True;
  11461. { If it's in TmpUsedRegs, then this register
  11462. is being used more than once and hence has
  11463. already had its value defined (it gets
  11464. added to UsedRegs through AllocRegBetween
  11465. below) }
  11466. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11467. begin
  11468. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11469. asml.InsertBefore(hp_new, hp_flagalloc);
  11470. if Assigned(hp_prev2) then
  11471. TrySwapMovOp(hp_prev2, hp_new);
  11472. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11473. end
  11474. else
  11475. { We just need an instruction between hp_prev and hp1
  11476. where we know the register is marked as in use }
  11477. hp_new := hpmov1;
  11478. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11479. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11480. Break;
  11481. end;
  11482. if not RegMatch then
  11483. InternalError(2021100412);
  11484. end;
  11485. taicpu(hp1).opcode := A_CMOVcc;
  11486. taicpu(hp1).condition := condition;
  11487. end;
  11488. GetNextInstruction(hp1, hp1);
  11489. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11490. UpdateUsedRegs(tai(hp_jump.next));
  11491. UpdateUsedRegs(tai(hp_lblyyy.next));
  11492. { Get first instruction after label }
  11493. hp1 := p;
  11494. GetNextInstruction(hp_lblyyy, p);
  11495. { Don't dereference yet, as doing so will cause
  11496. GetNextInstruction to skip the label and
  11497. optional align marker. [Kit] }
  11498. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11499. { remove Jcc }
  11500. RemoveInstruction(hp1);
  11501. { Now we can safely decrement it }
  11502. tasmlabel(symbol).decrefs;
  11503. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11504. { Make sure the aligns get stripped too }
  11505. hp1 := tai(hp_lblxxx.Previous);
  11506. while Assigned(hp1) and (hp1.typ = ait_align) do
  11507. begin
  11508. hp_lblxxx := hp1;
  11509. hp1 := tai(hp_lblxxx.Previous);
  11510. end;
  11511. StripLabelFast(hp_lblxxx);
  11512. { remove jmp }
  11513. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11514. RemoveInstruction(hp_jump);
  11515. { As before, now we can safely decrement it }
  11516. TAsmLabel(symbol).decrefs;
  11517. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11518. if TAsmLabel(symbol).getrefs = 0 then
  11519. begin
  11520. { Make sure the aligns get stripped too }
  11521. hp1 := tai(hp_lblyyy.Previous);
  11522. while Assigned(hp1) and (hp1.typ = ait_align) do
  11523. begin
  11524. hp_lblyyy := hp1;
  11525. hp1 := tai(hp_lblyyy.Previous);
  11526. end;
  11527. StripLabelFast(hp_lblyyy);
  11528. end;
  11529. if Assigned(p) then
  11530. result := True;
  11531. exit;
  11532. end;
  11533. end;
  11534. end;
  11535. {$endif i8086}
  11536. end;
  11537. end;
  11538. end;
  11539. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11540. var
  11541. hp1,hp2,hp3: tai;
  11542. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11543. NewSize: TOpSize;
  11544. NewRegSize: TSubRegister;
  11545. Limit: TCgInt;
  11546. SwapOper: POper;
  11547. begin
  11548. result:=false;
  11549. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11550. GetNextInstruction(p,hp1) and
  11551. (hp1.typ = ait_instruction);
  11552. if reg_and_hp1_is_instr and
  11553. (
  11554. (taicpu(hp1).opcode <> A_LEA) or
  11555. { If the LEA instruction can be converted into an arithmetic instruction,
  11556. it may be possible to then fold it. }
  11557. (
  11558. { If the flags register is in use, don't change the instruction
  11559. to an ADD otherwise this will scramble the flags. [Kit] }
  11560. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11561. ConvertLEA(taicpu(hp1))
  11562. )
  11563. ) and
  11564. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11565. GetNextInstruction(hp1,hp2) and
  11566. MatchInstruction(hp2,A_MOV,[]) and
  11567. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11568. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11569. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11570. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11571. {$ifdef i386}
  11572. { not all registers have byte size sub registers on i386 }
  11573. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11574. {$endif i386}
  11575. (((taicpu(hp1).ops=2) and
  11576. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11577. ((taicpu(hp1).ops=1) and
  11578. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11579. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11580. begin
  11581. { change movsX/movzX reg/ref, reg2
  11582. add/sub/or/... reg3/$const, reg2
  11583. mov reg2 reg/ref
  11584. to add/sub/or/... reg3/$const, reg/ref }
  11585. { by example:
  11586. movswl %si,%eax movswl %si,%eax p
  11587. decl %eax addl %edx,%eax hp1
  11588. movw %ax,%si movw %ax,%si hp2
  11589. ->
  11590. movswl %si,%eax movswl %si,%eax p
  11591. decw %eax addw %edx,%eax hp1
  11592. movw %ax,%si movw %ax,%si hp2
  11593. }
  11594. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11595. {
  11596. ->
  11597. movswl %si,%eax movswl %si,%eax p
  11598. decw %si addw %dx,%si hp1
  11599. movw %ax,%si movw %ax,%si hp2
  11600. }
  11601. case taicpu(hp1).ops of
  11602. 1:
  11603. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11604. 2:
  11605. begin
  11606. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11607. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11608. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11609. end;
  11610. else
  11611. internalerror(2008042702);
  11612. end;
  11613. {
  11614. ->
  11615. decw %si addw %dx,%si p
  11616. }
  11617. DebugMsg(SPeepholeOptimization + 'var3',p);
  11618. RemoveCurrentP(p, hp1);
  11619. RemoveInstruction(hp2);
  11620. Result := True;
  11621. Exit;
  11622. end;
  11623. if reg_and_hp1_is_instr and
  11624. (taicpu(hp1).opcode = A_MOV) and
  11625. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11626. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11627. {$ifdef x86_64}
  11628. { check for implicit extension to 64 bit }
  11629. or
  11630. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11631. (taicpu(hp1).opsize=S_Q) and
  11632. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11633. )
  11634. {$endif x86_64}
  11635. )
  11636. then
  11637. begin
  11638. { change
  11639. movx %reg1,%reg2
  11640. mov %reg2,%reg3
  11641. dealloc %reg2
  11642. into
  11643. movx %reg,%reg3
  11644. }
  11645. TransferUsedRegs(TmpUsedRegs);
  11646. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11647. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11648. begin
  11649. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11650. {$ifdef x86_64}
  11651. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11652. (taicpu(hp1).opsize=S_Q) then
  11653. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11654. else
  11655. {$endif x86_64}
  11656. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11657. RemoveInstruction(hp1);
  11658. Result := True;
  11659. Exit;
  11660. end;
  11661. end;
  11662. if reg_and_hp1_is_instr and
  11663. ((taicpu(hp1).opcode=A_MOV) or
  11664. (taicpu(hp1).opcode=A_ADD) or
  11665. (taicpu(hp1).opcode=A_SUB) or
  11666. (taicpu(hp1).opcode=A_CMP) or
  11667. (taicpu(hp1).opcode=A_OR) or
  11668. (taicpu(hp1).opcode=A_XOR) or
  11669. (taicpu(hp1).opcode=A_AND)
  11670. ) and
  11671. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11672. begin
  11673. AndTest := (taicpu(hp1).opcode=A_AND) and
  11674. GetNextInstruction(hp1, hp2) and
  11675. (hp2.typ = ait_instruction) and
  11676. (
  11677. (
  11678. (taicpu(hp2).opcode=A_TEST) and
  11679. (
  11680. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11681. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11682. (
  11683. { If the AND and TEST instructions share a constant, this is also valid }
  11684. (taicpu(hp1).oper[0]^.typ = top_const) and
  11685. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11686. )
  11687. ) and
  11688. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11689. ) or
  11690. (
  11691. (taicpu(hp2).opcode=A_CMP) and
  11692. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11693. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11694. )
  11695. );
  11696. { change
  11697. movx (oper),%reg2
  11698. and $x,%reg2
  11699. test %reg2,%reg2
  11700. dealloc %reg2
  11701. into
  11702. op %reg1,%reg3
  11703. if the second op accesses only the bits stored in reg1
  11704. }
  11705. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11706. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11707. (taicpu(hp1).oper[0]^.typ = top_const) and
  11708. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11709. AndTest then
  11710. begin
  11711. { Check if the AND constant is in range }
  11712. case taicpu(p).opsize of
  11713. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11714. begin
  11715. NewSize := S_B;
  11716. Limit := $FF;
  11717. end;
  11718. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11719. begin
  11720. NewSize := S_W;
  11721. Limit := $FFFF;
  11722. end;
  11723. {$ifdef x86_64}
  11724. S_LQ:
  11725. begin
  11726. NewSize := S_L;
  11727. Limit := $FFFFFFFF;
  11728. end;
  11729. {$endif x86_64}
  11730. else
  11731. InternalError(2021120303);
  11732. end;
  11733. if (
  11734. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11735. { Check for negative operands }
  11736. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11737. ) and
  11738. GetNextInstruction(hp2,hp3) and
  11739. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11740. (taicpu(hp3).condition in [C_E,C_NE]) then
  11741. begin
  11742. TransferUsedRegs(TmpUsedRegs);
  11743. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11744. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11745. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11746. begin
  11747. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11748. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11749. taicpu(hp1).opcode := A_TEST;
  11750. taicpu(hp1).opsize := NewSize;
  11751. RemoveInstruction(hp2);
  11752. RemoveCurrentP(p, hp1);
  11753. Result:=true;
  11754. exit;
  11755. end;
  11756. end;
  11757. end;
  11758. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11759. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11760. (taicpu(hp1).opsize=S_B)) or
  11761. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11762. (taicpu(hp1).opsize=S_W))
  11763. {$ifdef x86_64}
  11764. or ((taicpu(p).opsize=S_LQ) and
  11765. (taicpu(hp1).opsize=S_L))
  11766. {$endif x86_64}
  11767. ) and
  11768. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11769. begin
  11770. { change
  11771. movx %reg1,%reg2
  11772. op %reg2,%reg3
  11773. dealloc %reg2
  11774. into
  11775. op %reg1,%reg3
  11776. if the second op accesses only the bits stored in reg1
  11777. }
  11778. TransferUsedRegs(TmpUsedRegs);
  11779. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11780. if AndTest then
  11781. begin
  11782. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11783. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11784. end
  11785. else
  11786. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11787. if not RegUsed then
  11788. begin
  11789. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11790. if taicpu(p).oper[0]^.typ=top_reg then
  11791. begin
  11792. case taicpu(hp1).opsize of
  11793. S_B:
  11794. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11795. S_W:
  11796. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11797. S_L:
  11798. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11799. else
  11800. Internalerror(2020102301);
  11801. end;
  11802. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11803. end
  11804. else
  11805. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11806. RemoveCurrentP(p);
  11807. if AndTest then
  11808. RemoveInstruction(hp2);
  11809. result:=true;
  11810. exit;
  11811. end;
  11812. end
  11813. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11814. (
  11815. { Bitwise operations only }
  11816. (taicpu(hp1).opcode=A_AND) or
  11817. (taicpu(hp1).opcode=A_TEST) or
  11818. (
  11819. (taicpu(hp1).oper[0]^.typ = top_const) and
  11820. (
  11821. (taicpu(hp1).opcode=A_OR) or
  11822. (taicpu(hp1).opcode=A_XOR)
  11823. )
  11824. )
  11825. ) and
  11826. (
  11827. (taicpu(hp1).oper[0]^.typ = top_const) or
  11828. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11829. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11830. ) then
  11831. begin
  11832. { change
  11833. movx %reg2,%reg2
  11834. op const,%reg2
  11835. into
  11836. op const,%reg2 (smaller version)
  11837. movx %reg2,%reg2
  11838. also change
  11839. movx %reg1,%reg2
  11840. and/test (oper),%reg2
  11841. dealloc %reg2
  11842. into
  11843. and/test (oper),%reg1
  11844. }
  11845. case taicpu(p).opsize of
  11846. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11847. begin
  11848. NewSize := S_B;
  11849. NewRegSize := R_SUBL;
  11850. Limit := $FF;
  11851. end;
  11852. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11853. begin
  11854. NewSize := S_W;
  11855. NewRegSize := R_SUBW;
  11856. Limit := $FFFF;
  11857. end;
  11858. {$ifdef x86_64}
  11859. S_LQ:
  11860. begin
  11861. NewSize := S_L;
  11862. NewRegSize := R_SUBD;
  11863. Limit := $FFFFFFFF;
  11864. end;
  11865. {$endif x86_64}
  11866. else
  11867. Internalerror(2021120302);
  11868. end;
  11869. TransferUsedRegs(TmpUsedRegs);
  11870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11871. if AndTest then
  11872. begin
  11873. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11874. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11875. end
  11876. else
  11877. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11878. if
  11879. (
  11880. (taicpu(p).opcode = A_MOVZX) and
  11881. (
  11882. (taicpu(hp1).opcode=A_AND) or
  11883. (taicpu(hp1).opcode=A_TEST)
  11884. ) and
  11885. not (
  11886. { If both are references, then the final instruction will have
  11887. both operands as references, which is not allowed }
  11888. (taicpu(p).oper[0]^.typ = top_ref) and
  11889. (taicpu(hp1).oper[0]^.typ = top_ref)
  11890. ) and
  11891. not RegUsed
  11892. ) or
  11893. (
  11894. (
  11895. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11896. not RegUsed
  11897. ) and
  11898. (taicpu(p).oper[0]^.typ = top_reg) and
  11899. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11900. (taicpu(hp1).oper[0]^.typ = top_const) and
  11901. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11902. ) then
  11903. begin
  11904. {$if defined(i386) or defined(i8086)}
  11905. { If the target size is 8-bit, make sure we can actually encode it }
  11906. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  11907. Exit;
  11908. {$endif i386 or i8086}
  11909. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11910. taicpu(hp1).opsize := NewSize;
  11911. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11912. if AndTest then
  11913. begin
  11914. RemoveInstruction(hp2);
  11915. if not RegUsed then
  11916. begin
  11917. taicpu(hp1).opcode := A_TEST;
  11918. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11919. begin
  11920. { Make sure the reference is the second operand }
  11921. SwapOper := taicpu(hp1).oper[0];
  11922. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11923. taicpu(hp1).oper[1] := SwapOper;
  11924. end;
  11925. end;
  11926. end;
  11927. case taicpu(hp1).oper[0]^.typ of
  11928. top_reg:
  11929. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11930. top_const:
  11931. { For the AND/TEST case }
  11932. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11933. else
  11934. ;
  11935. end;
  11936. if RegUsed then
  11937. begin
  11938. AsmL.Remove(p);
  11939. AsmL.InsertAfter(p, hp1);
  11940. p := hp1;
  11941. end
  11942. else
  11943. RemoveCurrentP(p, hp1);
  11944. result:=true;
  11945. exit;
  11946. end;
  11947. end;
  11948. end;
  11949. if reg_and_hp1_is_instr and
  11950. (taicpu(p).oper[0]^.typ = top_reg) and
  11951. (
  11952. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11953. ) and
  11954. (taicpu(hp1).oper[0]^.typ = top_const) and
  11955. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11956. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11957. { Minimum shift value allowed is the bit difference between the sizes }
  11958. (taicpu(hp1).oper[0]^.val >=
  11959. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11960. 8 * (
  11961. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11962. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11963. )
  11964. ) then
  11965. begin
  11966. { For:
  11967. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11968. shl/sal ##, %reg1
  11969. Remove the movsx/movzx instruction if the shift overwrites the
  11970. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11971. }
  11972. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11973. RemoveCurrentP(p, hp1);
  11974. Result := True;
  11975. Exit;
  11976. end
  11977. else if reg_and_hp1_is_instr and
  11978. (taicpu(p).oper[0]^.typ = top_reg) and
  11979. (
  11980. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11981. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11982. ) and
  11983. (taicpu(hp1).oper[0]^.typ = top_const) and
  11984. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11985. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11986. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11987. (taicpu(hp1).oper[0]^.val <
  11988. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11989. 8 * (
  11990. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11991. )
  11992. ) then
  11993. begin
  11994. { For:
  11995. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11996. sar ##, %reg1 shr ##, %reg1
  11997. Move the shift to before the movx instruction if the shift value
  11998. is not too large.
  11999. }
  12000. asml.Remove(hp1);
  12001. asml.InsertBefore(hp1, p);
  12002. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12003. case taicpu(p).opsize of
  12004. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12005. taicpu(hp1).opsize := S_B;
  12006. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12007. taicpu(hp1).opsize := S_W;
  12008. {$ifdef x86_64}
  12009. S_LQ:
  12010. taicpu(hp1).opsize := S_L;
  12011. {$endif}
  12012. else
  12013. InternalError(2020112401);
  12014. end;
  12015. if (taicpu(hp1).opcode = A_SHR) then
  12016. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12017. else
  12018. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12019. Result := True;
  12020. end;
  12021. if reg_and_hp1_is_instr and
  12022. (taicpu(p).oper[0]^.typ = top_reg) and
  12023. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12024. (
  12025. (taicpu(hp1).opcode = taicpu(p).opcode)
  12026. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12027. {$ifdef x86_64}
  12028. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12029. {$endif x86_64}
  12030. ) then
  12031. begin
  12032. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12033. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12034. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12035. begin
  12036. {
  12037. For example:
  12038. movzbw %al,%ax
  12039. movzwl %ax,%eax
  12040. Compress into:
  12041. movzbl %al,%eax
  12042. }
  12043. RegUsed := False;
  12044. case taicpu(p).opsize of
  12045. S_BW:
  12046. case taicpu(hp1).opsize of
  12047. S_WL:
  12048. begin
  12049. taicpu(p).opsize := S_BL;
  12050. RegUsed := True;
  12051. end;
  12052. {$ifdef x86_64}
  12053. S_WQ:
  12054. begin
  12055. if taicpu(p).opcode = A_MOVZX then
  12056. begin
  12057. taicpu(p).opsize := S_BL;
  12058. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12059. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12060. end
  12061. else
  12062. taicpu(p).opsize := S_BQ;
  12063. RegUsed := True;
  12064. end;
  12065. {$endif x86_64}
  12066. else
  12067. ;
  12068. end;
  12069. {$ifdef x86_64}
  12070. S_BL:
  12071. case taicpu(hp1).opsize of
  12072. S_LQ:
  12073. begin
  12074. if taicpu(p).opcode = A_MOVZX then
  12075. begin
  12076. taicpu(p).opsize := S_BL;
  12077. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12078. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12079. end
  12080. else
  12081. taicpu(p).opsize := S_BQ;
  12082. RegUsed := True;
  12083. end;
  12084. else
  12085. ;
  12086. end;
  12087. S_WL:
  12088. case taicpu(hp1).opsize of
  12089. S_LQ:
  12090. begin
  12091. if taicpu(p).opcode = A_MOVZX then
  12092. begin
  12093. taicpu(p).opsize := S_WL;
  12094. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12095. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12096. end
  12097. else
  12098. taicpu(p).opsize := S_WQ;
  12099. RegUsed := True;
  12100. end;
  12101. else
  12102. ;
  12103. end;
  12104. {$endif x86_64}
  12105. else
  12106. ;
  12107. end;
  12108. if RegUsed then
  12109. begin
  12110. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12111. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12112. RemoveInstruction(hp1);
  12113. Result := True;
  12114. Exit;
  12115. end;
  12116. end;
  12117. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12118. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12119. GetNextInstruction(hp1, hp2) and
  12120. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12121. (
  12122. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12123. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12124. {$ifdef x86_64}
  12125. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12126. {$endif x86_64}
  12127. ) and
  12128. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12129. (
  12130. (
  12131. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12132. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12133. ) or
  12134. (
  12135. { Only allow the operands in reverse order for TEST instructions }
  12136. (taicpu(hp2).opcode = A_TEST) and
  12137. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12138. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12139. )
  12140. ) then
  12141. begin
  12142. {
  12143. For example:
  12144. movzbl %al,%eax
  12145. movzbl (ref),%edx
  12146. andl %edx,%eax
  12147. (%edx deallocated)
  12148. Change to:
  12149. andb (ref),%al
  12150. movzbl %al,%eax
  12151. Rules are:
  12152. - First two instructions have the same opcode and opsize
  12153. - First instruction's operands are the same super-register
  12154. - Second instruction operates on a different register
  12155. - Third instruction is AND, OR, XOR or TEST
  12156. - Third instruction's operands are the destination registers of the first two instructions
  12157. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12158. - Second instruction's destination register is deallocated afterwards
  12159. }
  12160. TransferUsedRegs(TmpUsedRegs);
  12161. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12162. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12163. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12164. begin
  12165. case taicpu(p).opsize of
  12166. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12167. NewSize := S_B;
  12168. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12169. NewSize := S_W;
  12170. {$ifdef x86_64}
  12171. S_LQ:
  12172. NewSize := S_L;
  12173. {$endif x86_64}
  12174. else
  12175. InternalError(2021120301);
  12176. end;
  12177. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12178. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12179. taicpu(hp2).opsize := NewSize;
  12180. RemoveInstruction(hp1);
  12181. { With TEST, it's best to keep the MOVX instruction at the top }
  12182. if (taicpu(hp2).opcode <> A_TEST) then
  12183. begin
  12184. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12185. asml.Remove(p);
  12186. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12187. asml.InsertAfter(p, hp2);
  12188. p := hp2;
  12189. end
  12190. else
  12191. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12192. Result := True;
  12193. Exit;
  12194. end;
  12195. end;
  12196. end;
  12197. if taicpu(p).opcode=A_MOVZX then
  12198. begin
  12199. { removes superfluous And's after movzx's }
  12200. if reg_and_hp1_is_instr and
  12201. (taicpu(hp1).opcode = A_AND) and
  12202. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12203. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12204. {$ifdef x86_64}
  12205. { check for implicit extension to 64 bit }
  12206. or
  12207. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12208. (taicpu(hp1).opsize=S_Q) and
  12209. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12210. )
  12211. {$endif x86_64}
  12212. )
  12213. then
  12214. begin
  12215. case taicpu(p).opsize Of
  12216. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12217. if (taicpu(hp1).oper[0]^.val = $ff) then
  12218. begin
  12219. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12220. RemoveInstruction(hp1);
  12221. Result:=true;
  12222. exit;
  12223. end;
  12224. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12225. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12226. begin
  12227. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12228. RemoveInstruction(hp1);
  12229. Result:=true;
  12230. exit;
  12231. end;
  12232. {$ifdef x86_64}
  12233. S_LQ:
  12234. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12235. begin
  12236. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12237. RemoveInstruction(hp1);
  12238. Result:=true;
  12239. exit;
  12240. end;
  12241. {$endif x86_64}
  12242. else
  12243. ;
  12244. end;
  12245. { we cannot get rid of the and, but can we get rid of the movz ?}
  12246. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12247. begin
  12248. case taicpu(p).opsize Of
  12249. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12250. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12251. begin
  12252. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12253. RemoveCurrentP(p,hp1);
  12254. Result:=true;
  12255. exit;
  12256. end;
  12257. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12258. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12259. begin
  12260. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12261. RemoveCurrentP(p,hp1);
  12262. Result:=true;
  12263. exit;
  12264. end;
  12265. {$ifdef x86_64}
  12266. S_LQ:
  12267. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12268. begin
  12269. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12270. RemoveCurrentP(p,hp1);
  12271. Result:=true;
  12272. exit;
  12273. end;
  12274. {$endif x86_64}
  12275. else
  12276. ;
  12277. end;
  12278. end;
  12279. end;
  12280. { changes some movzx constructs to faster synonyms (all examples
  12281. are given with eax/ax, but are also valid for other registers)}
  12282. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12283. begin
  12284. case taicpu(p).opsize of
  12285. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12286. (the machine code is equivalent to movzbl %al,%eax), but the
  12287. code generator still generates that assembler instruction and
  12288. it is silently converted. This should probably be checked.
  12289. [Kit] }
  12290. S_BW:
  12291. begin
  12292. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12293. (
  12294. not IsMOVZXAcceptable
  12295. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12296. or (
  12297. (cs_opt_size in current_settings.optimizerswitches) and
  12298. (taicpu(p).oper[1]^.reg = NR_AX)
  12299. )
  12300. ) then
  12301. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12302. begin
  12303. DebugMsg(SPeepholeOptimization + 'var7',p);
  12304. taicpu(p).opcode := A_AND;
  12305. taicpu(p).changeopsize(S_W);
  12306. taicpu(p).loadConst(0,$ff);
  12307. Result := True;
  12308. end
  12309. else if not IsMOVZXAcceptable and
  12310. GetNextInstruction(p, hp1) and
  12311. (tai(hp1).typ = ait_instruction) and
  12312. (taicpu(hp1).opcode = A_AND) and
  12313. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12314. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12315. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12316. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12317. begin
  12318. DebugMsg(SPeepholeOptimization + 'var8',p);
  12319. taicpu(p).opcode := A_MOV;
  12320. taicpu(p).changeopsize(S_W);
  12321. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12322. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12323. Result := True;
  12324. end;
  12325. end;
  12326. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12327. S_BL:
  12328. if not IsMOVZXAcceptable then
  12329. begin
  12330. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12331. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12332. begin
  12333. DebugMsg(SPeepholeOptimization + 'var9',p);
  12334. taicpu(p).opcode := A_AND;
  12335. taicpu(p).changeopsize(S_L);
  12336. taicpu(p).loadConst(0,$ff);
  12337. Result := True;
  12338. end
  12339. else if GetNextInstruction(p, hp1) and
  12340. (tai(hp1).typ = ait_instruction) and
  12341. (taicpu(hp1).opcode = A_AND) and
  12342. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12343. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12344. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12345. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12346. begin
  12347. DebugMsg(SPeepholeOptimization + 'var10',p);
  12348. taicpu(p).opcode := A_MOV;
  12349. taicpu(p).changeopsize(S_L);
  12350. { do not use R_SUBWHOLE
  12351. as movl %rdx,%eax
  12352. is invalid in assembler PM }
  12353. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12354. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12355. Result := True;
  12356. end;
  12357. end;
  12358. {$endif i8086}
  12359. S_WL:
  12360. if not IsMOVZXAcceptable then
  12361. begin
  12362. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12363. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12364. begin
  12365. DebugMsg(SPeepholeOptimization + 'var11',p);
  12366. taicpu(p).opcode := A_AND;
  12367. taicpu(p).changeopsize(S_L);
  12368. taicpu(p).loadConst(0,$ffff);
  12369. Result := True;
  12370. end
  12371. else if GetNextInstruction(p, hp1) and
  12372. (tai(hp1).typ = ait_instruction) and
  12373. (taicpu(hp1).opcode = A_AND) and
  12374. (taicpu(hp1).oper[0]^.typ = top_const) and
  12375. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12376. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12377. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12378. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12379. begin
  12380. DebugMsg(SPeepholeOptimization + 'var12',p);
  12381. taicpu(p).opcode := A_MOV;
  12382. taicpu(p).changeopsize(S_L);
  12383. { do not use R_SUBWHOLE
  12384. as movl %rdx,%eax
  12385. is invalid in assembler PM }
  12386. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12387. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12388. Result := True;
  12389. end;
  12390. end;
  12391. else
  12392. InternalError(2017050705);
  12393. end;
  12394. end
  12395. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12396. begin
  12397. if GetNextInstruction(p, hp1) and
  12398. (tai(hp1).typ = ait_instruction) and
  12399. (taicpu(hp1).opcode = A_AND) and
  12400. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12401. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12402. begin
  12403. //taicpu(p).opcode := A_MOV;
  12404. case taicpu(p).opsize Of
  12405. S_BL:
  12406. begin
  12407. DebugMsg(SPeepholeOptimization + 'var13',p);
  12408. taicpu(hp1).changeopsize(S_L);
  12409. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12410. end;
  12411. S_WL:
  12412. begin
  12413. DebugMsg(SPeepholeOptimization + 'var14',p);
  12414. taicpu(hp1).changeopsize(S_L);
  12415. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12416. end;
  12417. S_BW:
  12418. begin
  12419. DebugMsg(SPeepholeOptimization + 'var15',p);
  12420. taicpu(hp1).changeopsize(S_W);
  12421. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12422. end;
  12423. else
  12424. Internalerror(2017050704)
  12425. end;
  12426. Result := True;
  12427. end;
  12428. end;
  12429. end;
  12430. end;
  12431. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12432. var
  12433. hp1, hp2 : tai;
  12434. MaskLength : Cardinal;
  12435. MaskedBits : TCgInt;
  12436. ActiveReg : TRegister;
  12437. begin
  12438. Result:=false;
  12439. { There are no optimisations for reference targets }
  12440. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12441. Exit;
  12442. while GetNextInstruction(p, hp1) and
  12443. (hp1.typ = ait_instruction) do
  12444. begin
  12445. if (taicpu(p).oper[0]^.typ = top_const) then
  12446. begin
  12447. case taicpu(hp1).opcode of
  12448. A_AND:
  12449. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12450. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12451. { the second register must contain the first one, so compare their subreg types }
  12452. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12453. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12454. { change
  12455. and const1, reg
  12456. and const2, reg
  12457. to
  12458. and (const1 and const2), reg
  12459. }
  12460. begin
  12461. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12462. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12463. RemoveCurrentP(p, hp1);
  12464. Result:=true;
  12465. exit;
  12466. end;
  12467. A_CMP:
  12468. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12469. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12470. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12471. { Just check that the condition on the next instruction is compatible }
  12472. GetNextInstruction(hp1, hp2) and
  12473. (hp2.typ = ait_instruction) and
  12474. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12475. then
  12476. { change
  12477. and 2^n, reg
  12478. cmp 2^n, reg
  12479. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12480. to
  12481. and 2^n, reg
  12482. test reg, reg
  12483. j(~c) / set(~c) / cmov(~c)
  12484. }
  12485. begin
  12486. { Keep TEST instruction in, rather than remove it, because
  12487. it may trigger other optimisations such as MovAndTest2Test }
  12488. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12489. taicpu(hp1).opcode := A_TEST;
  12490. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12491. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12492. Result := True;
  12493. Exit;
  12494. end
  12495. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12496. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12497. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12498. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12499. { change
  12500. and $ff/$ff/$ffff, reg
  12501. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12502. dealloc reg
  12503. to
  12504. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12505. }
  12506. begin
  12507. TransferUsedRegs(TmpUsedRegs);
  12508. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12509. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12510. begin
  12511. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12512. case taicpu(p).oper[0]^.val of
  12513. $ff:
  12514. begin
  12515. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12516. taicpu(hp1).opsize:=S_B;
  12517. end;
  12518. $ffff:
  12519. begin
  12520. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12521. taicpu(hp1).opsize:=S_W;
  12522. end;
  12523. $ffffffff:
  12524. begin
  12525. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12526. taicpu(hp1).opsize:=S_L;
  12527. end;
  12528. else
  12529. Internalerror(2023030401);
  12530. end;
  12531. RemoveCurrentP(p);
  12532. Result := True;
  12533. Exit;
  12534. end;
  12535. end;
  12536. A_MOVZX:
  12537. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12538. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12539. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12540. (
  12541. (
  12542. (taicpu(p).opsize=S_W) and
  12543. (taicpu(hp1).opsize=S_BW)
  12544. ) or
  12545. (
  12546. (taicpu(p).opsize=S_L) and
  12547. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12548. )
  12549. {$ifdef x86_64}
  12550. or
  12551. (
  12552. (taicpu(p).opsize=S_Q) and
  12553. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12554. )
  12555. {$endif x86_64}
  12556. ) then
  12557. begin
  12558. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12559. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12560. ) or
  12561. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12562. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12563. then
  12564. begin
  12565. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12566. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12567. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12568. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12569. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12570. }
  12571. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12572. RemoveInstruction(hp1);
  12573. { See if there are other optimisations possible }
  12574. Continue;
  12575. end;
  12576. end;
  12577. A_SHL:
  12578. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12579. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12580. begin
  12581. {$ifopt R+}
  12582. {$define RANGE_WAS_ON}
  12583. {$R-}
  12584. {$endif}
  12585. { get length of potential and mask }
  12586. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12587. { really a mask? }
  12588. {$ifdef RANGE_WAS_ON}
  12589. {$R+}
  12590. {$endif}
  12591. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12592. { unmasked part shifted out? }
  12593. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12594. begin
  12595. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12596. RemoveCurrentP(p, hp1);
  12597. Result:=true;
  12598. exit;
  12599. end;
  12600. end;
  12601. A_SHR:
  12602. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12603. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12604. (taicpu(hp1).oper[0]^.val <= 63) then
  12605. begin
  12606. { Does SHR combined with the AND cover all the bits?
  12607. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12608. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12609. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12610. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12611. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12612. begin
  12613. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12614. RemoveCurrentP(p, hp1);
  12615. Result := True;
  12616. Exit;
  12617. end;
  12618. end;
  12619. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12620. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12621. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12622. begin
  12623. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12624. (
  12625. (
  12626. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12627. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12628. ) or (
  12629. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12630. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12631. {$ifdef x86_64}
  12632. ) or (
  12633. (taicpu(hp1).opsize = S_LQ) and
  12634. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12635. {$endif x86_64}
  12636. )
  12637. ) then
  12638. begin
  12639. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12640. begin
  12641. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12642. RemoveInstruction(hp1);
  12643. { See if there are other optimisations possible }
  12644. Continue;
  12645. end;
  12646. { The super-registers are the same though.
  12647. Note that this change by itself doesn't improve
  12648. code speed, but it opens up other optimisations. }
  12649. {$ifdef x86_64}
  12650. { Convert 64-bit register to 32-bit }
  12651. case taicpu(hp1).opsize of
  12652. S_BQ:
  12653. begin
  12654. taicpu(hp1).opsize := S_BL;
  12655. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12656. end;
  12657. S_WQ:
  12658. begin
  12659. taicpu(hp1).opsize := S_WL;
  12660. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12661. end
  12662. else
  12663. ;
  12664. end;
  12665. {$endif x86_64}
  12666. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12667. taicpu(hp1).opcode := A_MOVZX;
  12668. { See if there are other optimisations possible }
  12669. Continue;
  12670. end;
  12671. end;
  12672. else
  12673. ;
  12674. end;
  12675. end
  12676. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12677. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12678. begin
  12679. {$ifdef x86_64}
  12680. if (taicpu(p).opsize = S_Q) then
  12681. begin
  12682. { Never necessary }
  12683. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12684. RemoveCurrentP(p, hp1);
  12685. Result := True;
  12686. Exit;
  12687. end;
  12688. {$endif x86_64}
  12689. { Forward check to determine necessity of and %reg,%reg }
  12690. TransferUsedRegs(TmpUsedRegs);
  12691. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12692. { Saves on a bunch of dereferences }
  12693. ActiveReg := taicpu(p).oper[1]^.reg;
  12694. case taicpu(hp1).opcode of
  12695. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12696. if (
  12697. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12698. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12699. ) and
  12700. (
  12701. (taicpu(hp1).opcode <> A_MOV) or
  12702. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12703. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12704. ) and
  12705. not (
  12706. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12707. (taicpu(hp1).opcode = A_MOV) and
  12708. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12709. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12710. ) and
  12711. (
  12712. (
  12713. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12714. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12715. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12716. ) or
  12717. (
  12718. {$ifdef x86_64}
  12719. (
  12720. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12721. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12722. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12723. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12724. ) and
  12725. {$endif x86_64}
  12726. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12727. )
  12728. ) then
  12729. begin
  12730. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12731. RemoveCurrentP(p, hp1);
  12732. Result := True;
  12733. Exit;
  12734. end;
  12735. A_ADD,
  12736. A_AND,
  12737. A_BSF,
  12738. A_BSR,
  12739. A_BTC,
  12740. A_BTR,
  12741. A_BTS,
  12742. A_OR,
  12743. A_SUB,
  12744. A_XOR:
  12745. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12746. if (
  12747. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12748. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12749. ) and
  12750. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12751. begin
  12752. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12753. RemoveCurrentP(p, hp1);
  12754. Result := True;
  12755. Exit;
  12756. end;
  12757. A_CMP,
  12758. A_TEST:
  12759. if (
  12760. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12761. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12762. ) and
  12763. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12764. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12765. begin
  12766. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12767. RemoveCurrentP(p, hp1);
  12768. Result := True;
  12769. Exit;
  12770. end;
  12771. A_BSWAP,
  12772. A_NEG,
  12773. A_NOT:
  12774. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12775. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12776. begin
  12777. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12778. RemoveCurrentP(p, hp1);
  12779. Result := True;
  12780. Exit;
  12781. end;
  12782. else
  12783. ;
  12784. end;
  12785. end;
  12786. if (taicpu(hp1).is_jmp) and
  12787. (taicpu(hp1).opcode<>A_JMP) and
  12788. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12789. begin
  12790. { change
  12791. and x, reg
  12792. jxx
  12793. to
  12794. test x, reg
  12795. jxx
  12796. if reg is deallocated before the
  12797. jump, but only if it's a conditional jump (PFV)
  12798. }
  12799. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12800. taicpu(p).opcode := A_TEST;
  12801. Exit;
  12802. end;
  12803. Break;
  12804. end;
  12805. { Lone AND tests }
  12806. if (taicpu(p).oper[0]^.typ = top_const) then
  12807. begin
  12808. {
  12809. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12810. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12811. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12812. }
  12813. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12814. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12815. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12816. begin
  12817. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12818. if taicpu(p).opsize = S_L then
  12819. begin
  12820. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12821. Result := True;
  12822. end;
  12823. end;
  12824. end;
  12825. { Backward check to determine necessity of and %reg,%reg }
  12826. if (taicpu(p).oper[0]^.typ = top_reg) and
  12827. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12828. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12829. GetLastInstruction(p, hp2) and
  12830. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12831. { Check size of adjacent instruction to determine if the AND is
  12832. effectively a null operation }
  12833. (
  12834. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12835. { Note: Don't include S_Q }
  12836. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12837. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12838. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12839. ) then
  12840. begin
  12841. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12842. { If GetNextInstruction returned False, hp1 will be nil }
  12843. RemoveCurrentP(p, hp1);
  12844. Result := True;
  12845. Exit;
  12846. end;
  12847. end;
  12848. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12849. var
  12850. hp1, hp2: tai;
  12851. NewRef: TReference;
  12852. Distance: Cardinal;
  12853. TempTracking: TAllUsedRegs;
  12854. { This entire nested function is used in an if-statement below, but we
  12855. want to avoid all the used reg transfers and GetNextInstruction calls
  12856. until we really have to check }
  12857. function MemRegisterNotUsedLater: Boolean; inline;
  12858. var
  12859. hp2: tai;
  12860. begin
  12861. TransferUsedRegs(TmpUsedRegs);
  12862. hp2 := p;
  12863. repeat
  12864. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12865. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12866. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12867. end;
  12868. begin
  12869. Result := False;
  12870. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12871. (taicpu(p).oper[1]^.typ = top_reg) then
  12872. begin
  12873. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12874. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12875. (hp1.typ <> ait_instruction) or
  12876. not
  12877. (
  12878. (cs_opt_level3 in current_settings.optimizerswitches) or
  12879. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12880. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12881. ) then
  12882. Exit;
  12883. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12884. addq $x, %rax
  12885. movq %rax, %rdx
  12886. sarq $63, %rdx
  12887. (%rax still in use)
  12888. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12889. leaq $x(%rax),%rdx
  12890. addq $x, %rax
  12891. sarq $63, %rdx
  12892. ...which is okay since it breaks the dependency chain between
  12893. addq and movq, but if OptPass2MOV is called first:
  12894. addq $x, %rax
  12895. cqto
  12896. ...which is better in all ways, taking only 2 cycles to execute
  12897. and much smaller in code size.
  12898. }
  12899. { The extra register tracking is quite strenuous }
  12900. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12901. MatchInstruction(hp1, A_MOV, []) then
  12902. begin
  12903. { Update the register tracking to the MOV instruction }
  12904. CopyUsedRegs(TempTracking);
  12905. hp2 := p;
  12906. repeat
  12907. UpdateUsedRegs(tai(hp2.Next));
  12908. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12909. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12910. OptPass2ADD get called again }
  12911. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12912. begin
  12913. { Reset the tracking to the current instruction }
  12914. RestoreUsedRegs(TempTracking);
  12915. ReleaseUsedRegs(TempTracking);
  12916. Result := True;
  12917. Exit;
  12918. end;
  12919. { Reset the tracking to the current instruction }
  12920. RestoreUsedRegs(TempTracking);
  12921. ReleaseUsedRegs(TempTracking);
  12922. { If OptPass2MOV returned True, we don't need to set Result to
  12923. True if hp1 didn't change because the ADD instruction didn't
  12924. get modified and we'll be evaluating hp1 again when the
  12925. peephole optimizer reaches it }
  12926. end;
  12927. { Change:
  12928. add %reg2,%reg1
  12929. (%reg2 not modified in between)
  12930. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12931. To:
  12932. mov/s/z #(%reg1,%reg2),%reg1
  12933. }
  12934. if (taicpu(p).oper[0]^.typ = top_reg) and
  12935. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12936. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12937. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12938. (
  12939. (
  12940. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12941. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12942. { r/esp cannot be an index }
  12943. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12944. ) or (
  12945. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12946. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12947. )
  12948. ) and (
  12949. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12950. (
  12951. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12952. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12953. MemRegisterNotUsedLater
  12954. )
  12955. ) then
  12956. begin
  12957. if (
  12958. { Instructions are guaranteed to be adjacent on -O2 and under }
  12959. (cs_opt_level3 in current_settings.optimizerswitches) and
  12960. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12961. ) then
  12962. begin
  12963. { If the other register is used in between, move the MOV
  12964. instruction to right after the ADD instruction so a
  12965. saving can still be made }
  12966. Asml.Remove(hp1);
  12967. Asml.InsertAfter(hp1, p);
  12968. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12969. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12970. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12971. RemoveCurrentp(p, hp1);
  12972. end
  12973. else
  12974. begin
  12975. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12976. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12977. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12978. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12979. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12980. { hp1 may not be the immediate next instruction under -O3 }
  12981. RemoveCurrentp(p)
  12982. else
  12983. RemoveCurrentp(p, hp1);
  12984. end;
  12985. Result := True;
  12986. Exit;
  12987. end;
  12988. { Change:
  12989. addl/q $x,%reg1
  12990. movl/q %reg1,%reg2
  12991. To:
  12992. leal/q $x(%reg1),%reg2
  12993. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12994. Breaks the dependency chain.
  12995. }
  12996. if (taicpu(p).oper[0]^.typ = top_const) and
  12997. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12998. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12999. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13000. (
  13001. { Instructions are guaranteed to be adjacent on -O2 and under }
  13002. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13003. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13004. ) then
  13005. begin
  13006. TransferUsedRegs(TmpUsedRegs);
  13007. hp2 := p;
  13008. repeat
  13009. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13010. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13011. if (
  13012. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13013. not (cs_opt_size in current_settings.optimizerswitches) or
  13014. (
  13015. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13016. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13017. )
  13018. ) then
  13019. begin
  13020. { Change the MOV instruction to a LEA instruction, and update the
  13021. first operand }
  13022. reference_reset(NewRef, 1, []);
  13023. NewRef.base := taicpu(p).oper[1]^.reg;
  13024. NewRef.scalefactor := 1;
  13025. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13026. taicpu(hp1).opcode := A_LEA;
  13027. taicpu(hp1).loadref(0, NewRef);
  13028. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13029. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13030. begin
  13031. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13032. { Move what is now the LEA instruction to before the ADD instruction }
  13033. Asml.Remove(hp1);
  13034. Asml.InsertBefore(hp1, p);
  13035. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13036. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13037. p := hp1;
  13038. end
  13039. else
  13040. begin
  13041. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13042. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13043. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13044. { hp1 may not be the immediate next instruction under -O3 }
  13045. RemoveCurrentp(p)
  13046. else
  13047. RemoveCurrentp(p, hp1);
  13048. end;
  13049. Result := True;
  13050. end;
  13051. end;
  13052. end;
  13053. end;
  13054. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13055. var
  13056. SubReg: TSubRegister;
  13057. begin
  13058. Result:=false;
  13059. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13060. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13061. with taicpu(p).oper[0]^.ref^ do
  13062. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13063. begin
  13064. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13065. begin
  13066. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13067. taicpu(p).opcode := A_ADD;
  13068. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13069. Result := True;
  13070. end
  13071. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13072. begin
  13073. if (base <> NR_NO) then
  13074. begin
  13075. if (scalefactor <= 1) then
  13076. begin
  13077. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13078. taicpu(p).opcode := A_ADD;
  13079. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13080. Result := True;
  13081. end;
  13082. end
  13083. else
  13084. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13085. if (scalefactor in [2, 4, 8]) then
  13086. begin
  13087. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13088. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13089. taicpu(p).opcode := A_SHL;
  13090. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13091. Result := True;
  13092. end;
  13093. end;
  13094. end;
  13095. end;
  13096. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13097. var
  13098. hp1, hp2: tai;
  13099. NewRef: TReference;
  13100. Distance: Cardinal;
  13101. TempTracking: TAllUsedRegs;
  13102. begin
  13103. Result := False;
  13104. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13105. MatchOpType(taicpu(p),top_const,top_reg) then
  13106. begin
  13107. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13108. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13109. (hp1.typ <> ait_instruction) or
  13110. not
  13111. (
  13112. (cs_opt_level3 in current_settings.optimizerswitches) or
  13113. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13114. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13115. ) then
  13116. Exit;
  13117. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13118. subq $x, %rax
  13119. movq %rax, %rdx
  13120. sarq $63, %rdx
  13121. (%rax still in use)
  13122. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13123. leaq $-x(%rax),%rdx
  13124. movq $x, %rax
  13125. sarq $63, %rdx
  13126. ...which is okay since it breaks the dependency chain between
  13127. subq and movq, but if OptPass2MOV is called first:
  13128. subq $x, %rax
  13129. cqto
  13130. ...which is better in all ways, taking only 2 cycles to execute
  13131. and much smaller in code size.
  13132. }
  13133. { The extra register tracking is quite strenuous }
  13134. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13135. MatchInstruction(hp1, A_MOV, []) then
  13136. begin
  13137. { Update the register tracking to the MOV instruction }
  13138. CopyUsedRegs(TempTracking);
  13139. hp2 := p;
  13140. repeat
  13141. UpdateUsedRegs(tai(hp2.Next));
  13142. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13143. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13144. OptPass2SUB get called again }
  13145. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13146. begin
  13147. { Reset the tracking to the current instruction }
  13148. RestoreUsedRegs(TempTracking);
  13149. ReleaseUsedRegs(TempTracking);
  13150. Result := True;
  13151. Exit;
  13152. end;
  13153. { Reset the tracking to the current instruction }
  13154. RestoreUsedRegs(TempTracking);
  13155. ReleaseUsedRegs(TempTracking);
  13156. { If OptPass2MOV returned True, we don't need to set Result to
  13157. True if hp1 didn't change because the SUB instruction didn't
  13158. get modified and we'll be evaluating hp1 again when the
  13159. peephole optimizer reaches it }
  13160. end;
  13161. { Change:
  13162. subl/q $x,%reg1
  13163. movl/q %reg1,%reg2
  13164. To:
  13165. leal/q $-x(%reg1),%reg2
  13166. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13167. Breaks the dependency chain and potentially permits the removal of
  13168. a CMP instruction if one follows.
  13169. }
  13170. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13171. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13172. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13173. (
  13174. { Instructions are guaranteed to be adjacent on -O2 and under }
  13175. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13176. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13177. ) then
  13178. begin
  13179. TransferUsedRegs(TmpUsedRegs);
  13180. hp2 := p;
  13181. repeat
  13182. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13183. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13184. if (
  13185. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13186. not (cs_opt_size in current_settings.optimizerswitches) or
  13187. (
  13188. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13189. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13190. )
  13191. ) then
  13192. begin
  13193. { Change the MOV instruction to a LEA instruction, and update the
  13194. first operand }
  13195. reference_reset(NewRef, 1, []);
  13196. NewRef.base := taicpu(p).oper[1]^.reg;
  13197. NewRef.scalefactor := 1;
  13198. NewRef.offset := -taicpu(p).oper[0]^.val;
  13199. taicpu(hp1).opcode := A_LEA;
  13200. taicpu(hp1).loadref(0, NewRef);
  13201. TransferUsedRegs(TmpUsedRegs);
  13202. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13203. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13204. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13205. begin
  13206. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13207. { Move what is now the LEA instruction to before the SUB instruction }
  13208. Asml.Remove(hp1);
  13209. Asml.InsertBefore(hp1, p);
  13210. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13211. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13212. p := hp1;
  13213. end
  13214. else
  13215. begin
  13216. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13217. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13218. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13219. { hp1 may not be the immediate next instruction under -O3 }
  13220. RemoveCurrentp(p)
  13221. else
  13222. RemoveCurrentp(p, hp1);
  13223. end;
  13224. Result := True;
  13225. end;
  13226. end;
  13227. end;
  13228. end;
  13229. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13230. begin
  13231. { we can skip all instructions not messing with the stack pointer }
  13232. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13233. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13234. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13235. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13236. ({(taicpu(hp1).ops=0) or }
  13237. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13238. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13239. ) and }
  13240. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13241. )
  13242. ) do
  13243. GetNextInstruction(hp1,hp1);
  13244. Result:=assigned(hp1);
  13245. end;
  13246. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13247. var
  13248. hp1, hp2, hp3, hp4, hp5: tai;
  13249. begin
  13250. Result:=false;
  13251. hp5:=nil;
  13252. { replace
  13253. leal(q) x(<stackpointer>),<stackpointer>
  13254. call procname
  13255. leal(q) -x(<stackpointer>),<stackpointer>
  13256. ret
  13257. by
  13258. jmp procname
  13259. but do it only on level 4 because it destroys stack back traces
  13260. }
  13261. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13262. MatchOpType(taicpu(p),top_ref,top_reg) and
  13263. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13264. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13265. { the -8 or -24 are not required, but bail out early if possible,
  13266. higher values are unlikely }
  13267. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13268. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13269. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13270. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13271. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13272. GetNextInstruction(p, hp1) and
  13273. { Take a copy of hp1 }
  13274. SetAndTest(hp1, hp4) and
  13275. { trick to skip label }
  13276. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13277. SkipSimpleInstructions(hp1) and
  13278. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13279. GetNextInstruction(hp1, hp2) and
  13280. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13281. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13282. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13283. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13284. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13285. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13286. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13287. { Segment register will be NR_NO }
  13288. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13289. GetNextInstruction(hp2, hp3) and
  13290. { trick to skip label }
  13291. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13292. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13293. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13294. SetAndTest(hp3,hp5) and
  13295. GetNextInstruction(hp3,hp3) and
  13296. MatchInstruction(hp3,A_RET,[S_NO])
  13297. )
  13298. ) and
  13299. (taicpu(hp3).ops=0) then
  13300. begin
  13301. taicpu(hp1).opcode := A_JMP;
  13302. taicpu(hp1).is_jmp := true;
  13303. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13304. RemoveCurrentP(p, hp4);
  13305. RemoveInstruction(hp2);
  13306. RemoveInstruction(hp3);
  13307. if Assigned(hp5) then
  13308. begin
  13309. AsmL.Remove(hp5);
  13310. ASmL.InsertBefore(hp5,hp1)
  13311. end;
  13312. Result:=true;
  13313. end;
  13314. end;
  13315. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13316. {$ifdef x86_64}
  13317. var
  13318. hp1, hp2, hp3, hp4, hp5: tai;
  13319. {$endif x86_64}
  13320. begin
  13321. Result:=false;
  13322. {$ifdef x86_64}
  13323. hp5:=nil;
  13324. { replace
  13325. push %rax
  13326. call procname
  13327. pop %rcx
  13328. ret
  13329. by
  13330. jmp procname
  13331. but do it only on level 4 because it destroys stack back traces
  13332. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13333. for all supported calling conventions
  13334. }
  13335. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13336. MatchOpType(taicpu(p),top_reg) and
  13337. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13338. GetNextInstruction(p, hp1) and
  13339. { Take a copy of hp1 }
  13340. SetAndTest(hp1, hp4) and
  13341. { trick to skip label }
  13342. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13343. SkipSimpleInstructions(hp1) and
  13344. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13345. GetNextInstruction(hp1, hp2) and
  13346. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13347. MatchOpType(taicpu(hp2),top_reg) and
  13348. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13349. GetNextInstruction(hp2, hp3) and
  13350. { trick to skip label }
  13351. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13352. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13353. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13354. SetAndTest(hp3,hp5) and
  13355. GetNextInstruction(hp3,hp3) and
  13356. MatchInstruction(hp3,A_RET,[S_NO])
  13357. )
  13358. ) and
  13359. (taicpu(hp3).ops=0) then
  13360. begin
  13361. taicpu(hp1).opcode := A_JMP;
  13362. taicpu(hp1).is_jmp := true;
  13363. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13364. RemoveCurrentP(p, hp4);
  13365. RemoveInstruction(hp2);
  13366. RemoveInstruction(hp3);
  13367. if Assigned(hp5) then
  13368. begin
  13369. AsmL.Remove(hp5);
  13370. ASmL.InsertBefore(hp5,hp1)
  13371. end;
  13372. Result:=true;
  13373. end;
  13374. {$endif x86_64}
  13375. end;
  13376. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13377. var
  13378. Value, RegName: string;
  13379. begin
  13380. Result:=false;
  13381. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13382. begin
  13383. case taicpu(p).oper[0]^.val of
  13384. 0:
  13385. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13386. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13387. begin
  13388. { change "mov $0,%reg" into "xor %reg,%reg" }
  13389. taicpu(p).opcode := A_XOR;
  13390. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13391. Result := True;
  13392. {$ifdef x86_64}
  13393. end
  13394. else if (taicpu(p).opsize = S_Q) then
  13395. begin
  13396. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13397. { The actual optimization }
  13398. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13399. taicpu(p).changeopsize(S_L);
  13400. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13401. Result := True;
  13402. end;
  13403. $1..$FFFFFFFF:
  13404. begin
  13405. { Code size reduction by J. Gareth "Kit" Moreton }
  13406. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13407. case taicpu(p).opsize of
  13408. S_Q:
  13409. begin
  13410. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13411. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13412. { The actual optimization }
  13413. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13414. taicpu(p).changeopsize(S_L);
  13415. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13416. Result := True;
  13417. end;
  13418. else
  13419. { Do nothing };
  13420. end;
  13421. {$endif x86_64}
  13422. end;
  13423. -1:
  13424. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13425. if (cs_opt_size in current_settings.optimizerswitches) and
  13426. (taicpu(p).opsize <> S_B) and
  13427. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13428. begin
  13429. { change "mov $-1,%reg" into "or $-1,%reg" }
  13430. { NOTES:
  13431. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13432. - This operation creates a false dependency on the register, so only do it when optimising for size
  13433. - 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
  13434. }
  13435. taicpu(p).opcode := A_OR;
  13436. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13437. Result := True;
  13438. end;
  13439. else
  13440. { Do nothing };
  13441. end;
  13442. end;
  13443. end;
  13444. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13445. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13446. begin
  13447. Result := False;
  13448. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13449. Exit;
  13450. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13451. so don't bother optimising }
  13452. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13453. Exit;
  13454. if (taicpu(p).oper[0]^.typ <> top_const) or
  13455. { If the value can fit into an 8-bit signed integer, a smaller
  13456. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13457. falls within this range }
  13458. (
  13459. (taicpu(p).oper[0]^.val > -128) and
  13460. (taicpu(p).oper[0]^.val <= 127)
  13461. ) then
  13462. Exit;
  13463. { If we're optimising for size, this is acceptable }
  13464. if (cs_opt_size in current_settings.optimizerswitches) then
  13465. Exit(True);
  13466. if (taicpu(p).oper[1]^.typ = top_reg) and
  13467. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13468. Exit(True);
  13469. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13470. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13471. Exit(True);
  13472. end;
  13473. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13474. var
  13475. hp1: tai;
  13476. Value: TCGInt;
  13477. begin
  13478. Result := False;
  13479. if MatchOpType(taicpu(p), top_const, top_reg) then
  13480. begin
  13481. { Detect:
  13482. andw x, %ax (0 <= x < $8000)
  13483. ...
  13484. movzwl %ax,%eax
  13485. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13486. }
  13487. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13488. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13489. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13490. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13491. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13492. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13493. begin
  13494. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13495. taicpu(hp1).opcode := A_CWDE;
  13496. taicpu(hp1).clearop(0);
  13497. taicpu(hp1).clearop(1);
  13498. taicpu(hp1).ops := 0;
  13499. { A change was made, but not with p, so don't set Result, but
  13500. notify the compiler that a change was made }
  13501. Include(OptsToCheck, aoc_ForceNewIteration);
  13502. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13503. end;
  13504. end;
  13505. { If "not x" is a power of 2 (popcnt = 1), change:
  13506. and $x, %reg/ref
  13507. To:
  13508. btr lb(x), %reg/ref
  13509. }
  13510. if IsBTXAcceptable(p) and
  13511. (
  13512. { Make sure a TEST doesn't follow that plays with the register }
  13513. not GetNextInstruction(p, hp1) or
  13514. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13515. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13516. ) then
  13517. begin
  13518. {$push}{$R-}{$Q-}
  13519. { Value is a sign-extended 32-bit integer - just correct it
  13520. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13521. checks to see if this operand is an immediate. }
  13522. Value := not taicpu(p).oper[0]^.val;
  13523. {$pop}
  13524. {$ifdef x86_64}
  13525. if taicpu(p).opsize = S_L then
  13526. {$endif x86_64}
  13527. Value := Value and $FFFFFFFF;
  13528. if (PopCnt(QWord(Value)) = 1) then
  13529. begin
  13530. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13531. taicpu(p).opcode := A_BTR;
  13532. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13533. Result := True;
  13534. Exit;
  13535. end;
  13536. end;
  13537. end;
  13538. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13539. begin
  13540. Result := False;
  13541. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13542. Exit;
  13543. { Convert:
  13544. movswl %ax,%eax -> cwtl
  13545. movslq %eax,%rax -> cdqe
  13546. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13547. refer to the same opcode and depends only on the assembler's
  13548. current operand-size attribute. [Kit]
  13549. }
  13550. with taicpu(p) do
  13551. case opsize of
  13552. S_WL:
  13553. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13554. begin
  13555. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13556. opcode := A_CWDE;
  13557. clearop(0);
  13558. clearop(1);
  13559. ops := 0;
  13560. Result := True;
  13561. end;
  13562. {$ifdef x86_64}
  13563. S_LQ:
  13564. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13565. begin
  13566. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13567. opcode := A_CDQE;
  13568. clearop(0);
  13569. clearop(1);
  13570. ops := 0;
  13571. Result := True;
  13572. end;
  13573. {$endif x86_64}
  13574. else
  13575. ;
  13576. end;
  13577. end;
  13578. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13579. var
  13580. hp1, hp2: tai;
  13581. IdentityMask, Shift: TCGInt;
  13582. LimitSize: Topsize;
  13583. DoNotMerge: Boolean;
  13584. begin
  13585. Result := False;
  13586. { All these optimisations work on "shr const,%reg" }
  13587. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13588. Exit;
  13589. DoNotMerge := False;
  13590. Shift := taicpu(p).oper[0]^.val;
  13591. LimitSize := taicpu(p).opsize;
  13592. hp1 := p;
  13593. repeat
  13594. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13595. Break;
  13596. { Detect:
  13597. shr x, %reg
  13598. and y, %reg
  13599. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13600. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13601. }
  13602. case taicpu(hp1).opcode of
  13603. A_AND:
  13604. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13605. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13606. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13607. begin
  13608. { Make sure the FLAGS register isn't in use }
  13609. TransferUsedRegs(TmpUsedRegs);
  13610. hp2 := p;
  13611. repeat
  13612. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13613. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13614. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13615. begin
  13616. { Generate the identity mask }
  13617. case taicpu(p).opsize of
  13618. S_B:
  13619. IdentityMask := $FF shr Shift;
  13620. S_W:
  13621. IdentityMask := $FFFF shr Shift;
  13622. S_L:
  13623. IdentityMask := $FFFFFFFF shr Shift;
  13624. {$ifdef x86_64}
  13625. S_Q:
  13626. { We need to force the operands to be unsigned 64-bit
  13627. integers otherwise the wrong value is generated }
  13628. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13629. {$endif x86_64}
  13630. else
  13631. InternalError(2022081501);
  13632. end;
  13633. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13634. begin
  13635. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13636. { All the possible 1 bits are covered, so we can remove the AND }
  13637. hp2 := tai(hp1.Previous);
  13638. RemoveInstruction(hp1);
  13639. { p wasn't actually changed, so don't set Result to True,
  13640. but a change was nonetheless made elsewhere }
  13641. Include(OptsToCheck, aoc_ForceNewIteration);
  13642. { Do another pass in case other AND or MOVZX instructions
  13643. follow }
  13644. hp1 := hp2;
  13645. Continue;
  13646. end;
  13647. end;
  13648. end;
  13649. A_TEST, A_CMP, A_Jcc:
  13650. { Skip over conditional jumps and relevant comparisons }
  13651. Continue;
  13652. A_MOVZX:
  13653. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13654. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13655. begin
  13656. { Since the original register is being read as is, subsequent
  13657. SHRs must not be merged at this point }
  13658. DoNotMerge := True;
  13659. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13660. begin
  13661. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13662. begin
  13663. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13664. { All the possible 1 bits are covered, so we can remove the AND }
  13665. hp2 := tai(hp1.Previous);
  13666. RemoveInstruction(hp1);
  13667. hp1 := hp2;
  13668. end
  13669. else { Different register target }
  13670. begin
  13671. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13672. taicpu(hp1).opcode := A_MOV;
  13673. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13674. case taicpu(hp1).opsize of
  13675. S_BW:
  13676. taicpu(hp1).opsize := S_W;
  13677. S_BL, S_WL:
  13678. taicpu(hp1).opsize := S_L;
  13679. else
  13680. InternalError(2022081503);
  13681. end;
  13682. end;
  13683. end
  13684. else if (Shift > 0) and
  13685. (taicpu(p).opsize = S_W) and
  13686. (taicpu(hp1).opsize = S_WL) and
  13687. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13688. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13689. begin
  13690. { Detect:
  13691. shr x, %ax (x > 0)
  13692. ...
  13693. movzwl %ax,%eax
  13694. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13695. }
  13696. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13697. taicpu(hp1).opcode := A_CWDE;
  13698. taicpu(hp1).clearop(0);
  13699. taicpu(hp1).clearop(1);
  13700. taicpu(hp1).ops := 0;
  13701. end;
  13702. { Move onto the next instruction }
  13703. Continue;
  13704. end;
  13705. A_SHL, A_SAL, A_SHR:
  13706. if (taicpu(hp1).opsize <= LimitSize) and
  13707. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13708. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13709. begin
  13710. { Make sure the sizes don't exceed the register size limit
  13711. (measured by the shift value falling below the limit) }
  13712. if taicpu(hp1).opsize < LimitSize then
  13713. LimitSize := taicpu(hp1).opsize;
  13714. if taicpu(hp1).opcode = A_SHR then
  13715. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13716. else
  13717. begin
  13718. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13719. DoNotMerge := True;
  13720. end;
  13721. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13722. Break;
  13723. { Since we've established that the combined shift is within
  13724. limits, we can actually combine the adjacent SHR
  13725. instructions even if they're different sizes }
  13726. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13727. begin
  13728. hp2 := tai(hp1.Previous);
  13729. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13730. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13731. RemoveInstruction(hp1);
  13732. hp1 := hp2;
  13733. end;
  13734. { Move onto the next instruction }
  13735. Continue;
  13736. end;
  13737. else
  13738. ;
  13739. end;
  13740. Break;
  13741. until False;
  13742. { Detect the following (looking backwards):
  13743. shr %cl,%reg
  13744. shr x, %reg
  13745. Swap the two SHR instructions to minimise a pipeline stall.
  13746. }
  13747. if GetLastInstruction(p, hp1) and
  13748. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13749. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13750. { First operand will be %cl }
  13751. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13752. { Just to be sure }
  13753. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13754. begin
  13755. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13756. { Moving the entries this way ensures the register tracking remains correct }
  13757. Asml.Remove(p);
  13758. Asml.InsertBefore(p, hp1);
  13759. p := hp1;
  13760. { Don't set Result to True because the current instruction is now
  13761. "shr %cl,%reg" and there's nothing more we can do with it }
  13762. end;
  13763. end;
  13764. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13765. var
  13766. hp1, hp2: tai;
  13767. Opposite, SecondOpposite: TAsmOp;
  13768. NewCond: TAsmCond;
  13769. begin
  13770. Result := False;
  13771. { Change:
  13772. add/sub 128,(dest)
  13773. To:
  13774. sub/add -128,(dest)
  13775. This generaally takes fewer bytes to encode because -128 can be stored
  13776. in a signed byte, whereas +128 cannot.
  13777. }
  13778. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13779. begin
  13780. if taicpu(p).opcode = A_ADD then
  13781. Opposite := A_SUB
  13782. else
  13783. Opposite := A_ADD;
  13784. { Be careful if the flags are in use, because the CF flag inverts
  13785. when changing from ADD to SUB and vice versa }
  13786. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13787. GetNextInstruction(p, hp1) then
  13788. begin
  13789. TransferUsedRegs(TmpUsedRegs);
  13790. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13791. hp2 := hp1;
  13792. { Scan ahead to check if everything's safe }
  13793. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13794. begin
  13795. if (hp1.typ <> ait_instruction) then
  13796. { Probably unsafe since the flags are still in use }
  13797. Exit;
  13798. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13799. { Stop searching at an unconditional jump }
  13800. Break;
  13801. if not
  13802. (
  13803. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13804. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13805. ) and
  13806. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13807. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13808. Exit;
  13809. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13810. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13811. { Move to the next instruction }
  13812. GetNextInstruction(hp1, hp1);
  13813. end;
  13814. while Assigned(hp2) and (hp2 <> hp1) do
  13815. begin
  13816. NewCond := C_None;
  13817. case taicpu(hp2).condition of
  13818. C_A, C_NBE:
  13819. NewCond := C_BE;
  13820. C_B, C_C, C_NAE:
  13821. NewCond := C_AE;
  13822. C_AE, C_NB, C_NC:
  13823. NewCond := C_B;
  13824. C_BE, C_NA:
  13825. NewCond := C_A;
  13826. else
  13827. { No change needed };
  13828. end;
  13829. if NewCond <> C_None then
  13830. begin
  13831. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13832. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13833. taicpu(hp2).condition := NewCond;
  13834. end
  13835. else
  13836. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13837. begin
  13838. { Because of the flipping of the carry bit, to ensure
  13839. the operation remains equivalent, ADC becomes SBB
  13840. and vice versa, and the constant is not-inverted.
  13841. If multiple ADCs or SBBs appear in a row, each one
  13842. changed causes the carry bit to invert, so they all
  13843. need to be flipped }
  13844. if taicpu(hp2).opcode = A_ADC then
  13845. SecondOpposite := A_SBB
  13846. else
  13847. SecondOpposite := A_ADC;
  13848. if taicpu(hp2).oper[0]^.typ <> top_const then
  13849. { Should have broken out of this optimisation already }
  13850. InternalError(2021112901);
  13851. 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]^) + ' -> ' +
  13852. 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);
  13853. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13854. taicpu(hp2).opcode := SecondOpposite;
  13855. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13856. end;
  13857. { Move to the next instruction }
  13858. GetNextInstruction(hp2, hp2);
  13859. end;
  13860. if (hp2 <> hp1) then
  13861. InternalError(2021111501);
  13862. end;
  13863. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13864. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13865. taicpu(p).opcode := Opposite;
  13866. taicpu(p).oper[0]^.val := -128;
  13867. { No further optimisations can be made on this instruction, so move
  13868. onto the next one to save time }
  13869. p := tai(p.Next);
  13870. UpdateUsedRegs(p);
  13871. Result := True;
  13872. Exit;
  13873. end;
  13874. { Detect:
  13875. add/sub %reg2,(dest)
  13876. add/sub x, (dest)
  13877. (dest can be a register or a reference)
  13878. Swap the instructions to minimise a pipeline stall. This reverses the
  13879. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13880. optimisations could be made.
  13881. }
  13882. if (taicpu(p).oper[0]^.typ = top_reg) and
  13883. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13884. (
  13885. (
  13886. (taicpu(p).oper[1]^.typ = top_reg) and
  13887. { We can try searching further ahead if we're writing to a register }
  13888. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13889. ) or
  13890. (
  13891. (taicpu(p).oper[1]^.typ = top_ref) and
  13892. GetNextInstruction(p, hp1)
  13893. )
  13894. ) and
  13895. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13896. (taicpu(hp1).oper[0]^.typ = top_const) and
  13897. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13898. begin
  13899. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13900. TransferUsedRegs(TmpUsedRegs);
  13901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13902. hp2 := p;
  13903. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13904. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13905. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13906. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13907. begin
  13908. asml.remove(hp1);
  13909. asml.InsertBefore(hp1, p);
  13910. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13911. Result := True;
  13912. end;
  13913. end;
  13914. end;
  13915. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13916. var
  13917. hp1: tai;
  13918. begin
  13919. Result:=false;
  13920. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13921. while GetNextInstruction(p, hp1) and
  13922. TrySwapMovCmp(p, hp1) do
  13923. begin
  13924. if MatchInstruction(hp1, A_MOV, []) then
  13925. begin
  13926. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13927. begin
  13928. { A little hacky, but since CMP doesn't read the flags, only
  13929. modify them, it's safe if they get scrambled by MOV -> XOR }
  13930. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13931. Result := PostPeepholeOptMov(hp1);
  13932. {$ifdef x86_64}
  13933. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13934. { Used to shrink instruction size }
  13935. PostPeepholeOptXor(hp1);
  13936. {$endif x86_64}
  13937. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13938. end
  13939. else
  13940. begin
  13941. Result := PostPeepholeOptMov(hp1);
  13942. {$ifdef x86_64}
  13943. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13944. { Used to shrink instruction size }
  13945. PostPeepholeOptXor(hp1);
  13946. {$endif x86_64}
  13947. end;
  13948. end;
  13949. { Enabling this flag is actually a null operation, but it marks
  13950. the code as 'modified' during this pass }
  13951. Include(OptsToCheck, aoc_ForceNewIteration);
  13952. end;
  13953. { change "cmp $0, %reg" to "test %reg, %reg" }
  13954. if MatchOpType(taicpu(p),top_const,top_reg) and
  13955. (taicpu(p).oper[0]^.val = 0) then
  13956. begin
  13957. taicpu(p).opcode := A_TEST;
  13958. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13959. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13960. Result:=true;
  13961. end;
  13962. end;
  13963. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13964. var
  13965. IsTestConstX, IsValid : Boolean;
  13966. hp1,hp2 : tai;
  13967. begin
  13968. Result:=false;
  13969. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13970. if (taicpu(p).opcode = A_TEST) then
  13971. while GetNextInstruction(p, hp1) and
  13972. TrySwapMovCmp(p, hp1) do
  13973. begin
  13974. if MatchInstruction(hp1, A_MOV, []) then
  13975. begin
  13976. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13977. begin
  13978. { A little hacky, but since TEST doesn't read the flags, only
  13979. modify them, it's safe if they get scrambled by MOV -> XOR }
  13980. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13981. Result := PostPeepholeOptMov(hp1);
  13982. {$ifdef x86_64}
  13983. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13984. { Used to shrink instruction size }
  13985. PostPeepholeOptXor(hp1);
  13986. {$endif x86_64}
  13987. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13988. end
  13989. else
  13990. begin
  13991. Result := PostPeepholeOptMov(hp1);
  13992. {$ifdef x86_64}
  13993. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13994. { Used to shrink instruction size }
  13995. PostPeepholeOptXor(hp1);
  13996. {$endif x86_64}
  13997. end;
  13998. end;
  13999. { Enabling this flag is actually a null operation, but it marks
  14000. the code as 'modified' during this pass }
  14001. Include(OptsToCheck, aoc_ForceNewIteration);
  14002. end;
  14003. { If x is a power of 2 (popcnt = 1), change:
  14004. or $x, %reg/ref
  14005. To:
  14006. bts lb(x), %reg/ref
  14007. }
  14008. if (taicpu(p).opcode = A_OR) and
  14009. IsBTXAcceptable(p) and
  14010. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14011. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14012. (
  14013. { Don't optimise if a test instruction follows }
  14014. not GetNextInstruction(p, hp1) or
  14015. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14016. ) then
  14017. begin
  14018. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  14019. taicpu(p).opcode := A_BTS;
  14020. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14021. Result := True;
  14022. Exit;
  14023. end;
  14024. { If x is a power of 2 (popcnt = 1), change:
  14025. test $x, %reg/ref
  14026. je / sete / cmove (or jne / setne)
  14027. To:
  14028. bt lb(x), %reg/ref
  14029. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14030. }
  14031. if (taicpu(p).opcode = A_TEST) and
  14032. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14033. (taicpu(p).oper[0]^.typ = top_const) and
  14034. (
  14035. (cs_opt_size in current_settings.optimizerswitches) or
  14036. (
  14037. (taicpu(p).oper[1]^.typ = top_reg) and
  14038. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14039. ) or
  14040. (
  14041. (taicpu(p).oper[1]^.typ <> top_reg) and
  14042. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14043. )
  14044. ) and
  14045. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14046. { For sizes less than S_L, the byte size is equal or larger with BT,
  14047. so don't bother optimising }
  14048. (taicpu(p).opsize >= S_L) then
  14049. begin
  14050. IsValid := True;
  14051. { Check the next set of instructions, watching the FLAGS register
  14052. and the conditions used }
  14053. TransferUsedRegs(TmpUsedRegs);
  14054. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14055. hp1 := p;
  14056. hp2 := nil;
  14057. while GetNextInstruction(hp1, hp1) do
  14058. begin
  14059. if not Assigned(hp2) then
  14060. { The first instruction after TEST }
  14061. hp2 := hp1;
  14062. if (hp1.typ <> ait_instruction) then
  14063. begin
  14064. { If the flags are no longer in use, everything is fine }
  14065. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14066. IsValid := False;
  14067. Break;
  14068. end;
  14069. case taicpu(hp1).condition of
  14070. C_None:
  14071. begin
  14072. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14073. { Something is not quite normal, so play safe and don't change }
  14074. IsValid := False;
  14075. Break;
  14076. end;
  14077. C_E, C_Z, C_NE, C_NZ:
  14078. { This is fine };
  14079. else
  14080. begin
  14081. { Unsupported condition }
  14082. IsValid := False;
  14083. Break;
  14084. end;
  14085. end;
  14086. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14087. end;
  14088. if IsValid then
  14089. begin
  14090. while hp2 <> hp1 do
  14091. begin
  14092. case taicpu(hp2).condition of
  14093. C_Z, C_E:
  14094. taicpu(hp2).condition := C_NC;
  14095. C_NZ, C_NE:
  14096. taicpu(hp2).condition := C_C;
  14097. else
  14098. { Should not get this by this point }
  14099. InternalError(2022110701);
  14100. end;
  14101. GetNextInstruction(hp2, hp2);
  14102. end;
  14103. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  14104. taicpu(p).opcode := A_BT;
  14105. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14106. Result := True;
  14107. Exit;
  14108. end;
  14109. end;
  14110. { removes the line marked with (x) from the sequence
  14111. and/or/xor/add/sub/... $x, %y
  14112. test/or %y, %y | test $-1, %y (x)
  14113. j(n)z _Label
  14114. as the first instruction already adjusts the ZF
  14115. %y operand may also be a reference }
  14116. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14117. MatchOperand(taicpu(p).oper[0]^,-1);
  14118. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14119. GetLastInstruction(p, hp1) and
  14120. (tai(hp1).typ = ait_instruction) and
  14121. GetNextInstruction(p,hp2) and
  14122. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14123. case taicpu(hp1).opcode Of
  14124. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14125. { These two instructions set the zero flag if the result is zero }
  14126. A_POPCNT, A_LZCNT:
  14127. begin
  14128. if (
  14129. { With POPCNT, an input of zero will set the zero flag
  14130. because the population count of zero is zero }
  14131. (taicpu(hp1).opcode = A_POPCNT) and
  14132. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14133. (
  14134. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14135. { Faster than going through the second half of the 'or'
  14136. condition below }
  14137. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14138. )
  14139. ) or (
  14140. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14141. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14142. { and in case of carry for A(E)/B(E)/C/NC }
  14143. (
  14144. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14145. (
  14146. (taicpu(hp1).opcode <> A_ADD) and
  14147. (taicpu(hp1).opcode <> A_SUB) and
  14148. (taicpu(hp1).opcode <> A_LZCNT)
  14149. )
  14150. )
  14151. ) then
  14152. begin
  14153. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14154. RemoveCurrentP(p, hp2);
  14155. Result:=true;
  14156. Exit;
  14157. end;
  14158. end;
  14159. A_SHL, A_SAL, A_SHR, A_SAR:
  14160. begin
  14161. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14162. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14163. { therefore, it's only safe to do this optimization for }
  14164. { shifts by a (nonzero) constant }
  14165. (taicpu(hp1).oper[0]^.typ = top_const) and
  14166. (taicpu(hp1).oper[0]^.val <> 0) and
  14167. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14168. { and in case of carry for A(E)/B(E)/C/NC }
  14169. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14170. begin
  14171. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14172. RemoveCurrentP(p, hp2);
  14173. Result:=true;
  14174. Exit;
  14175. end;
  14176. end;
  14177. A_DEC, A_INC, A_NEG:
  14178. begin
  14179. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14180. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14181. { and in case of carry for A(E)/B(E)/C/NC }
  14182. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14183. begin
  14184. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14185. RemoveCurrentP(p, hp2);
  14186. Result:=true;
  14187. Exit;
  14188. end;
  14189. end;
  14190. A_ANDN, A_BZHI:
  14191. begin
  14192. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14193. { Only the zero and sign flags are consistent with what the result is }
  14194. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14195. begin
  14196. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14197. RemoveCurrentP(p, hp2);
  14198. Result:=true;
  14199. Exit;
  14200. end;
  14201. end;
  14202. A_BEXTR:
  14203. begin
  14204. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14205. { Only the zero flag is set }
  14206. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14207. begin
  14208. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14209. RemoveCurrentP(p, hp2);
  14210. Result:=true;
  14211. Exit;
  14212. end;
  14213. end;
  14214. else
  14215. ;
  14216. end; { case }
  14217. { change "test $-1,%reg" into "test %reg,%reg" }
  14218. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14219. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14220. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14221. if MatchInstruction(p, A_OR, []) and
  14222. { Can only match if they're both registers }
  14223. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14224. begin
  14225. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14226. taicpu(p).opcode := A_TEST;
  14227. { No need to set Result to True, as we've done all the optimisations we can }
  14228. end;
  14229. end;
  14230. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14231. var
  14232. hp1,hp3 : tai;
  14233. {$ifndef x86_64}
  14234. hp2 : taicpu;
  14235. {$endif x86_64}
  14236. begin
  14237. Result:=false;
  14238. hp3:=nil;
  14239. {$ifndef x86_64}
  14240. { don't do this on modern CPUs, this really hurts them due to
  14241. broken call/ret pairing }
  14242. if (current_settings.optimizecputype < cpu_Pentium2) and
  14243. not(cs_create_pic in current_settings.moduleswitches) and
  14244. GetNextInstruction(p, hp1) and
  14245. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14246. MatchOpType(taicpu(hp1),top_ref) and
  14247. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14248. begin
  14249. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14250. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14251. InsertLLItem(p.previous, p, hp2);
  14252. taicpu(p).opcode := A_JMP;
  14253. taicpu(p).is_jmp := true;
  14254. RemoveInstruction(hp1);
  14255. Result:=true;
  14256. end
  14257. else
  14258. {$endif x86_64}
  14259. { replace
  14260. call procname
  14261. ret
  14262. by
  14263. jmp procname
  14264. but do it only on level 4 because it destroys stack back traces
  14265. else if the subroutine is marked as no return, remove the ret
  14266. }
  14267. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14268. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14269. GetNextInstruction(p, hp1) and
  14270. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14271. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14272. SetAndTest(hp1,hp3) and
  14273. GetNextInstruction(hp1,hp1) and
  14274. MatchInstruction(hp1,A_RET,[S_NO])
  14275. )
  14276. ) and
  14277. (taicpu(hp1).ops=0) then
  14278. begin
  14279. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14280. { we might destroy stack alignment here if we do not do a call }
  14281. (target_info.stackalign<=sizeof(SizeUInt)) then
  14282. begin
  14283. taicpu(p).opcode := A_JMP;
  14284. taicpu(p).is_jmp := true;
  14285. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14286. end
  14287. else
  14288. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14289. RemoveInstruction(hp1);
  14290. if Assigned(hp3) then
  14291. begin
  14292. AsmL.Remove(hp3);
  14293. AsmL.InsertBefore(hp3,p)
  14294. end;
  14295. Result:=true;
  14296. end;
  14297. end;
  14298. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14299. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14300. begin
  14301. case OpSize of
  14302. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14303. Result := (Val <= $FF) and (Val >= -128);
  14304. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14305. Result := (Val <= $FFFF) and (Val >= -32768);
  14306. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14307. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14308. else
  14309. Result := True;
  14310. end;
  14311. end;
  14312. var
  14313. hp1, hp2 : tai;
  14314. SizeChange: Boolean;
  14315. PreMessage: string;
  14316. begin
  14317. Result := False;
  14318. if (taicpu(p).oper[0]^.typ = top_reg) and
  14319. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14320. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14321. begin
  14322. { Change (using movzbl %al,%eax as an example):
  14323. movzbl %al, %eax movzbl %al, %eax
  14324. cmpl x, %eax testl %eax,%eax
  14325. To:
  14326. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14327. movzbl %al, %eax movzbl %al, %eax
  14328. Smaller instruction and minimises pipeline stall as the CPU
  14329. doesn't have to wait for the register to get zero-extended. [Kit]
  14330. Also allow if the smaller of the two registers is being checked,
  14331. as this still removes the false dependency.
  14332. }
  14333. if
  14334. (
  14335. (
  14336. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14337. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14338. ) or (
  14339. { If MatchOperand returns True, they must both be registers }
  14340. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14341. )
  14342. ) and
  14343. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14344. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14345. begin
  14346. 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);
  14347. asml.Remove(hp1);
  14348. asml.InsertBefore(hp1, p);
  14349. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14350. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14351. begin
  14352. taicpu(hp1).opcode := A_TEST;
  14353. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14354. end;
  14355. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14356. case taicpu(p).opsize of
  14357. S_BW, S_BL:
  14358. begin
  14359. SizeChange := taicpu(hp1).opsize <> S_B;
  14360. taicpu(hp1).changeopsize(S_B);
  14361. end;
  14362. S_WL:
  14363. begin
  14364. SizeChange := taicpu(hp1).opsize <> S_W;
  14365. taicpu(hp1).changeopsize(S_W);
  14366. end
  14367. else
  14368. InternalError(2020112701);
  14369. end;
  14370. UpdateUsedRegs(tai(p.Next));
  14371. { Check if the register is used aferwards - if not, we can
  14372. remove the movzx instruction completely }
  14373. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14374. begin
  14375. { Hp1 is a better position than p for debugging purposes }
  14376. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14377. RemoveCurrentp(p, hp1);
  14378. Result := True;
  14379. end;
  14380. if SizeChange then
  14381. DebugMsg(SPeepholeOptimization + PreMessage +
  14382. 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)
  14383. else
  14384. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14385. Exit;
  14386. end;
  14387. { Change (using movzwl %ax,%eax as an example):
  14388. movzwl %ax, %eax
  14389. movb %al, (dest) (Register is smaller than read register in movz)
  14390. To:
  14391. movb %al, (dest) (Move one back to avoid a false dependency)
  14392. movzwl %ax, %eax
  14393. }
  14394. if (taicpu(hp1).opcode = A_MOV) and
  14395. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14396. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14397. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14398. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14399. begin
  14400. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14401. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14402. asml.Remove(hp1);
  14403. asml.InsertBefore(hp1, p);
  14404. if taicpu(hp1).oper[1]^.typ = top_reg then
  14405. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14406. { Check if the register is used aferwards - if not, we can
  14407. remove the movzx instruction completely }
  14408. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14409. begin
  14410. { Hp1 is a better position than p for debugging purposes }
  14411. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14412. RemoveCurrentp(p, hp1);
  14413. Result := True;
  14414. end;
  14415. Exit;
  14416. end;
  14417. end;
  14418. end;
  14419. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14420. var
  14421. hp1: tai;
  14422. {$ifdef x86_64}
  14423. PreMessage, RegName: string;
  14424. {$endif x86_64}
  14425. begin
  14426. Result := False;
  14427. { If x is a power of 2 (popcnt = 1), change:
  14428. xor $x, %reg/ref
  14429. To:
  14430. btc lb(x), %reg/ref
  14431. }
  14432. if IsBTXAcceptable(p) and
  14433. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14434. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14435. (
  14436. { Don't optimise if a test instruction follows }
  14437. not GetNextInstruction(p, hp1) or
  14438. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14439. ) then
  14440. begin
  14441. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  14442. taicpu(p).opcode := A_BTC;
  14443. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14444. Result := True;
  14445. Exit;
  14446. end;
  14447. {$ifdef x86_64}
  14448. { Code size reduction by J. Gareth "Kit" Moreton }
  14449. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14450. as this removes the REX prefix }
  14451. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14452. Exit;
  14453. if taicpu(p).oper[0]^.typ <> top_reg then
  14454. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14455. InternalError(2018011500);
  14456. case taicpu(p).opsize of
  14457. S_Q:
  14458. begin
  14459. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14460. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14461. { The actual optimization }
  14462. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14463. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14464. taicpu(p).changeopsize(S_L);
  14465. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14466. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14467. end;
  14468. else
  14469. ;
  14470. end;
  14471. {$endif x86_64}
  14472. end;
  14473. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14474. var
  14475. XReg: TRegister;
  14476. begin
  14477. Result := False;
  14478. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14479. Smaller encoding and slightly faster on some platforms (also works for
  14480. ZMM-sized registers) }
  14481. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14482. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14483. begin
  14484. XReg := taicpu(p).oper[0]^.reg;
  14485. if (taicpu(p).oper[1]^.reg = XReg) then
  14486. begin
  14487. taicpu(p).changeopsize(S_XMM);
  14488. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14489. if (cs_opt_size in current_settings.optimizerswitches) then
  14490. begin
  14491. { Change input registers to %xmm0 to reduce size. Note that
  14492. there's a risk of a false dependency doing this, so only
  14493. optimise for size here }
  14494. XReg := NR_XMM0;
  14495. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14496. end
  14497. else
  14498. begin
  14499. setsubreg(XReg, R_SUBMMX);
  14500. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14501. end;
  14502. taicpu(p).oper[0]^.reg := XReg;
  14503. taicpu(p).oper[1]^.reg := XReg;
  14504. Result := True;
  14505. end;
  14506. end;
  14507. end;
  14508. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14509. var
  14510. OperIdx: Integer;
  14511. begin
  14512. for OperIdx := 0 to p.ops - 1 do
  14513. if p.oper[OperIdx]^.typ = top_ref then
  14514. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14515. end;
  14516. end.