aoptx86.pas 700 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176
  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. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  76. { Attempts to allocate a volatile integer register for use between p and hp,
  77. using AUsedRegs for the current register usage information. Returns NR_NO
  78. if no free register could be found }
  79. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  80. { Attempts to allocate a volatile MM register for use between p and hp,
  81. using AUsedRegs for the current register usage information. Returns NR_NO
  82. if no free register could be found }
  83. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  84. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  85. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  86. { checks whether reading the value in reg1 depends on the value of reg2. This
  87. is very similar to SuperRegisterEquals, except it takes into account that
  88. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  89. depend on the value in AH). }
  90. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  91. { Replaces all references to AOldReg in a memory reference to ANewReg }
  92. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Replaces all references to AOldReg in an operand to ANewReg }
  94. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  95. { Replaces all references to AOldReg in an instruction to ANewReg,
  96. except where the register is being written }
  97. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  99. or writes to a global symbol }
  100. class function IsRefSafe(const ref: PReference): Boolean; static;
  101. { Returns true if the given MOV instruction can be safely converted to CMOV }
  102. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  103. { Like UpdateUsedRegs, but ignores deallocations }
  104. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  105. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  106. class function IsBTXAcceptable(p : tai) : boolean; static;
  107. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  108. conversion was successful }
  109. function ConvertLEA(const p : taicpu): Boolean;
  110. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  111. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  112. procedure DebugMsg(const s : string; p : tai);inline;
  113. class function IsExitCode(p : tai) : boolean; static;
  114. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  115. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  116. procedure RemoveLastDeallocForFuncRes(p : tai);
  117. function DoArithCombineOpt(var p : tai) : Boolean;
  118. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  119. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  120. function PrePeepholeOptSxx(var p : tai) : boolean;
  121. function PrePeepholeOptIMUL(var p : tai) : boolean;
  122. function PrePeepholeOptAND(var p : tai) : boolean;
  123. function OptPass1Test(var p: tai): boolean;
  124. function OptPass1Add(var p: tai): boolean;
  125. function OptPass1AND(var p : tai) : boolean;
  126. function OptPass1_V_MOVAP(var p : tai) : boolean;
  127. function OptPass1VOP(var p : tai) : boolean;
  128. function OptPass1MOV(var p : tai) : boolean;
  129. function OptPass1Movx(var p : tai) : boolean;
  130. function OptPass1MOVXX(var p : tai) : boolean;
  131. function OptPass1OP(var p : tai) : boolean;
  132. function OptPass1LEA(var p : tai) : boolean;
  133. function OptPass1Sub(var p : tai) : boolean;
  134. function OptPass1SHLSAL(var p : tai) : boolean;
  135. function OptPass1SHR(var p : tai) : boolean;
  136. function OptPass1FSTP(var p : tai) : boolean;
  137. function OptPass1FLD(var p : tai) : boolean;
  138. function OptPass1Cmp(var p : tai) : boolean;
  139. function OptPass1PXor(var p : tai) : boolean;
  140. function OptPass1VPXor(var p: tai): boolean;
  141. function OptPass1Imul(var p : tai) : boolean;
  142. function OptPass1Jcc(var p : tai) : boolean;
  143. function OptPass1SHXX(var p: tai): boolean;
  144. function OptPass1VMOVDQ(var p: tai): Boolean;
  145. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  146. function OptPass2Movx(var p : tai): Boolean;
  147. function OptPass2MOV(var p : tai) : boolean;
  148. function OptPass2Imul(var p : tai) : boolean;
  149. function OptPass2Jmp(var p : tai) : boolean;
  150. function OptPass2Jcc(var p : tai) : boolean;
  151. function OptPass2Lea(var p: tai): Boolean;
  152. function OptPass2SUB(var p: tai): Boolean;
  153. function OptPass2ADD(var p : tai): Boolean;
  154. function OptPass2SETcc(var p : tai) : boolean;
  155. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  156. function PostPeepholeOptMov(var p : tai) : Boolean;
  157. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  158. function PostPeepholeOptXor(var p : tai) : Boolean;
  159. function PostPeepholeOptAnd(var p : tai) : boolean;
  160. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  161. function PostPeepholeOptCmp(var p : tai) : Boolean;
  162. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  163. function PostPeepholeOptCall(var p : tai) : Boolean;
  164. function PostPeepholeOptLea(var p : tai) : Boolean;
  165. function PostPeepholeOptPush(var p: tai): Boolean;
  166. function PostPeepholeOptShr(var p : tai) : boolean;
  167. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  168. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  169. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  170. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  171. function TrySwapMovOp(var p, hp1: tai): Boolean;
  172. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  173. { Processor-dependent reference optimisation }
  174. class procedure OptimizeRefs(var p: taicpu); static;
  175. end;
  176. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  179. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  180. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  181. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  182. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  183. {$if max_operands>2}
  184. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  185. {$endif max_operands>2}
  186. function RefsEqual(const r1, r2: treference): boolean;
  187. { Note that Result is set to True if the references COULD overlap but the
  188. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  189. might still overlap because %reg2 could be equal to %reg1-4 }
  190. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  191. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  192. { returns true, if ref is a reference using only the registers passed as base and index
  193. and having an offset }
  194. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  195. implementation
  196. uses
  197. cutils,verbose,
  198. systems,
  199. globals,
  200. cpuinfo,
  201. procinfo,
  202. paramgr,
  203. aasmbase,
  204. aoptbase,aoptutils,
  205. symconst,symsym,
  206. cgx86,
  207. itcpugas;
  208. {$ifdef DEBUG_AOPTCPU}
  209. const
  210. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  211. {$else DEBUG_AOPTCPU}
  212. { Empty strings help the optimizer to remove string concatenations that won't
  213. ever appear to the user on release builds. [Kit] }
  214. const
  215. SPeepholeOptimization = '';
  216. {$endif DEBUG_AOPTCPU}
  217. LIST_STEP_SIZE = 4;
  218. {$ifndef 8086}
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. {$endif 8086}
  222. type
  223. TJumpTrackingItem = class(TLinkedListItem)
  224. private
  225. FSymbol: TAsmSymbol;
  226. FRefs: LongInt;
  227. public
  228. constructor Create(ASymbol: TAsmSymbol);
  229. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  230. property Symbol: TAsmSymbol read FSymbol;
  231. property Refs: LongInt read FRefs;
  232. end;
  233. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  234. begin
  235. inherited Create;
  236. FSymbol := ASymbol;
  237. FRefs := 0;
  238. end;
  239. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  240. begin
  241. Inc(FRefs);
  242. end;
  243. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  244. begin
  245. result :=
  246. (instr.typ = ait_instruction) and
  247. (taicpu(instr).opcode = op) and
  248. ((opsize = []) or (taicpu(instr).opsize in opsize));
  249. end;
  250. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  251. begin
  252. result :=
  253. (instr.typ = ait_instruction) and
  254. ((taicpu(instr).opcode = op1) or
  255. (taicpu(instr).opcode = op2)
  256. ) and
  257. ((opsize = []) or (taicpu(instr).opsize in opsize));
  258. end;
  259. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  260. begin
  261. result :=
  262. (instr.typ = ait_instruction) and
  263. ((taicpu(instr).opcode = op1) or
  264. (taicpu(instr).opcode = op2) or
  265. (taicpu(instr).opcode = op3)
  266. ) and
  267. ((opsize = []) or (taicpu(instr).opsize in opsize));
  268. end;
  269. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  270. const opsize : topsizes) : boolean;
  271. var
  272. op : TAsmOp;
  273. begin
  274. result:=false;
  275. if (instr.typ <> ait_instruction) or
  276. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  277. exit;
  278. for op in ops do
  279. begin
  280. if taicpu(instr).opcode = op then
  281. begin
  282. result:=true;
  283. exit;
  284. end;
  285. end;
  286. end;
  287. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  288. begin
  289. result := (oper.typ = top_reg) and (oper.reg = reg);
  290. end;
  291. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  292. begin
  293. result := (oper.typ = top_const) and (oper.val = a);
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  296. begin
  297. result := oper1.typ = oper2.typ;
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=oper1.val = oper2.val;
  302. top_reg:
  303. Result:=oper1.reg = oper2.reg;
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  306. else
  307. internalerror(2013102801);
  308. end
  309. end;
  310. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  311. begin
  312. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  313. if result then
  314. case oper1.typ of
  315. top_const:
  316. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  317. top_reg:
  318. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  319. top_ref:
  320. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  321. else
  322. internalerror(2020052401);
  323. end
  324. end;
  325. function RefsEqual(const r1, r2: treference): boolean;
  326. begin
  327. RefsEqual :=
  328. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  329. (r1.relsymbol = r2.relsymbol) and
  330. (r1.segment = r2.segment) and (r1.base = r2.base) and
  331. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  332. (r1.offset = r2.offset) and
  333. (r1.volatility + r2.volatility = []);
  334. end;
  335. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  336. begin
  337. if (r1.symbol<>r2.symbol) then
  338. { If the index registers are different, there's a chance one could
  339. be set so it equals the other symbol }
  340. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  341. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  342. (r1.relsymbol = r2.relsymbol) and
  343. (r1.segment = r2.segment) and (r1.base = r2.base) and
  344. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  345. (r1.volatility + r2.volatility = []) then
  346. { In this case, it all depends on the offsets }
  347. Exit(abs(r1.offset - r2.offset) < Range);
  348. { There's a chance things MIGHT overlap, so take no chances }
  349. Result := True;
  350. end;
  351. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  352. begin
  353. Result:=(ref.offset=0) and
  354. (ref.scalefactor in [0,1]) and
  355. (ref.segment=NR_NO) and
  356. (ref.symbol=nil) and
  357. (ref.relsymbol=nil) and
  358. ((base=NR_INVALID) or
  359. (ref.base=base)) and
  360. ((index=NR_INVALID) or
  361. (ref.index=index)) and
  362. (ref.volatility=[]);
  363. end;
  364. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  365. begin
  366. Result:=(ref.scalefactor in [0,1]) and
  367. (ref.segment=NR_NO) and
  368. (ref.symbol=nil) and
  369. (ref.relsymbol=nil) and
  370. ((base=NR_INVALID) or
  371. (ref.base=base)) and
  372. ((index=NR_INVALID) or
  373. (ref.index=index)) and
  374. (ref.volatility=[]);
  375. end;
  376. function InstrReadsFlags(p: tai): boolean;
  377. begin
  378. InstrReadsFlags := true;
  379. case p.typ of
  380. ait_instruction:
  381. if InsProp[taicpu(p).opcode].Ch*
  382. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  383. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  384. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  385. exit;
  386. ait_label:
  387. exit;
  388. else
  389. ;
  390. end;
  391. InstrReadsFlags := false;
  392. end;
  393. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  394. begin
  395. Next:=Current;
  396. repeat
  397. Result:=GetNextInstruction(Next,Next);
  398. until not (Result) or
  399. not(cs_opt_level3 in current_settings.optimizerswitches) or
  400. (Next.typ<>ait_instruction) or
  401. RegInInstruction(reg,Next) or
  402. is_calljmp(taicpu(Next).opcode);
  403. end;
  404. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  405. var
  406. GetNextResult: Boolean;
  407. begin
  408. Result:=0;
  409. Next:=Current;
  410. repeat
  411. GetNextResult := GetNextInstruction(Next,Next);
  412. if GetNextResult then
  413. Inc(Result)
  414. else
  415. { Must return zero upon hitting the end of the linked list without a match }
  416. Result := 0;
  417. until not (GetNextResult) or
  418. not(cs_opt_level3 in current_settings.optimizerswitches) or
  419. (Next.typ<>ait_instruction) or
  420. RegInInstruction(reg,Next) or
  421. is_calljmp(taicpu(Next).opcode);
  422. end;
  423. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  424. procedure TrackJump(Symbol: TAsmSymbol);
  425. var
  426. Search: TJumpTrackingItem;
  427. begin
  428. { See if an entry already exists in our jump tracking list
  429. (faster to search backwards due to the higher chance of
  430. matching destinations) }
  431. Search := TJumpTrackingItem(JumpTracking.Last);
  432. while Assigned(Search) do
  433. begin
  434. if Search.Symbol = Symbol then
  435. begin
  436. { Found it - remove it so it can be pushed to the front }
  437. JumpTracking.Remove(Search);
  438. Break;
  439. end;
  440. Search := TJumpTrackingItem(Search.Previous);
  441. end;
  442. if not Assigned(Search) then
  443. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  444. JumpTracking.Concat(Search);
  445. Search.IncRefs;
  446. end;
  447. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  448. var
  449. Search: TJumpTrackingItem;
  450. begin
  451. Result := False;
  452. { See if this label appears in the tracking list }
  453. Search := TJumpTrackingItem(JumpTracking.Last);
  454. while Assigned(Search) do
  455. begin
  456. if Search.Symbol = Symbol then
  457. begin
  458. { Found it - let's see what we can discover }
  459. if Search.Symbol.getrefs = Search.Refs then
  460. begin
  461. { Success - all the references are accounted for }
  462. JumpTracking.Remove(Search);
  463. Search.Free;
  464. { It is logically impossible for CrossJump to be false here
  465. because we must have run into a conditional jump for
  466. this label at some point }
  467. if not CrossJump then
  468. InternalError(2022041710);
  469. if JumpTracking.First = nil then
  470. { Tracking list is now empty - no more cross jumps }
  471. CrossJump := False;
  472. Result := True;
  473. Exit;
  474. end;
  475. { If the references don't match, it's possible to enter
  476. this label through other means, so drop out }
  477. Exit;
  478. end;
  479. Search := TJumpTrackingItem(Search.Previous);
  480. end;
  481. end;
  482. var
  483. Next_Label: tai;
  484. begin
  485. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  486. Next := Current;
  487. repeat
  488. Result := GetNextInstruction(Next,Next);
  489. if not Result then
  490. Break;
  491. if Next.typ = ait_align then
  492. Result := SkipAligns(Next, Next);
  493. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  494. if is_calljmpuncondret(taicpu(Next).opcode) then
  495. begin
  496. if (taicpu(Next).opcode = A_JMP) and
  497. { Remove dead code now to save time }
  498. RemoveDeadCodeAfterJump(taicpu(Next)) then
  499. { A jump was removed, but not the current instruction, and
  500. Result doesn't necessarily translate into an optimisation
  501. routine's Result, so use the "Force New Iteration" flag so
  502. mark a new pass }
  503. Include(OptsToCheck, aoc_ForceNewIteration);
  504. if not Assigned(JumpTracking) then
  505. begin
  506. { Cross-label optimisations often causes other optimisations
  507. to perform worse because they're not given the chance to
  508. optimise locally. In this case, don't do the cross-label
  509. optimisations yet, but flag them as a potential possibility
  510. for the next iteration of Pass 1 }
  511. if not NotFirstIteration then
  512. Include(OptsToCheck, aoc_ForceNewIteration);
  513. end
  514. else if IsJumpToLabel(taicpu(Next)) and
  515. GetNextInstruction(Next, Next_Label) and
  516. SkipAligns(Next_Label, Next_Label) then
  517. begin
  518. { If we have JMP .lbl, and the label after it has all of its
  519. references tracked, then this is probably an if-else style of
  520. block and we can keep tracking. If the label for this jump
  521. then appears later and is fully tracked, then it's the end
  522. of the if-else blocks and the code paths converge (thus
  523. marking the end of the cross-jump) }
  524. if (Next_Label.typ = ait_label) then
  525. begin
  526. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  527. begin
  528. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  529. Next := Next_Label;
  530. { CrossJump gets set to false by LabelAccountedFor if the
  531. list is completely emptied (as it indicates that all
  532. code paths have converged). We could avoid this nuance
  533. by moving the TrackJump call to before the
  534. LabelAccountedFor call, but this is slower in situations
  535. where LabelAccountedFor would return False due to the
  536. creation of a new object that is not used and destroyed
  537. soon after. }
  538. CrossJump := True;
  539. Continue;
  540. end;
  541. end
  542. else if (Next_Label.typ <> ait_marker) then
  543. { We just did a RemoveDeadCodeAfterJump, so either we find
  544. a label, the end of the procedure or some kind of marker}
  545. InternalError(2022041720);
  546. end;
  547. Result := False;
  548. Exit;
  549. end
  550. else
  551. begin
  552. if not Assigned(JumpTracking) then
  553. begin
  554. { Cross-label optimisations often causes other optimisations
  555. to perform worse because they're not given the chance to
  556. optimise locally. In this case, don't do the cross-label
  557. optimisations yet, but flag them as a potential possibility
  558. for the next iteration of Pass 1 }
  559. if not NotFirstIteration then
  560. Include(OptsToCheck, aoc_ForceNewIteration);
  561. end
  562. else if IsJumpToLabel(taicpu(Next)) then
  563. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  564. else
  565. { Conditional jumps should always be a jump to label }
  566. InternalError(2022041701);
  567. CrossJump := True;
  568. Continue;
  569. end;
  570. if Next.typ = ait_label then
  571. begin
  572. if not Assigned(JumpTracking) then
  573. begin
  574. { Cross-label optimisations often causes other optimisations
  575. to perform worse because they're not given the chance to
  576. optimise locally. In this case, don't do the cross-label
  577. optimisations yet, but flag them as a potential possibility
  578. for the next iteration of Pass 1 }
  579. if not NotFirstIteration then
  580. Include(OptsToCheck, aoc_ForceNewIteration);
  581. end
  582. else if LabelAccountedFor(tai_label(Next).labsym) then
  583. Continue;
  584. { If we reach here, we're at a label that hasn't been seen before
  585. (or JumpTracking was nil) }
  586. Break;
  587. end;
  588. until not Result or
  589. not (cs_opt_level3 in current_settings.optimizerswitches) or
  590. not (Next.typ in [ait_label, ait_instruction]) or
  591. RegInInstruction(reg,Next);
  592. end;
  593. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  594. begin
  595. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  596. begin
  597. Result:=GetNextInstruction(Current,Next);
  598. exit;
  599. end;
  600. Next:=tai(Current.Next);
  601. Result:=false;
  602. while assigned(Next) do
  603. begin
  604. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  605. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  606. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  607. exit
  608. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  609. begin
  610. Result:=true;
  611. exit;
  612. end;
  613. Next:=tai(Next.Next);
  614. end;
  615. end;
  616. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  617. begin
  618. Result:=RegReadByInstruction(reg,hp);
  619. end;
  620. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  621. var
  622. p: taicpu;
  623. opcount: longint;
  624. begin
  625. RegReadByInstruction := false;
  626. if hp.typ <> ait_instruction then
  627. exit;
  628. p := taicpu(hp);
  629. case p.opcode of
  630. A_CALL:
  631. regreadbyinstruction := true;
  632. A_IMUL:
  633. case p.ops of
  634. 1:
  635. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  636. (
  637. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  638. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  639. );
  640. 2,3:
  641. regReadByInstruction :=
  642. reginop(reg,p.oper[0]^) or
  643. reginop(reg,p.oper[1]^);
  644. else
  645. InternalError(2019112801);
  646. end;
  647. A_MUL:
  648. begin
  649. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  650. (
  651. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  652. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  653. );
  654. end;
  655. A_IDIV,A_DIV:
  656. begin
  657. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  658. (
  659. (getregtype(reg)=R_INTREGISTER) and
  660. (
  661. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  662. )
  663. );
  664. end;
  665. else
  666. begin
  667. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  668. begin
  669. RegReadByInstruction := false;
  670. exit;
  671. end;
  672. for opcount := 0 to p.ops-1 do
  673. if (p.oper[opCount]^.typ = top_ref) and
  674. RegInRef(reg,p.oper[opcount]^.ref^) then
  675. begin
  676. RegReadByInstruction := true;
  677. exit
  678. end;
  679. { special handling for SSE MOVSD }
  680. if (p.opcode=A_MOVSD) and (p.ops>0) then
  681. begin
  682. if p.ops<>2 then
  683. internalerror(2017042702);
  684. regReadByInstruction := reginop(reg,p.oper[0]^) or
  685. (
  686. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  687. );
  688. exit;
  689. end;
  690. with insprop[p.opcode] do
  691. begin
  692. case getregtype(reg) of
  693. R_INTREGISTER:
  694. begin
  695. case getsupreg(reg) of
  696. RS_EAX:
  697. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  698. begin
  699. RegReadByInstruction := true;
  700. exit
  701. end;
  702. RS_ECX:
  703. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  704. begin
  705. RegReadByInstruction := true;
  706. exit
  707. end;
  708. RS_EDX:
  709. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  710. begin
  711. RegReadByInstruction := true;
  712. exit
  713. end;
  714. RS_EBX:
  715. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  716. begin
  717. RegReadByInstruction := true;
  718. exit
  719. end;
  720. RS_ESP:
  721. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. RS_EBP:
  727. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  728. begin
  729. RegReadByInstruction := true;
  730. exit
  731. end;
  732. RS_ESI:
  733. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  734. begin
  735. RegReadByInstruction := true;
  736. exit
  737. end;
  738. RS_EDI:
  739. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  740. begin
  741. RegReadByInstruction := true;
  742. exit
  743. end;
  744. end;
  745. end;
  746. R_MMREGISTER:
  747. begin
  748. case getsupreg(reg) of
  749. RS_XMM0:
  750. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. end;
  756. end;
  757. else
  758. ;
  759. end;
  760. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  761. begin
  762. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  763. begin
  764. case p.condition of
  765. C_A,C_NBE, { CF=0 and ZF=0 }
  766. C_BE,C_NA: { CF=1 or ZF=1 }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  768. C_AE,C_NB,C_NC, { CF=0 }
  769. C_B,C_NAE,C_C: { CF=1 }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  771. C_NE,C_NZ, { ZF=0 }
  772. C_E,C_Z: { ZF=1 }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  774. C_G,C_NLE, { ZF=0 and SF=OF }
  775. C_LE,C_NG: { ZF=1 or SF<>OF }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  777. C_GE,C_NL, { SF=OF }
  778. C_L,C_NGE: { SF<>OF }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  780. C_NO, { OF=0 }
  781. C_O: { OF=1 }
  782. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  783. C_NP,C_PO, { PF=0 }
  784. C_P,C_PE: { PF=1 }
  785. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  786. C_NS, { SF=0 }
  787. C_S: { SF=1 }
  788. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  789. else
  790. internalerror(2017042701);
  791. end;
  792. if RegReadByInstruction then
  793. exit;
  794. end;
  795. case getsubreg(reg) of
  796. R_SUBW,R_SUBD,R_SUBQ:
  797. RegReadByInstruction :=
  798. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  799. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  800. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  801. R_SUBFLAGCARRY:
  802. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  803. R_SUBFLAGPARITY:
  804. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  805. R_SUBFLAGAUXILIARY:
  806. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  807. R_SUBFLAGZERO:
  808. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  809. R_SUBFLAGSIGN:
  810. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  811. R_SUBFLAGOVERFLOW:
  812. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  813. R_SUBFLAGINTERRUPT:
  814. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  815. R_SUBFLAGDIRECTION:
  816. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  817. else
  818. internalerror(2017042601);
  819. end;
  820. exit;
  821. end;
  822. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  823. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  824. (p.oper[0]^.reg=p.oper[1]^.reg) then
  825. exit;
  826. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  827. begin
  828. RegReadByInstruction := true;
  829. exit
  830. end;
  831. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  832. begin
  833. RegReadByInstruction := true;
  834. exit
  835. end;
  836. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  837. begin
  838. RegReadByInstruction := true;
  839. exit
  840. end;
  841. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  842. begin
  843. RegReadByInstruction := true;
  844. exit
  845. end;
  846. end;
  847. end;
  848. end;
  849. end;
  850. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  851. begin
  852. result:=false;
  853. if p1.typ<>ait_instruction then
  854. exit;
  855. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  856. exit(true);
  857. if (getregtype(reg)=R_INTREGISTER) and
  858. { change information for xmm movsd are not correct }
  859. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  860. begin
  861. { Handle instructions that behave differently depending on the size and operand count }
  862. case taicpu(p1).opcode of
  863. A_MUL, A_DIV, A_IDIV:
  864. if taicpu(p1).opsize = S_B then
  865. Result := (getsupreg(Reg) = RS_EAX)
  866. else
  867. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  868. A_IMUL:
  869. if taicpu(p1).ops = 1 then
  870. begin
  871. if taicpu(p1).opsize = S_B then
  872. Result := (getsupreg(Reg) = RS_EAX)
  873. else
  874. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  875. end;
  876. { If ops are greater than 1, call inherited method }
  877. else
  878. case getsupreg(reg) of
  879. { RS_EAX = RS_RAX on x86-64 }
  880. RS_EAX:
  881. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  882. RS_ECX:
  883. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  884. RS_EDX:
  885. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  886. RS_EBX:
  887. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  888. RS_ESP:
  889. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  890. RS_EBP:
  891. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  892. RS_ESI:
  893. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  894. RS_EDI:
  895. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  896. else
  897. ;
  898. end;
  899. end;
  900. if result then
  901. exit;
  902. end
  903. else if getregtype(reg)=R_MMREGISTER then
  904. begin
  905. case getsupreg(reg) of
  906. RS_XMM0:
  907. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. else
  909. ;
  910. end;
  911. if result then
  912. exit;
  913. end
  914. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  915. begin
  916. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  917. exit(true);
  918. case getsubreg(reg) of
  919. R_SUBFLAGCARRY:
  920. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  921. R_SUBFLAGPARITY:
  922. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  923. R_SUBFLAGAUXILIARY:
  924. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  925. R_SUBFLAGZERO:
  926. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. R_SUBFLAGSIGN:
  928. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. R_SUBFLAGOVERFLOW:
  930. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. R_SUBFLAGINTERRUPT:
  932. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. R_SUBFLAGDIRECTION:
  934. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. R_SUBW,R_SUBD,R_SUBQ:
  936. { Everything except the direction bits }
  937. Result:=
  938. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  939. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  940. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  941. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  942. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  943. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  944. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. else
  946. ;
  947. end;
  948. if result then
  949. exit;
  950. end
  951. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  952. exit(true);
  953. Result:=inherited RegInInstruction(Reg, p1);
  954. end;
  955. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  956. const
  957. WriteOps: array[0..3] of set of TInsChange =
  958. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  959. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  960. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  961. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  962. var
  963. OperIdx: Integer;
  964. begin
  965. Result := False;
  966. if p1.typ <> ait_instruction then
  967. exit;
  968. with insprop[taicpu(p1).opcode] do
  969. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  970. begin
  971. case getsubreg(reg) of
  972. R_SUBW,R_SUBD,R_SUBQ:
  973. Result :=
  974. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  975. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  976. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  977. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  978. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  979. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  980. R_SUBFLAGCARRY:
  981. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  982. R_SUBFLAGPARITY:
  983. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  984. R_SUBFLAGAUXILIARY:
  985. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  986. R_SUBFLAGZERO:
  987. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  988. R_SUBFLAGSIGN:
  989. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  990. R_SUBFLAGOVERFLOW:
  991. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  992. R_SUBFLAGINTERRUPT:
  993. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  994. R_SUBFLAGDIRECTION:
  995. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  996. else
  997. internalerror(2017042602);
  998. end;
  999. exit;
  1000. end;
  1001. case taicpu(p1).opcode of
  1002. A_CALL:
  1003. { We could potentially set Result to False if the register in
  1004. question is non-volatile for the subroutine's calling convention,
  1005. but this would require detecting the calling convention in use and
  1006. also assuming that the routine doesn't contain malformed assembly
  1007. language, for example... so it could only be done under -O4 as it
  1008. would be considered a side-effect. [Kit] }
  1009. Result := True;
  1010. A_MOVSD:
  1011. { special handling for SSE MOVSD }
  1012. if (taicpu(p1).ops>0) then
  1013. begin
  1014. if taicpu(p1).ops<>2 then
  1015. internalerror(2017042703);
  1016. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1017. end;
  1018. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1019. so fix it here (FK)
  1020. }
  1021. A_VMOVSS,
  1022. A_VMOVSD:
  1023. begin
  1024. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1025. exit;
  1026. end;
  1027. A_MUL, A_DIV, A_IDIV:
  1028. begin
  1029. if taicpu(p1).opsize = S_B then
  1030. Result := (getsupreg(Reg) = RS_EAX)
  1031. else
  1032. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1033. end;
  1034. A_IMUL:
  1035. begin
  1036. if taicpu(p1).ops = 1 then
  1037. begin
  1038. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1039. end
  1040. else
  1041. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1042. Exit;
  1043. end;
  1044. else
  1045. ;
  1046. end;
  1047. if Result then
  1048. exit;
  1049. with insprop[taicpu(p1).opcode] do
  1050. begin
  1051. if getregtype(reg)=R_INTREGISTER then
  1052. begin
  1053. case getsupreg(reg) of
  1054. RS_EAX:
  1055. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1056. begin
  1057. Result := True;
  1058. exit
  1059. end;
  1060. RS_ECX:
  1061. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1062. begin
  1063. Result := True;
  1064. exit
  1065. end;
  1066. RS_EDX:
  1067. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1068. begin
  1069. Result := True;
  1070. exit
  1071. end;
  1072. RS_EBX:
  1073. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1074. begin
  1075. Result := True;
  1076. exit
  1077. end;
  1078. RS_ESP:
  1079. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1080. begin
  1081. Result := True;
  1082. exit
  1083. end;
  1084. RS_EBP:
  1085. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1086. begin
  1087. Result := True;
  1088. exit
  1089. end;
  1090. RS_ESI:
  1091. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1092. begin
  1093. Result := True;
  1094. exit
  1095. end;
  1096. RS_EDI:
  1097. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1098. begin
  1099. Result := True;
  1100. exit
  1101. end;
  1102. end;
  1103. end;
  1104. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1105. if (WriteOps[OperIdx]*Ch<>[]) and
  1106. { The register doesn't get modified inside a reference }
  1107. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1108. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1109. begin
  1110. Result := true;
  1111. exit
  1112. end;
  1113. end;
  1114. end;
  1115. {$ifdef DEBUG_AOPTCPU}
  1116. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1117. begin
  1118. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1119. end;
  1120. function debug_tostr(i: tcgint): string; inline;
  1121. begin
  1122. Result := tostr(i);
  1123. end;
  1124. function debug_hexstr(i: tcgint): string;
  1125. begin
  1126. Result := '0x';
  1127. case i of
  1128. 0..$FF:
  1129. Result := Result + hexstr(i, 2);
  1130. $100..$FFFF:
  1131. Result := Result + hexstr(i, 4);
  1132. $10000..$FFFFFF:
  1133. Result := Result + hexstr(i, 6);
  1134. $1000000..$FFFFFFFF:
  1135. Result := Result + hexstr(i, 8);
  1136. else
  1137. Result := Result + hexstr(i, 16);
  1138. end;
  1139. end;
  1140. function debug_regname(r: TRegister): string; inline;
  1141. begin
  1142. Result := '%' + std_regname(r);
  1143. end;
  1144. { Debug output function - creates a string representation of an operator }
  1145. function debug_operstr(oper: TOper): string;
  1146. begin
  1147. case oper.typ of
  1148. top_const:
  1149. Result := '$' + debug_tostr(oper.val);
  1150. top_reg:
  1151. Result := debug_regname(oper.reg);
  1152. top_ref:
  1153. begin
  1154. if oper.ref^.offset <> 0 then
  1155. Result := debug_tostr(oper.ref^.offset) + '('
  1156. else
  1157. Result := '(';
  1158. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1159. begin
  1160. Result := Result + debug_regname(oper.ref^.base);
  1161. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1162. Result := Result + ',' + debug_regname(oper.ref^.index);
  1163. end
  1164. else
  1165. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1166. Result := Result + debug_regname(oper.ref^.index);
  1167. if (oper.ref^.scalefactor > 1) then
  1168. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1169. else
  1170. Result := Result + ')';
  1171. end;
  1172. else
  1173. Result := '[UNKNOWN]';
  1174. end;
  1175. end;
  1176. function debug_op2str(opcode: tasmop): string; inline;
  1177. begin
  1178. Result := std_op2str[opcode];
  1179. end;
  1180. function debug_opsize2str(opsize: topsize): string; inline;
  1181. begin
  1182. Result := gas_opsize2str[opsize];
  1183. end;
  1184. {$else DEBUG_AOPTCPU}
  1185. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1186. begin
  1187. end;
  1188. function debug_tostr(i: tcgint): string; inline;
  1189. begin
  1190. Result := '';
  1191. end;
  1192. function debug_hexstr(i: tcgint): string; inline;
  1193. begin
  1194. Result := '';
  1195. end;
  1196. function debug_regname(r: TRegister): string; inline;
  1197. begin
  1198. Result := '';
  1199. end;
  1200. function debug_operstr(oper: TOper): string; inline;
  1201. begin
  1202. Result := '';
  1203. end;
  1204. function debug_op2str(opcode: tasmop): string; inline;
  1205. begin
  1206. Result := '';
  1207. end;
  1208. function debug_opsize2str(opsize: topsize): string; inline;
  1209. begin
  1210. Result := '';
  1211. end;
  1212. {$endif DEBUG_AOPTCPU}
  1213. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1214. begin
  1215. {$ifdef x86_64}
  1216. { Always fine on x86-64 }
  1217. Result := True;
  1218. {$else x86_64}
  1219. Result :=
  1220. {$ifdef i8086}
  1221. (current_settings.cputype >= cpu_386) and
  1222. {$endif i8086}
  1223. (
  1224. { Always accept if optimising for size }
  1225. (cs_opt_size in current_settings.optimizerswitches) or
  1226. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1227. (current_settings.optimizecputype >= cpu_Pentium2)
  1228. );
  1229. {$endif x86_64}
  1230. end;
  1231. { Attempts to allocate a volatile integer register for use between p and hp,
  1232. using AUsedRegs for the current register usage information. Returns NR_NO
  1233. if no free register could be found }
  1234. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1235. var
  1236. RegSet: TCPURegisterSet;
  1237. CurrentSuperReg: Integer;
  1238. CurrentReg: TRegister;
  1239. Currentp: tai;
  1240. Breakout: Boolean;
  1241. begin
  1242. Result := NR_NO;
  1243. RegSet :=
  1244. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1245. current_procinfo.saved_regs_int;
  1246. (*
  1247. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1248. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1249. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1250. *)
  1251. for CurrentSuperReg in RegSet do
  1252. begin
  1253. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1254. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1255. {$if defined(i386) or defined(i8086)}
  1256. { If the target size is 8-bit, make sure we can actually encode it }
  1257. and (
  1258. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1259. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1260. )
  1261. {$endif i386 or i8086}
  1262. then
  1263. begin
  1264. Currentp := p;
  1265. Breakout := False;
  1266. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1267. begin
  1268. case Currentp.typ of
  1269. ait_instruction:
  1270. begin
  1271. if RegInInstruction(CurrentReg, Currentp) then
  1272. begin
  1273. Breakout := True;
  1274. Break;
  1275. end;
  1276. { Cannot allocate across an unconditional jump }
  1277. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1278. Exit;
  1279. end;
  1280. ait_marker:
  1281. { Don't try anything more if a marker is hit }
  1282. Exit;
  1283. ait_regalloc:
  1284. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1285. begin
  1286. Breakout := True;
  1287. Break;
  1288. end;
  1289. else
  1290. ;
  1291. end;
  1292. end;
  1293. if Breakout then
  1294. { Try the next register }
  1295. Continue;
  1296. { We have a free register available }
  1297. Result := CurrentReg;
  1298. if not DontAlloc then
  1299. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1300. Exit;
  1301. end;
  1302. end;
  1303. end;
  1304. { Attempts to allocate a volatile MM register for use between p and hp,
  1305. using AUsedRegs for the current register usage information. Returns NR_NO
  1306. if no free register could be found }
  1307. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1308. var
  1309. RegSet: TCPURegisterSet;
  1310. CurrentSuperReg: Integer;
  1311. CurrentReg: TRegister;
  1312. Currentp: tai;
  1313. Breakout: Boolean;
  1314. begin
  1315. Result := NR_NO;
  1316. RegSet :=
  1317. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1318. current_procinfo.saved_regs_mm;
  1319. for CurrentSuperReg in RegSet do
  1320. begin
  1321. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1322. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1323. begin
  1324. Currentp := p;
  1325. Breakout := False;
  1326. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1327. begin
  1328. case Currentp.typ of
  1329. ait_instruction:
  1330. begin
  1331. if RegInInstruction(CurrentReg, Currentp) then
  1332. begin
  1333. Breakout := True;
  1334. Break;
  1335. end;
  1336. { Cannot allocate across an unconditional jump }
  1337. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1338. Exit;
  1339. end;
  1340. ait_marker:
  1341. { Don't try anything more if a marker is hit }
  1342. Exit;
  1343. ait_regalloc:
  1344. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1345. begin
  1346. Breakout := True;
  1347. Break;
  1348. end;
  1349. else
  1350. ;
  1351. end;
  1352. end;
  1353. if Breakout then
  1354. { Try the next register }
  1355. Continue;
  1356. { We have a free register available }
  1357. Result := CurrentReg;
  1358. if not DontAlloc then
  1359. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1360. Exit;
  1361. end;
  1362. end;
  1363. end;
  1364. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1365. begin
  1366. if not SuperRegistersEqual(reg1,reg2) then
  1367. exit(false);
  1368. if getregtype(reg1)<>R_INTREGISTER then
  1369. exit(true); {because SuperRegisterEqual is true}
  1370. case getsubreg(reg1) of
  1371. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1372. higher, it preserves the high bits, so the new value depends on
  1373. reg2's previous value. In other words, it is equivalent to doing:
  1374. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1375. R_SUBL:
  1376. exit(getsubreg(reg2)=R_SUBL);
  1377. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1378. higher, it actually does a:
  1379. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1380. R_SUBH:
  1381. exit(getsubreg(reg2)=R_SUBH);
  1382. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1383. bits of reg2:
  1384. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1385. R_SUBW:
  1386. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1387. { a write to R_SUBD always overwrites every other subregister,
  1388. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1389. R_SUBD,
  1390. R_SUBQ:
  1391. exit(true);
  1392. else
  1393. internalerror(2017042801);
  1394. end;
  1395. end;
  1396. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1397. begin
  1398. if not SuperRegistersEqual(reg1,reg2) then
  1399. exit(false);
  1400. if getregtype(reg1)<>R_INTREGISTER then
  1401. exit(true); {because SuperRegisterEqual is true}
  1402. case getsubreg(reg1) of
  1403. R_SUBL:
  1404. exit(getsubreg(reg2)<>R_SUBH);
  1405. R_SUBH:
  1406. exit(getsubreg(reg2)<>R_SUBL);
  1407. R_SUBW,
  1408. R_SUBD,
  1409. R_SUBQ:
  1410. exit(true);
  1411. else
  1412. internalerror(2017042802);
  1413. end;
  1414. end;
  1415. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1416. var
  1417. hp1 : tai;
  1418. l : TCGInt;
  1419. begin
  1420. result:=false;
  1421. if not(GetNextInstruction(p, hp1)) then
  1422. exit;
  1423. { changes the code sequence
  1424. shr/sar const1, x
  1425. shl const2, x
  1426. to
  1427. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1428. if (taicpu(p).oper[0]^.typ = top_const) and
  1429. MatchInstruction(hp1,A_SHL,[]) and
  1430. (taicpu(hp1).oper[0]^.typ = top_const) and
  1431. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1432. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1433. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1434. begin
  1435. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1436. not(cs_opt_size in current_settings.optimizerswitches) then
  1437. begin
  1438. { shr/sar const1, %reg
  1439. shl const2, %reg
  1440. with const1 > const2 }
  1441. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1442. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1443. taicpu(hp1).opcode := A_AND;
  1444. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1445. case taicpu(p).opsize Of
  1446. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1447. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1448. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1449. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1450. else
  1451. Internalerror(2017050703)
  1452. end;
  1453. end
  1454. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1455. not(cs_opt_size in current_settings.optimizerswitches) then
  1456. begin
  1457. { shr/sar const1, %reg
  1458. shl const2, %reg
  1459. with const1 < const2 }
  1460. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1461. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1462. taicpu(p).opcode := A_AND;
  1463. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1464. case taicpu(p).opsize Of
  1465. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1466. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1467. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1468. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1469. else
  1470. Internalerror(2017050702)
  1471. end;
  1472. end
  1473. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1474. begin
  1475. { shr/sar const1, %reg
  1476. shl const2, %reg
  1477. with const1 = const2 }
  1478. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1479. taicpu(p).opcode := A_AND;
  1480. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1481. case taicpu(p).opsize Of
  1482. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1483. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1484. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1485. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1486. else
  1487. Internalerror(2017050701)
  1488. end;
  1489. RemoveInstruction(hp1);
  1490. end;
  1491. end;
  1492. end;
  1493. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1494. var
  1495. opsize : topsize;
  1496. hp1, hp2 : tai;
  1497. tmpref : treference;
  1498. ShiftValue : Cardinal;
  1499. BaseValue : TCGInt;
  1500. begin
  1501. result:=false;
  1502. opsize:=taicpu(p).opsize;
  1503. { changes certain "imul const, %reg"'s to lea sequences }
  1504. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1505. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1506. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1507. if (taicpu(p).oper[0]^.val = 1) then
  1508. if (taicpu(p).ops = 2) then
  1509. { remove "imul $1, reg" }
  1510. begin
  1511. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1512. Result := RemoveCurrentP(p);
  1513. end
  1514. else
  1515. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1516. begin
  1517. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1518. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1519. asml.InsertAfter(hp1, p);
  1520. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1521. RemoveCurrentP(p, hp1);
  1522. Result := True;
  1523. end
  1524. else if ((taicpu(p).ops <= 2) or
  1525. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1526. not(cs_opt_size in current_settings.optimizerswitches) and
  1527. (not(GetNextInstruction(p, hp1)) or
  1528. not((tai(hp1).typ = ait_instruction) and
  1529. ((taicpu(hp1).opcode=A_Jcc) and
  1530. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1531. begin
  1532. {
  1533. imul X, reg1, reg2 to
  1534. lea (reg1,reg1,Y), reg2
  1535. shl ZZ,reg2
  1536. imul XX, reg1 to
  1537. lea (reg1,reg1,YY), reg1
  1538. shl ZZ,reg2
  1539. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1540. it does not exist as a separate optimization target in FPC though.
  1541. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1542. at most two zeros
  1543. }
  1544. reference_reset(tmpref,1,[]);
  1545. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1546. begin
  1547. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1548. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1549. TmpRef.base := taicpu(p).oper[1]^.reg;
  1550. TmpRef.index := taicpu(p).oper[1]^.reg;
  1551. if not(BaseValue in [3,5,9]) then
  1552. Internalerror(2018110101);
  1553. TmpRef.ScaleFactor := BaseValue-1;
  1554. if (taicpu(p).ops = 2) then
  1555. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1556. else
  1557. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1558. AsmL.InsertAfter(hp1,p);
  1559. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1560. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1561. RemoveCurrentP(p, hp1);
  1562. if ShiftValue>0 then
  1563. begin
  1564. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1565. AsmL.InsertAfter(hp2,hp1);
  1566. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1567. end;
  1568. Result := True;
  1569. end;
  1570. end;
  1571. end;
  1572. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1573. begin
  1574. Result := False;
  1575. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1576. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1577. begin
  1578. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1579. taicpu(p).opcode := A_MOV;
  1580. Result := True;
  1581. end;
  1582. end;
  1583. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1584. var
  1585. p: taicpu absolute hp; { Implicit typecast }
  1586. i: Integer;
  1587. begin
  1588. Result := False;
  1589. if not assigned(hp) or
  1590. (hp.typ <> ait_instruction) then
  1591. Exit;
  1592. Prefetch(insprop[p.opcode]);
  1593. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1594. with insprop[p.opcode] do
  1595. begin
  1596. case getsubreg(reg) of
  1597. R_SUBW,R_SUBD,R_SUBQ:
  1598. Result:=
  1599. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1600. uncommon flags are checked first }
  1601. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1602. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1606. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1607. R_SUBFLAGCARRY:
  1608. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1609. R_SUBFLAGPARITY:
  1610. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1611. R_SUBFLAGAUXILIARY:
  1612. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1613. R_SUBFLAGZERO:
  1614. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1615. R_SUBFLAGSIGN:
  1616. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1617. R_SUBFLAGOVERFLOW:
  1618. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1619. R_SUBFLAGINTERRUPT:
  1620. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1621. R_SUBFLAGDIRECTION:
  1622. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1623. else
  1624. internalerror(2017050501);
  1625. end;
  1626. exit;
  1627. end;
  1628. { Handle special cases first }
  1629. case p.opcode of
  1630. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1631. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1632. begin
  1633. Result :=
  1634. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1635. (p.oper[1]^.typ = top_reg) and
  1636. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1637. (
  1638. (p.oper[0]^.typ = top_const) or
  1639. (
  1640. (p.oper[0]^.typ = top_reg) and
  1641. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1642. ) or (
  1643. (p.oper[0]^.typ = top_ref) and
  1644. not RegInRef(reg,p.oper[0]^.ref^)
  1645. )
  1646. );
  1647. end;
  1648. A_MUL, A_IMUL:
  1649. Result :=
  1650. (
  1651. (p.ops=3) and { IMUL only }
  1652. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1653. (
  1654. (
  1655. (p.oper[1]^.typ=top_reg) and
  1656. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1657. ) or (
  1658. (p.oper[1]^.typ=top_ref) and
  1659. not RegInRef(reg,p.oper[1]^.ref^)
  1660. )
  1661. )
  1662. ) or (
  1663. (
  1664. (p.ops=1) and
  1665. (
  1666. (
  1667. (
  1668. (p.oper[0]^.typ=top_reg) and
  1669. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1670. )
  1671. ) or (
  1672. (p.oper[0]^.typ=top_ref) and
  1673. not RegInRef(reg,p.oper[0]^.ref^)
  1674. )
  1675. ) and (
  1676. (
  1677. (p.opsize=S_B) and
  1678. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1679. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1680. ) or (
  1681. (p.opsize=S_W) and
  1682. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1683. ) or (
  1684. (p.opsize=S_L) and
  1685. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1686. {$ifdef x86_64}
  1687. ) or (
  1688. (p.opsize=S_Q) and
  1689. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1690. {$endif x86_64}
  1691. )
  1692. )
  1693. )
  1694. );
  1695. A_CBW:
  1696. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1697. {$ifndef x86_64}
  1698. A_LDS:
  1699. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1700. A_LES:
  1701. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1702. {$endif not x86_64}
  1703. A_LFS:
  1704. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1705. A_LGS:
  1706. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1707. A_LSS:
  1708. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1709. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1710. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1711. A_LODSB:
  1712. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1713. A_LODSW:
  1714. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1715. {$ifdef x86_64}
  1716. A_LODSQ:
  1717. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1718. {$endif x86_64}
  1719. A_LODSD:
  1720. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1721. A_FSTSW, A_FNSTSW:
  1722. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1723. else
  1724. begin
  1725. with insprop[p.opcode] do
  1726. begin
  1727. if (
  1728. { xor %reg,%reg etc. is classed as a new value }
  1729. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1730. MatchOpType(p, top_reg, top_reg) and
  1731. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1732. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1733. ) then
  1734. begin
  1735. Result := True;
  1736. Exit;
  1737. end;
  1738. { Make sure the entire register is overwritten }
  1739. if (getregtype(reg) = R_INTREGISTER) then
  1740. begin
  1741. if (p.ops > 0) then
  1742. begin
  1743. if RegInOp(reg, p.oper[0]^) then
  1744. begin
  1745. if (p.oper[0]^.typ = top_ref) then
  1746. begin
  1747. if RegInRef(reg, p.oper[0]^.ref^) then
  1748. begin
  1749. Result := False;
  1750. Exit;
  1751. end;
  1752. end
  1753. else if (p.oper[0]^.typ = top_reg) then
  1754. begin
  1755. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1756. begin
  1757. Result := False;
  1758. Exit;
  1759. end
  1760. else if ([Ch_WOp1]*Ch<>[]) then
  1761. begin
  1762. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1763. Result := True
  1764. else
  1765. begin
  1766. Result := False;
  1767. Exit;
  1768. end;
  1769. end;
  1770. end;
  1771. end;
  1772. if (p.ops > 1) then
  1773. begin
  1774. if RegInOp(reg, p.oper[1]^) then
  1775. begin
  1776. if (p.oper[1]^.typ = top_ref) then
  1777. begin
  1778. if RegInRef(reg, p.oper[1]^.ref^) then
  1779. begin
  1780. Result := False;
  1781. Exit;
  1782. end;
  1783. end
  1784. else if (p.oper[1]^.typ = top_reg) then
  1785. begin
  1786. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1787. begin
  1788. Result := False;
  1789. Exit;
  1790. end
  1791. else if ([Ch_WOp2]*Ch<>[]) then
  1792. begin
  1793. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1794. Result := True
  1795. else
  1796. begin
  1797. Result := False;
  1798. Exit;
  1799. end;
  1800. end;
  1801. end;
  1802. end;
  1803. if (p.ops > 2) then
  1804. begin
  1805. if RegInOp(reg, p.oper[2]^) then
  1806. begin
  1807. if (p.oper[2]^.typ = top_ref) then
  1808. begin
  1809. if RegInRef(reg, p.oper[2]^.ref^) then
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end;
  1814. end
  1815. else if (p.oper[2]^.typ = top_reg) then
  1816. begin
  1817. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1818. begin
  1819. Result := False;
  1820. Exit;
  1821. end
  1822. else if ([Ch_WOp3]*Ch<>[]) then
  1823. begin
  1824. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1825. Result := True
  1826. else
  1827. begin
  1828. Result := False;
  1829. Exit;
  1830. end;
  1831. end;
  1832. end;
  1833. end;
  1834. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1835. begin
  1836. if (p.oper[3]^.typ = top_ref) then
  1837. begin
  1838. if RegInRef(reg, p.oper[3]^.ref^) then
  1839. begin
  1840. Result := False;
  1841. Exit;
  1842. end;
  1843. end
  1844. else if (p.oper[3]^.typ = top_reg) then
  1845. begin
  1846. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1847. begin
  1848. Result := False;
  1849. Exit;
  1850. end
  1851. else if ([Ch_WOp4]*Ch<>[]) then
  1852. begin
  1853. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1854. Result := True
  1855. else
  1856. begin
  1857. Result := False;
  1858. Exit;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. end;
  1866. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1867. case getsupreg(reg) of
  1868. RS_EAX:
  1869. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1870. begin
  1871. Result := True;
  1872. Exit;
  1873. end;
  1874. RS_ECX:
  1875. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1876. begin
  1877. Result := True;
  1878. Exit;
  1879. end;
  1880. RS_EDX:
  1881. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1882. begin
  1883. Result := True;
  1884. Exit;
  1885. end;
  1886. RS_EBX:
  1887. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1888. begin
  1889. Result := True;
  1890. Exit;
  1891. end;
  1892. RS_ESP:
  1893. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1894. begin
  1895. Result := True;
  1896. Exit;
  1897. end;
  1898. RS_EBP:
  1899. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1900. begin
  1901. Result := True;
  1902. Exit;
  1903. end;
  1904. RS_ESI:
  1905. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1906. begin
  1907. Result := True;
  1908. Exit;
  1909. end;
  1910. RS_EDI:
  1911. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1912. begin
  1913. Result := True;
  1914. Exit;
  1915. end;
  1916. else
  1917. ;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. end;
  1924. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1925. var
  1926. hp2,hp3 : tai;
  1927. begin
  1928. { some x86-64 issue a NOP before the real exit code }
  1929. if MatchInstruction(p,A_NOP,[]) then
  1930. GetNextInstruction(p,p);
  1931. result:=assigned(p) and (p.typ=ait_instruction) and
  1932. ((taicpu(p).opcode = A_RET) or
  1933. ((taicpu(p).opcode=A_LEAVE) and
  1934. GetNextInstruction(p,hp2) and
  1935. MatchInstruction(hp2,A_RET,[S_NO])
  1936. ) or
  1937. (((taicpu(p).opcode=A_LEA) and
  1938. MatchOpType(taicpu(p),top_ref,top_reg) and
  1939. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1940. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1941. ) and
  1942. GetNextInstruction(p,hp2) and
  1943. MatchInstruction(hp2,A_RET,[S_NO])
  1944. ) or
  1945. ((((taicpu(p).opcode=A_MOV) and
  1946. MatchOpType(taicpu(p),top_reg,top_reg) and
  1947. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1948. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1949. ((taicpu(p).opcode=A_LEA) and
  1950. MatchOpType(taicpu(p),top_ref,top_reg) and
  1951. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1952. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1953. )
  1954. ) and
  1955. GetNextInstruction(p,hp2) and
  1956. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1957. MatchOpType(taicpu(hp2),top_reg) and
  1958. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1959. GetNextInstruction(hp2,hp3) and
  1960. MatchInstruction(hp3,A_RET,[S_NO])
  1961. )
  1962. );
  1963. end;
  1964. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1965. begin
  1966. isFoldableArithOp := False;
  1967. case hp1.opcode of
  1968. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1969. isFoldableArithOp :=
  1970. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1971. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1972. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1973. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1974. (taicpu(hp1).oper[1]^.reg = reg);
  1975. A_INC,A_DEC,A_NEG,A_NOT:
  1976. isFoldableArithOp :=
  1977. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1978. (taicpu(hp1).oper[0]^.reg = reg);
  1979. else
  1980. ;
  1981. end;
  1982. end;
  1983. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1984. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1985. var
  1986. hp2: tai;
  1987. begin
  1988. hp2 := p;
  1989. repeat
  1990. hp2 := tai(hp2.previous);
  1991. if assigned(hp2) and
  1992. (hp2.typ = ait_regalloc) and
  1993. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1994. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1995. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1996. begin
  1997. RemoveInstruction(hp2);
  1998. break;
  1999. end;
  2000. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2001. end;
  2002. begin
  2003. case current_procinfo.procdef.returndef.typ of
  2004. arraydef,recorddef,pointerdef,
  2005. stringdef,enumdef,procdef,objectdef,errordef,
  2006. filedef,setdef,procvardef,
  2007. classrefdef,forwarddef:
  2008. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2009. orddef:
  2010. if current_procinfo.procdef.returndef.size <> 0 then
  2011. begin
  2012. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2013. { for int64/qword }
  2014. if current_procinfo.procdef.returndef.size = 8 then
  2015. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2016. end;
  2017. else
  2018. ;
  2019. end;
  2020. end;
  2021. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2022. var
  2023. hp1,hp2 : tai;
  2024. begin
  2025. result:=false;
  2026. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2027. begin
  2028. { vmova* reg1,reg1
  2029. =>
  2030. <nop> }
  2031. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2032. begin
  2033. RemoveCurrentP(p);
  2034. result:=true;
  2035. exit;
  2036. end;
  2037. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2038. (hp1.typ = ait_instruction) and
  2039. (
  2040. { Under -O2 and below, the instructions are always adjacent }
  2041. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2042. (taicpu(hp1).ops <= 1) or
  2043. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2044. { If reg1 = reg3, reg1 must not be modified in between }
  2045. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2046. ) then
  2047. begin
  2048. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2049. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2050. begin
  2051. { vmova* reg1,reg2
  2052. ...
  2053. vmova* reg2,reg3
  2054. dealloc reg2
  2055. =>
  2056. vmova* reg1,reg3 }
  2057. TransferUsedRegs(TmpUsedRegs);
  2058. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2059. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2060. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2061. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2062. begin
  2063. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2064. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2065. TransferUsedRegs(TmpUsedRegs);
  2066. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2067. RemoveInstruction(hp1);
  2068. result:=true;
  2069. exit;
  2070. end;
  2071. { special case:
  2072. vmova* reg1,<op>
  2073. ...
  2074. vmova* <op>,reg1
  2075. =>
  2076. vmova* reg1,<op> }
  2077. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2078. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2079. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2080. ) then
  2081. begin
  2082. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2083. RemoveInstruction(hp1);
  2084. result:=true;
  2085. exit;
  2086. end
  2087. end
  2088. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2089. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2090. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2091. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2092. ) and
  2093. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2094. begin
  2095. { vmova* reg1,reg2
  2096. ...
  2097. vmovs* reg2,<op>
  2098. dealloc reg2
  2099. =>
  2100. vmovs* reg1,<op> }
  2101. TransferUsedRegs(TmpUsedRegs);
  2102. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2103. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2104. begin
  2105. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2106. taicpu(p).opcode:=taicpu(hp1).opcode;
  2107. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2108. TransferUsedRegs(TmpUsedRegs);
  2109. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2110. RemoveInstruction(hp1);
  2111. result:=true;
  2112. exit;
  2113. end
  2114. end;
  2115. if MatchInstruction(hp1,[A_VFMADDPD,
  2116. A_VFMADD132PD,
  2117. A_VFMADD132PS,
  2118. A_VFMADD132SD,
  2119. A_VFMADD132SS,
  2120. A_VFMADD213PD,
  2121. A_VFMADD213PS,
  2122. A_VFMADD213SD,
  2123. A_VFMADD213SS,
  2124. A_VFMADD231PD,
  2125. A_VFMADD231PS,
  2126. A_VFMADD231SD,
  2127. A_VFMADD231SS,
  2128. A_VFMADDSUB132PD,
  2129. A_VFMADDSUB132PS,
  2130. A_VFMADDSUB213PD,
  2131. A_VFMADDSUB213PS,
  2132. A_VFMADDSUB231PD,
  2133. A_VFMADDSUB231PS,
  2134. A_VFMSUB132PD,
  2135. A_VFMSUB132PS,
  2136. A_VFMSUB132SD,
  2137. A_VFMSUB132SS,
  2138. A_VFMSUB213PD,
  2139. A_VFMSUB213PS,
  2140. A_VFMSUB213SD,
  2141. A_VFMSUB213SS,
  2142. A_VFMSUB231PD,
  2143. A_VFMSUB231PS,
  2144. A_VFMSUB231SD,
  2145. A_VFMSUB231SS,
  2146. A_VFMSUBADD132PD,
  2147. A_VFMSUBADD132PS,
  2148. A_VFMSUBADD213PD,
  2149. A_VFMSUBADD213PS,
  2150. A_VFMSUBADD231PD,
  2151. A_VFMSUBADD231PS,
  2152. A_VFNMADD132PD,
  2153. A_VFNMADD132PS,
  2154. A_VFNMADD132SD,
  2155. A_VFNMADD132SS,
  2156. A_VFNMADD213PD,
  2157. A_VFNMADD213PS,
  2158. A_VFNMADD213SD,
  2159. A_VFNMADD213SS,
  2160. A_VFNMADD231PD,
  2161. A_VFNMADD231PS,
  2162. A_VFNMADD231SD,
  2163. A_VFNMADD231SS,
  2164. A_VFNMSUB132PD,
  2165. A_VFNMSUB132PS,
  2166. A_VFNMSUB132SD,
  2167. A_VFNMSUB132SS,
  2168. A_VFNMSUB213PD,
  2169. A_VFNMSUB213PS,
  2170. A_VFNMSUB213SD,
  2171. A_VFNMSUB213SS,
  2172. A_VFNMSUB231PD,
  2173. A_VFNMSUB231PS,
  2174. A_VFNMSUB231SD,
  2175. A_VFNMSUB231SS],[S_NO]) and
  2176. { we mix single and double opperations here because we assume that the compiler
  2177. generates vmovapd only after double operations and vmovaps only after single operations }
  2178. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2179. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2180. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2181. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2182. begin
  2183. TransferUsedRegs(TmpUsedRegs);
  2184. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2185. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2186. begin
  2187. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2188. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2189. RemoveCurrentP(p)
  2190. else
  2191. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2192. RemoveInstruction(hp2);
  2193. end;
  2194. end
  2195. else if (hp1.typ = ait_instruction) and
  2196. (((taicpu(p).opcode=A_MOVAPS) and
  2197. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2198. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2199. ((taicpu(p).opcode=A_MOVAPD) and
  2200. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2201. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2202. ) and
  2203. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2204. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2205. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2206. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2207. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2208. { change
  2209. movapX reg,reg2
  2210. addsX/subsX/... reg3, reg2
  2211. movapX reg2,reg
  2212. to
  2213. addsX/subsX/... reg3,reg
  2214. }
  2215. begin
  2216. TransferUsedRegs(TmpUsedRegs);
  2217. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2218. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2219. begin
  2220. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2221. debug_op2str(taicpu(p).opcode)+' '+
  2222. debug_op2str(taicpu(hp1).opcode)+' '+
  2223. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2224. { we cannot eliminate the first move if
  2225. the operations uses the same register for source and dest }
  2226. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { Remember that hp1 is not necessarily the immediate
  2228. next instruction }
  2229. RemoveCurrentP(p);
  2230. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2231. RemoveInstruction(hp2);
  2232. result:=true;
  2233. end;
  2234. end
  2235. else if (hp1.typ = ait_instruction) and
  2236. (((taicpu(p).opcode=A_VMOVAPD) and
  2237. (taicpu(hp1).opcode=A_VCOMISD)) or
  2238. ((taicpu(p).opcode=A_VMOVAPS) and
  2239. ((taicpu(hp1).opcode=A_VCOMISS))
  2240. )
  2241. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2242. { change
  2243. movapX reg,reg1
  2244. vcomisX reg1,reg1
  2245. to
  2246. vcomisX reg,reg
  2247. }
  2248. begin
  2249. TransferUsedRegs(TmpUsedRegs);
  2250. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2251. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2252. begin
  2253. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2254. debug_op2str(taicpu(p).opcode)+' '+
  2255. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2256. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2257. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2258. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2259. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2260. RemoveCurrentP(p);
  2261. result:=true;
  2262. exit;
  2263. end;
  2264. end
  2265. end;
  2266. end;
  2267. end;
  2268. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2269. var
  2270. hp1 : tai;
  2271. begin
  2272. result:=false;
  2273. { replace
  2274. V<Op>X %mreg1,%mreg2,%mreg3
  2275. VMovX %mreg3,%mreg4
  2276. dealloc %mreg3
  2277. by
  2278. V<Op>X %mreg1,%mreg2,%mreg4
  2279. ?
  2280. }
  2281. if GetNextInstruction(p,hp1) and
  2282. { we mix single and double operations here because we assume that the compiler
  2283. generates vmovapd only after double operations and vmovaps only after single operations }
  2284. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2285. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2286. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2287. begin
  2288. TransferUsedRegs(TmpUsedRegs);
  2289. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2290. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2291. begin
  2292. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2293. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2294. RemoveInstruction(hp1);
  2295. result:=true;
  2296. end;
  2297. end;
  2298. end;
  2299. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2300. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2301. begin
  2302. Result := False;
  2303. { For safety reasons, only check for exact register matches }
  2304. { Check base register }
  2305. if (ref.base = AOldReg) then
  2306. begin
  2307. ref.base := ANewReg;
  2308. Result := True;
  2309. end;
  2310. { Check index register }
  2311. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2312. begin
  2313. ref.index := ANewReg;
  2314. Result := True;
  2315. end;
  2316. end;
  2317. { Replaces all references to AOldReg in an operand to ANewReg }
  2318. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2319. var
  2320. OldSupReg, NewSupReg: TSuperRegister;
  2321. OldSubReg, NewSubReg: TSubRegister;
  2322. OldRegType: TRegisterType;
  2323. ThisOper: POper;
  2324. begin
  2325. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2326. Result := False;
  2327. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2328. InternalError(2020011801);
  2329. OldSupReg := getsupreg(AOldReg);
  2330. OldSubReg := getsubreg(AOldReg);
  2331. OldRegType := getregtype(AOldReg);
  2332. NewSupReg := getsupreg(ANewReg);
  2333. NewSubReg := getsubreg(ANewReg);
  2334. if OldRegType <> getregtype(ANewReg) then
  2335. InternalError(2020011802);
  2336. if OldSubReg <> NewSubReg then
  2337. InternalError(2020011803);
  2338. case ThisOper^.typ of
  2339. top_reg:
  2340. if (
  2341. (ThisOper^.reg = AOldReg) or
  2342. (
  2343. (OldRegType = R_INTREGISTER) and
  2344. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2345. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2346. (
  2347. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2348. {$ifndef x86_64}
  2349. and (
  2350. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2351. don't have an 8-bit representation }
  2352. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2353. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2354. )
  2355. {$endif x86_64}
  2356. )
  2357. )
  2358. ) then
  2359. begin
  2360. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2361. Result := True;
  2362. end;
  2363. top_ref:
  2364. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2365. Result := True;
  2366. else
  2367. ;
  2368. end;
  2369. end;
  2370. { Replaces all references to AOldReg in an instruction to ANewReg }
  2371. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2372. const
  2373. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2374. var
  2375. OperIdx: Integer;
  2376. begin
  2377. Result := False;
  2378. for OperIdx := 0 to p.ops - 1 do
  2379. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2380. begin
  2381. { The shift and rotate instructions can only use CL }
  2382. if not (
  2383. (OperIdx = 0) and
  2384. { This second condition just helps to avoid unnecessarily
  2385. calling MatchInstruction for 10 different opcodes }
  2386. (p.oper[0]^.reg = NR_CL) and
  2387. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2388. ) then
  2389. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2390. end
  2391. else if p.oper[OperIdx]^.typ = top_ref then
  2392. { It's okay to replace registers in references that get written to }
  2393. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2394. end;
  2395. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2396. begin
  2397. Result :=
  2398. (ref^.index = NR_NO) and
  2399. (
  2400. {$ifdef x86_64}
  2401. (
  2402. (ref^.base = NR_RIP) and
  2403. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2404. ) or
  2405. {$endif x86_64}
  2406. (ref^.refaddr = addr_full) or
  2407. (ref^.base = NR_STACK_POINTER_REG) or
  2408. (ref^.base = current_procinfo.framepointer)
  2409. );
  2410. end;
  2411. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2412. var
  2413. l: asizeint;
  2414. begin
  2415. Result := False;
  2416. { Should have been checked previously }
  2417. if p.opcode <> A_LEA then
  2418. InternalError(2020072501);
  2419. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2420. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2421. not(cs_opt_size in current_settings.optimizerswitches) then
  2422. exit;
  2423. with p.oper[0]^.ref^ do
  2424. begin
  2425. if (base <> p.oper[1]^.reg) or
  2426. (index <> NR_NO) or
  2427. assigned(symbol) then
  2428. exit;
  2429. l:=offset;
  2430. if (l=1) and UseIncDec then
  2431. begin
  2432. p.opcode:=A_INC;
  2433. p.loadreg(0,p.oper[1]^.reg);
  2434. p.ops:=1;
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2436. end
  2437. else if (l=-1) and UseIncDec then
  2438. begin
  2439. p.opcode:=A_DEC;
  2440. p.loadreg(0,p.oper[1]^.reg);
  2441. p.ops:=1;
  2442. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2443. end
  2444. else
  2445. begin
  2446. if (l<0) and (l<>-2147483648) then
  2447. begin
  2448. p.opcode:=A_SUB;
  2449. p.loadConst(0,-l);
  2450. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2451. end
  2452. else
  2453. begin
  2454. p.opcode:=A_ADD;
  2455. p.loadConst(0,l);
  2456. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2457. end;
  2458. end;
  2459. end;
  2460. Result := True;
  2461. end;
  2462. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2463. var
  2464. CurrentReg, ReplaceReg: TRegister;
  2465. begin
  2466. Result := False;
  2467. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2468. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2469. case hp.opcode of
  2470. A_FSTSW, A_FNSTSW,
  2471. A_IN, A_INS, A_OUT, A_OUTS,
  2472. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2473. { These routines have explicit operands, but they are restricted in
  2474. what they can be (e.g. IN and OUT can only read from AL, AX or
  2475. EAX. }
  2476. Exit;
  2477. A_IMUL:
  2478. begin
  2479. { The 1-operand version writes to implicit registers
  2480. The 2-operand version reads from the first operator, and reads
  2481. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2482. the 3-operand version reads from a register that it doesn't write to
  2483. }
  2484. case hp.ops of
  2485. 1:
  2486. if (
  2487. (
  2488. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2489. ) or
  2490. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2491. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2492. begin
  2493. Result := True;
  2494. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2495. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2496. end;
  2497. 2:
  2498. { Only modify the first parameter }
  2499. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2500. begin
  2501. Result := True;
  2502. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2503. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2504. end;
  2505. 3:
  2506. { Only modify the second parameter }
  2507. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2508. begin
  2509. Result := True;
  2510. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2511. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2512. end;
  2513. else
  2514. InternalError(2020012901);
  2515. end;
  2516. end;
  2517. else
  2518. if (hp.ops > 0) and
  2519. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2520. begin
  2521. Result := True;
  2522. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2523. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2524. end;
  2525. end;
  2526. end;
  2527. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2528. var
  2529. hp2: tai;
  2530. p_SourceReg, p_TargetReg: TRegister;
  2531. begin
  2532. Result := False;
  2533. { Backward optimisation. If we have:
  2534. func. %reg1,%reg2
  2535. mov %reg2,%reg3
  2536. (dealloc %reg2)
  2537. Change to:
  2538. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2539. Perform similar optimisations with 1, 3 and 4-operand instructions
  2540. that only have one output.
  2541. }
  2542. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2543. begin
  2544. p_SourceReg := taicpu(p).oper[0]^.reg;
  2545. p_TargetReg := taicpu(p).oper[1]^.reg;
  2546. TransferUsedRegs(TmpUsedRegs);
  2547. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2548. GetLastInstruction(p, hp2) and
  2549. (hp2.typ = ait_instruction) and
  2550. { Have to make sure it's an instruction that only reads from
  2551. the first operands and only writes (not reads or modifies) to
  2552. the last one; in essence, a pure function such as BSR, POPCNT
  2553. or ANDN }
  2554. (
  2555. (
  2556. (taicpu(hp2).ops = 1) and
  2557. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2558. ) or
  2559. (
  2560. (taicpu(hp2).ops = 2) and
  2561. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2562. ) or
  2563. (
  2564. (taicpu(hp2).ops = 3) and
  2565. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2566. ) or
  2567. (
  2568. (taicpu(hp2).ops = 4) and
  2569. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2570. )
  2571. ) and
  2572. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2573. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2574. begin
  2575. case taicpu(hp2).opcode of
  2576. A_FSTSW, A_FNSTSW,
  2577. A_IN, A_INS, A_OUT, A_OUTS,
  2578. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2579. { These routines have explicit operands, but they are restricted in
  2580. what they can be (e.g. IN and OUT can only read from AL, AX or
  2581. EAX. }
  2582. ;
  2583. else
  2584. begin
  2585. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2586. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2587. if not RegInInstruction(p_TargetReg, hp2) then
  2588. begin
  2589. { Since we're allocating from an earlier point, we
  2590. need to remove the register from the tracking }
  2591. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2592. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2593. end;
  2594. RemoveCurrentp(p, hp1);
  2595. { If the Func was another MOV instruction, we might get
  2596. "mov %reg,%reg" that doesn't get removed in Pass 2
  2597. otherwise, so deal with it here (also do something
  2598. similar with lea (%reg),%reg}
  2599. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2600. begin
  2601. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2602. if p = hp2 then
  2603. RemoveCurrentp(p)
  2604. else
  2605. RemoveInstruction(hp2);
  2606. end;
  2607. Result := True;
  2608. Exit;
  2609. end;
  2610. end;
  2611. end;
  2612. end;
  2613. end;
  2614. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2615. begin
  2616. Result := False;
  2617. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2618. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2619. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2620. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2621. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2622. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2623. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2624. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2625. begin
  2626. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2627. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2628. Result := True;
  2629. end;
  2630. end;
  2631. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2632. var
  2633. hp1, hp2, hp3, hp4: tai;
  2634. DoOptimisation, TempBool: Boolean;
  2635. {$ifdef x86_64}
  2636. NewConst: TCGInt;
  2637. {$endif x86_64}
  2638. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2639. begin
  2640. if taicpu(hp1).opcode = signed_movop then
  2641. begin
  2642. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2643. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2644. end
  2645. else
  2646. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2647. end;
  2648. function TryConstMerge(var p1, p2: tai): Boolean;
  2649. var
  2650. ThisRef: TReference;
  2651. begin
  2652. Result := False;
  2653. ThisRef := taicpu(p2).oper[1]^.ref^;
  2654. { Only permit writes to the stack, since we can guarantee alignment with that }
  2655. if (ThisRef.index = NR_NO) and
  2656. (
  2657. (ThisRef.base = NR_STACK_POINTER_REG) or
  2658. (ThisRef.base = current_procinfo.framepointer)
  2659. ) then
  2660. begin
  2661. case taicpu(p).opsize of
  2662. S_B:
  2663. begin
  2664. { Word writes must be on a 2-byte boundary }
  2665. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2666. begin
  2667. { Reduce offset of second reference to see if it is sequential with the first }
  2668. Dec(ThisRef.offset, 1);
  2669. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2670. begin
  2671. { Make sure the constants aren't represented as a
  2672. negative number, as these won't merge properly }
  2673. taicpu(p1).opsize := S_W;
  2674. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2675. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2676. RemoveInstruction(p2);
  2677. Result := True;
  2678. end;
  2679. end;
  2680. end;
  2681. S_W:
  2682. begin
  2683. { Longword writes must be on a 4-byte boundary }
  2684. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2685. begin
  2686. { Reduce offset of second reference to see if it is sequential with the first }
  2687. Dec(ThisRef.offset, 2);
  2688. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2689. begin
  2690. { Make sure the constants aren't represented as a
  2691. negative number, as these won't merge properly }
  2692. taicpu(p1).opsize := S_L;
  2693. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2694. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2695. RemoveInstruction(p2);
  2696. Result := True;
  2697. end;
  2698. end;
  2699. end;
  2700. {$ifdef x86_64}
  2701. S_L:
  2702. begin
  2703. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2704. see if the constants can be encoded this way. }
  2705. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2706. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2707. { Quadword writes must be on an 8-byte boundary }
  2708. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2709. begin
  2710. { Reduce offset of second reference to see if it is sequential with the first }
  2711. Dec(ThisRef.offset, 4);
  2712. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2713. begin
  2714. { Make sure the constants aren't represented as a
  2715. negative number, as these won't merge properly }
  2716. taicpu(p1).opsize := S_Q;
  2717. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2718. taicpu(p1).oper[0]^.val := NewConst;
  2719. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2720. RemoveInstruction(p2);
  2721. Result := True;
  2722. end;
  2723. end;
  2724. end;
  2725. {$endif x86_64}
  2726. else
  2727. ;
  2728. end;
  2729. end;
  2730. end;
  2731. var
  2732. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2733. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2734. NewSize: topsize; NewOffset: asizeint;
  2735. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2736. SourceRef, TargetRef: TReference;
  2737. MovAligned, MovUnaligned: TAsmOp;
  2738. ThisRef: TReference;
  2739. JumpTracking: TLinkedList;
  2740. begin
  2741. Result:=false;
  2742. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2743. { remove mov reg1,reg1? }
  2744. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2745. then
  2746. begin
  2747. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2748. { take care of the register (de)allocs following p }
  2749. RemoveCurrentP(p, hp1);
  2750. Result:=true;
  2751. exit;
  2752. end;
  2753. { All the next optimisations require a next instruction }
  2754. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2755. Exit;
  2756. { Prevent compiler warnings }
  2757. p_TargetReg := NR_NO;
  2758. if taicpu(p).oper[1]^.typ = top_reg then
  2759. begin
  2760. { Saves on a large number of dereferences }
  2761. p_TargetReg := taicpu(p).oper[1]^.reg;
  2762. { Look for:
  2763. mov %reg1,%reg2
  2764. ??? %reg2,r/m
  2765. Change to:
  2766. mov %reg1,%reg2
  2767. ??? %reg1,r/m
  2768. }
  2769. if taicpu(p).oper[0]^.typ = top_reg then
  2770. begin
  2771. if RegReadByInstruction(p_TargetReg, hp1) and
  2772. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2773. begin
  2774. { A change has occurred, just not in p }
  2775. Result := True;
  2776. TransferUsedRegs(TmpUsedRegs);
  2777. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2778. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2779. { Just in case something didn't get modified (e.g. an
  2780. implicit register) }
  2781. not RegReadByInstruction(p_TargetReg, hp1) then
  2782. begin
  2783. { We can remove the original MOV }
  2784. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2785. RemoveCurrentp(p, hp1);
  2786. { UsedRegs got updated by RemoveCurrentp }
  2787. Result := True;
  2788. Exit;
  2789. end;
  2790. { If we know a MOV instruction has become a null operation, we might as well
  2791. get rid of it now to save time. }
  2792. if (taicpu(hp1).opcode = A_MOV) and
  2793. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2794. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2795. { Just being a register is enough to confirm it's a null operation }
  2796. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2797. begin
  2798. Result := True;
  2799. { Speed-up to reduce a pipeline stall... if we had something like...
  2800. movl %eax,%edx
  2801. movw %dx,%ax
  2802. ... the second instruction would change to movw %ax,%ax, but
  2803. given that it is now %ax that's active rather than %eax,
  2804. penalties might occur due to a partial register write, so instead,
  2805. change it to a MOVZX instruction when optimising for speed.
  2806. }
  2807. if not (cs_opt_size in current_settings.optimizerswitches) and
  2808. IsMOVZXAcceptable and
  2809. (taicpu(hp1).opsize < taicpu(p).opsize)
  2810. {$ifdef x86_64}
  2811. { operations already implicitly set the upper 64 bits to zero }
  2812. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2813. {$endif x86_64}
  2814. then
  2815. begin
  2816. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2817. case taicpu(p).opsize of
  2818. S_W:
  2819. if taicpu(hp1).opsize = S_B then
  2820. taicpu(hp1).opsize := S_BL
  2821. else
  2822. InternalError(2020012911);
  2823. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2824. case taicpu(hp1).opsize of
  2825. S_B:
  2826. taicpu(hp1).opsize := S_BL;
  2827. S_W:
  2828. taicpu(hp1).opsize := S_WL;
  2829. else
  2830. InternalError(2020012912);
  2831. end;
  2832. else
  2833. InternalError(2020012910);
  2834. end;
  2835. taicpu(hp1).opcode := A_MOVZX;
  2836. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2837. end
  2838. else
  2839. begin
  2840. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2841. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2842. RemoveInstruction(hp1);
  2843. { The instruction after what was hp1 is now the immediate next instruction,
  2844. so we can continue to make optimisations if it's present }
  2845. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2846. Exit;
  2847. hp1 := hp2;
  2848. end;
  2849. end;
  2850. end;
  2851. end;
  2852. end;
  2853. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2854. overwrites the original destination register. e.g.
  2855. movl ###,%reg2d
  2856. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2857. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2858. }
  2859. if (taicpu(p).oper[1]^.typ = top_reg) and
  2860. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2861. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2862. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2863. begin
  2864. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2865. begin
  2866. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2867. case taicpu(p).oper[0]^.typ of
  2868. top_const:
  2869. { We have something like:
  2870. movb $x, %regb
  2871. movzbl %regb,%regd
  2872. Change to:
  2873. movl $x, %regd
  2874. }
  2875. begin
  2876. case taicpu(hp1).opsize of
  2877. S_BW:
  2878. begin
  2879. convert_mov_value(A_MOVSX, $FF);
  2880. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2881. taicpu(p).opsize := S_W;
  2882. end;
  2883. S_BL:
  2884. begin
  2885. convert_mov_value(A_MOVSX, $FF);
  2886. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2887. taicpu(p).opsize := S_L;
  2888. end;
  2889. S_WL:
  2890. begin
  2891. convert_mov_value(A_MOVSX, $FFFF);
  2892. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2893. taicpu(p).opsize := S_L;
  2894. end;
  2895. {$ifdef x86_64}
  2896. S_BQ:
  2897. begin
  2898. convert_mov_value(A_MOVSX, $FF);
  2899. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2900. taicpu(p).opsize := S_Q;
  2901. end;
  2902. S_WQ:
  2903. begin
  2904. convert_mov_value(A_MOVSX, $FFFF);
  2905. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2906. taicpu(p).opsize := S_Q;
  2907. end;
  2908. S_LQ:
  2909. begin
  2910. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2911. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2912. taicpu(p).opsize := S_Q;
  2913. end;
  2914. {$endif x86_64}
  2915. else
  2916. { If hp1 was a MOV instruction, it should have been
  2917. optimised already }
  2918. InternalError(2020021001);
  2919. end;
  2920. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2921. RemoveInstruction(hp1);
  2922. Result := True;
  2923. Exit;
  2924. end;
  2925. top_ref:
  2926. begin
  2927. { We have something like:
  2928. movb mem, %regb
  2929. movzbl %regb,%regd
  2930. Change to:
  2931. movzbl mem, %regd
  2932. }
  2933. ThisRef := taicpu(p).oper[0]^.ref^;
  2934. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2935. begin
  2936. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2937. taicpu(hp1).loadref(0, ThisRef);
  2938. { Make sure any registers in the references are properly tracked }
  2939. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2940. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2941. if (ThisRef.index <> NR_NO) then
  2942. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2943. RemoveCurrentP(p, hp1);
  2944. Result := True;
  2945. Exit;
  2946. end;
  2947. end;
  2948. else
  2949. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2950. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2951. Exit;
  2952. end;
  2953. end
  2954. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2955. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2956. optimised }
  2957. else
  2958. begin
  2959. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2960. RemoveCurrentP(p, hp1);
  2961. Result := True;
  2962. Exit;
  2963. end;
  2964. end;
  2965. if (taicpu(hp1).opcode = A_AND) and
  2966. (taicpu(p).oper[1]^.typ = top_reg) and
  2967. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2968. begin
  2969. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2970. begin
  2971. case taicpu(p).opsize of
  2972. S_L:
  2973. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2974. begin
  2975. { Optimize out:
  2976. mov x, %reg
  2977. and ffffffffh, %reg
  2978. }
  2979. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2980. RemoveInstruction(hp1);
  2981. Result:=true;
  2982. exit;
  2983. end;
  2984. S_Q: { TODO: Confirm if this is even possible }
  2985. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2986. begin
  2987. { Optimize out:
  2988. mov x, %reg
  2989. and ffffffffffffffffh, %reg
  2990. }
  2991. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2992. RemoveInstruction(hp1);
  2993. Result:=true;
  2994. exit;
  2995. end;
  2996. else
  2997. ;
  2998. end;
  2999. if (
  3000. (taicpu(p).oper[0]^.typ=top_reg) or
  3001. (
  3002. (taicpu(p).oper[0]^.typ=top_ref) and
  3003. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3004. )
  3005. ) and
  3006. GetNextInstruction(hp1,hp2) and
  3007. MatchInstruction(hp2,A_TEST,[]) and
  3008. (
  3009. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3010. (
  3011. { If the register being tested is smaller than the one
  3012. that received a bitwise AND, permit it if the constant
  3013. fits into the smaller size }
  3014. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3015. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3016. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3017. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3018. (
  3019. (
  3020. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3021. (taicpu(hp1).oper[0]^.val <= $FF)
  3022. ) or
  3023. (
  3024. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3025. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3026. {$ifdef x86_64}
  3027. ) or
  3028. (
  3029. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3030. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3031. {$endif x86_64}
  3032. )
  3033. )
  3034. )
  3035. ) and
  3036. (
  3037. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3038. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3039. ) and
  3040. GetNextInstruction(hp2,hp3) and
  3041. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3042. (taicpu(hp3).condition in [C_E,C_NE]) then
  3043. begin
  3044. TransferUsedRegs(TmpUsedRegs);
  3045. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3046. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3047. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3048. begin
  3049. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3050. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3051. taicpu(hp1).opcode:=A_TEST;
  3052. { Shrink the TEST instruction down to the smallest possible size }
  3053. case taicpu(hp1).oper[0]^.val of
  3054. 0..255:
  3055. if (taicpu(hp1).opsize <> S_B)
  3056. {$ifndef x86_64}
  3057. and (
  3058. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3059. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3060. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3061. )
  3062. {$endif x86_64}
  3063. then
  3064. begin
  3065. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3066. { Only print debug message if the TEST instruction
  3067. is a different size before and after }
  3068. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3069. taicpu(hp1).opsize := S_B;
  3070. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3071. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3072. end;
  3073. 256..65535:
  3074. if (taicpu(hp1).opsize <> S_W) then
  3075. begin
  3076. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3077. { Only print debug message if the TEST instruction
  3078. is a different size before and after }
  3079. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3080. taicpu(hp1).opsize := S_W;
  3081. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3082. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3083. end;
  3084. {$ifdef x86_64}
  3085. 65536..$7FFFFFFF:
  3086. if (taicpu(hp1).opsize <> S_L) then
  3087. begin
  3088. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3089. { Only print debug message if the TEST instruction
  3090. is a different size before and after }
  3091. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3092. taicpu(hp1).opsize := S_L;
  3093. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3094. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3095. end;
  3096. {$endif x86_64}
  3097. else
  3098. ;
  3099. end;
  3100. RemoveInstruction(hp2);
  3101. RemoveCurrentP(p, hp1);
  3102. Result:=true;
  3103. exit;
  3104. end;
  3105. end;
  3106. end
  3107. else if IsMOVZXAcceptable and
  3108. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3109. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3110. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3111. then
  3112. begin
  3113. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3114. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3115. case taicpu(p).opsize of
  3116. S_B:
  3117. if (taicpu(hp1).oper[0]^.val = $ff) then
  3118. begin
  3119. { Convert:
  3120. movb x, %regl movb x, %regl
  3121. andw ffh, %regw andl ffh, %regd
  3122. To:
  3123. movzbw x, %regd movzbl x, %regd
  3124. (Identical registers, just different sizes)
  3125. }
  3126. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3127. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3128. case taicpu(hp1).opsize of
  3129. S_W: NewSize := S_BW;
  3130. S_L: NewSize := S_BL;
  3131. {$ifdef x86_64}
  3132. S_Q: NewSize := S_BQ;
  3133. {$endif x86_64}
  3134. else
  3135. InternalError(2018011510);
  3136. end;
  3137. end
  3138. else
  3139. NewSize := S_NO;
  3140. S_W:
  3141. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3142. begin
  3143. { Convert:
  3144. movw x, %regw
  3145. andl ffffh, %regd
  3146. To:
  3147. movzwl x, %regd
  3148. (Identical registers, just different sizes)
  3149. }
  3150. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3151. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3152. case taicpu(hp1).opsize of
  3153. S_L: NewSize := S_WL;
  3154. {$ifdef x86_64}
  3155. S_Q: NewSize := S_WQ;
  3156. {$endif x86_64}
  3157. else
  3158. InternalError(2018011511);
  3159. end;
  3160. end
  3161. else
  3162. NewSize := S_NO;
  3163. else
  3164. NewSize := S_NO;
  3165. end;
  3166. if NewSize <> S_NO then
  3167. begin
  3168. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3169. { The actual optimization }
  3170. taicpu(p).opcode := A_MOVZX;
  3171. taicpu(p).changeopsize(NewSize);
  3172. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3173. { Safeguard if "and" is followed by a conditional command }
  3174. TransferUsedRegs(TmpUsedRegs);
  3175. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3176. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3177. begin
  3178. { At this point, the "and" command is effectively equivalent to
  3179. "test %reg,%reg". This will be handled separately by the
  3180. Peephole Optimizer. [Kit] }
  3181. DebugMsg(SPeepholeOptimization + PreMessage +
  3182. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3183. end
  3184. else
  3185. begin
  3186. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3187. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3188. RemoveInstruction(hp1);
  3189. end;
  3190. Result := True;
  3191. Exit;
  3192. end;
  3193. end;
  3194. end;
  3195. if (taicpu(hp1).opcode = A_OR) and
  3196. (taicpu(p).oper[1]^.typ = top_reg) and
  3197. MatchOperand(taicpu(p).oper[0]^, 0) and
  3198. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3199. begin
  3200. { mov 0, %reg
  3201. or ###,%reg
  3202. Change to (only if the flags are not used):
  3203. mov ###,%reg
  3204. }
  3205. TransferUsedRegs(TmpUsedRegs);
  3206. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3207. DoOptimisation := True;
  3208. { Even if the flags are used, we might be able to do the optimisation
  3209. if the conditions are predictable }
  3210. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3211. begin
  3212. { Only perform if ### = %reg (the same register) or equal to 0,
  3213. so %reg is guaranteed to still have a value of zero }
  3214. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3215. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3216. begin
  3217. hp2 := hp1;
  3218. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3219. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3220. GetNextInstruction(hp2, hp3) do
  3221. begin
  3222. { Don't continue modifying if the flags state is getting changed }
  3223. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3224. Break;
  3225. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3226. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3227. begin
  3228. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3229. begin
  3230. { Condition is always true }
  3231. case taicpu(hp3).opcode of
  3232. A_Jcc:
  3233. begin
  3234. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3235. { Check for jump shortcuts before we destroy the condition }
  3236. DoJumpOptimizations(hp3, TempBool);
  3237. MakeUnconditional(taicpu(hp3));
  3238. Result := True;
  3239. end;
  3240. A_CMOVcc:
  3241. begin
  3242. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3243. taicpu(hp3).opcode := A_MOV;
  3244. taicpu(hp3).condition := C_None;
  3245. Result := True;
  3246. end;
  3247. A_SETcc:
  3248. begin
  3249. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3250. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3251. taicpu(hp3).opcode := A_MOV;
  3252. taicpu(hp3).ops := 2;
  3253. taicpu(hp3).condition := C_None;
  3254. taicpu(hp3).opsize := S_B;
  3255. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3256. taicpu(hp3).loadconst(0, 1);
  3257. Result := True;
  3258. end;
  3259. else
  3260. InternalError(2021090701);
  3261. end;
  3262. end
  3263. 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
  3264. begin
  3265. { Condition is always false }
  3266. case taicpu(hp3).opcode of
  3267. A_Jcc:
  3268. begin
  3269. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3270. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3271. RemoveInstruction(hp3);
  3272. Result := True;
  3273. { Since hp3 was deleted, hp2 must not be updated }
  3274. Continue;
  3275. end;
  3276. A_CMOVcc:
  3277. begin
  3278. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3279. RemoveInstruction(hp3);
  3280. Result := True;
  3281. { Since hp3 was deleted, hp2 must not be updated }
  3282. Continue;
  3283. end;
  3284. A_SETcc:
  3285. begin
  3286. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3287. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3288. taicpu(hp3).opcode := A_MOV;
  3289. taicpu(hp3).ops := 2;
  3290. taicpu(hp3).condition := C_None;
  3291. taicpu(hp3).opsize := S_B;
  3292. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3293. taicpu(hp3).loadconst(0, 0);
  3294. Result := True;
  3295. end;
  3296. else
  3297. InternalError(2021090702);
  3298. end;
  3299. end
  3300. else
  3301. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3302. DoOptimisation := False;
  3303. end;
  3304. hp2 := hp3;
  3305. end;
  3306. { Flags are still in use - don't optimise }
  3307. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3308. DoOptimisation := False;
  3309. end
  3310. else
  3311. DoOptimisation := False;
  3312. end;
  3313. if DoOptimisation then
  3314. begin
  3315. {$ifdef x86_64}
  3316. { OR only supports 32-bit sign-extended constants for 64-bit
  3317. instructions, so compensate for this if the constant is
  3318. encoded as a value greater than or equal to 2^31 }
  3319. if (taicpu(hp1).opsize = S_Q) and
  3320. (taicpu(hp1).oper[0]^.typ = top_const) and
  3321. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3322. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3323. {$endif x86_64}
  3324. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3325. taicpu(hp1).opcode := A_MOV;
  3326. RemoveCurrentP(p, hp1);
  3327. Result := True;
  3328. Exit;
  3329. end;
  3330. end;
  3331. { Next instruction is also a MOV ? }
  3332. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3333. begin
  3334. if MatchOpType(taicpu(p), top_const, top_ref) and
  3335. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3336. TryConstMerge(p, hp1) then
  3337. begin
  3338. Result := True;
  3339. { In case we have four byte writes in a row, check for 2 more
  3340. right now so we don't have to wait for another iteration of
  3341. pass 1
  3342. }
  3343. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3344. case taicpu(p).opsize of
  3345. S_W:
  3346. begin
  3347. if GetNextInstruction(p, hp1) and
  3348. MatchInstruction(hp1, A_MOV, [S_B]) and
  3349. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3350. GetNextInstruction(hp1, hp2) and
  3351. MatchInstruction(hp2, A_MOV, [S_B]) and
  3352. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3353. { Try to merge the two bytes }
  3354. TryConstMerge(hp1, hp2) then
  3355. { Now try to merge the two words (hp2 will get deleted) }
  3356. TryConstMerge(p, hp1);
  3357. end;
  3358. S_L:
  3359. begin
  3360. { Though this only really benefits x86_64 and not i386, it
  3361. gets a potential optimisation done faster and hence
  3362. reduces the number of times OptPass1MOV is entered }
  3363. if GetNextInstruction(p, hp1) and
  3364. MatchInstruction(hp1, A_MOV, [S_W]) and
  3365. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3366. GetNextInstruction(hp1, hp2) and
  3367. MatchInstruction(hp2, A_MOV, [S_W]) and
  3368. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3369. { Try to merge the two words }
  3370. TryConstMerge(hp1, hp2) then
  3371. { This will always fail on i386, so don't bother
  3372. calling it unless we're doing x86_64 }
  3373. {$ifdef x86_64}
  3374. { Now try to merge the two longwords (hp2 will get deleted) }
  3375. TryConstMerge(p, hp1)
  3376. {$endif x86_64}
  3377. ;
  3378. end;
  3379. else
  3380. ;
  3381. end;
  3382. Exit;
  3383. end;
  3384. if (taicpu(p).oper[1]^.typ = top_reg) and
  3385. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3386. begin
  3387. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3388. TransferUsedRegs(TmpUsedRegs);
  3389. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3390. { we have
  3391. mov x, %treg
  3392. mov %treg, y
  3393. }
  3394. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3395. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3396. { we've got
  3397. mov x, %treg
  3398. mov %treg, y
  3399. with %treg is not used after }
  3400. case taicpu(p).oper[0]^.typ Of
  3401. { top_reg is covered by DeepMOVOpt }
  3402. top_const:
  3403. begin
  3404. { change
  3405. mov const, %treg
  3406. mov %treg, y
  3407. to
  3408. mov const, y
  3409. }
  3410. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3411. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3412. begin
  3413. if taicpu(hp1).oper[1]^.typ=top_reg then
  3414. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3415. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3416. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3417. RemoveInstruction(hp1);
  3418. Result:=true;
  3419. Exit;
  3420. end;
  3421. end;
  3422. top_ref:
  3423. case taicpu(hp1).oper[1]^.typ of
  3424. top_reg:
  3425. begin
  3426. { change
  3427. mov mem, %treg
  3428. mov %treg, %reg
  3429. to
  3430. mov mem, %reg"
  3431. }
  3432. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3433. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3434. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3435. RemoveInstruction(hp1);
  3436. Result:=true;
  3437. Exit;
  3438. end;
  3439. top_ref:
  3440. begin
  3441. {$ifdef x86_64}
  3442. { Look for the following to simplify:
  3443. mov x(mem1), %reg
  3444. mov %reg, y(mem2)
  3445. mov x+8(mem1), %reg
  3446. mov %reg, y+8(mem2)
  3447. Change to:
  3448. movdqu x(mem1), %xmmreg
  3449. movdqu %xmmreg, y(mem2)
  3450. ...but only as long as the memory blocks don't overlap
  3451. }
  3452. SourceRef := taicpu(p).oper[0]^.ref^;
  3453. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3454. if (taicpu(p).opsize = S_Q) and
  3455. GetNextInstruction(hp1, hp2) and
  3456. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3457. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3458. begin
  3459. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3460. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3461. Inc(SourceRef.offset, 8);
  3462. if UseAVX then
  3463. begin
  3464. MovAligned := A_VMOVDQA;
  3465. MovUnaligned := A_VMOVDQU;
  3466. end
  3467. else
  3468. begin
  3469. MovAligned := A_MOVDQA;
  3470. MovUnaligned := A_MOVDQU;
  3471. end;
  3472. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3473. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3474. begin
  3475. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3476. Inc(TargetRef.offset, 8);
  3477. if GetNextInstruction(hp2, hp3) and
  3478. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3479. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3480. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3481. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3482. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3483. begin
  3484. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3485. if NewMMReg <> NR_NO then
  3486. begin
  3487. { Remember that the offsets are 8 ahead }
  3488. if ((SourceRef.offset mod 16) = 8) and
  3489. (
  3490. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3491. (SourceRef.base = current_procinfo.framepointer) or
  3492. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3493. ) then
  3494. taicpu(p).opcode := MovAligned
  3495. else
  3496. taicpu(p).opcode := MovUnaligned;
  3497. taicpu(p).opsize := S_XMM;
  3498. taicpu(p).oper[1]^.reg := NewMMReg;
  3499. if ((TargetRef.offset mod 16) = 8) and
  3500. (
  3501. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3502. (TargetRef.base = current_procinfo.framepointer) or
  3503. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3504. ) then
  3505. taicpu(hp1).opcode := MovAligned
  3506. else
  3507. taicpu(hp1).opcode := MovUnaligned;
  3508. taicpu(hp1).opsize := S_XMM;
  3509. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3510. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3511. RemoveInstruction(hp2);
  3512. RemoveInstruction(hp3);
  3513. Result := True;
  3514. Exit;
  3515. end;
  3516. end;
  3517. end
  3518. else
  3519. begin
  3520. { See if the next references are 8 less rather than 8 greater }
  3521. Dec(SourceRef.offset, 16); { -8 the other way }
  3522. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3523. begin
  3524. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3525. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3526. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3527. GetNextInstruction(hp2, hp3) and
  3528. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3529. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3530. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3531. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3532. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3533. begin
  3534. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3535. if NewMMReg <> NR_NO then
  3536. begin
  3537. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3538. if ((SourceRef.offset mod 16) = 0) and
  3539. (
  3540. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3541. (SourceRef.base = current_procinfo.framepointer) or
  3542. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3543. ) then
  3544. taicpu(hp2).opcode := MovAligned
  3545. else
  3546. taicpu(hp2).opcode := MovUnaligned;
  3547. taicpu(hp2).opsize := S_XMM;
  3548. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3549. if ((TargetRef.offset mod 16) = 0) and
  3550. (
  3551. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3552. (TargetRef.base = current_procinfo.framepointer) or
  3553. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3554. ) then
  3555. taicpu(hp3).opcode := MovAligned
  3556. else
  3557. taicpu(hp3).opcode := MovUnaligned;
  3558. taicpu(hp3).opsize := S_XMM;
  3559. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3560. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3561. RemoveInstruction(hp1);
  3562. RemoveCurrentP(p, hp2);
  3563. Result := True;
  3564. Exit;
  3565. end;
  3566. end;
  3567. end;
  3568. end;
  3569. end;
  3570. {$endif x86_64}
  3571. end;
  3572. else
  3573. { The write target should be a reg or a ref }
  3574. InternalError(2021091601);
  3575. end;
  3576. else
  3577. ;
  3578. end
  3579. else
  3580. { %treg is used afterwards, but all eventualities
  3581. other than the first MOV instruction being a constant
  3582. are covered by DeepMOVOpt, so only check for that }
  3583. if (taicpu(p).oper[0]^.typ = top_const) and
  3584. (
  3585. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3586. not (cs_opt_size in current_settings.optimizerswitches) or
  3587. (taicpu(hp1).opsize = S_B)
  3588. ) and
  3589. (
  3590. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3591. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3592. ) then
  3593. begin
  3594. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3595. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3596. end;
  3597. end;
  3598. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3599. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3600. { mov reg1, mem1 or mov mem1, reg1
  3601. mov mem2, reg2 mov reg2, mem2}
  3602. begin
  3603. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3604. { mov reg1, mem1 or mov mem1, reg1
  3605. mov mem2, reg1 mov reg2, mem1}
  3606. begin
  3607. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3608. { Removes the second statement from
  3609. mov reg1, mem1/reg2
  3610. mov mem1/reg2, reg1 }
  3611. begin
  3612. if taicpu(p).oper[0]^.typ=top_reg then
  3613. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3614. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3615. RemoveInstruction(hp1);
  3616. Result:=true;
  3617. exit;
  3618. end
  3619. else
  3620. begin
  3621. TransferUsedRegs(TmpUsedRegs);
  3622. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3623. if (taicpu(p).oper[1]^.typ = top_ref) and
  3624. { mov reg1, mem1
  3625. mov mem2, reg1 }
  3626. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3627. GetNextInstruction(hp1, hp2) and
  3628. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3629. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3630. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3631. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3632. { change to
  3633. mov reg1, mem1 mov reg1, mem1
  3634. mov mem2, reg1 cmp reg1, mem2
  3635. cmp mem1, reg1
  3636. }
  3637. begin
  3638. RemoveInstruction(hp2);
  3639. taicpu(hp1).opcode := A_CMP;
  3640. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3641. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3642. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3643. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3644. end;
  3645. end;
  3646. end
  3647. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3648. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3649. begin
  3650. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3651. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3652. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3653. end
  3654. else
  3655. begin
  3656. TransferUsedRegs(TmpUsedRegs);
  3657. if GetNextInstruction(hp1, hp2) and
  3658. MatchOpType(taicpu(p),top_ref,top_reg) and
  3659. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3660. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3661. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3662. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3663. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3664. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3665. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3666. { mov mem1, %reg1
  3667. mov %reg1, mem2
  3668. mov mem2, reg2
  3669. to:
  3670. mov mem1, reg2
  3671. mov reg2, mem2}
  3672. begin
  3673. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3674. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3675. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3676. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3677. RemoveInstruction(hp2);
  3678. Result := True;
  3679. end
  3680. {$ifdef i386}
  3681. { this is enabled for i386 only, as the rules to create the reg sets below
  3682. are too complicated for x86-64, so this makes this code too error prone
  3683. on x86-64
  3684. }
  3685. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3686. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3687. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3688. { mov mem1, reg1 mov mem1, reg1
  3689. mov reg1, mem2 mov reg1, mem2
  3690. mov mem2, reg2 mov mem2, reg1
  3691. to: to:
  3692. mov mem1, reg1 mov mem1, reg1
  3693. mov mem1, reg2 mov reg1, mem2
  3694. mov reg1, mem2
  3695. or (if mem1 depends on reg1
  3696. and/or if mem2 depends on reg2)
  3697. to:
  3698. mov mem1, reg1
  3699. mov reg1, mem2
  3700. mov reg1, reg2
  3701. }
  3702. begin
  3703. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3704. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3705. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3706. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3707. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3708. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3709. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3710. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3711. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3712. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3713. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3714. end
  3715. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3716. begin
  3717. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3718. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3719. end
  3720. else
  3721. begin
  3722. RemoveInstruction(hp2);
  3723. end
  3724. {$endif i386}
  3725. ;
  3726. end;
  3727. end
  3728. { movl [mem1],reg1
  3729. movl [mem1],reg2
  3730. to
  3731. movl [mem1],reg1
  3732. movl reg1,reg2
  3733. }
  3734. else if not CheckMovMov2MovMov2(p, hp1) and
  3735. { movl const1,[mem1]
  3736. movl [mem1],reg1
  3737. to
  3738. movl const1,reg1
  3739. movl reg1,[mem1]
  3740. }
  3741. MatchOpType(Taicpu(p),top_const,top_ref) and
  3742. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3743. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3744. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3745. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3746. begin
  3747. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3748. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3749. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3750. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3751. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3752. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3753. Result:=true;
  3754. exit;
  3755. end;
  3756. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3757. { Change:
  3758. movl %reg1,%reg2
  3759. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3760. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3761. To:
  3762. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3763. movl x(%reg1),%reg1
  3764. movl %reg1,%regX
  3765. }
  3766. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3767. begin
  3768. p_SourceReg := taicpu(p).oper[0]^.reg;
  3769. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3770. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3771. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3772. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3773. GetNextInstruction(hp1, hp2) and
  3774. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3775. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3776. begin
  3777. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3778. if RegInRef(p_TargetReg, SourceRef) and
  3779. { If %reg1 also appears in the second reference, then it will
  3780. not refer to the same memory block as the first reference }
  3781. not RegInRef(p_SourceReg, SourceRef) then
  3782. begin
  3783. { Check to see if the references match if %reg2 is changed to %reg1 }
  3784. if SourceRef.base = p_TargetReg then
  3785. SourceRef.base := p_SourceReg;
  3786. if SourceRef.index = p_TargetReg then
  3787. SourceRef.index := p_SourceReg;
  3788. { RefsEqual also checks to ensure both references are non-volatile }
  3789. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3790. begin
  3791. taicpu(hp2).loadreg(0, p_SourceReg);
  3792. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3793. Result := True;
  3794. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3795. begin
  3796. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3797. RemoveCurrentP(p, hp1);
  3798. Exit;
  3799. end
  3800. else
  3801. begin
  3802. { Check to see if %reg2 is no longer in use }
  3803. TransferUsedRegs(TmpUsedRegs);
  3804. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3805. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3806. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3807. begin
  3808. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3809. RemoveCurrentP(p, hp1);
  3810. Exit;
  3811. end;
  3812. end;
  3813. { If we reach this point, p and hp1 weren't actually modified,
  3814. so we can do a bit more work on this pass }
  3815. end;
  3816. end;
  3817. end;
  3818. end;
  3819. end;
  3820. {$ifdef x86_64}
  3821. { Change:
  3822. movl %reg1l,%reg2l
  3823. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3824. To:
  3825. movl %reg1l,%reg2l
  3826. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3827. If %reg1 = %reg3, convert to:
  3828. movl %reg1l,%reg2l
  3829. andl %reg1l,%reg1l
  3830. }
  3831. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3832. MatchOpType(taicpu(p), top_reg, top_reg) and
  3833. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3834. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3835. begin
  3836. TransferUsedRegs(TmpUsedRegs);
  3837. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3838. taicpu(hp1).opsize := S_L;
  3839. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3840. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3841. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3842. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3843. begin
  3844. { %reg1 = %reg3 }
  3845. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3846. taicpu(hp1).opcode := A_AND;
  3847. end
  3848. else
  3849. begin
  3850. { %reg1 <> %reg3 }
  3851. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3852. end;
  3853. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3854. begin
  3855. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3856. RemoveCurrentP(p, hp1);
  3857. Result := True;
  3858. Exit;
  3859. end
  3860. else
  3861. begin
  3862. { Initial instruction wasn't actually changed }
  3863. Include(OptsToCheck, aoc_ForceNewIteration);
  3864. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3865. appears below since %reg1 has technically changed }
  3866. if taicpu(hp1).opcode = A_AND then
  3867. Exit;
  3868. end;
  3869. end;
  3870. {$endif x86_64}
  3871. { search further than the next instruction for a mov (as long as it's not a jump) }
  3872. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3873. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3874. (taicpu(p).oper[1]^.typ = top_reg) and
  3875. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3876. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3877. begin
  3878. { we work with hp2 here, so hp1 can be still used later on when
  3879. checking for GetNextInstruction_p }
  3880. hp3 := hp1;
  3881. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3882. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3883. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3884. TransferUsedRegs(TmpUsedRegs);
  3885. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3886. if NotFirstIteration then
  3887. JumpTracking := TLinkedList.Create
  3888. else
  3889. JumpTracking := nil;
  3890. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3891. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3892. (hp2.typ=ait_instruction) do
  3893. begin
  3894. case taicpu(hp2).opcode of
  3895. A_POP:
  3896. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3897. begin
  3898. if not CrossJump and
  3899. not RegUsedBetween(p_TargetReg, p, hp2) then
  3900. begin
  3901. { We can remove the original MOV since the register
  3902. wasn't used between it and its popping from the stack }
  3903. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3904. RemoveCurrentp(p, hp1);
  3905. Result := True;
  3906. JumpTracking.Free;
  3907. Exit;
  3908. end;
  3909. { Can't go any further }
  3910. Break;
  3911. end;
  3912. A_MOV:
  3913. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3914. ((taicpu(p).oper[0]^.typ=top_const) or
  3915. ((taicpu(p).oper[0]^.typ=top_reg) and
  3916. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3917. )
  3918. ) then
  3919. begin
  3920. { we have
  3921. mov x, %treg
  3922. mov %treg, y
  3923. }
  3924. { We don't need to call UpdateUsedRegs for every instruction between
  3925. p and hp2 because the register we're concerned about will not
  3926. become deallocated (otherwise GetNextInstructionUsingReg would
  3927. have stopped at an earlier instruction). [Kit] }
  3928. TempRegUsed :=
  3929. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3930. RegReadByInstruction(p_TargetReg, hp3) or
  3931. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3932. case taicpu(p).oper[0]^.typ Of
  3933. top_reg:
  3934. begin
  3935. { change
  3936. mov %reg, %treg
  3937. mov %treg, y
  3938. to
  3939. mov %reg, y
  3940. }
  3941. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3942. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3943. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3944. begin
  3945. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3946. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3947. if TempRegUsed then
  3948. begin
  3949. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3950. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3951. { Set the start of the next GetNextInstructionUsingRegCond search
  3952. to start at the entry right before hp2 (which is about to be removed) }
  3953. hp3 := tai(hp2.Previous);
  3954. RemoveInstruction(hp2);
  3955. Include(OptsToCheck, aoc_ForceNewIteration);
  3956. { See if there's more we can optimise }
  3957. Continue;
  3958. end
  3959. else
  3960. begin
  3961. RemoveInstruction(hp2);
  3962. { We can remove the original MOV too }
  3963. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3964. RemoveCurrentP(p, hp1);
  3965. Result:=true;
  3966. JumpTracking.Free;
  3967. Exit;
  3968. end;
  3969. end
  3970. else
  3971. begin
  3972. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3973. taicpu(hp2).loadReg(0, p_SourceReg);
  3974. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3975. { Check to see if the register also appears in the reference }
  3976. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3977. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3978. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3979. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3980. begin
  3981. { Don't remove the first instruction if the temporary register is in use }
  3982. if not TempRegUsed then
  3983. begin
  3984. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3985. RemoveCurrentP(p, hp1);
  3986. Result:=true;
  3987. JumpTracking.Free;
  3988. Exit;
  3989. end;
  3990. { No need to set Result to True here. If there's another instruction later
  3991. on that can be optimised, it will be detected when the main Pass 1 loop
  3992. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3993. hp3 := hp2;
  3994. Continue;
  3995. end;
  3996. end;
  3997. end;
  3998. top_const:
  3999. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4000. begin
  4001. { change
  4002. mov const, %treg
  4003. mov %treg, y
  4004. to
  4005. mov const, y
  4006. }
  4007. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4008. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4009. begin
  4010. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4011. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4012. if TempRegUsed then
  4013. begin
  4014. { Don't remove the first instruction if the temporary register is in use }
  4015. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4016. { No need to set Result to True. If there's another instruction later on
  4017. that can be optimised, it will be detected when the main Pass 1 loop
  4018. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4019. end
  4020. else
  4021. begin
  4022. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4023. RemoveCurrentP(p, hp1);
  4024. Result:=true;
  4025. Exit;
  4026. end;
  4027. end;
  4028. end;
  4029. else
  4030. Internalerror(2019103001);
  4031. end;
  4032. end
  4033. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4034. begin
  4035. if not CrossJump and
  4036. not RegUsedBetween(p_TargetReg, p, hp2) and
  4037. not RegReadByInstruction(p_TargetReg, hp2) then
  4038. begin
  4039. { Register is not used before it is overwritten }
  4040. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4041. RemoveCurrentp(p, hp1);
  4042. Result := True;
  4043. Exit;
  4044. end;
  4045. if (taicpu(p).oper[0]^.typ = top_const) and
  4046. (taicpu(hp2).oper[0]^.typ = top_const) then
  4047. begin
  4048. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4049. begin
  4050. { Same value - register hasn't changed }
  4051. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4052. RemoveInstruction(hp2);
  4053. Include(OptsToCheck, aoc_ForceNewIteration);
  4054. { See if there's more we can optimise }
  4055. Continue;
  4056. end;
  4057. end;
  4058. {$ifdef x86_64}
  4059. end
  4060. { Change:
  4061. movl %reg1l,%reg2l
  4062. ...
  4063. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4064. To:
  4065. movl %reg1l,%reg2l
  4066. ...
  4067. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4068. If %reg1 = %reg3, convert to:
  4069. movl %reg1l,%reg2l
  4070. ...
  4071. andl %reg1l,%reg1l
  4072. }
  4073. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4074. (taicpu(p).oper[0]^.typ = top_reg) and
  4075. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4076. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4077. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4078. begin
  4079. TempRegUsed :=
  4080. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4081. RegReadByInstruction(p_TargetReg, hp3) or
  4082. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4083. taicpu(hp2).opsize := S_L;
  4084. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4085. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4086. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4087. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4088. begin
  4089. { %reg1 = %reg3 }
  4090. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4091. taicpu(hp2).opcode := A_AND;
  4092. end
  4093. else
  4094. begin
  4095. { %reg1 <> %reg3 }
  4096. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4097. end;
  4098. if not TempRegUsed then
  4099. begin
  4100. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4101. RemoveCurrentP(p, hp1);
  4102. Result := True;
  4103. Exit;
  4104. end
  4105. else
  4106. begin
  4107. { Initial instruction wasn't actually changed }
  4108. Include(OptsToCheck, aoc_ForceNewIteration);
  4109. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4110. appears below since %reg1 has technically changed }
  4111. if taicpu(hp2).opcode = A_AND then
  4112. Break;
  4113. end;
  4114. {$endif x86_64}
  4115. end
  4116. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4117. GetNextInstruction(hp2, hp4) and
  4118. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4119. { Optimise the following first:
  4120. movl [mem1],reg1
  4121. movl [mem1],reg2
  4122. to
  4123. movl [mem1],reg1
  4124. movl reg1,reg2
  4125. If [mem1] contains the target register and reg1 is the
  4126. the source register, this optimisation will get missed
  4127. and produce less efficient code later on.
  4128. }
  4129. if CheckMovMov2MovMov2(hp2, hp4) then
  4130. { Initial instruction wasn't actually changed }
  4131. Include(OptsToCheck, aoc_ForceNewIteration);
  4132. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4133. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4134. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4135. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4136. begin
  4137. {
  4138. Change from:
  4139. mov ###, %reg
  4140. ...
  4141. movs/z %reg,%reg (Same register, just different sizes)
  4142. To:
  4143. movs/z ###, %reg (Longer version)
  4144. ...
  4145. (remove)
  4146. }
  4147. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4148. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4149. { Keep the first instruction as mov if ### is a constant }
  4150. if taicpu(p).oper[0]^.typ = top_const then
  4151. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4152. else
  4153. begin
  4154. taicpu(p).opcode := taicpu(hp2).opcode;
  4155. taicpu(p).opsize := taicpu(hp2).opsize;
  4156. end;
  4157. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4158. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4159. RemoveInstruction(hp2);
  4160. Result := True;
  4161. JumpTracking.Free;
  4162. Exit;
  4163. end;
  4164. else
  4165. { Move down to the if-block below };
  4166. end;
  4167. { Also catches MOV/S/Z instructions that aren't modified }
  4168. if taicpu(p).oper[0]^.typ = top_reg then
  4169. begin
  4170. p_SourceReg := taicpu(p).oper[0]^.reg;
  4171. if
  4172. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4173. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4174. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4175. begin
  4176. Result := True;
  4177. { Just in case something didn't get modified (e.g. an
  4178. implicit register). Also, if it does read from this
  4179. register, then there's no longer an advantage to
  4180. changing the register on subsequent instructions.}
  4181. if not RegReadByInstruction(p_TargetReg, hp2) then
  4182. begin
  4183. { If a conditional jump was crossed, do not delete
  4184. the original MOV no matter what }
  4185. if not CrossJump and
  4186. { RegEndOfLife returns True if the register is
  4187. deallocated before the next instruction or has
  4188. been loaded with a new value }
  4189. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4190. begin
  4191. { We can remove the original MOV }
  4192. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4193. RemoveCurrentp(p, hp1);
  4194. JumpTracking.Free;
  4195. Result := True;
  4196. Exit;
  4197. end;
  4198. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4199. begin
  4200. { See if there's more we can optimise }
  4201. hp3 := hp2;
  4202. Continue;
  4203. end;
  4204. end;
  4205. end;
  4206. end;
  4207. { Break out of the while loop under normal circumstances }
  4208. Break;
  4209. end;
  4210. JumpTracking.Free;
  4211. end;
  4212. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4213. (taicpu(p).oper[1]^.typ = top_reg) and
  4214. (taicpu(p).opsize = S_L) and
  4215. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4216. (hp2.typ = ait_instruction) and
  4217. (taicpu(hp2).opcode = A_AND) and
  4218. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4219. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4220. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4221. ) then
  4222. begin
  4223. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4224. begin
  4225. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4226. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4227. begin
  4228. { Optimize out:
  4229. mov x, %reg
  4230. and ffffffffh, %reg
  4231. }
  4232. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4233. RemoveInstruction(hp2);
  4234. Result:=true;
  4235. exit;
  4236. end;
  4237. end;
  4238. end;
  4239. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4240. x >= RetOffset) as it doesn't do anything (it writes either to a
  4241. parameter or to the temporary storage room for the function
  4242. result)
  4243. }
  4244. if IsExitCode(hp1) and
  4245. (taicpu(p).oper[1]^.typ = top_ref) and
  4246. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4247. (
  4248. (
  4249. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4250. not (
  4251. assigned(current_procinfo.procdef.funcretsym) and
  4252. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4253. )
  4254. ) or
  4255. { Also discard writes to the stack that are below the base pointer,
  4256. as this is temporary storage rather than a function result on the
  4257. stack, say. }
  4258. (
  4259. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4260. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4261. )
  4262. ) then
  4263. begin
  4264. RemoveCurrentp(p, hp1);
  4265. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4266. RemoveLastDeallocForFuncRes(p);
  4267. Result:=true;
  4268. exit;
  4269. end;
  4270. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4271. begin
  4272. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4273. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4274. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4275. begin
  4276. { change
  4277. mov reg1, mem1
  4278. test/cmp x, mem1
  4279. to
  4280. mov reg1, mem1
  4281. test/cmp x, reg1
  4282. }
  4283. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4284. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4285. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4286. Result := True;
  4287. Exit;
  4288. end;
  4289. if DoMovCmpMemOpt(p, hp1) then
  4290. begin
  4291. Result := True;
  4292. Exit;
  4293. end;
  4294. end;
  4295. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4296. { If the flags register is in use, don't change the instruction to an
  4297. ADD otherwise this will scramble the flags. [Kit] }
  4298. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4299. begin
  4300. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4301. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4302. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4303. ) or
  4304. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4305. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4306. )
  4307. ) then
  4308. { mov reg1,ref
  4309. lea reg2,[reg1,reg2]
  4310. to
  4311. add reg2,ref}
  4312. begin
  4313. TransferUsedRegs(TmpUsedRegs);
  4314. { reg1 may not be used afterwards }
  4315. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4316. begin
  4317. Taicpu(hp1).opcode:=A_ADD;
  4318. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4319. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4320. RemoveCurrentp(p, hp1);
  4321. result:=true;
  4322. exit;
  4323. end;
  4324. end;
  4325. { If the LEA instruction can be converted into an arithmetic instruction,
  4326. it may be possible to then fold it in the next optimisation, otherwise
  4327. there's nothing more that can be optimised here. }
  4328. if not ConvertLEA(taicpu(hp1)) then
  4329. Exit;
  4330. end;
  4331. if (taicpu(p).oper[1]^.typ = top_reg) and
  4332. (hp1.typ = ait_instruction) and
  4333. GetNextInstruction(hp1, hp2) and
  4334. MatchInstruction(hp2,A_MOV,[]) and
  4335. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4336. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4337. (
  4338. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4339. {$ifdef x86_64}
  4340. or
  4341. (
  4342. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4343. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4344. )
  4345. {$endif x86_64}
  4346. ) then
  4347. begin
  4348. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4349. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4350. { change movsX/movzX reg/ref, reg2
  4351. add/sub/or/... reg3/$const, reg2
  4352. mov reg2 reg/ref
  4353. dealloc reg2
  4354. to
  4355. add/sub/or/... reg3/$const, reg/ref }
  4356. begin
  4357. TransferUsedRegs(TmpUsedRegs);
  4358. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4359. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4360. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4361. begin
  4362. { by example:
  4363. movswl %si,%eax movswl %si,%eax p
  4364. decl %eax addl %edx,%eax hp1
  4365. movw %ax,%si movw %ax,%si hp2
  4366. ->
  4367. movswl %si,%eax movswl %si,%eax p
  4368. decw %eax addw %edx,%eax hp1
  4369. movw %ax,%si movw %ax,%si hp2
  4370. }
  4371. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4372. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4373. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4374. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4375. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4376. {
  4377. ->
  4378. movswl %si,%eax movswl %si,%eax p
  4379. decw %si addw %dx,%si hp1
  4380. movw %ax,%si movw %ax,%si hp2
  4381. }
  4382. case taicpu(hp1).ops of
  4383. 1:
  4384. begin
  4385. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4386. if taicpu(hp1).oper[0]^.typ=top_reg then
  4387. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4388. end;
  4389. 2:
  4390. begin
  4391. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4392. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4393. (taicpu(hp1).opcode<>A_SHL) and
  4394. (taicpu(hp1).opcode<>A_SHR) and
  4395. (taicpu(hp1).opcode<>A_SAR) then
  4396. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4397. end;
  4398. else
  4399. internalerror(2008042701);
  4400. end;
  4401. {
  4402. ->
  4403. decw %si addw %dx,%si p
  4404. }
  4405. RemoveInstruction(hp2);
  4406. RemoveCurrentP(p, hp1);
  4407. Result:=True;
  4408. Exit;
  4409. end;
  4410. end;
  4411. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4412. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4413. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4414. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4415. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4416. )
  4417. {$ifdef i386}
  4418. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4419. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4420. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4421. {$endif i386}
  4422. then
  4423. { change movsX/movzX reg/ref, reg2
  4424. add/sub/or/... regX/$const, reg2
  4425. mov reg2, reg3
  4426. dealloc reg2
  4427. to
  4428. movsX/movzX reg/ref, reg3
  4429. add/sub/or/... reg3/$const, reg3
  4430. }
  4431. begin
  4432. TransferUsedRegs(TmpUsedRegs);
  4433. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4434. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4435. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4436. begin
  4437. { by example:
  4438. movswl %si,%eax movswl %si,%eax p
  4439. decl %eax addl %edx,%eax hp1
  4440. movw %ax,%si movw %ax,%si hp2
  4441. ->
  4442. movswl %si,%eax movswl %si,%eax p
  4443. decw %eax addw %edx,%eax hp1
  4444. movw %ax,%si movw %ax,%si hp2
  4445. }
  4446. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4447. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4448. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4449. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4450. { limit size of constants as well to avoid assembler errors, but
  4451. check opsize to avoid overflow when left shifting the 1 }
  4452. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4453. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4454. {$ifdef x86_64}
  4455. { Be careful of, for example:
  4456. movl %reg1,%reg2
  4457. addl %reg3,%reg2
  4458. movq %reg2,%reg4
  4459. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4460. }
  4461. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4462. begin
  4463. taicpu(hp2).changeopsize(S_L);
  4464. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4465. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4466. end;
  4467. {$endif x86_64}
  4468. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4469. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4470. if taicpu(p).oper[0]^.typ=top_reg then
  4471. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4472. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4473. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4474. {
  4475. ->
  4476. movswl %si,%eax movswl %si,%eax p
  4477. decw %si addw %dx,%si hp1
  4478. movw %ax,%si movw %ax,%si hp2
  4479. }
  4480. case taicpu(hp1).ops of
  4481. 1:
  4482. begin
  4483. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4484. if taicpu(hp1).oper[0]^.typ=top_reg then
  4485. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4486. end;
  4487. 2:
  4488. begin
  4489. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4490. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4491. (taicpu(hp1).opcode<>A_SHL) and
  4492. (taicpu(hp1).opcode<>A_SHR) and
  4493. (taicpu(hp1).opcode<>A_SAR) then
  4494. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4495. end;
  4496. else
  4497. internalerror(2018111801);
  4498. end;
  4499. {
  4500. ->
  4501. decw %si addw %dx,%si p
  4502. }
  4503. RemoveInstruction(hp2);
  4504. end;
  4505. end;
  4506. end;
  4507. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4508. GetNextInstruction(hp1, hp2) and
  4509. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4510. MatchOperand(Taicpu(p).oper[0]^,0) and
  4511. (Taicpu(p).oper[1]^.typ = top_reg) and
  4512. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4513. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4514. { mov reg1,0
  4515. bts reg1,operand1 --> mov reg1,operand2
  4516. or reg1,operand2 bts reg1,operand1}
  4517. begin
  4518. Taicpu(hp2).opcode:=A_MOV;
  4519. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4520. asml.remove(hp1);
  4521. insertllitem(hp2,hp2.next,hp1);
  4522. RemoveCurrentp(p, hp1);
  4523. Result:=true;
  4524. exit;
  4525. end;
  4526. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4527. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4528. GetNextInstruction(hp1, hp2) and
  4529. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4530. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4531. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4532. { change
  4533. mov reg1,reg2
  4534. sub reg3,reg2
  4535. cmp reg3,reg1
  4536. into
  4537. mov reg1,reg2
  4538. sub reg3,reg2
  4539. }
  4540. begin
  4541. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4542. RemoveInstruction(hp2);
  4543. Result:=true;
  4544. exit;
  4545. end;
  4546. {
  4547. mov ref,reg0
  4548. <op> reg0,reg1
  4549. dealloc reg0
  4550. to
  4551. <op> ref,reg1
  4552. }
  4553. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4554. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4555. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4556. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4557. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4558. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4559. begin
  4560. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4561. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4562. RemoveCurrentp(p, hp1);
  4563. Result:=true;
  4564. exit;
  4565. end;
  4566. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4567. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4568. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4569. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4570. begin
  4571. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4572. {$ifdef x86_64}
  4573. { Convert:
  4574. movq x(ref),%reg64
  4575. shrq y,%reg64
  4576. To:
  4577. movl x+4(ref),%reg32
  4578. shrl y-32,%reg32 (Remove if y = 32)
  4579. }
  4580. if (taicpu(p).opsize = S_Q) and
  4581. (taicpu(hp1).opcode = A_SHR) and
  4582. (taicpu(hp1).oper[0]^.val >= 32) then
  4583. begin
  4584. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4585. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4586. { Convert to 32-bit }
  4587. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4588. taicpu(p).opsize := S_L;
  4589. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4590. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4591. if (taicpu(hp1).oper[0]^.val = 32) then
  4592. begin
  4593. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4594. RemoveInstruction(hp1);
  4595. end
  4596. else
  4597. begin
  4598. { This will potentially open up more arithmetic operations since
  4599. the peephole optimizer now has a big hint that only the lower
  4600. 32 bits are currently in use (and opcodes are smaller in size) }
  4601. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4602. taicpu(hp1).opsize := S_L;
  4603. Dec(taicpu(hp1).oper[0]^.val, 32);
  4604. DebugMsg(SPeepholeOptimization + PreMessage +
  4605. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4606. end;
  4607. Result := True;
  4608. Exit;
  4609. end;
  4610. {$endif x86_64}
  4611. { Convert:
  4612. movl x(ref),%reg
  4613. shrl $24,%reg
  4614. To:
  4615. movzbl x+3(ref),%reg
  4616. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4617. Also accept sar instead of shr, but convert to movsx instead of movzx
  4618. }
  4619. if taicpu(hp1).opcode = A_SHR then
  4620. MovUnaligned := A_MOVZX
  4621. else
  4622. MovUnaligned := A_MOVSX;
  4623. NewSize := S_NO;
  4624. NewOffset := 0;
  4625. case taicpu(p).opsize of
  4626. S_B:
  4627. { No valid combinations };
  4628. S_W:
  4629. if (taicpu(hp1).oper[0]^.val = 8) then
  4630. begin
  4631. NewSize := S_BW;
  4632. NewOffset := 1;
  4633. end;
  4634. S_L:
  4635. case taicpu(hp1).oper[0]^.val of
  4636. 16:
  4637. begin
  4638. NewSize := S_WL;
  4639. NewOffset := 2;
  4640. end;
  4641. 24:
  4642. begin
  4643. NewSize := S_BL;
  4644. NewOffset := 3;
  4645. end;
  4646. else
  4647. ;
  4648. end;
  4649. {$ifdef x86_64}
  4650. S_Q:
  4651. case taicpu(hp1).oper[0]^.val of
  4652. 32:
  4653. begin
  4654. if taicpu(hp1).opcode = A_SAR then
  4655. begin
  4656. { 32-bit to 64-bit is a distinct instruction }
  4657. MovUnaligned := A_MOVSXD;
  4658. NewSize := S_LQ;
  4659. NewOffset := 4;
  4660. end
  4661. else
  4662. { Should have been handled by MovShr2Mov above }
  4663. InternalError(2022081811);
  4664. end;
  4665. 48:
  4666. begin
  4667. NewSize := S_WQ;
  4668. NewOffset := 6;
  4669. end;
  4670. 56:
  4671. begin
  4672. NewSize := S_BQ;
  4673. NewOffset := 7;
  4674. end;
  4675. else
  4676. ;
  4677. end;
  4678. {$endif x86_64}
  4679. else
  4680. InternalError(2022081810);
  4681. end;
  4682. if (NewSize <> S_NO) and
  4683. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4684. begin
  4685. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4686. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4687. debug_op2str(MovUnaligned);
  4688. {$ifdef x86_64}
  4689. if MovUnaligned <> A_MOVSXD then
  4690. { Don't add size suffix for MOVSXD }
  4691. {$endif x86_64}
  4692. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4693. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4694. taicpu(p).opcode := MovUnaligned;
  4695. taicpu(p).opsize := NewSize;
  4696. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4697. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4698. RemoveInstruction(hp1);
  4699. Result := True;
  4700. Exit;
  4701. end;
  4702. end;
  4703. { Backward optimisation shared with OptPass2MOV }
  4704. if FuncMov2Func(p, hp1) then
  4705. begin
  4706. Result := True;
  4707. Exit;
  4708. end;
  4709. end;
  4710. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4711. var
  4712. hp1 : tai;
  4713. begin
  4714. Result:=false;
  4715. if taicpu(p).ops <> 2 then
  4716. exit;
  4717. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4718. GetNextInstruction(p,hp1) then
  4719. begin
  4720. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4721. (taicpu(hp1).ops = 2) then
  4722. begin
  4723. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4724. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4725. { movXX reg1, mem1 or movXX mem1, reg1
  4726. movXX mem2, reg2 movXX reg2, mem2}
  4727. begin
  4728. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4729. { movXX reg1, mem1 or movXX mem1, reg1
  4730. movXX mem2, reg1 movXX reg2, mem1}
  4731. begin
  4732. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4733. begin
  4734. { Removes the second statement from
  4735. movXX reg1, mem1/reg2
  4736. movXX mem1/reg2, reg1
  4737. }
  4738. if taicpu(p).oper[0]^.typ=top_reg then
  4739. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4740. { Removes the second statement from
  4741. movXX mem1/reg1, reg2
  4742. movXX reg2, mem1/reg1
  4743. }
  4744. if (taicpu(p).oper[1]^.typ=top_reg) and
  4745. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4746. begin
  4747. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4748. RemoveInstruction(hp1);
  4749. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4750. Result:=true;
  4751. exit;
  4752. end
  4753. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4754. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4755. begin
  4756. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4757. RemoveInstruction(hp1);
  4758. Result:=true;
  4759. exit;
  4760. end;
  4761. end
  4762. end;
  4763. end;
  4764. end;
  4765. end;
  4766. end;
  4767. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4768. var
  4769. hp1 : tai;
  4770. begin
  4771. result:=false;
  4772. { replace
  4773. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4774. MovX %mreg2,%mreg1
  4775. dealloc %mreg2
  4776. by
  4777. <Op>X %mreg2,%mreg1
  4778. ?
  4779. }
  4780. if GetNextInstruction(p,hp1) and
  4781. { we mix single and double opperations here because we assume that the compiler
  4782. generates vmovapd only after double operations and vmovaps only after single operations }
  4783. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4784. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4785. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4786. (taicpu(p).oper[0]^.typ=top_reg) then
  4787. begin
  4788. TransferUsedRegs(TmpUsedRegs);
  4789. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4790. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4791. begin
  4792. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4793. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4794. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4795. RemoveInstruction(hp1);
  4796. result:=true;
  4797. end;
  4798. end;
  4799. end;
  4800. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4801. var
  4802. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4803. JumpLabel, JumpLabel_dist: TAsmLabel;
  4804. FirstValue, SecondValue: TCGInt;
  4805. TempBool: Boolean;
  4806. begin
  4807. Result := False;
  4808. if (taicpu(p).oper[0]^.typ = top_const) and
  4809. (taicpu(p).oper[0]^.val <> -1) then
  4810. begin
  4811. { Convert unsigned maximum constants to -1 to aid optimisation }
  4812. case taicpu(p).opsize of
  4813. S_B:
  4814. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4815. begin
  4816. taicpu(p).oper[0]^.val := -1;
  4817. Result := True;
  4818. Exit;
  4819. end;
  4820. S_W:
  4821. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4822. begin
  4823. taicpu(p).oper[0]^.val := -1;
  4824. Result := True;
  4825. Exit;
  4826. end;
  4827. S_L:
  4828. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4829. begin
  4830. taicpu(p).oper[0]^.val := -1;
  4831. Result := True;
  4832. Exit;
  4833. end;
  4834. {$ifdef x86_64}
  4835. S_Q:
  4836. { Storing anything greater than $7FFFFFFF is not possible so do
  4837. nothing };
  4838. {$endif x86_64}
  4839. else
  4840. InternalError(2021121001);
  4841. end;
  4842. end;
  4843. if GetNextInstruction(p, hp1) and
  4844. TrySwapMovCmp(p, hp1) then
  4845. begin
  4846. Result := True;
  4847. Exit;
  4848. end;
  4849. if MatchInstruction(hp1, A_Jcc, []) then
  4850. begin
  4851. TempBool := True;
  4852. if DoJumpOptimizations(hp1, TempBool) or
  4853. not TempBool then
  4854. begin
  4855. Result := True;
  4856. if Assigned(hp1) then
  4857. begin
  4858. if (hp1.typ in [ait_align]) then
  4859. SkipAligns(hp1, hp1);
  4860. { CollapseZeroDistJump will be set to the label after the
  4861. jump if it optimises, whether or not it's live or dead }
  4862. if (hp1.typ in [ait_label]) and
  4863. not (tai_label(hp1).labsym.is_used) then
  4864. GetNextInstruction(hp1, hp1);
  4865. end;
  4866. TransferUsedRegs(TmpUsedRegs);
  4867. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4868. if not Assigned(hp1) or
  4869. (
  4870. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4871. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4872. ) then
  4873. begin
  4874. { No more conditional jumps; conditional statement is no longer required }
  4875. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4876. RemoveCurrentP(p);
  4877. end;
  4878. Exit;
  4879. end;
  4880. end;
  4881. { Search for:
  4882. test $x,(reg/ref)
  4883. jne @lbl1
  4884. test $y,(reg/ref) (same register or reference)
  4885. jne @lbl1
  4886. Change to:
  4887. test $(x or y),(reg/ref)
  4888. jne @lbl1
  4889. (Note, this doesn't work with je instead of jne)
  4890. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4891. Also search for:
  4892. test $x,(reg/ref)
  4893. je @lbl1
  4894. ...
  4895. test $y,(reg/ref)
  4896. je/jne @lbl2
  4897. If (x or y) = x, then the second jump is deterministic
  4898. }
  4899. if (
  4900. (
  4901. (taicpu(p).oper[0]^.typ = top_const) or
  4902. (
  4903. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4904. (taicpu(p).oper[0]^.typ = top_reg) and
  4905. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4906. )
  4907. ) and
  4908. MatchInstruction(hp1, A_JCC, [])
  4909. ) then
  4910. begin
  4911. if (taicpu(p).oper[0]^.typ = top_reg) and
  4912. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4913. FirstValue := -1
  4914. else
  4915. FirstValue := taicpu(p).oper[0]^.val;
  4916. { If we have several test/jne's in a row, it might be the case that
  4917. the second label doesn't go to the same location, but the one
  4918. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4919. so accommodate for this with a while loop.
  4920. }
  4921. hp1_last := hp1;
  4922. while (
  4923. (
  4924. (taicpu(p).oper[1]^.typ = top_reg) and
  4925. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4926. ) or GetNextInstruction(hp1_last, p_dist)
  4927. ) and (p_dist.typ = ait_instruction) do
  4928. begin
  4929. if (
  4930. (
  4931. (taicpu(p_dist).opcode = A_TEST) and
  4932. (
  4933. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4934. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4935. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4936. )
  4937. ) or
  4938. (
  4939. { cmp 0,%reg = test %reg,%reg }
  4940. (taicpu(p_dist).opcode = A_CMP) and
  4941. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4942. )
  4943. ) and
  4944. { Make sure the destination operands are actually the same }
  4945. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4946. GetNextInstruction(p_dist, hp1_dist) and
  4947. MatchInstruction(hp1_dist, A_JCC, []) then
  4948. begin
  4949. if
  4950. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4951. (
  4952. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4953. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4954. ) then
  4955. SecondValue := -1
  4956. else
  4957. SecondValue := taicpu(p_dist).oper[0]^.val;
  4958. { If both of the TEST constants are identical, delete the
  4959. second TEST that is unnecessary (be careful though, just
  4960. in case the flags are modified in between) }
  4961. if (FirstValue = SecondValue) then
  4962. begin
  4963. { We have to check the entire range }
  4964. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4965. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4966. begin
  4967. { Since the second jump's condition is a subset of the first, we
  4968. know it will never branch because the first jump dominates it.
  4969. Get it out of the way now rather than wait for the jump
  4970. optimisations for a speed boost. }
  4971. if IsJumpToLabel(taicpu(hp1_dist)) then
  4972. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4973. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4974. RemoveInstruction(hp1_dist);
  4975. Result := True;
  4976. end
  4977. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4978. begin
  4979. { If the inverse of the first condition is a subset of the second,
  4980. the second one will definitely branch if the first one doesn't }
  4981. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4982. { We can remove the TEST instruction too }
  4983. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4984. RemoveInstruction(p_dist);
  4985. MakeUnconditional(taicpu(hp1_dist));
  4986. RemoveDeadCodeAfterJump(hp1_dist);
  4987. { Since the jump is now unconditional, we can't
  4988. continue any further with this particular
  4989. optimisation. The original TEST is still intact
  4990. though, so there might be something else we can
  4991. do }
  4992. Include(OptsToCheck, aoc_ForceNewIteration);
  4993. Break;
  4994. end;
  4995. if Result or
  4996. { If a jump wasn't removed or made unconditional, only
  4997. remove the identical TEST instruction if the flags
  4998. weren't modified }
  4999. TempBool then
  5000. begin
  5001. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5002. RemoveInstruction(p_dist);
  5003. { If the jump was removed or made unconditional, we
  5004. don't need to allocate NR_DEFAULTFLAGS over the
  5005. entire range }
  5006. if not Result then
  5007. begin
  5008. { Mark the flags as 'in use' over the entire range }
  5009. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5010. { Speed gain - continue search from the Jcc instruction }
  5011. hp1_last := hp1_dist;
  5012. { Only the TEST instruction was removed, and the
  5013. original was unchanged, so we can safely do
  5014. another iteration of the while loop }
  5015. Include(OptsToCheck, aoc_ForceNewIteration);
  5016. Continue;
  5017. end;
  5018. Exit;
  5019. end;
  5020. end;
  5021. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5022. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5023. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5024. then the second jump will never branch, so it can also be
  5025. removed regardless of where it goes }
  5026. (
  5027. (FirstValue = -1) or
  5028. (SecondValue = -1) or
  5029. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5030. ) and
  5031. (
  5032. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5033. { Always adjacent under -O2 and under }
  5034. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5035. (
  5036. GetNextInstruction(hp1, hp1_last) and
  5037. (hp1_last = p_dist)
  5038. )
  5039. ) then
  5040. begin
  5041. { Same jump location... can be a register since nothing's changed }
  5042. { If any of the entries are equivalent to test %reg,%reg, then the
  5043. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5044. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5045. if IsJumpToLabel(taicpu(hp1_dist)) then
  5046. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5047. { Only remove the second test if no jumps or other conditional instructions follow }
  5048. TransferUsedRegs(TmpUsedRegs);
  5049. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5050. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5051. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5052. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5053. begin
  5054. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5055. RemoveInstruction(p_dist);
  5056. { Remove the first jump, not the second, to keep
  5057. any register deallocations between the second
  5058. TEST/JNE pair in the same place. Aids future
  5059. optimisation. }
  5060. RemoveInstruction(hp1);
  5061. end
  5062. else
  5063. begin
  5064. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5065. { Remove second jump in this instance }
  5066. RemoveInstruction(hp1_dist);
  5067. end;
  5068. Result := True;
  5069. Exit;
  5070. end;
  5071. end;
  5072. if { If -O2 and under, it may stop on any old instruction }
  5073. (cs_opt_level3 in current_settings.optimizerswitches) and
  5074. (taicpu(p).oper[1]^.typ = top_reg) and
  5075. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5076. begin
  5077. hp1_last := p_dist;
  5078. Continue;
  5079. end;
  5080. Break;
  5081. end;
  5082. end;
  5083. { Search for:
  5084. test %reg,%reg
  5085. j(c1) @lbl1
  5086. ...
  5087. @lbl:
  5088. test %reg,%reg (same register)
  5089. j(c2) @lbl2
  5090. If c2 is a subset of c1, change to:
  5091. test %reg,%reg
  5092. j(c1) @lbl2
  5093. (@lbl1 may become a dead label as a result)
  5094. }
  5095. if (taicpu(p).oper[1]^.typ = top_reg) and
  5096. (taicpu(p).oper[0]^.typ = top_reg) and
  5097. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5098. MatchInstruction(hp1, A_JCC, []) and
  5099. IsJumpToLabel(taicpu(hp1)) then
  5100. begin
  5101. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5102. p_label := nil;
  5103. if Assigned(JumpLabel) then
  5104. p_label := getlabelwithsym(JumpLabel);
  5105. if Assigned(p_label) and
  5106. GetNextInstruction(p_label, p_dist) and
  5107. MatchInstruction(p_dist, A_TEST, []) and
  5108. { It's fine if the second test uses smaller sub-registers }
  5109. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5110. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5111. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5112. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5113. GetNextInstruction(p_dist, hp1_dist) and
  5114. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5115. begin
  5116. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5117. if JumpLabel = JumpLabel_dist then
  5118. { This is an infinite loop }
  5119. Exit;
  5120. { Best optimisation when the first condition is a subset (or equal) of the second }
  5121. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5122. begin
  5123. { Any registers used here will already be allocated }
  5124. if Assigned(JumpLabel) then
  5125. JumpLabel.DecRefs;
  5126. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5127. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5128. Result := True;
  5129. Exit;
  5130. end;
  5131. end;
  5132. end;
  5133. end;
  5134. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5135. var
  5136. hp1, hp2: tai;
  5137. ActiveReg: TRegister;
  5138. OldOffset: asizeint;
  5139. ThisConst: TCGInt;
  5140. function RegDeallocated: Boolean;
  5141. begin
  5142. TransferUsedRegs(TmpUsedRegs);
  5143. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5144. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5145. end;
  5146. begin
  5147. result:=false;
  5148. hp1 := nil;
  5149. { replace
  5150. addX const,%reg1
  5151. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5152. dealloc %reg1
  5153. by
  5154. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5155. }
  5156. if MatchOpType(taicpu(p),top_const,top_reg) then
  5157. begin
  5158. ActiveReg := taicpu(p).oper[1]^.reg;
  5159. { Ensures the entire register was updated }
  5160. if (taicpu(p).opsize >= S_L) and
  5161. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5162. MatchInstruction(hp1,A_LEA,[]) and
  5163. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5164. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5165. (
  5166. { Cover the case where the register in the reference is also the destination register }
  5167. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5168. (
  5169. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5170. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5171. RegDeallocated
  5172. )
  5173. ) then
  5174. begin
  5175. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5176. {$push}
  5177. {$R-}{$Q-}
  5178. { Explicitly disable overflow checking for these offset calculation
  5179. as those do not matter for the final result }
  5180. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5181. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5182. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5183. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5184. {$pop}
  5185. {$ifdef x86_64}
  5186. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5187. begin
  5188. { Overflow; abort }
  5189. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5190. end
  5191. else
  5192. {$endif x86_64}
  5193. begin
  5194. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5195. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5196. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5197. RemoveCurrentP(p, hp1)
  5198. else
  5199. RemoveCurrentP(p);
  5200. result:=true;
  5201. Exit;
  5202. end;
  5203. end;
  5204. if (
  5205. { Save calling GetNextInstructionUsingReg again }
  5206. Assigned(hp1) or
  5207. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5208. ) and
  5209. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5210. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5211. begin
  5212. if taicpu(hp1).oper[0]^.typ = top_const then
  5213. begin
  5214. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5215. if taicpu(hp1).opcode = A_ADD then
  5216. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5217. else
  5218. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5219. Result := True;
  5220. { Handle any overflows }
  5221. case taicpu(p).opsize of
  5222. S_B:
  5223. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5224. S_W:
  5225. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5226. S_L:
  5227. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5228. {$ifdef x86_64}
  5229. S_Q:
  5230. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5231. { Overflow; abort }
  5232. Result := False
  5233. else
  5234. taicpu(p).oper[0]^.val := ThisConst;
  5235. {$endif x86_64}
  5236. else
  5237. InternalError(2021102610);
  5238. end;
  5239. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5240. if Result then
  5241. begin
  5242. if (taicpu(p).oper[0]^.val < 0) and
  5243. (
  5244. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5245. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5246. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5247. ) then
  5248. begin
  5249. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5250. taicpu(p).opcode := A_SUB;
  5251. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5252. end
  5253. else
  5254. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5255. RemoveInstruction(hp1);
  5256. end;
  5257. end
  5258. else
  5259. begin
  5260. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5261. TransferUsedRegs(TmpUsedRegs);
  5262. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5263. hp2 := p;
  5264. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5265. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5266. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5267. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5268. begin
  5269. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5270. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5271. Asml.Remove(p);
  5272. Asml.InsertAfter(p, hp1);
  5273. p := hp1;
  5274. Result := True;
  5275. Exit;
  5276. end;
  5277. end;
  5278. end;
  5279. if DoArithCombineOpt(p) then
  5280. Result:=true;
  5281. end;
  5282. end;
  5283. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5284. var
  5285. hp1, hp2: tai;
  5286. ref: Integer;
  5287. saveref: treference;
  5288. offsetcalc: Int64;
  5289. TempReg: TRegister;
  5290. Multiple: TCGInt;
  5291. Adjacent, IntermediateRegDiscarded: Boolean;
  5292. begin
  5293. Result:=false;
  5294. { play save and throw an error if LEA uses a seg register prefix,
  5295. this is most likely an error somewhere else }
  5296. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5297. internalerror(2022022001);
  5298. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5299. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5300. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5301. (
  5302. { do not mess with leas accessing the stack pointer
  5303. unless it's a null operation }
  5304. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5305. (
  5306. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5307. (taicpu(p).oper[0]^.ref^.offset = 0)
  5308. )
  5309. ) and
  5310. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5311. begin
  5312. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5313. begin
  5314. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5315. begin
  5316. taicpu(p).opcode := A_MOV;
  5317. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5318. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5319. end
  5320. else
  5321. begin
  5322. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5323. RemoveCurrentP(p);
  5324. end;
  5325. Result:=true;
  5326. exit;
  5327. end
  5328. else if (
  5329. { continue to use lea to adjust the stack pointer,
  5330. it is the recommended way, but only if not optimizing for size }
  5331. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5332. (cs_opt_size in current_settings.optimizerswitches)
  5333. ) and
  5334. { If the flags register is in use, don't change the instruction
  5335. to an ADD otherwise this will scramble the flags. [Kit] }
  5336. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5337. ConvertLEA(taicpu(p)) then
  5338. begin
  5339. Result:=true;
  5340. exit;
  5341. end;
  5342. end;
  5343. { Don't optimise if the stack or frame pointer is the destination register }
  5344. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5345. Exit;
  5346. if GetNextInstruction(p,hp1) and
  5347. (hp1.typ=ait_instruction) then
  5348. begin
  5349. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5350. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5351. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5352. begin
  5353. TransferUsedRegs(TmpUsedRegs);
  5354. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5355. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5356. begin
  5357. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5358. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5359. RemoveInstruction(hp1);
  5360. result:=true;
  5361. exit;
  5362. end;
  5363. end;
  5364. { changes
  5365. lea <ref1>, reg1
  5366. <op> ...,<ref. with reg1>,...
  5367. to
  5368. <op> ...,<ref1>,... }
  5369. { find a reference which uses reg1 }
  5370. 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
  5371. ref:=0
  5372. 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
  5373. ref:=1
  5374. else
  5375. ref:=-1;
  5376. if (ref<>-1) and
  5377. { reg1 must be either the base or the index }
  5378. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5379. begin
  5380. { reg1 can be removed from the reference }
  5381. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5382. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5383. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5384. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5385. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5386. else
  5387. Internalerror(2019111201);
  5388. { check if the can insert all data of the lea into the second instruction }
  5389. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5390. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5391. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5392. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5393. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5394. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5395. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5396. {$ifdef x86_64}
  5397. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5398. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5399. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5400. )
  5401. {$endif x86_64}
  5402. then
  5403. begin
  5404. { reg1 might not used by the second instruction after it is remove from the reference }
  5405. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5406. begin
  5407. TransferUsedRegs(TmpUsedRegs);
  5408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5409. { reg1 is not updated so it might not be used afterwards }
  5410. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5411. begin
  5412. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5413. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5414. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5415. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5416. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5417. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5418. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5419. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5420. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5421. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5422. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5423. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5424. RemoveCurrentP(p, hp1);
  5425. result:=true;
  5426. exit;
  5427. end
  5428. end;
  5429. end;
  5430. { recover }
  5431. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5432. end;
  5433. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5434. if Adjacent or
  5435. { Check further ahead (up to 2 instructions ahead for -O2) }
  5436. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5437. begin
  5438. { Check common LEA/LEA conditions }
  5439. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5440. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5441. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5442. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5443. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5444. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5445. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5446. (
  5447. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5448. calling it (since it calls GetNextInstruction) }
  5449. Adjacent or
  5450. (
  5451. (
  5452. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5453. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5454. ) and (
  5455. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5456. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5457. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5458. )
  5459. )
  5460. ) then
  5461. begin
  5462. TransferUsedRegs(TmpUsedRegs);
  5463. hp2 := p;
  5464. repeat
  5465. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5466. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5467. IntermediateRegDiscarded :=
  5468. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5469. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5470. { changes
  5471. lea offset1(regX,scale), reg1
  5472. lea offset2(reg1,reg1), reg2
  5473. to
  5474. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5475. and
  5476. lea offset1(regX,scale1), reg1
  5477. lea offset2(reg1,scale2), reg2
  5478. to
  5479. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5480. and
  5481. lea offset1(regX,scale1), reg1
  5482. lea offset2(reg3,reg1,scale2), reg2
  5483. to
  5484. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5485. ... so long as the final scale does not exceed 8
  5486. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5487. }
  5488. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5489. (
  5490. { Don't optimise if size is a concern and the intermediate register remains in use }
  5491. IntermediateRegDiscarded or
  5492. not (cs_opt_size in current_settings.optimizerswitches)
  5493. ) and
  5494. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5495. (
  5496. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5497. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5498. ) and (
  5499. (
  5500. { lea (reg1,scale2), reg2 variant }
  5501. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5502. (
  5503. Adjacent or
  5504. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5505. ) and
  5506. (
  5507. (
  5508. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5509. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5510. ) or (
  5511. { lea (regX,regX), reg1 variant }
  5512. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5513. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5514. )
  5515. )
  5516. ) or (
  5517. { lea (reg1,reg1), reg1 variant }
  5518. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5519. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5520. )
  5521. ) then
  5522. begin
  5523. { Make everything homogeneous to make calculations easier }
  5524. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5525. begin
  5526. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5527. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5528. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5529. else
  5530. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5531. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5532. end;
  5533. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5534. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5535. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5536. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5537. begin
  5538. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5539. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5540. begin
  5541. { Put the register to change in the index register }
  5542. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5543. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5544. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5545. end;
  5546. { Change lea (reg,reg) to lea(,reg,2) }
  5547. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5548. begin
  5549. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5550. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5551. end;
  5552. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5553. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5554. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5555. { Just to prevent miscalculations }
  5556. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5557. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5558. else
  5559. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5560. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5561. if IntermediateRegDiscarded then
  5562. begin
  5563. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5564. RemoveCurrentP(p);
  5565. end
  5566. else
  5567. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5568. result:=true;
  5569. exit;
  5570. end;
  5571. end;
  5572. { changes
  5573. lea offset1(regX), reg1
  5574. lea offset2(reg1), reg2
  5575. to
  5576. lea offset1+offset2(regX), reg2 }
  5577. if (
  5578. { Don't optimise if size is a concern and the intermediate register remains in use }
  5579. IntermediateRegDiscarded or
  5580. not (cs_opt_size in current_settings.optimizerswitches)
  5581. ) and
  5582. (
  5583. (
  5584. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5585. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5586. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5587. ) or (
  5588. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5589. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5590. (
  5591. (
  5592. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5593. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5594. ) or (
  5595. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5596. (
  5597. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5598. (
  5599. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5600. (
  5601. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5602. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5603. )
  5604. )
  5605. )
  5606. )
  5607. )
  5608. )
  5609. ) then
  5610. begin
  5611. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5612. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5613. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5614. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5615. begin
  5616. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5617. begin
  5618. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5619. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5620. { if the register is used as index and base, we have to increase for base as well
  5621. and adapt base }
  5622. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5623. begin
  5624. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5625. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5626. end;
  5627. end
  5628. else
  5629. begin
  5630. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5631. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5632. end;
  5633. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5634. begin
  5635. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5636. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5637. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5638. end;
  5639. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5640. if IntermediateRegDiscarded then
  5641. begin
  5642. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5643. RemoveCurrentP(p);
  5644. end
  5645. else
  5646. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5647. result:=true;
  5648. exit;
  5649. end;
  5650. end;
  5651. end;
  5652. { Change:
  5653. leal/q $x(%reg1),%reg2
  5654. ...
  5655. shll/q $y,%reg2
  5656. To:
  5657. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5658. }
  5659. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5660. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5661. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5662. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5663. (taicpu(hp1).oper[0]^.val <= 3) then
  5664. begin
  5665. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5666. TransferUsedRegs(TmpUsedRegs);
  5667. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5668. if
  5669. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5670. (this works even if scalefactor is zero) }
  5671. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5672. { Ensure offset doesn't go out of bounds }
  5673. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5674. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5675. (
  5676. (
  5677. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5678. (
  5679. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5680. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5681. (
  5682. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5683. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5684. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5685. )
  5686. )
  5687. ) or (
  5688. (
  5689. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5690. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5691. ) and
  5692. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5693. )
  5694. ) then
  5695. begin
  5696. repeat
  5697. with taicpu(p).oper[0]^.ref^ do
  5698. begin
  5699. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5700. if index = base then
  5701. begin
  5702. if Multiple > 4 then
  5703. { Optimisation will no longer work because resultant
  5704. scale factor will exceed 8 }
  5705. Break;
  5706. base := NR_NO;
  5707. scalefactor := 2;
  5708. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5709. end
  5710. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5711. begin
  5712. { Scale factor only works on the index register }
  5713. index := base;
  5714. base := NR_NO;
  5715. end;
  5716. { For safety }
  5717. if scalefactor <= 1 then
  5718. begin
  5719. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5720. scalefactor := Multiple;
  5721. end
  5722. else
  5723. begin
  5724. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5725. scalefactor := scalefactor * Multiple;
  5726. end;
  5727. offset := offset * Multiple;
  5728. end;
  5729. RemoveInstruction(hp1);
  5730. Result := True;
  5731. Exit;
  5732. { This repeat..until loop exists for the benefit of Break }
  5733. until True;
  5734. end;
  5735. end;
  5736. end;
  5737. end;
  5738. end;
  5739. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5740. var
  5741. hp1 : tai;
  5742. SubInstr: Boolean;
  5743. ThisConst: TCGInt;
  5744. const
  5745. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5746. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5747. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5748. begin
  5749. Result := False;
  5750. if taicpu(p).oper[0]^.typ <> top_const then
  5751. { Should have been confirmed before calling }
  5752. InternalError(2021102601);
  5753. SubInstr := (taicpu(p).opcode = A_SUB);
  5754. if GetLastInstruction(p, hp1) and
  5755. (hp1.typ = ait_instruction) and
  5756. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5757. begin
  5758. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5759. { Bad size }
  5760. InternalError(2022042001);
  5761. case taicpu(hp1).opcode Of
  5762. A_INC:
  5763. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5764. begin
  5765. if SubInstr then
  5766. ThisConst := taicpu(p).oper[0]^.val - 1
  5767. else
  5768. ThisConst := taicpu(p).oper[0]^.val + 1;
  5769. end
  5770. else
  5771. Exit;
  5772. A_DEC:
  5773. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5774. begin
  5775. if SubInstr then
  5776. ThisConst := taicpu(p).oper[0]^.val + 1
  5777. else
  5778. ThisConst := taicpu(p).oper[0]^.val - 1;
  5779. end
  5780. else
  5781. Exit;
  5782. A_SUB:
  5783. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5784. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5785. begin
  5786. if SubInstr then
  5787. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5788. else
  5789. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5790. end
  5791. else
  5792. Exit;
  5793. A_ADD:
  5794. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5795. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5796. begin
  5797. if SubInstr then
  5798. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5799. else
  5800. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5801. end
  5802. else
  5803. Exit;
  5804. else
  5805. Exit;
  5806. end;
  5807. { Check that the values are in range }
  5808. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5809. { Overflow; abort }
  5810. Exit;
  5811. if (ThisConst = 0) then
  5812. begin
  5813. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5814. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5815. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5816. RemoveInstruction(hp1);
  5817. hp1 := tai(p.next);
  5818. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5819. if not GetLastInstruction(hp1, p) then
  5820. p := hp1;
  5821. end
  5822. else
  5823. begin
  5824. if taicpu(hp1).opercnt=1 then
  5825. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5826. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5827. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5828. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5829. else
  5830. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5831. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5832. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5833. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5834. RemoveInstruction(hp1);
  5835. taicpu(p).loadconst(0, ThisConst);
  5836. end;
  5837. Result := True;
  5838. end;
  5839. end;
  5840. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5841. begin
  5842. Result := False;
  5843. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5844. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5845. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5846. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5847. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5848. (
  5849. (
  5850. (taicpu(hp1).opcode = A_TEST)
  5851. ) or (
  5852. (taicpu(hp1).opcode = A_CMP) and
  5853. { A sanity check more than anything }
  5854. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5855. )
  5856. ) then
  5857. begin
  5858. { change
  5859. mov mem, %reg
  5860. ...
  5861. cmp/test x, %reg / test %reg,%reg
  5862. (reg deallocated)
  5863. to
  5864. cmp/test x, mem / cmp 0, mem
  5865. }
  5866. TransferUsedRegs(TmpUsedRegs);
  5867. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5868. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5869. begin
  5870. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5871. if (taicpu(hp1).opcode = A_TEST) and
  5872. (
  5873. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5874. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5875. ) then
  5876. begin
  5877. taicpu(hp1).opcode := A_CMP;
  5878. taicpu(hp1).loadconst(0, 0);
  5879. end;
  5880. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5881. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5882. RemoveCurrentP(p);
  5883. if (p <> hp1) then
  5884. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5885. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5886. { Make sure the flags are allocated across the CMP instruction }
  5887. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5888. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5889. Result := True;
  5890. Exit;
  5891. end;
  5892. end;
  5893. end;
  5894. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5895. var
  5896. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5897. ThisReg, SecondReg: TRegister;
  5898. JumpLoc: TAsmLabel;
  5899. NewSize: TOpSize;
  5900. begin
  5901. Result := False;
  5902. {
  5903. Convert:
  5904. j<c> .L1
  5905. .L2:
  5906. mov 1,reg
  5907. jmp .L3 (or ret, although it might not be a RET yet)
  5908. .L1:
  5909. mov 0,reg
  5910. jmp .L3 (or ret)
  5911. ( As long as .L3 <> .L1 or .L2)
  5912. To:
  5913. mov 0,reg
  5914. set<not(c)> reg
  5915. jmp .L3 (or ret)
  5916. .L2:
  5917. mov 1,reg
  5918. jmp .L3 (or ret)
  5919. .L1:
  5920. mov 0,reg
  5921. jmp .L3 (or ret)
  5922. }
  5923. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5924. Exit;
  5925. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5926. if GetNextInstruction(hp_label, hp2) and
  5927. MatchInstruction(hp2,A_MOV,[]) and
  5928. (taicpu(hp2).oper[0]^.typ = top_const) and
  5929. (
  5930. (
  5931. (taicpu(hp2).oper[1]^.typ = top_reg)
  5932. {$ifdef i386}
  5933. { Under i386, ESI, EDI, EBP and ESP
  5934. don't have an 8-bit representation }
  5935. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5936. {$endif i386}
  5937. ) or (
  5938. {$ifdef i386}
  5939. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5940. {$endif i386}
  5941. (taicpu(hp2).opsize = S_B)
  5942. )
  5943. ) and
  5944. GetNextInstruction(hp2, hp3) and
  5945. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5946. (
  5947. (taicpu(hp3).opcode=A_RET) or
  5948. (
  5949. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5950. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5951. )
  5952. ) and
  5953. GetNextInstruction(hp3, hp4) and
  5954. SkipAligns(hp4, hp4) and
  5955. (hp4.typ=ait_label) and
  5956. (tai_label(hp4).labsym=JumpLoc) and
  5957. (
  5958. not (cs_opt_size in current_settings.optimizerswitches) or
  5959. { If the initial jump is the label's only reference, then it will
  5960. become a dead label if the other conditions are met and hence
  5961. remove at least 2 instructions, including a jump }
  5962. (JumpLoc.getrefs = 1)
  5963. ) and
  5964. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5965. that will be optimised out }
  5966. GetNextInstruction(hp4, hp5) and
  5967. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5968. (taicpu(hp5).oper[0]^.typ = top_const) and
  5969. (
  5970. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5971. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5972. ) and
  5973. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5974. GetNextInstruction(hp5,hp6) and
  5975. (
  5976. (hp6.typ<>ait_label) or
  5977. SkipLabels(hp6, hp6)
  5978. ) and
  5979. (hp6.typ=ait_instruction) then
  5980. begin
  5981. { First, let's look at the two jumps that are hp3 and hp6 }
  5982. if not
  5983. (
  5984. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5985. (
  5986. (taicpu(hp6).opcode=A_RET) or
  5987. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5988. )
  5989. ) then
  5990. { If condition is False, then the JMP/RET instructions matched conventionally }
  5991. begin
  5992. { See if one of the jumps can be instantly converted into a RET }
  5993. if (taicpu(hp3).opcode=A_JMP) then
  5994. begin
  5995. { Reuse hp5 }
  5996. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5997. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5998. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5999. Exit;
  6000. if MatchInstruction(hp5, A_RET, []) then
  6001. begin
  6002. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6003. ConvertJumpToRET(hp3, hp5);
  6004. Result := True;
  6005. end
  6006. else
  6007. Exit;
  6008. end;
  6009. if (taicpu(hp6).opcode=A_JMP) then
  6010. begin
  6011. { Reuse hp5 }
  6012. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6013. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6014. Exit;
  6015. if MatchInstruction(hp5, A_RET, []) then
  6016. begin
  6017. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6018. ConvertJumpToRET(hp6, hp5);
  6019. Result := True;
  6020. end
  6021. else
  6022. Exit;
  6023. end;
  6024. if not
  6025. (
  6026. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6027. (
  6028. (taicpu(hp6).opcode=A_RET) or
  6029. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6030. )
  6031. ) then
  6032. { Still doesn't match }
  6033. Exit;
  6034. end;
  6035. if (taicpu(hp2).oper[0]^.val = 1) then
  6036. begin
  6037. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6038. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6039. end
  6040. else
  6041. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6042. if taicpu(hp2).opsize=S_B then
  6043. begin
  6044. if taicpu(hp2).oper[1]^.typ = top_reg then
  6045. begin
  6046. SecondReg := taicpu(hp2).oper[1]^.reg;
  6047. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6048. end
  6049. else
  6050. begin
  6051. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6052. SecondReg := NR_NO;
  6053. end;
  6054. hp_pos := p;
  6055. hp_allocstart := hp4;
  6056. end
  6057. else
  6058. begin
  6059. { Will be a register because the size can't be S_B otherwise }
  6060. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6061. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6062. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6063. if (cs_opt_size in current_settings.optimizerswitches) then
  6064. begin
  6065. { Favour using MOVZX when optimising for size }
  6066. case taicpu(hp2).opsize of
  6067. S_W:
  6068. NewSize := S_BW;
  6069. S_L:
  6070. NewSize := S_BL;
  6071. {$ifdef x86_64}
  6072. S_Q:
  6073. begin
  6074. NewSize := S_BL;
  6075. { Will implicitly zero-extend to 64-bit }
  6076. setsubreg(SecondReg, R_SUBD);
  6077. end;
  6078. {$endif x86_64}
  6079. else
  6080. InternalError(2022101301);
  6081. end;
  6082. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6083. { Inserting it right before p will guarantee that the flags are also tracked }
  6084. Asml.InsertBefore(hp5, p);
  6085. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6086. hp_pos := hp5;
  6087. hp_allocstart := hp4;
  6088. end
  6089. else
  6090. begin
  6091. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6092. { Inserting it right before p will guarantee that the flags are also tracked }
  6093. Asml.InsertBefore(hp5, p);
  6094. hp_pos := p;
  6095. hp_allocstart := hp5;
  6096. end;
  6097. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6098. end;
  6099. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6100. taicpu(hp4).condition := taicpu(p).condition;
  6101. asml.InsertBefore(hp4, hp_pos);
  6102. if taicpu(hp3).is_jmp then
  6103. begin
  6104. JumpLoc.decrefs;
  6105. MakeUnconditional(taicpu(p));
  6106. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6107. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6108. end
  6109. else
  6110. ConvertJumpToRET(p, hp3);
  6111. if SecondReg <> NR_NO then
  6112. { Ensure the destination register is allocated over this region }
  6113. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6114. if (JumpLoc.getrefs = 0) then
  6115. RemoveDeadCodeAfterJump(hp3);
  6116. Result:=true;
  6117. exit;
  6118. end;
  6119. end;
  6120. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6121. var
  6122. hp1, hp2: tai;
  6123. ActiveReg: TRegister;
  6124. OldOffset: asizeint;
  6125. ThisConst: TCGInt;
  6126. function RegDeallocated: Boolean;
  6127. begin
  6128. TransferUsedRegs(TmpUsedRegs);
  6129. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6130. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6131. end;
  6132. begin
  6133. Result:=false;
  6134. hp1 := nil;
  6135. { replace
  6136. subX const,%reg1
  6137. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6138. dealloc %reg1
  6139. by
  6140. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6141. }
  6142. if MatchOpType(taicpu(p),top_const,top_reg) then
  6143. begin
  6144. ActiveReg := taicpu(p).oper[1]^.reg;
  6145. { Ensures the entire register was updated }
  6146. if (taicpu(p).opsize >= S_L) and
  6147. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6148. MatchInstruction(hp1,A_LEA,[]) and
  6149. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6150. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6151. (
  6152. { Cover the case where the register in the reference is also the destination register }
  6153. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6154. (
  6155. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6156. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6157. RegDeallocated
  6158. )
  6159. ) then
  6160. begin
  6161. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6162. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6163. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6164. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6165. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6166. {$ifdef x86_64}
  6167. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6168. begin
  6169. { Overflow; abort }
  6170. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6171. end
  6172. else
  6173. {$endif x86_64}
  6174. begin
  6175. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6176. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6177. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6178. RemoveCurrentP(p, hp1)
  6179. else
  6180. RemoveCurrentP(p);
  6181. result:=true;
  6182. Exit;
  6183. end;
  6184. end;
  6185. if (
  6186. { Save calling GetNextInstructionUsingReg again }
  6187. Assigned(hp1) or
  6188. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6189. ) and
  6190. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6191. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6192. begin
  6193. if taicpu(hp1).oper[0]^.typ = top_const then
  6194. begin
  6195. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6196. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6197. Result := True;
  6198. { Handle any overflows }
  6199. case taicpu(p).opsize of
  6200. S_B:
  6201. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6202. S_W:
  6203. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6204. S_L:
  6205. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6206. {$ifdef x86_64}
  6207. S_Q:
  6208. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6209. { Overflow; abort }
  6210. Result := False
  6211. else
  6212. taicpu(p).oper[0]^.val := ThisConst;
  6213. {$endif x86_64}
  6214. else
  6215. InternalError(2021102611);
  6216. end;
  6217. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6218. if Result then
  6219. begin
  6220. if (taicpu(p).oper[0]^.val < 0) and
  6221. (
  6222. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6223. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6224. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6225. ) then
  6226. begin
  6227. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6228. taicpu(p).opcode := A_SUB;
  6229. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6230. end
  6231. else
  6232. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6233. RemoveInstruction(hp1);
  6234. end;
  6235. end
  6236. else
  6237. begin
  6238. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6239. TransferUsedRegs(TmpUsedRegs);
  6240. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6241. hp2 := p;
  6242. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6243. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6244. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6245. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6246. begin
  6247. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6248. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6249. Asml.Remove(p);
  6250. Asml.InsertAfter(p, hp1);
  6251. p := hp1;
  6252. Result := True;
  6253. Exit;
  6254. end;
  6255. end;
  6256. end;
  6257. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6258. { * change "sub/add const1, reg" or "dec reg" followed by
  6259. "sub const2, reg" to one "sub ..., reg" }
  6260. {$ifdef i386}
  6261. if (taicpu(p).oper[0]^.val = 2) and
  6262. (ActiveReg = NR_ESP) and
  6263. { Don't do the sub/push optimization if the sub }
  6264. { comes from setting up the stack frame (JM) }
  6265. (not(GetLastInstruction(p,hp1)) or
  6266. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6267. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6268. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6269. begin
  6270. hp1 := tai(p.next);
  6271. while Assigned(hp1) and
  6272. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6273. not RegReadByInstruction(NR_ESP,hp1) and
  6274. not RegModifiedByInstruction(NR_ESP,hp1) do
  6275. hp1 := tai(hp1.next);
  6276. if Assigned(hp1) and
  6277. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6278. begin
  6279. taicpu(hp1).changeopsize(S_L);
  6280. if taicpu(hp1).oper[0]^.typ=top_reg then
  6281. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6282. hp1 := tai(p.next);
  6283. RemoveCurrentp(p, hp1);
  6284. Result:=true;
  6285. exit;
  6286. end;
  6287. end;
  6288. {$endif i386}
  6289. if DoArithCombineOpt(p) then
  6290. Result:=true;
  6291. end;
  6292. end;
  6293. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6294. var
  6295. TmpBool1,TmpBool2 : Boolean;
  6296. tmpref : treference;
  6297. hp1,hp2: tai;
  6298. mask, shiftval: tcgint;
  6299. begin
  6300. Result:=false;
  6301. { All these optimisations work on "shl/sal const,%reg" }
  6302. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6303. Exit;
  6304. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6305. (taicpu(p).oper[0]^.val <= 3) then
  6306. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6307. begin
  6308. { should we check the next instruction? }
  6309. TmpBool1 := True;
  6310. { have we found an add/sub which could be
  6311. integrated in the lea? }
  6312. TmpBool2 := False;
  6313. reference_reset(tmpref,2,[]);
  6314. TmpRef.index := taicpu(p).oper[1]^.reg;
  6315. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6316. while TmpBool1 and
  6317. GetNextInstruction(p, hp1) and
  6318. (tai(hp1).typ = ait_instruction) and
  6319. ((((taicpu(hp1).opcode = A_ADD) or
  6320. (taicpu(hp1).opcode = A_SUB)) and
  6321. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6322. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6323. (((taicpu(hp1).opcode = A_INC) or
  6324. (taicpu(hp1).opcode = A_DEC)) and
  6325. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6326. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6327. ((taicpu(hp1).opcode = A_LEA) and
  6328. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6329. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6330. (not GetNextInstruction(hp1,hp2) or
  6331. not instrReadsFlags(hp2)) Do
  6332. begin
  6333. TmpBool1 := False;
  6334. if taicpu(hp1).opcode=A_LEA then
  6335. begin
  6336. if (TmpRef.base = NR_NO) and
  6337. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6338. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6339. { Segment register isn't a concern here }
  6340. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6341. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6342. begin
  6343. TmpBool1 := True;
  6344. TmpBool2 := True;
  6345. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6346. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6347. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6348. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6349. RemoveInstruction(hp1);
  6350. end
  6351. end
  6352. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6353. begin
  6354. TmpBool1 := True;
  6355. TmpBool2 := True;
  6356. case taicpu(hp1).opcode of
  6357. A_ADD:
  6358. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6359. A_SUB:
  6360. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6361. else
  6362. internalerror(2019050536);
  6363. end;
  6364. RemoveInstruction(hp1);
  6365. end
  6366. else
  6367. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6368. (((taicpu(hp1).opcode = A_ADD) and
  6369. (TmpRef.base = NR_NO)) or
  6370. (taicpu(hp1).opcode = A_INC) or
  6371. (taicpu(hp1).opcode = A_DEC)) then
  6372. begin
  6373. TmpBool1 := True;
  6374. TmpBool2 := True;
  6375. case taicpu(hp1).opcode of
  6376. A_ADD:
  6377. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6378. A_INC:
  6379. inc(TmpRef.offset);
  6380. A_DEC:
  6381. dec(TmpRef.offset);
  6382. else
  6383. internalerror(2019050535);
  6384. end;
  6385. RemoveInstruction(hp1);
  6386. end;
  6387. end;
  6388. if TmpBool2
  6389. {$ifndef x86_64}
  6390. or
  6391. ((current_settings.optimizecputype < cpu_Pentium2) and
  6392. (taicpu(p).oper[0]^.val <= 3) and
  6393. not(cs_opt_size in current_settings.optimizerswitches))
  6394. {$endif x86_64}
  6395. then
  6396. begin
  6397. if not(TmpBool2) and
  6398. (taicpu(p).oper[0]^.val=1) then
  6399. begin
  6400. taicpu(p).opcode := A_ADD;
  6401. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6402. end
  6403. else
  6404. begin
  6405. taicpu(p).opcode := A_LEA;
  6406. taicpu(p).loadref(0, TmpRef);
  6407. end;
  6408. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6409. Result := True;
  6410. end;
  6411. end
  6412. {$ifndef x86_64}
  6413. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6414. begin
  6415. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6416. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6417. (unlike shl, which is only Tairable in the U pipe) }
  6418. if taicpu(p).oper[0]^.val=1 then
  6419. begin
  6420. taicpu(p).opcode := A_ADD;
  6421. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6422. Result := True;
  6423. end
  6424. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6425. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6426. else if (taicpu(p).opsize = S_L) and
  6427. (taicpu(p).oper[0]^.val<= 3) then
  6428. begin
  6429. reference_reset(tmpref,2,[]);
  6430. TmpRef.index := taicpu(p).oper[1]^.reg;
  6431. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6432. taicpu(p).opcode := A_LEA;
  6433. taicpu(p).loadref(0, TmpRef);
  6434. Result := True;
  6435. end;
  6436. end
  6437. {$endif x86_64}
  6438. else if
  6439. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6440. (
  6441. (
  6442. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6443. SetAndTest(hp1, hp2)
  6444. {$ifdef x86_64}
  6445. ) or
  6446. (
  6447. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6448. GetNextInstruction(hp1, hp2) and
  6449. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6450. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6451. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6452. {$endif x86_64}
  6453. )
  6454. ) and
  6455. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6456. begin
  6457. { Change:
  6458. shl x, %reg1
  6459. mov -(1<<x), %reg2
  6460. and %reg2, %reg1
  6461. Or:
  6462. shl x, %reg1
  6463. and -(1<<x), %reg1
  6464. To just:
  6465. shl x, %reg1
  6466. Since the and operation only zeroes bits that are already zero from the shl operation
  6467. }
  6468. case taicpu(p).oper[0]^.val of
  6469. 8:
  6470. mask:=$FFFFFFFFFFFFFF00;
  6471. 16:
  6472. mask:=$FFFFFFFFFFFF0000;
  6473. 32:
  6474. mask:=$FFFFFFFF00000000;
  6475. 63:
  6476. { Constant pre-calculated to prevent overflow errors with Int64 }
  6477. mask:=$8000000000000000;
  6478. else
  6479. begin
  6480. if taicpu(p).oper[0]^.val >= 64 then
  6481. { Shouldn't happen realistically, since the register
  6482. is guaranteed to be set to zero at this point }
  6483. mask := 0
  6484. else
  6485. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6486. end;
  6487. end;
  6488. if taicpu(hp1).oper[0]^.val = mask then
  6489. begin
  6490. { Everything checks out, perform the optimisation, as long as
  6491. the FLAGS register isn't being used}
  6492. TransferUsedRegs(TmpUsedRegs);
  6493. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6494. {$ifdef x86_64}
  6495. if (hp1 <> hp2) then
  6496. begin
  6497. { "shl/mov/and" version }
  6498. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6499. { Don't do the optimisation if the FLAGS register is in use }
  6500. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6501. begin
  6502. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6503. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6504. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6505. begin
  6506. RemoveInstruction(hp1);
  6507. Result := True;
  6508. end;
  6509. { Only set Result to True if the 'mov' instruction was removed }
  6510. RemoveInstruction(hp2);
  6511. end;
  6512. end
  6513. else
  6514. {$endif x86_64}
  6515. begin
  6516. { "shl/and" version }
  6517. { Don't do the optimisation if the FLAGS register is in use }
  6518. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6519. begin
  6520. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6521. RemoveInstruction(hp1);
  6522. Result := True;
  6523. end;
  6524. end;
  6525. Exit;
  6526. end
  6527. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6528. begin
  6529. { Even if the mask doesn't allow for its removal, we might be
  6530. able to optimise the mask for the "shl/and" version, which
  6531. may permit other peephole optimisations }
  6532. {$ifdef DEBUG_AOPTCPU}
  6533. mask := taicpu(hp1).oper[0]^.val and mask;
  6534. if taicpu(hp1).oper[0]^.val <> mask then
  6535. begin
  6536. DebugMsg(
  6537. SPeepholeOptimization +
  6538. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6539. ' to $' + debug_tostr(mask) +
  6540. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6541. taicpu(hp1).oper[0]^.val := mask;
  6542. end;
  6543. {$else DEBUG_AOPTCPU}
  6544. { If debugging is off, just set the operand even if it's the same }
  6545. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6546. {$endif DEBUG_AOPTCPU}
  6547. end;
  6548. end;
  6549. {
  6550. change
  6551. shl/sal const,reg
  6552. <op> ...(...,reg,1),...
  6553. into
  6554. <op> ...(...,reg,1 shl const),...
  6555. if const in 1..3
  6556. }
  6557. if MatchOpType(taicpu(p), top_const, top_reg) and
  6558. (taicpu(p).oper[0]^.val in [1..3]) and
  6559. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6560. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6561. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6562. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6563. MatchOpType(taicpu(hp1),top_ref))
  6564. ) and
  6565. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6566. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6567. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6568. begin
  6569. TransferUsedRegs(TmpUsedRegs);
  6570. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6571. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6572. begin
  6573. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6574. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6575. RemoveCurrentP(p);
  6576. Result:=true;
  6577. exit;
  6578. end;
  6579. end;
  6580. if MatchOpType(taicpu(p), top_const, top_reg) and
  6581. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6582. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6583. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6584. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6585. begin
  6586. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6587. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6588. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6589. {$ifdef x86_64}
  6590. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6591. {$endif x86_64}
  6592. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6593. begin
  6594. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6595. taicpu(hp1).opcode:=A_MOV;
  6596. taicpu(hp1).oper[0]^.val:=0;
  6597. end
  6598. else
  6599. begin
  6600. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6601. taicpu(hp1).oper[0]^.val:=shiftval;
  6602. end;
  6603. RemoveCurrentP(p);
  6604. Result:=true;
  6605. exit;
  6606. end;
  6607. end;
  6608. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6609. begin
  6610. case shr_size of
  6611. S_B:
  6612. { No valid combinations }
  6613. Result := False;
  6614. S_W:
  6615. Result := (Shift >= 8) and (movz_size = S_BW);
  6616. S_L:
  6617. Result :=
  6618. (Shift >= 24) { Any opsize is valid for this shift } or
  6619. ((Shift >= 16) and (movz_size = S_WL));
  6620. {$ifdef x86_64}
  6621. S_Q:
  6622. Result :=
  6623. (Shift >= 56) { Any opsize is valid for this shift } or
  6624. ((Shift >= 48) and (movz_size = S_WL));
  6625. {$endif x86_64}
  6626. else
  6627. InternalError(2022081510);
  6628. end;
  6629. end;
  6630. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6631. var
  6632. hp1, hp2: tai;
  6633. Shift: TCGInt;
  6634. LimitSize: Topsize;
  6635. DoNotMerge: Boolean;
  6636. begin
  6637. Result := False;
  6638. { All these optimisations work on "shr const,%reg" }
  6639. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6640. Exit;
  6641. DoNotMerge := False;
  6642. Shift := taicpu(p).oper[0]^.val;
  6643. LimitSize := taicpu(p).opsize;
  6644. hp1 := p;
  6645. repeat
  6646. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6647. Exit;
  6648. case taicpu(hp1).opcode of
  6649. A_TEST, A_CMP, A_Jcc:
  6650. { Skip over conditional jumps and relevant comparisons }
  6651. Continue;
  6652. A_MOVZX:
  6653. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6654. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6655. begin
  6656. { Since the original register is being read as is, subsequent
  6657. SHRs must not be merged at this point }
  6658. DoNotMerge := True;
  6659. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6660. begin
  6661. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6662. begin
  6663. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6664. taicpu(hp1).opcode := A_MOV;
  6665. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6666. case taicpu(hp1).opsize of
  6667. S_BW:
  6668. taicpu(hp1).opsize := S_W;
  6669. S_BL, S_WL:
  6670. taicpu(hp1).opsize := S_L;
  6671. else
  6672. InternalError(2022081503);
  6673. end;
  6674. { p itself hasn't changed, so no need to set Result to True }
  6675. Include(OptsToCheck, aoc_ForceNewIteration);
  6676. { See if there's anything afterwards that can be
  6677. optimised, since the input register hasn't changed }
  6678. Continue;
  6679. end;
  6680. { NOTE: If the MOVZX instruction reads and writes the same
  6681. register, defer this to the post-peephole optimisation stage }
  6682. Exit;
  6683. end;
  6684. end;
  6685. A_SHL, A_SAL, A_SHR:
  6686. if (taicpu(hp1).opsize <= LimitSize) and
  6687. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6688. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6689. begin
  6690. { Make sure the sizes don't exceed the register size limit
  6691. (measured by the shift value falling below the limit) }
  6692. if taicpu(hp1).opsize < LimitSize then
  6693. LimitSize := taicpu(hp1).opsize;
  6694. if taicpu(hp1).opcode = A_SHR then
  6695. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6696. else
  6697. begin
  6698. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6699. DoNotMerge := True;
  6700. end;
  6701. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6702. Exit;
  6703. { Since we've established that the combined shift is within
  6704. limits, we can actually combine the adjacent SHR
  6705. instructions even if they're different sizes }
  6706. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6707. begin
  6708. hp2 := tai(hp1.Previous);
  6709. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6710. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6711. RemoveInstruction(hp1);
  6712. hp1 := hp2;
  6713. { Though p has changed, only the constant has, and its
  6714. effects can still be detected on the next iteration of
  6715. the repeat..until loop }
  6716. Include(OptsToCheck, aoc_ForceNewIteration);
  6717. end;
  6718. { Move onto the next instruction }
  6719. Continue;
  6720. end;
  6721. else
  6722. ;
  6723. end;
  6724. Break;
  6725. until False;
  6726. end;
  6727. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6728. var
  6729. CurrentRef: TReference;
  6730. FullReg: TRegister;
  6731. hp1, hp2: tai;
  6732. begin
  6733. Result := False;
  6734. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6735. Exit;
  6736. { We assume you've checked if the operand is actually a reference by
  6737. this point. If it isn't, you'll most likely get an access violation }
  6738. CurrentRef := first_mov.oper[1]^.ref^;
  6739. { Memory must be aligned }
  6740. if (CurrentRef.offset mod 4) <> 0 then
  6741. Exit;
  6742. Inc(CurrentRef.offset);
  6743. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6744. if MatchOperand(second_mov.oper[0]^, 0) and
  6745. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6746. GetNextInstruction(second_mov, hp1) and
  6747. (hp1.typ = ait_instruction) and
  6748. (taicpu(hp1).opcode = A_MOV) and
  6749. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6750. (taicpu(hp1).oper[0]^.val = 0) then
  6751. begin
  6752. Inc(CurrentRef.offset);
  6753. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6754. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6755. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6756. begin
  6757. case taicpu(hp1).opsize of
  6758. S_B:
  6759. if GetNextInstruction(hp1, hp2) and
  6760. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6761. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6762. (taicpu(hp2).oper[0]^.val = 0) then
  6763. begin
  6764. Inc(CurrentRef.offset);
  6765. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6766. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6767. (taicpu(hp2).opsize = S_B) then
  6768. begin
  6769. RemoveInstruction(hp1);
  6770. RemoveInstruction(hp2);
  6771. first_mov.opsize := S_L;
  6772. if first_mov.oper[0]^.typ = top_reg then
  6773. begin
  6774. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6775. { Reuse second_mov as a MOVZX instruction }
  6776. second_mov.opcode := A_MOVZX;
  6777. second_mov.opsize := S_BL;
  6778. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6779. second_mov.loadreg(1, FullReg);
  6780. first_mov.oper[0]^.reg := FullReg;
  6781. asml.Remove(second_mov);
  6782. asml.InsertBefore(second_mov, first_mov);
  6783. end
  6784. else
  6785. { It's a value }
  6786. begin
  6787. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6788. RemoveInstruction(second_mov);
  6789. end;
  6790. Result := True;
  6791. Exit;
  6792. end;
  6793. end;
  6794. S_W:
  6795. begin
  6796. RemoveInstruction(hp1);
  6797. first_mov.opsize := S_L;
  6798. if first_mov.oper[0]^.typ = top_reg then
  6799. begin
  6800. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6801. { Reuse second_mov as a MOVZX instruction }
  6802. second_mov.opcode := A_MOVZX;
  6803. second_mov.opsize := S_BL;
  6804. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6805. second_mov.loadreg(1, FullReg);
  6806. first_mov.oper[0]^.reg := FullReg;
  6807. asml.Remove(second_mov);
  6808. asml.InsertBefore(second_mov, first_mov);
  6809. end
  6810. else
  6811. { It's a value }
  6812. begin
  6813. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6814. RemoveInstruction(second_mov);
  6815. end;
  6816. Result := True;
  6817. Exit;
  6818. end;
  6819. else
  6820. ;
  6821. end;
  6822. end;
  6823. end;
  6824. end;
  6825. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6826. { returns true if a "continue" should be done after this optimization }
  6827. var
  6828. hp1, hp2, hp3: tai;
  6829. begin
  6830. Result := false;
  6831. hp3 := nil;
  6832. if MatchOpType(taicpu(p),top_ref) and
  6833. GetNextInstruction(p, hp1) and
  6834. (hp1.typ = ait_instruction) and
  6835. (((taicpu(hp1).opcode = A_FLD) and
  6836. (taicpu(p).opcode = A_FSTP)) or
  6837. ((taicpu(p).opcode = A_FISTP) and
  6838. (taicpu(hp1).opcode = A_FILD))) and
  6839. MatchOpType(taicpu(hp1),top_ref) and
  6840. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6841. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6842. begin
  6843. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6844. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6845. GetNextInstruction(hp1, hp2) and
  6846. (((hp2.typ = ait_instruction) and
  6847. IsExitCode(hp2) and
  6848. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6849. not(assigned(current_procinfo.procdef.funcretsym) and
  6850. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6851. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6852. { fstp <temp>
  6853. fld <temp>
  6854. <dealloc> <temp>
  6855. }
  6856. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6857. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6858. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6859. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6860. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6861. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6862. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6863. )
  6864. )
  6865. ) then
  6866. begin
  6867. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6868. RemoveInstruction(hp1);
  6869. RemoveCurrentP(p, hp2);
  6870. { first case: exit code }
  6871. if hp2.typ = ait_instruction then
  6872. RemoveLastDeallocForFuncRes(p);
  6873. Result := true;
  6874. end
  6875. else
  6876. { we can do this only in fast math mode as fstp is rounding ...
  6877. ... still disabled as it breaks the compiler and/or rtl }
  6878. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6879. { ... or if another fstp equal to the first one follows }
  6880. GetNextInstruction(hp1,hp2) and
  6881. (hp2.typ = ait_instruction) and
  6882. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6883. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6884. begin
  6885. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6886. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6887. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6888. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6889. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6890. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6891. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6892. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6893. ) then
  6894. begin
  6895. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6896. RemoveCurrentP(p,hp2);
  6897. RemoveInstruction(hp1);
  6898. Result := true;
  6899. end
  6900. else if { fst can't store an extended/comp value }
  6901. (taicpu(p).opsize <> S_FX) and
  6902. (taicpu(p).opsize <> S_IQ) then
  6903. begin
  6904. if (taicpu(p).opcode = A_FSTP) then
  6905. taicpu(p).opcode := A_FST
  6906. else
  6907. taicpu(p).opcode := A_FIST;
  6908. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6909. RemoveInstruction(hp1);
  6910. Result := true;
  6911. end;
  6912. end;
  6913. end;
  6914. end;
  6915. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6916. var
  6917. hp1, hp2, hp3: tai;
  6918. begin
  6919. result:=false;
  6920. if MatchOpType(taicpu(p),top_reg) and
  6921. GetNextInstruction(p, hp1) and
  6922. (hp1.typ = Ait_Instruction) and
  6923. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6924. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6925. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6926. { change to
  6927. fld reg fxxx reg,st
  6928. fxxxp st, st1 (hp1)
  6929. Remark: non commutative operations must be reversed!
  6930. }
  6931. begin
  6932. case taicpu(hp1).opcode Of
  6933. A_FMULP,A_FADDP,
  6934. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6935. begin
  6936. case taicpu(hp1).opcode Of
  6937. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6938. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6939. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6940. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6941. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6942. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6943. else
  6944. internalerror(2019050534);
  6945. end;
  6946. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6947. taicpu(hp1).oper[1]^.reg := NR_ST;
  6948. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6949. RemoveCurrentP(p, hp1);
  6950. Result:=true;
  6951. exit;
  6952. end;
  6953. else
  6954. ;
  6955. end;
  6956. end
  6957. else
  6958. if MatchOpType(taicpu(p),top_ref) and
  6959. GetNextInstruction(p, hp2) and
  6960. (hp2.typ = Ait_Instruction) and
  6961. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6962. (taicpu(p).opsize in [S_FS, S_FL]) and
  6963. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6964. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6965. if GetLastInstruction(p, hp1) and
  6966. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6967. MatchOpType(taicpu(hp1),top_ref) and
  6968. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6969. if ((taicpu(hp2).opcode = A_FMULP) or
  6970. (taicpu(hp2).opcode = A_FADDP)) then
  6971. { change to
  6972. fld/fst mem1 (hp1) fld/fst mem1
  6973. fld mem1 (p) fadd/
  6974. faddp/ fmul st, st
  6975. fmulp st, st1 (hp2) }
  6976. begin
  6977. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6978. RemoveCurrentP(p, hp1);
  6979. if (taicpu(hp2).opcode = A_FADDP) then
  6980. taicpu(hp2).opcode := A_FADD
  6981. else
  6982. taicpu(hp2).opcode := A_FMUL;
  6983. taicpu(hp2).oper[1]^.reg := NR_ST;
  6984. end
  6985. else
  6986. { change to
  6987. fld/fst mem1 (hp1) fld/fst mem1
  6988. fld mem1 (p) fld st
  6989. }
  6990. begin
  6991. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6992. taicpu(p).changeopsize(S_FL);
  6993. taicpu(p).loadreg(0,NR_ST);
  6994. end
  6995. else
  6996. begin
  6997. case taicpu(hp2).opcode Of
  6998. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6999. { change to
  7000. fld/fst mem1 (hp1) fld/fst mem1
  7001. fld mem2 (p) fxxx mem2
  7002. fxxxp st, st1 (hp2) }
  7003. begin
  7004. case taicpu(hp2).opcode Of
  7005. A_FADDP: taicpu(p).opcode := A_FADD;
  7006. A_FMULP: taicpu(p).opcode := A_FMUL;
  7007. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7008. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7009. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7010. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7011. else
  7012. internalerror(2019050533);
  7013. end;
  7014. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7015. RemoveInstruction(hp2);
  7016. end
  7017. else
  7018. ;
  7019. end
  7020. end
  7021. end;
  7022. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7023. begin
  7024. Result := condition_in(cond1, cond2) or
  7025. { Not strictly subsets due to the actual flags checked, but because we're
  7026. comparing integers, E is a subset of AE and GE and their aliases }
  7027. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7028. end;
  7029. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7030. var
  7031. v: TCGInt;
  7032. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7033. FirstMatch, TempBool: Boolean;
  7034. NewReg: TRegister;
  7035. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7036. begin
  7037. Result:=false;
  7038. { All these optimisations need a next instruction }
  7039. if not GetNextInstruction(p, hp1) then
  7040. Exit;
  7041. { Search for:
  7042. cmp ###,###
  7043. j(c1) @lbl1
  7044. ...
  7045. @lbl:
  7046. cmp ###,### (same comparison as above)
  7047. j(c2) @lbl2
  7048. If c1 is a subset of c2, change to:
  7049. cmp ###,###
  7050. j(c1) @lbl2
  7051. (@lbl1 may become a dead label as a result)
  7052. }
  7053. { Also handle cases where there are multiple jumps in a row }
  7054. p_jump := hp1;
  7055. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7056. begin
  7057. if IsJumpToLabel(taicpu(p_jump)) then
  7058. begin
  7059. { Do jump optimisations first in case the condition becomes
  7060. unnecessary }
  7061. TempBool := True;
  7062. if DoJumpOptimizations(p_jump, TempBool) or
  7063. not TempBool then
  7064. begin
  7065. if Assigned(p_jump) then
  7066. begin
  7067. hp1 := p_jump;
  7068. if (p_jump.typ in [ait_align]) then
  7069. SkipAligns(p_jump, p_jump);
  7070. { CollapseZeroDistJump will be set to the label after the
  7071. jump if it optimises, whether or not it's live or dead }
  7072. if (p_jump.typ in [ait_label]) and
  7073. not (tai_label(p_jump).labsym.is_used) then
  7074. GetNextInstruction(p_jump, p_jump);
  7075. end;
  7076. TransferUsedRegs(TmpUsedRegs);
  7077. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7078. if not Assigned(p_jump) or
  7079. (
  7080. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7081. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7082. ) then
  7083. begin
  7084. { No more conditional jumps; conditional statement is no longer required }
  7085. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7086. RemoveCurrentP(p);
  7087. Result := True;
  7088. Exit;
  7089. end;
  7090. hp1 := p_jump;
  7091. Include(OptsToCheck, aoc_ForceNewIteration);
  7092. Continue;
  7093. end;
  7094. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7095. if GetNextInstruction(p_jump, hp2) and
  7096. (
  7097. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7098. not TempBool
  7099. ) then
  7100. begin
  7101. hp1 := p_jump;
  7102. Include(OptsToCheck, aoc_ForceNewIteration);
  7103. Continue;
  7104. end;
  7105. p_label := nil;
  7106. if Assigned(JumpLabel) then
  7107. p_label := getlabelwithsym(JumpLabel);
  7108. if Assigned(p_label) and
  7109. GetNextInstruction(p_label, p_dist) and
  7110. MatchInstruction(p_dist, A_CMP, []) and
  7111. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7112. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7113. GetNextInstruction(p_dist, hp1_dist) and
  7114. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7115. begin
  7116. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7117. if JumpLabel = JumpLabel_dist then
  7118. { This is an infinite loop }
  7119. Exit;
  7120. { Best optimisation when the first condition is a subset (or equal) of the second }
  7121. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7122. begin
  7123. { Any registers used here will already be allocated }
  7124. if Assigned(JumpLabel) then
  7125. JumpLabel.DecRefs;
  7126. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7127. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7128. Result := True;
  7129. { Don't exit yet. Since p and p_jump haven't actually been
  7130. removed, we can check for more on this iteration }
  7131. end
  7132. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7133. GetNextInstruction(hp1_dist, hp1_label) and
  7134. SkipAligns(hp1_label, hp1_label) and
  7135. (hp1_label.typ = ait_label) then
  7136. begin
  7137. JumpLabel_far := tai_label(hp1_label).labsym;
  7138. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7139. { This is an infinite loop }
  7140. Exit;
  7141. if Assigned(JumpLabel_far) then
  7142. begin
  7143. { In this situation, if the first jump branches, the second one will never,
  7144. branch so change the destination label to after the second jump }
  7145. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7146. if Assigned(JumpLabel) then
  7147. JumpLabel.DecRefs;
  7148. JumpLabel_far.IncRefs;
  7149. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7150. Result := True;
  7151. { Don't exit yet. Since p and p_jump haven't actually been
  7152. removed, we can check for more on this iteration }
  7153. Continue;
  7154. end;
  7155. end;
  7156. end;
  7157. end;
  7158. { Search for:
  7159. cmp ###,###
  7160. j(c1) @lbl1
  7161. cmp ###,### (same as first)
  7162. Remove second cmp
  7163. }
  7164. if GetNextInstruction(p_jump, hp2) and
  7165. (
  7166. (
  7167. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7168. (
  7169. (
  7170. MatchOpType(taicpu(p), top_const, top_reg) and
  7171. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7172. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7173. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7174. ) or (
  7175. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7176. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7177. )
  7178. )
  7179. ) or (
  7180. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7181. MatchOperand(taicpu(p).oper[0]^, 0) and
  7182. (taicpu(p).oper[1]^.typ = top_reg) and
  7183. MatchInstruction(hp2, A_TEST, []) and
  7184. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7185. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7186. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7187. )
  7188. ) then
  7189. begin
  7190. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7191. RemoveInstruction(hp2);
  7192. Result := True;
  7193. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7194. end;
  7195. GetNextInstruction(p_jump, p_jump);
  7196. end;
  7197. if (
  7198. { Don't call GetNextInstruction again if we already have it }
  7199. (hp1 = p_jump) or
  7200. GetNextInstruction(p, hp1)
  7201. ) and
  7202. MatchInstruction(hp1, A_Jcc, []) and
  7203. IsJumpToLabel(taicpu(hp1)) and
  7204. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7205. GetNextInstruction(hp1, hp2) then
  7206. begin
  7207. {
  7208. cmp x, y (or "cmp y, x")
  7209. je @lbl
  7210. mov x, y
  7211. @lbl:
  7212. (x and y can be constants, registers or references)
  7213. Change to:
  7214. mov x, y (x and y will always be equal in the end)
  7215. @lbl: (may beceome a dead label)
  7216. Also:
  7217. cmp x, y (or "cmp y, x")
  7218. jne @lbl
  7219. mov x, y
  7220. @lbl:
  7221. (x and y can be constants, registers or references)
  7222. Change to:
  7223. Absolutely nothing! (Except @lbl if it's still live)
  7224. }
  7225. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7226. (
  7227. (
  7228. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7229. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7230. ) or (
  7231. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7232. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7233. )
  7234. ) and
  7235. GetNextInstruction(hp2, hp1_label) and
  7236. SkipAligns(hp1_label, hp1_label) and
  7237. (hp1_label.typ = ait_label) and
  7238. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7239. begin
  7240. tai_label(hp1_label).labsym.DecRefs;
  7241. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7242. begin
  7243. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7244. RemoveInstruction(hp2);
  7245. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7246. end
  7247. else
  7248. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7249. RemoveInstruction(hp1);
  7250. RemoveCurrentp(p, hp2);
  7251. Result := True;
  7252. Exit;
  7253. end;
  7254. {
  7255. Try to optimise the following:
  7256. cmp $x,### ($x and $y can be registers or constants)
  7257. je @lbl1 (only reference)
  7258. cmp $y,### (### are identical)
  7259. @Lbl:
  7260. sete %reg1
  7261. Change to:
  7262. cmp $x,###
  7263. sete %reg2 (allocate new %reg2)
  7264. cmp $y,###
  7265. sete %reg1
  7266. orb %reg2,%reg1
  7267. (dealloc %reg2)
  7268. This adds an instruction (so don't perform under -Os), but it removes
  7269. a conditional branch.
  7270. }
  7271. if not (cs_opt_size in current_settings.optimizerswitches) and
  7272. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7273. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7274. { The first operand of CMP instructions can only be a register or
  7275. immediate anyway, so no need to check }
  7276. GetNextInstruction(hp2, p_label) and
  7277. (p_label.typ = ait_label) and
  7278. (tai_label(p_label).labsym.getrefs = 1) and
  7279. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7280. GetNextInstruction(p_label, p_dist) and
  7281. MatchInstruction(p_dist, A_SETcc, []) and
  7282. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7283. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7284. begin
  7285. TransferUsedRegs(TmpUsedRegs);
  7286. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7287. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7288. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7289. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7290. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7291. { Get the instruction after the SETcc instruction so we can
  7292. allocate a new register over the entire range }
  7293. GetNextInstruction(p_dist, hp1_dist) then
  7294. begin
  7295. { Register can appear in p if it's not used afterwards, so only
  7296. allocate between hp1 and hp1_dist }
  7297. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7298. if NewReg <> NR_NO then
  7299. begin
  7300. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7301. { Change the jump instruction into a SETcc instruction }
  7302. taicpu(hp1).opcode := A_SETcc;
  7303. taicpu(hp1).opsize := S_B;
  7304. taicpu(hp1).loadreg(0, NewReg);
  7305. { This is now a dead label }
  7306. tai_label(p_label).labsym.decrefs;
  7307. { Prefer adding before the next instruction so the FLAGS
  7308. register is deallicated first }
  7309. AsmL.InsertBefore(
  7310. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7311. hp1_dist
  7312. );
  7313. Result := True;
  7314. { Don't exit yet, as p wasn't changed and hp1, while
  7315. modified, is still intact and might be optimised by the
  7316. SETcc optimisation below }
  7317. end;
  7318. end;
  7319. end;
  7320. end;
  7321. if taicpu(p).oper[0]^.typ = top_const then
  7322. begin
  7323. if (taicpu(p).oper[0]^.val = 0) and
  7324. (taicpu(p).oper[1]^.typ = top_reg) and
  7325. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7326. begin
  7327. hp2 := p;
  7328. FirstMatch := True;
  7329. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7330. anything meaningful once it's converted to "test %reg,%reg";
  7331. additionally, some jumps will always (or never) branch, so
  7332. evaluate every jump immediately following the
  7333. comparison, optimising the conditions if possible.
  7334. Similarly with SETcc... those that are always set to 0 or 1
  7335. are changed to MOV instructions }
  7336. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7337. (
  7338. GetNextInstruction(hp2, hp1) and
  7339. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7340. ) do
  7341. begin
  7342. FirstMatch := False;
  7343. case taicpu(hp1).condition of
  7344. C_B, C_C, C_NAE, C_O:
  7345. { For B/NAE:
  7346. Will never branch since an unsigned integer can never be below zero
  7347. For C/O:
  7348. Result cannot overflow because 0 is being subtracted
  7349. }
  7350. begin
  7351. if taicpu(hp1).opcode = A_Jcc then
  7352. begin
  7353. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7354. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7355. RemoveInstruction(hp1);
  7356. { Since hp1 was deleted, hp2 must not be updated }
  7357. Continue;
  7358. end
  7359. else
  7360. begin
  7361. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7362. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7363. taicpu(hp1).opcode := A_MOV;
  7364. taicpu(hp1).ops := 2;
  7365. taicpu(hp1).condition := C_None;
  7366. taicpu(hp1).opsize := S_B;
  7367. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7368. taicpu(hp1).loadconst(0, 0);
  7369. end;
  7370. end;
  7371. C_BE, C_NA:
  7372. begin
  7373. { Will only branch if equal to zero }
  7374. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7375. taicpu(hp1).condition := C_E;
  7376. end;
  7377. C_A, C_NBE:
  7378. begin
  7379. { Will only branch if not equal to zero }
  7380. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7381. taicpu(hp1).condition := C_NE;
  7382. end;
  7383. C_AE, C_NB, C_NC, C_NO:
  7384. begin
  7385. { Will always branch }
  7386. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7387. if taicpu(hp1).opcode = A_Jcc then
  7388. begin
  7389. MakeUnconditional(taicpu(hp1));
  7390. { Any jumps/set that follow will now be dead code }
  7391. RemoveDeadCodeAfterJump(taicpu(hp1));
  7392. Break;
  7393. end
  7394. else
  7395. begin
  7396. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7397. taicpu(hp1).opcode := A_MOV;
  7398. taicpu(hp1).ops := 2;
  7399. taicpu(hp1).condition := C_None;
  7400. taicpu(hp1).opsize := S_B;
  7401. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7402. taicpu(hp1).loadconst(0, 1);
  7403. end;
  7404. end;
  7405. C_None:
  7406. InternalError(2020012201);
  7407. C_P, C_PE, C_NP, C_PO:
  7408. { We can't handle parity checks and they should never be generated
  7409. after a general-purpose CMP (it's used in some floating-point
  7410. comparisons that don't use CMP) }
  7411. InternalError(2020012202);
  7412. else
  7413. { Zero/Equality, Sign, their complements and all of the
  7414. signed comparisons do not need to be converted };
  7415. end;
  7416. hp2 := hp1;
  7417. end;
  7418. { Convert the instruction to a TEST }
  7419. taicpu(p).opcode := A_TEST;
  7420. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7421. Result := True;
  7422. Exit;
  7423. end
  7424. else if (taicpu(p).oper[0]^.val = 1) and
  7425. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7426. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7427. begin
  7428. { Convert; To:
  7429. cmp $1,r/m cmp $0,r/m
  7430. jl @lbl jle @lbl
  7431. (Also do inverted conditions)
  7432. }
  7433. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7434. taicpu(p).oper[0]^.val := 0;
  7435. if taicpu(hp1).condition in [C_L, C_NGE] then
  7436. taicpu(hp1).condition := C_LE
  7437. else
  7438. taicpu(hp1).condition := C_NLE;
  7439. { If the instruction is now "cmp $0,%reg", convert it to a
  7440. TEST (and effectively do the work of the "cmp $0,%reg" in
  7441. the block above)
  7442. }
  7443. if (taicpu(p).oper[1]^.typ = top_reg) then
  7444. begin
  7445. taicpu(p).opcode := A_TEST;
  7446. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7447. end;
  7448. Result := True;
  7449. Exit;
  7450. end
  7451. else if (taicpu(p).oper[1]^.typ = top_reg)
  7452. {$ifdef x86_64}
  7453. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7454. {$endif x86_64}
  7455. then
  7456. begin
  7457. { cmp register,$8000 neg register
  7458. je target --> jo target
  7459. .... only if register is deallocated before jump.}
  7460. case Taicpu(p).opsize of
  7461. S_B: v:=$80;
  7462. S_W: v:=$8000;
  7463. S_L: v:=qword($80000000);
  7464. else
  7465. internalerror(2013112905);
  7466. end;
  7467. if (taicpu(p).oper[0]^.val=v) and
  7468. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7469. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7470. begin
  7471. TransferUsedRegs(TmpUsedRegs);
  7472. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7473. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7474. begin
  7475. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7476. Taicpu(p).opcode:=A_NEG;
  7477. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7478. Taicpu(p).clearop(1);
  7479. Taicpu(p).ops:=1;
  7480. if Taicpu(hp1).condition=C_E then
  7481. Taicpu(hp1).condition:=C_O
  7482. else
  7483. Taicpu(hp1).condition:=C_NO;
  7484. Result:=true;
  7485. exit;
  7486. end;
  7487. end;
  7488. end;
  7489. end;
  7490. if TrySwapMovCmp(p, hp1) then
  7491. begin
  7492. Result := True;
  7493. Exit;
  7494. end;
  7495. end;
  7496. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7497. var
  7498. hp1: tai;
  7499. begin
  7500. {
  7501. remove the second (v)pxor from
  7502. pxor reg,reg
  7503. ...
  7504. pxor reg,reg
  7505. }
  7506. Result:=false;
  7507. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7508. MatchOpType(taicpu(p),top_reg,top_reg) and
  7509. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7510. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7511. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7512. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7513. begin
  7514. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7515. RemoveInstruction(hp1);
  7516. Result:=true;
  7517. Exit;
  7518. end
  7519. {
  7520. replace
  7521. pxor reg1,reg1
  7522. movapd/s reg1,reg2
  7523. dealloc reg1
  7524. by
  7525. pxor reg2,reg2
  7526. }
  7527. else if GetNextInstruction(p,hp1) and
  7528. { we mix single and double opperations here because we assume that the compiler
  7529. generates vmovapd only after double operations and vmovaps only after single operations }
  7530. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7531. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7532. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7533. (taicpu(p).oper[0]^.typ=top_reg) then
  7534. begin
  7535. TransferUsedRegs(TmpUsedRegs);
  7536. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7537. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7538. begin
  7539. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7540. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7541. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7542. RemoveInstruction(hp1);
  7543. result:=true;
  7544. end;
  7545. end;
  7546. end;
  7547. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7548. var
  7549. hp1: tai;
  7550. begin
  7551. {
  7552. remove the second (v)pxor from
  7553. (v)pxor reg,reg
  7554. ...
  7555. (v)pxor reg,reg
  7556. }
  7557. Result:=false;
  7558. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7559. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7560. begin
  7561. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7562. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7563. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7564. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7565. begin
  7566. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7567. RemoveInstruction(hp1);
  7568. Result:=true;
  7569. Exit;
  7570. end;
  7571. {$ifdef x86_64}
  7572. {
  7573. replace
  7574. vpxor reg1,reg1,reg1
  7575. vmov reg,mem
  7576. by
  7577. movq $0,mem
  7578. }
  7579. if GetNextInstruction(p,hp1) and
  7580. MatchInstruction(hp1,A_VMOVSD,[]) and
  7581. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7582. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7583. begin
  7584. TransferUsedRegs(TmpUsedRegs);
  7585. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7586. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7587. begin
  7588. taicpu(hp1).loadconst(0,0);
  7589. taicpu(hp1).opcode:=A_MOV;
  7590. taicpu(hp1).opsize:=S_Q;
  7591. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7592. RemoveCurrentP(p);
  7593. result:=true;
  7594. Exit;
  7595. end;
  7596. end;
  7597. {$endif x86_64}
  7598. end
  7599. {
  7600. replace
  7601. vpxor reg1,reg1,reg2
  7602. by
  7603. vpxor reg2,reg2,reg2
  7604. to avoid unncessary data dependencies
  7605. }
  7606. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7607. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7608. begin
  7609. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7610. { avoid unncessary data dependency }
  7611. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7612. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7613. result:=true;
  7614. exit;
  7615. end;
  7616. Result:=OptPass1VOP(p);
  7617. end;
  7618. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7619. var
  7620. hp1 : tai;
  7621. begin
  7622. result:=false;
  7623. { replace
  7624. IMul const,%mreg1,%mreg2
  7625. Mov %reg2,%mreg3
  7626. dealloc %mreg3
  7627. by
  7628. Imul const,%mreg1,%mreg23
  7629. }
  7630. if (taicpu(p).ops=3) and
  7631. GetNextInstruction(p,hp1) and
  7632. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7633. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7634. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7635. begin
  7636. TransferUsedRegs(TmpUsedRegs);
  7637. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7638. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7639. begin
  7640. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7641. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7642. RemoveInstruction(hp1);
  7643. result:=true;
  7644. end;
  7645. end;
  7646. end;
  7647. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7648. var
  7649. hp1 : tai;
  7650. begin
  7651. result:=false;
  7652. { replace
  7653. IMul %reg0,%reg1,%reg2
  7654. Mov %reg2,%reg3
  7655. dealloc %reg2
  7656. by
  7657. Imul %reg0,%reg1,%reg3
  7658. }
  7659. if GetNextInstruction(p,hp1) and
  7660. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7661. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7662. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7663. begin
  7664. TransferUsedRegs(TmpUsedRegs);
  7665. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7666. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7667. begin
  7668. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7669. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7670. RemoveInstruction(hp1);
  7671. result:=true;
  7672. end;
  7673. end;
  7674. end;
  7675. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7676. var
  7677. hp1: tai;
  7678. begin
  7679. Result:=false;
  7680. { get rid of
  7681. (v)cvtss2sd reg0,<reg1,>reg2
  7682. (v)cvtss2sd reg2,<reg2,>reg0
  7683. }
  7684. if GetNextInstruction(p,hp1) and
  7685. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7686. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7687. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7688. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7689. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7690. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7691. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7692. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7693. )
  7694. ) then
  7695. begin
  7696. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7697. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7698. begin
  7699. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7700. RemoveCurrentP(p);
  7701. RemoveInstruction(hp1);
  7702. end
  7703. else
  7704. begin
  7705. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7706. if taicpu(hp1).opcode=A_CVTSD2SS then
  7707. begin
  7708. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7709. taicpu(p).opcode:=A_MOVAPS;
  7710. end
  7711. else
  7712. begin
  7713. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7714. taicpu(p).opcode:=A_VMOVAPS;
  7715. end;
  7716. taicpu(p).ops:=2;
  7717. RemoveInstruction(hp1);
  7718. end;
  7719. Result:=true;
  7720. Exit;
  7721. end;
  7722. end;
  7723. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7724. var
  7725. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7726. ThisReg: TRegister;
  7727. begin
  7728. Result := False;
  7729. if not GetNextInstruction(p,hp1) then
  7730. Exit;
  7731. {
  7732. convert
  7733. j<c> .L1
  7734. mov 1,reg
  7735. jmp .L2
  7736. .L1
  7737. mov 0,reg
  7738. .L2
  7739. into
  7740. mov 0,reg
  7741. set<not(c)> reg
  7742. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7743. would destroy the flag contents
  7744. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7745. executed at the same time as a previous comparison.
  7746. set<not(c)> reg
  7747. movzx reg, reg
  7748. }
  7749. if MatchInstruction(hp1,A_MOV,[]) and
  7750. (taicpu(hp1).oper[0]^.typ = top_const) and
  7751. (
  7752. (
  7753. (taicpu(hp1).oper[1]^.typ = top_reg)
  7754. {$ifdef i386}
  7755. { Under i386, ESI, EDI, EBP and ESP
  7756. don't have an 8-bit representation }
  7757. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7758. {$endif i386}
  7759. ) or (
  7760. {$ifdef i386}
  7761. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7762. {$endif i386}
  7763. (taicpu(hp1).opsize = S_B)
  7764. )
  7765. ) and
  7766. GetNextInstruction(hp1,hp2) and
  7767. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7768. GetNextInstruction(hp2,hp3) and
  7769. SkipAligns(hp3, hp3) and
  7770. (hp3.typ=ait_label) and
  7771. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7772. GetNextInstruction(hp3,hp4) and
  7773. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7774. (taicpu(hp4).oper[0]^.typ = top_const) and
  7775. (
  7776. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7777. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7778. ) and
  7779. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7780. GetNextInstruction(hp4,hp5) and
  7781. SkipAligns(hp5, hp5) and
  7782. (hp5.typ=ait_label) and
  7783. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7784. begin
  7785. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7786. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7787. tai_label(hp3).labsym.DecRefs;
  7788. { If this isn't the only reference to the middle label, we can
  7789. still make a saving - only that the first jump and everything
  7790. that follows will remain. }
  7791. if (tai_label(hp3).labsym.getrefs = 0) then
  7792. begin
  7793. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7794. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7795. else
  7796. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7797. { remove jump, first label and second MOV (also catching any aligns) }
  7798. repeat
  7799. if not GetNextInstruction(hp2, hp3) then
  7800. InternalError(2021040810);
  7801. RemoveInstruction(hp2);
  7802. hp2 := hp3;
  7803. until hp2 = hp5;
  7804. { Don't decrement reference count before the removal loop
  7805. above, otherwise GetNextInstruction won't stop on the
  7806. the label }
  7807. tai_label(hp5).labsym.DecRefs;
  7808. end
  7809. else
  7810. begin
  7811. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7812. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7813. else
  7814. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7815. end;
  7816. taicpu(p).opcode:=A_SETcc;
  7817. taicpu(p).opsize:=S_B;
  7818. taicpu(p).is_jmp:=False;
  7819. if taicpu(hp1).opsize=S_B then
  7820. begin
  7821. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7822. if taicpu(hp1).oper[1]^.typ = top_reg then
  7823. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7824. RemoveInstruction(hp1);
  7825. end
  7826. else
  7827. begin
  7828. { Will be a register because the size can't be S_B otherwise }
  7829. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7830. taicpu(p).loadreg(0, ThisReg);
  7831. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7832. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7833. begin
  7834. case taicpu(hp1).opsize of
  7835. S_W:
  7836. taicpu(hp1).opsize := S_BW;
  7837. S_L:
  7838. taicpu(hp1).opsize := S_BL;
  7839. {$ifdef x86_64}
  7840. S_Q:
  7841. begin
  7842. taicpu(hp1).opsize := S_BL;
  7843. { Change the destination register to 32-bit }
  7844. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7845. end;
  7846. {$endif x86_64}
  7847. else
  7848. InternalError(2021040820);
  7849. end;
  7850. taicpu(hp1).opcode := A_MOVZX;
  7851. taicpu(hp1).loadreg(0, ThisReg);
  7852. end
  7853. else
  7854. begin
  7855. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7856. { hp1 is already a MOV instruction with the correct register }
  7857. taicpu(hp1).loadconst(0, 0);
  7858. { Inserting it right before p will guarantee that the flags are also tracked }
  7859. asml.Remove(hp1);
  7860. asml.InsertBefore(hp1, p);
  7861. end;
  7862. end;
  7863. Result:=true;
  7864. exit;
  7865. end
  7866. else if (hp1.typ = ait_label) then
  7867. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7868. end;
  7869. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7870. var
  7871. hp1, hp2, hp3: tai;
  7872. SourceRef, TargetRef: TReference;
  7873. CurrentReg: TRegister;
  7874. begin
  7875. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7876. if not UseAVX then
  7877. InternalError(2021100501);
  7878. Result := False;
  7879. { Look for the following to simplify:
  7880. vmovdqa/u x(mem1), %xmmreg
  7881. vmovdqa/u %xmmreg, y(mem2)
  7882. vmovdqa/u x+16(mem1), %xmmreg
  7883. vmovdqa/u %xmmreg, y+16(mem2)
  7884. Change to:
  7885. vmovdqa/u x(mem1), %ymmreg
  7886. vmovdqa/u %ymmreg, y(mem2)
  7887. vpxor %ymmreg, %ymmreg, %ymmreg
  7888. ( The VPXOR instruction is to zero the upper half, thus removing the
  7889. need to call the potentially expensive VZEROUPPER instruction. Other
  7890. peephole optimisations can remove VPXOR if it's unnecessary )
  7891. }
  7892. TransferUsedRegs(TmpUsedRegs);
  7893. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7894. { NOTE: In the optimisations below, if the references dictate that an
  7895. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7896. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7897. if (taicpu(p).opsize = S_XMM) and
  7898. MatchOpType(taicpu(p), top_ref, top_reg) and
  7899. GetNextInstruction(p, hp1) and
  7900. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7901. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7902. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7903. begin
  7904. SourceRef := taicpu(p).oper[0]^.ref^;
  7905. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7906. if GetNextInstruction(hp1, hp2) and
  7907. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7908. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7909. begin
  7910. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7911. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7912. Inc(SourceRef.offset, 16);
  7913. { Reuse the register in the first block move }
  7914. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7915. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7916. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7917. begin
  7918. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7919. Inc(TargetRef.offset, 16);
  7920. if GetNextInstruction(hp2, hp3) and
  7921. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7922. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7923. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7924. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7925. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7926. begin
  7927. { Update the register tracking to the new size }
  7928. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7929. { Remember that the offsets are 16 ahead }
  7930. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7931. if not (
  7932. ((SourceRef.offset mod 32) = 16) and
  7933. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7934. ) then
  7935. taicpu(p).opcode := A_VMOVDQU;
  7936. taicpu(p).opsize := S_YMM;
  7937. taicpu(p).oper[1]^.reg := CurrentReg;
  7938. if not (
  7939. ((TargetRef.offset mod 32) = 16) and
  7940. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7941. ) then
  7942. taicpu(hp1).opcode := A_VMOVDQU;
  7943. taicpu(hp1).opsize := S_YMM;
  7944. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7945. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7946. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7947. if (pi_uses_ymm in current_procinfo.flags) then
  7948. RemoveInstruction(hp2)
  7949. else
  7950. begin
  7951. taicpu(hp2).opcode := A_VPXOR;
  7952. taicpu(hp2).opsize := S_YMM;
  7953. taicpu(hp2).loadreg(0, CurrentReg);
  7954. taicpu(hp2).loadreg(1, CurrentReg);
  7955. taicpu(hp2).loadreg(2, CurrentReg);
  7956. taicpu(hp2).ops := 3;
  7957. end;
  7958. RemoveInstruction(hp3);
  7959. Result := True;
  7960. Exit;
  7961. end;
  7962. end
  7963. else
  7964. begin
  7965. { See if the next references are 16 less rather than 16 greater }
  7966. Dec(SourceRef.offset, 32); { -16 the other way }
  7967. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7968. begin
  7969. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7970. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7971. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7972. GetNextInstruction(hp2, hp3) and
  7973. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7974. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7975. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7976. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7977. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7978. begin
  7979. { Update the register tracking to the new size }
  7980. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7981. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7982. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7983. if not(
  7984. ((SourceRef.offset mod 32) = 0) and
  7985. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7986. ) then
  7987. taicpu(hp2).opcode := A_VMOVDQU;
  7988. taicpu(hp2).opsize := S_YMM;
  7989. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7990. if not (
  7991. ((TargetRef.offset mod 32) = 0) and
  7992. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7993. ) then
  7994. taicpu(hp3).opcode := A_VMOVDQU;
  7995. taicpu(hp3).opsize := S_YMM;
  7996. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7997. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7998. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7999. if (pi_uses_ymm in current_procinfo.flags) then
  8000. RemoveInstruction(hp1)
  8001. else
  8002. begin
  8003. taicpu(hp1).opcode := A_VPXOR;
  8004. taicpu(hp1).opsize := S_YMM;
  8005. taicpu(hp1).loadreg(0, CurrentReg);
  8006. taicpu(hp1).loadreg(1, CurrentReg);
  8007. taicpu(hp1).loadreg(2, CurrentReg);
  8008. taicpu(hp1).ops := 3;
  8009. Asml.Remove(hp1);
  8010. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8011. end;
  8012. RemoveCurrentP(p, hp2);
  8013. Result := True;
  8014. Exit;
  8015. end;
  8016. end;
  8017. end;
  8018. end;
  8019. end;
  8020. end;
  8021. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8022. var
  8023. hp2, hp3, first_assignment: tai;
  8024. IncCount, OperIdx: Integer;
  8025. OrigLabel: TAsmLabel;
  8026. begin
  8027. Count := 0;
  8028. Result := False;
  8029. first_assignment := nil;
  8030. if (LoopCount >= 20) then
  8031. begin
  8032. { Guard against infinite loops }
  8033. Exit;
  8034. end;
  8035. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8036. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8037. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8038. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8039. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8040. Exit;
  8041. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8042. {
  8043. change
  8044. jmp .L1
  8045. ...
  8046. .L1:
  8047. mov ##, ## ( multiple movs possible )
  8048. jmp/ret
  8049. into
  8050. mov ##, ##
  8051. jmp/ret
  8052. }
  8053. if not Assigned(hp1) then
  8054. begin
  8055. hp1 := GetLabelWithSym(OrigLabel);
  8056. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8057. Exit;
  8058. end;
  8059. hp2 := hp1;
  8060. while Assigned(hp2) do
  8061. begin
  8062. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8063. SkipLabels(hp2,hp2);
  8064. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8065. Break;
  8066. case taicpu(hp2).opcode of
  8067. A_MOVSD:
  8068. begin
  8069. if taicpu(hp2).ops = 0 then
  8070. { Wrong MOVSD }
  8071. Break;
  8072. Inc(Count);
  8073. if Count >= 5 then
  8074. { Too many to be worthwhile }
  8075. Break;
  8076. GetNextInstruction(hp2, hp2);
  8077. Continue;
  8078. end;
  8079. A_MOV,
  8080. A_MOVD,
  8081. A_MOVQ,
  8082. A_MOVSX,
  8083. {$ifdef x86_64}
  8084. A_MOVSXD,
  8085. {$endif x86_64}
  8086. A_MOVZX,
  8087. A_MOVAPS,
  8088. A_MOVUPS,
  8089. A_MOVSS,
  8090. A_MOVAPD,
  8091. A_MOVUPD,
  8092. A_MOVDQA,
  8093. A_MOVDQU,
  8094. A_VMOVSS,
  8095. A_VMOVAPS,
  8096. A_VMOVUPS,
  8097. A_VMOVSD,
  8098. A_VMOVAPD,
  8099. A_VMOVUPD,
  8100. A_VMOVDQA,
  8101. A_VMOVDQU:
  8102. begin
  8103. Inc(Count);
  8104. if Count >= 5 then
  8105. { Too many to be worthwhile }
  8106. Break;
  8107. GetNextInstruction(hp2, hp2);
  8108. Continue;
  8109. end;
  8110. A_JMP:
  8111. begin
  8112. { Guard against infinite loops }
  8113. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8114. Exit;
  8115. { Analyse this jump first in case it also duplicates assignments }
  8116. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8117. begin
  8118. { Something did change! }
  8119. Result := True;
  8120. Inc(Count, IncCount);
  8121. if Count >= 5 then
  8122. begin
  8123. { Too many to be worthwhile }
  8124. Exit;
  8125. end;
  8126. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8127. Break;
  8128. end;
  8129. Result := True;
  8130. Break;
  8131. end;
  8132. A_RET:
  8133. begin
  8134. Result := True;
  8135. Break;
  8136. end;
  8137. else
  8138. Break;
  8139. end;
  8140. end;
  8141. if Result then
  8142. begin
  8143. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8144. if Count = 0 then
  8145. begin
  8146. Result := False;
  8147. Exit;
  8148. end;
  8149. hp3 := p;
  8150. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8151. while True do
  8152. begin
  8153. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8154. SkipLabels(hp1,hp1);
  8155. if (hp1.typ <> ait_instruction) then
  8156. InternalError(2021040720);
  8157. case taicpu(hp1).opcode of
  8158. A_JMP:
  8159. begin
  8160. { Change the original jump to the new destination }
  8161. OrigLabel.decrefs;
  8162. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8163. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8164. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8165. if not Assigned(first_assignment) then
  8166. InternalError(2021040810)
  8167. else
  8168. p := first_assignment;
  8169. Exit;
  8170. end;
  8171. A_RET:
  8172. begin
  8173. { Now change the jump into a RET instruction }
  8174. ConvertJumpToRET(p, hp1);
  8175. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8176. if not Assigned(first_assignment) then
  8177. InternalError(2021040811)
  8178. else
  8179. p := first_assignment;
  8180. Exit;
  8181. end;
  8182. else
  8183. begin
  8184. { Duplicate the MOV instruction }
  8185. hp3:=tai(hp1.getcopy);
  8186. if first_assignment = nil then
  8187. first_assignment := hp3;
  8188. asml.InsertBefore(hp3, p);
  8189. { Make sure the compiler knows about any final registers written here }
  8190. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8191. with taicpu(hp3).oper[OperIdx]^ do
  8192. begin
  8193. case typ of
  8194. top_ref:
  8195. begin
  8196. if (ref^.base <> NR_NO) and
  8197. (getsupreg(ref^.base) <> RS_ESP) and
  8198. (getsupreg(ref^.base) <> RS_EBP)
  8199. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8200. then
  8201. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8202. if (ref^.index <> NR_NO) and
  8203. (getsupreg(ref^.index) <> RS_ESP) and
  8204. (getsupreg(ref^.index) <> RS_EBP)
  8205. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8206. (ref^.index <> ref^.base) then
  8207. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8208. end;
  8209. top_reg:
  8210. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8211. else
  8212. ;
  8213. end;
  8214. end;
  8215. end;
  8216. end;
  8217. if not GetNextInstruction(hp1, hp1) then
  8218. { Should have dropped out earlier }
  8219. InternalError(2021040710);
  8220. end;
  8221. end;
  8222. end;
  8223. const
  8224. WriteOp: array[0..3] of set of TInsChange = (
  8225. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8226. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8227. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8228. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8229. RegWriteFlags: array[0..7] of set of TInsChange = (
  8230. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8231. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8232. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8233. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8234. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8235. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8236. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8237. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8238. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8239. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8240. var
  8241. hp2: tai;
  8242. X: Integer;
  8243. begin
  8244. { If we have something like:
  8245. op ###,###
  8246. mov ###,###
  8247. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8248. interfere in regards to what they write to.
  8249. NOTE: p must be a 2-operand instruction
  8250. }
  8251. Result := False;
  8252. if (hp1.typ <> ait_instruction) or
  8253. taicpu(hp1).is_jmp or
  8254. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8255. Exit;
  8256. { NOP is a pipeline fence, likely marking the beginning of the function
  8257. epilogue, so drop out. Similarly, drop out if POP or RET are
  8258. encountered }
  8259. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8260. Exit;
  8261. if (taicpu(hp1).opcode = A_MOVSD) and
  8262. (taicpu(hp1).ops = 0) then
  8263. { Wrong MOVSD }
  8264. Exit;
  8265. { Check for writes to specific registers first }
  8266. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8267. for X := 0 to 7 do
  8268. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8269. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8270. Exit;
  8271. for X := 0 to taicpu(hp1).ops - 1 do
  8272. begin
  8273. { Check to see if this operand writes to something }
  8274. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8275. { And matches something in the CMP/TEST instruction }
  8276. (
  8277. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8278. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8279. (
  8280. { If it's a register, make sure the register written to doesn't
  8281. appear in the cmp instruction as part of a reference }
  8282. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8283. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8284. )
  8285. ) then
  8286. Exit;
  8287. end;
  8288. { Check p to make sure it doesn't write to something that affects hp1 }
  8289. { Check for writes to specific registers first }
  8290. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8291. for X := 0 to 7 do
  8292. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8293. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8294. Exit;
  8295. for X := 0 to taicpu(p).ops - 1 do
  8296. begin
  8297. { Check to see if this operand writes to something }
  8298. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8299. { And matches something in hp1 }
  8300. (taicpu(p).oper[X]^.typ = top_reg) and
  8301. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8302. Exit;
  8303. end;
  8304. { The instruction can be safely moved }
  8305. asml.Remove(hp1);
  8306. { Try to insert after the last instructions where the FLAGS register is not
  8307. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8308. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8309. asml.InsertBefore(hp1, hp2)
  8310. { Failing that, try to insert after the last instructions where the
  8311. FLAGS register is not yet in use }
  8312. else if GetLastInstruction(p, hp2) and
  8313. (
  8314. (hp2.typ <> ait_instruction) or
  8315. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8316. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8317. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8318. ) then
  8319. asml.InsertAfter(hp1, hp2)
  8320. else
  8321. { Note, if p.Previous is nil (even if it should logically never be the
  8322. case), FindRegAllocBackward immediately exits with False and so we
  8323. safely land here (we can't just pass p because FindRegAllocBackward
  8324. immediately exits on an instruction). [Kit] }
  8325. asml.InsertBefore(hp1, p);
  8326. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8327. { We can't trust UsedRegs because we're looking backwards, although we
  8328. know the registers are allocated after p at the very least, so manually
  8329. create tai_regalloc objects if needed }
  8330. for X := 0 to taicpu(hp1).ops - 1 do
  8331. case taicpu(hp1).oper[X]^.typ of
  8332. top_reg:
  8333. begin
  8334. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8335. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8336. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8337. end;
  8338. top_ref:
  8339. begin
  8340. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8341. begin
  8342. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8343. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8344. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8345. end;
  8346. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8347. begin
  8348. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8349. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8350. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8351. end;
  8352. end;
  8353. else
  8354. ;
  8355. end;
  8356. Result := True;
  8357. end;
  8358. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8359. var
  8360. hp2: tai;
  8361. X: Integer;
  8362. begin
  8363. { If we have something like:
  8364. cmp ###,%reg1
  8365. mov 0,%reg2
  8366. And no modified registers are shared, move the instruction to before
  8367. the comparison as this means it can be optimised without worrying
  8368. about the FLAGS register. (CMP/MOV is generated by
  8369. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8370. As long as the second instruction doesn't use the flags or one of the
  8371. registers used by CMP or TEST (also check any references that use the
  8372. registers), then it can be moved prior to the comparison.
  8373. }
  8374. Result := False;
  8375. if not TrySwapMovOp(p, hp1) then
  8376. Exit;
  8377. if taicpu(hp1).opcode = A_LEA then
  8378. { The flags will be overwritten by the CMP/TEST instruction }
  8379. ConvertLEA(taicpu(hp1));
  8380. Result := True;
  8381. { Can we move it one further back? }
  8382. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8383. { Check to see if CMP/TEST is a comparison against zero }
  8384. (
  8385. (
  8386. (taicpu(p).opcode = A_CMP) and
  8387. MatchOperand(taicpu(p).oper[0]^, 0)
  8388. ) or
  8389. (
  8390. (taicpu(p).opcode = A_TEST) and
  8391. (
  8392. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8393. MatchOperand(taicpu(p).oper[0]^, -1)
  8394. )
  8395. )
  8396. ) and
  8397. { These instructions set the zero flag if the result is zero }
  8398. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8399. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8400. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8401. TrySwapMovOp(hp2, hp1);
  8402. end;
  8403. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8404. function IsXCHGAcceptable: Boolean; inline;
  8405. begin
  8406. { Always accept if optimising for size }
  8407. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8408. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8409. than 3, so it becomes a saving compared to three MOVs with two of
  8410. them able to execute simultaneously. [Kit] }
  8411. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8412. end;
  8413. var
  8414. NewRef: TReference;
  8415. hp1, hp2, hp3, hp4: Tai;
  8416. {$ifndef x86_64}
  8417. OperIdx: Integer;
  8418. {$endif x86_64}
  8419. NewInstr : Taicpu;
  8420. NewAligh : Tai_align;
  8421. DestLabel: TAsmLabel;
  8422. TempTracking: TAllUsedRegs;
  8423. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8424. var
  8425. NextInstr: tai;
  8426. begin
  8427. Result := False;
  8428. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8429. if not GetNextInstruction(InputInstr, NextInstr) or
  8430. (
  8431. { The FLAGS register isn't always tracked properly, so do not
  8432. perform this optimisation if a conditional statement follows }
  8433. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8434. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8435. ) then
  8436. begin
  8437. reference_reset(NewRef, 1, []);
  8438. NewRef.base := taicpu(p).oper[0]^.reg;
  8439. NewRef.scalefactor := 1;
  8440. if taicpu(InputInstr).opcode = A_ADD then
  8441. begin
  8442. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8443. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8444. end
  8445. else
  8446. begin
  8447. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8448. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8449. end;
  8450. taicpu(p).opcode := A_LEA;
  8451. taicpu(p).loadref(0, NewRef);
  8452. RemoveInstruction(InputInstr);
  8453. Result := True;
  8454. end;
  8455. end;
  8456. begin
  8457. Result:=false;
  8458. { This optimisation adds an instruction, so only do it for speed }
  8459. if not (cs_opt_size in current_settings.optimizerswitches) and
  8460. MatchOpType(taicpu(p), top_const, top_reg) and
  8461. (taicpu(p).oper[0]^.val = 0) then
  8462. begin
  8463. { To avoid compiler warning }
  8464. DestLabel := nil;
  8465. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8466. InternalError(2021040750);
  8467. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8468. Exit;
  8469. case hp1.typ of
  8470. ait_align,
  8471. ait_label:
  8472. begin
  8473. { Change:
  8474. mov $0,%reg mov $0,%reg
  8475. @Lbl1: @Lbl1:
  8476. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8477. je @Lbl2 jne @Lbl2
  8478. To: To:
  8479. mov $0,%reg mov $0,%reg
  8480. jmp @Lbl2 jmp @Lbl3
  8481. (align) (align)
  8482. @Lbl1: @Lbl1:
  8483. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8484. je @Lbl2 je @Lbl2
  8485. @Lbl3: <-- Only if label exists
  8486. (Not if it's optimised for size)
  8487. }
  8488. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8489. Exit;
  8490. if (hp2.typ = ait_instruction) and
  8491. (
  8492. { Register sizes must exactly match }
  8493. (
  8494. (taicpu(hp2).opcode = A_CMP) and
  8495. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8496. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8497. ) or (
  8498. (taicpu(hp2).opcode = A_TEST) and
  8499. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8500. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8501. )
  8502. ) and GetNextInstruction(hp2, hp3) and
  8503. (hp3.typ = ait_instruction) and
  8504. (taicpu(hp3).opcode = A_JCC) and
  8505. (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
  8506. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8507. begin
  8508. { Check condition of jump }
  8509. { Always true? }
  8510. if condition_in(C_E, taicpu(hp3).condition) then
  8511. begin
  8512. { Copy label symbol and obtain matching label entry for the
  8513. conditional jump, as this will be our destination}
  8514. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8515. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8516. Result := True;
  8517. end
  8518. { Always false? }
  8519. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8520. begin
  8521. { This is only worth it if there's a jump to take }
  8522. case hp2.typ of
  8523. ait_instruction:
  8524. begin
  8525. if taicpu(hp2).opcode = A_JMP then
  8526. begin
  8527. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8528. { An unconditional jump follows the conditional jump which will always be false,
  8529. so use this jump's destination for the new jump }
  8530. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8531. Result := True;
  8532. end
  8533. else if taicpu(hp2).opcode = A_JCC then
  8534. begin
  8535. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8536. if condition_in(C_E, taicpu(hp2).condition) then
  8537. begin
  8538. { A second conditional jump follows the conditional jump which will always be false,
  8539. while the second jump is always True, so use this jump's destination for the new jump }
  8540. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8541. Result := True;
  8542. end;
  8543. { Don't risk it if the jump isn't always true (Result remains False) }
  8544. end;
  8545. end;
  8546. else
  8547. { If anything else don't optimise };
  8548. end;
  8549. end;
  8550. if Result then
  8551. begin
  8552. { Just so we have something to insert as a paremeter}
  8553. reference_reset(NewRef, 1, []);
  8554. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8555. { Now actually load the correct parameter (this also
  8556. increases the reference count) }
  8557. NewInstr.loadsymbol(0, DestLabel, 0);
  8558. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8559. begin
  8560. { Get instruction before original label (may not be p under -O3) }
  8561. if not GetLastInstruction(hp1, hp2) then
  8562. { Shouldn't fail here }
  8563. InternalError(2021040701);
  8564. { Before the aligns too }
  8565. while (hp2.typ = ait_align) do
  8566. if not GetLastInstruction(hp2, hp2) then
  8567. { Shouldn't fail here }
  8568. InternalError(2021040702);
  8569. end
  8570. else
  8571. hp2 := p;
  8572. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8573. AsmL.InsertAfter(NewInstr, hp2);
  8574. { Add new alignment field }
  8575. (* AsmL.InsertAfter(
  8576. cai_align.create_max(
  8577. current_settings.alignment.jumpalign,
  8578. current_settings.alignment.jumpalignskipmax
  8579. ),
  8580. NewInstr
  8581. ); *)
  8582. end;
  8583. Exit;
  8584. end;
  8585. end;
  8586. else
  8587. ;
  8588. end;
  8589. end;
  8590. if not GetNextInstruction(p, hp1) then
  8591. Exit;
  8592. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8593. and DoMovCmpMemOpt(p, hp1) then
  8594. begin
  8595. Result := True;
  8596. Exit;
  8597. end
  8598. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8599. begin
  8600. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8601. further, but we can't just put this jump optimisation in pass 1
  8602. because it tends to perform worse when conditional jumps are
  8603. nearby (e.g. when converting CMOV instructions). [Kit] }
  8604. CopyUsedRegs(TempTracking);
  8605. UpdateUsedRegs(tai(p.Next));
  8606. if OptPass2JMP(hp1) then
  8607. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8608. Result := OptPass1MOV(p);
  8609. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8610. returned True and the instruction is still a MOV, thus checking
  8611. the optimisations below }
  8612. { If OptPass2JMP returned False, no optimisations were done to
  8613. the jump and there are no further optimisations that can be done
  8614. to the MOV instruction on this pass }
  8615. { Restore register state }
  8616. RestoreUsedRegs(TempTracking);
  8617. ReleaseUsedRegs(TempTracking);
  8618. end
  8619. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8620. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8621. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8622. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8623. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8624. begin
  8625. { Change:
  8626. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8627. addl/q $x,%reg2 subl/q $x,%reg2
  8628. To:
  8629. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8630. }
  8631. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8632. { be lazy, checking separately for sub would be slightly better }
  8633. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8634. begin
  8635. TransferUsedRegs(TmpUsedRegs);
  8636. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8637. if TryMovArith2Lea(hp1) then
  8638. begin
  8639. Result := True;
  8640. Exit;
  8641. end
  8642. end
  8643. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8644. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8645. { Same as above, but also adds or subtracts to %reg2 in between.
  8646. It's still valid as long as the flags aren't in use }
  8647. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8648. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8649. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8650. { be lazy, checking separately for sub would be slightly better }
  8651. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8652. begin
  8653. TransferUsedRegs(TmpUsedRegs);
  8654. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8655. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8656. if TryMovArith2Lea(hp2) then
  8657. begin
  8658. Result := True;
  8659. Exit;
  8660. end;
  8661. end;
  8662. end
  8663. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8664. {$ifdef x86_64}
  8665. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8666. {$else x86_64}
  8667. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8668. {$endif x86_64}
  8669. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8670. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8671. { mov reg1, reg2 mov reg1, reg2
  8672. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8673. begin
  8674. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8675. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8676. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8677. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8678. TransferUsedRegs(TmpUsedRegs);
  8679. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8680. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8681. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8682. then
  8683. begin
  8684. RemoveCurrentP(p, hp1);
  8685. Result:=true;
  8686. end;
  8687. exit;
  8688. end
  8689. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8690. IsXCHGAcceptable and
  8691. { XCHG doesn't support 8-byte registers }
  8692. (taicpu(p).opsize <> S_B) and
  8693. MatchInstruction(hp1, A_MOV, []) and
  8694. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8695. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8696. GetNextInstruction(hp1, hp2) and
  8697. MatchInstruction(hp2, A_MOV, []) and
  8698. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8699. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8700. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8701. begin
  8702. { mov %reg1,%reg2
  8703. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8704. mov %reg2,%reg3
  8705. (%reg2 not used afterwards)
  8706. Note that xchg takes 3 cycles to execute, and generally mov's take
  8707. only one cycle apiece, but the first two mov's can be executed in
  8708. parallel, only taking 2 cycles overall. Older processors should
  8709. therefore only optimise for size. [Kit]
  8710. }
  8711. TransferUsedRegs(TmpUsedRegs);
  8712. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8713. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8714. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8715. begin
  8716. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8717. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8718. taicpu(hp1).opcode := A_XCHG;
  8719. RemoveCurrentP(p, hp1);
  8720. RemoveInstruction(hp2);
  8721. Result := True;
  8722. Exit;
  8723. end;
  8724. end
  8725. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8726. MatchInstruction(hp1, A_SAR, []) then
  8727. begin
  8728. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8729. begin
  8730. { the use of %edx also covers the opsize being S_L }
  8731. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8732. begin
  8733. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8734. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8735. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8736. begin
  8737. { Change:
  8738. movl %eax,%edx
  8739. sarl $31,%edx
  8740. To:
  8741. cltd
  8742. }
  8743. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8744. RemoveInstruction(hp1);
  8745. taicpu(p).opcode := A_CDQ;
  8746. taicpu(p).opsize := S_NO;
  8747. taicpu(p).clearop(1);
  8748. taicpu(p).clearop(0);
  8749. taicpu(p).ops:=0;
  8750. Result := True;
  8751. end
  8752. else if (cs_opt_size in current_settings.optimizerswitches) and
  8753. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8754. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8755. begin
  8756. { Change:
  8757. movl %edx,%eax
  8758. sarl $31,%edx
  8759. To:
  8760. movl %edx,%eax
  8761. cltd
  8762. Note that this creates a dependency between the two instructions,
  8763. so only perform if optimising for size.
  8764. }
  8765. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8766. taicpu(hp1).opcode := A_CDQ;
  8767. taicpu(hp1).opsize := S_NO;
  8768. taicpu(hp1).clearop(1);
  8769. taicpu(hp1).clearop(0);
  8770. taicpu(hp1).ops:=0;
  8771. end;
  8772. {$ifndef x86_64}
  8773. end
  8774. { Don't bother if CMOV is supported, because a more optimal
  8775. sequence would have been generated for the Abs() intrinsic }
  8776. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8777. { the use of %eax also covers the opsize being S_L }
  8778. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8779. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8780. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8781. GetNextInstruction(hp1, hp2) and
  8782. MatchInstruction(hp2, A_XOR, [S_L]) and
  8783. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8784. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8785. GetNextInstruction(hp2, hp3) and
  8786. MatchInstruction(hp3, A_SUB, [S_L]) and
  8787. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8788. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8789. begin
  8790. { Change:
  8791. movl %eax,%edx
  8792. sarl $31,%eax
  8793. xorl %eax,%edx
  8794. subl %eax,%edx
  8795. (Instruction that uses %edx)
  8796. (%eax deallocated)
  8797. (%edx deallocated)
  8798. To:
  8799. cltd
  8800. xorl %edx,%eax <-- Note the registers have swapped
  8801. subl %edx,%eax
  8802. (Instruction that uses %eax) <-- %eax rather than %edx
  8803. }
  8804. TransferUsedRegs(TmpUsedRegs);
  8805. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8806. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8807. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8808. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8809. begin
  8810. if GetNextInstruction(hp3, hp4) and
  8811. not RegModifiedByInstruction(NR_EDX, hp4) and
  8812. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8813. begin
  8814. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8815. taicpu(p).opcode := A_CDQ;
  8816. taicpu(p).clearop(1);
  8817. taicpu(p).clearop(0);
  8818. taicpu(p).ops:=0;
  8819. RemoveInstruction(hp1);
  8820. taicpu(hp2).loadreg(0, NR_EDX);
  8821. taicpu(hp2).loadreg(1, NR_EAX);
  8822. taicpu(hp3).loadreg(0, NR_EDX);
  8823. taicpu(hp3).loadreg(1, NR_EAX);
  8824. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8825. { Convert references in the following instruction (hp4) from %edx to %eax }
  8826. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8827. with taicpu(hp4).oper[OperIdx]^ do
  8828. case typ of
  8829. top_reg:
  8830. if getsupreg(reg) = RS_EDX then
  8831. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8832. top_ref:
  8833. begin
  8834. if getsupreg(reg) = RS_EDX then
  8835. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8836. if getsupreg(reg) = RS_EDX then
  8837. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8838. end;
  8839. else
  8840. ;
  8841. end;
  8842. end;
  8843. end;
  8844. {$else x86_64}
  8845. end;
  8846. end
  8847. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8848. { the use of %rdx also covers the opsize being S_Q }
  8849. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8850. begin
  8851. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8852. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8853. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8854. begin
  8855. { Change:
  8856. movq %rax,%rdx
  8857. sarq $63,%rdx
  8858. To:
  8859. cqto
  8860. }
  8861. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8862. RemoveInstruction(hp1);
  8863. taicpu(p).opcode := A_CQO;
  8864. taicpu(p).opsize := S_NO;
  8865. taicpu(p).clearop(1);
  8866. taicpu(p).clearop(0);
  8867. taicpu(p).ops:=0;
  8868. Result := True;
  8869. end
  8870. else if (cs_opt_size in current_settings.optimizerswitches) and
  8871. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8872. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8873. begin
  8874. { Change:
  8875. movq %rdx,%rax
  8876. sarq $63,%rdx
  8877. To:
  8878. movq %rdx,%rax
  8879. cqto
  8880. Note that this creates a dependency between the two instructions,
  8881. so only perform if optimising for size.
  8882. }
  8883. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8884. taicpu(hp1).opcode := A_CQO;
  8885. taicpu(hp1).opsize := S_NO;
  8886. taicpu(hp1).clearop(1);
  8887. taicpu(hp1).clearop(0);
  8888. taicpu(hp1).ops:=0;
  8889. {$endif x86_64}
  8890. end;
  8891. end;
  8892. end
  8893. else if MatchInstruction(hp1, A_MOV, []) and
  8894. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8895. { Though "GetNextInstruction" could be factored out, along with
  8896. the instructions that depend on hp2, it is an expensive call that
  8897. should be delayed for as long as possible, hence we do cheaper
  8898. checks first that are likely to be False. [Kit] }
  8899. begin
  8900. if (
  8901. (
  8902. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8903. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8904. (
  8905. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8906. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8907. )
  8908. ) or
  8909. (
  8910. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8911. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8912. (
  8913. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8914. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8915. )
  8916. )
  8917. ) and
  8918. GetNextInstruction(hp1, hp2) and
  8919. MatchInstruction(hp2, A_SAR, []) and
  8920. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8921. begin
  8922. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8923. begin
  8924. { Change:
  8925. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8926. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8927. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8928. To:
  8929. movl r/m,%eax <- Note the change in register
  8930. cltd
  8931. }
  8932. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8933. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8934. taicpu(p).loadreg(1, NR_EAX);
  8935. taicpu(hp1).opcode := A_CDQ;
  8936. taicpu(hp1).clearop(1);
  8937. taicpu(hp1).clearop(0);
  8938. taicpu(hp1).ops:=0;
  8939. RemoveInstruction(hp2);
  8940. (*
  8941. {$ifdef x86_64}
  8942. end
  8943. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8944. { This code sequence does not get generated - however it might become useful
  8945. if and when 128-bit signed integer types make an appearance, so the code
  8946. is kept here for when it is eventually needed. [Kit] }
  8947. (
  8948. (
  8949. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8950. (
  8951. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8952. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8953. )
  8954. ) or
  8955. (
  8956. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8957. (
  8958. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8959. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8960. )
  8961. )
  8962. ) and
  8963. GetNextInstruction(hp1, hp2) and
  8964. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8965. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8966. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8967. begin
  8968. { Change:
  8969. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8970. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8971. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8972. To:
  8973. movq r/m,%rax <- Note the change in register
  8974. cqto
  8975. }
  8976. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8977. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8978. taicpu(p).loadreg(1, NR_RAX);
  8979. taicpu(hp1).opcode := A_CQO;
  8980. taicpu(hp1).clearop(1);
  8981. taicpu(hp1).clearop(0);
  8982. taicpu(hp1).ops:=0;
  8983. RemoveInstruction(hp2);
  8984. {$endif x86_64}
  8985. *)
  8986. end;
  8987. end;
  8988. {$ifdef x86_64}
  8989. end
  8990. else if (taicpu(p).opsize = S_L) and
  8991. (taicpu(p).oper[1]^.typ = top_reg) and
  8992. (
  8993. MatchInstruction(hp1, A_MOV,[]) and
  8994. (taicpu(hp1).opsize = S_L) and
  8995. (taicpu(hp1).oper[1]^.typ = top_reg)
  8996. ) and (
  8997. GetNextInstruction(hp1, hp2) and
  8998. (tai(hp2).typ=ait_instruction) and
  8999. (taicpu(hp2).opsize = S_Q) and
  9000. (
  9001. (
  9002. MatchInstruction(hp2, A_ADD,[]) and
  9003. (taicpu(hp2).opsize = S_Q) and
  9004. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9005. (
  9006. (
  9007. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9008. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9009. ) or (
  9010. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9011. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9012. )
  9013. )
  9014. ) or (
  9015. MatchInstruction(hp2, A_LEA,[]) and
  9016. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9017. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9018. (
  9019. (
  9020. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9021. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9022. ) or (
  9023. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9024. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9025. )
  9026. ) and (
  9027. (
  9028. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9029. ) or (
  9030. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9031. )
  9032. )
  9033. )
  9034. )
  9035. ) and (
  9036. GetNextInstruction(hp2, hp3) and
  9037. MatchInstruction(hp3, A_SHR,[]) and
  9038. (taicpu(hp3).opsize = S_Q) and
  9039. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9040. (taicpu(hp3).oper[0]^.val = 1) and
  9041. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9042. ) then
  9043. begin
  9044. { Change movl x, reg1d movl x, reg1d
  9045. movl y, reg2d movl y, reg2d
  9046. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9047. shrq $1, reg1q shrq $1, reg1q
  9048. ( reg1d and reg2d can be switched around in the first two instructions )
  9049. To movl x, reg1d
  9050. addl y, reg1d
  9051. rcrl $1, reg1d
  9052. This corresponds to the common expression (x + y) shr 1, where
  9053. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9054. smaller code, but won't account for x + y causing an overflow). [Kit]
  9055. }
  9056. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9057. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9058. { Change first MOV command to have the same register as the final output }
  9059. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9060. else
  9061. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9062. { Change second MOV command to an ADD command. This is easier than
  9063. converting the existing command because it means we don't have to
  9064. touch 'y', which might be a complicated reference, and also the
  9065. fact that the third command might either be ADD or LEA. [Kit] }
  9066. taicpu(hp1).opcode := A_ADD;
  9067. { Delete old ADD/LEA instruction }
  9068. RemoveInstruction(hp2);
  9069. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9070. taicpu(hp3).opcode := A_RCR;
  9071. taicpu(hp3).changeopsize(S_L);
  9072. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9073. {$endif x86_64}
  9074. end;
  9075. if FuncMov2Func(p, hp1) then
  9076. begin
  9077. Result := True;
  9078. Exit;
  9079. end;
  9080. end;
  9081. {$push}
  9082. {$q-}{$r-}
  9083. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9084. var
  9085. ThisReg: TRegister;
  9086. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9087. TargetSubReg: TSubRegister;
  9088. hp1, hp2: tai;
  9089. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9090. { Store list of found instructions so we don't have to call
  9091. GetNextInstructionUsingReg multiple times }
  9092. InstrList: array of taicpu;
  9093. InstrMax, Index: Integer;
  9094. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9095. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9096. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9097. WorkingValue: TCgInt;
  9098. PreMessage: string;
  9099. { Data flow analysis }
  9100. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9101. BitwiseOnly, OrXorUsed,
  9102. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9103. function CheckOverflowConditions: Boolean;
  9104. begin
  9105. Result := True;
  9106. if (TestValSignedMax > SignedUpperLimit) then
  9107. UpperSignedOverflow := True;
  9108. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9109. LowerSignedOverflow := True;
  9110. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9111. LowerUnsignedOverflow := True;
  9112. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9113. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9114. begin
  9115. { Absolute overflow }
  9116. Result := False;
  9117. Exit;
  9118. end;
  9119. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9120. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9121. ShiftDownOverflow := True;
  9122. if (TestValMin < 0) or (TestValMax < 0) then
  9123. begin
  9124. LowerUnsignedOverflow := True;
  9125. UpperUnsignedOverflow := True;
  9126. end;
  9127. end;
  9128. function AdjustInitialLoadAndSize: Boolean;
  9129. begin
  9130. Result := False;
  9131. if not p_removed then
  9132. begin
  9133. if TargetSize = MinSize then
  9134. begin
  9135. { Convert the input MOVZX to a MOV }
  9136. if (taicpu(p).oper[0]^.typ = top_reg) and
  9137. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9138. begin
  9139. { Or remove it completely! }
  9140. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9141. RemoveCurrentP(p);
  9142. p_removed := True;
  9143. end
  9144. else
  9145. begin
  9146. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9147. taicpu(p).opcode := A_MOV;
  9148. taicpu(p).oper[1]^.reg := ThisReg;
  9149. taicpu(p).opsize := TargetSize;
  9150. end;
  9151. Result := True;
  9152. end
  9153. else if TargetSize <> MaxSize then
  9154. begin
  9155. case MaxSize of
  9156. S_L:
  9157. if TargetSize = S_W then
  9158. begin
  9159. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9160. taicpu(p).opsize := S_BW;
  9161. taicpu(p).oper[1]^.reg := ThisReg;
  9162. Result := True;
  9163. end
  9164. else
  9165. InternalError(2020112341);
  9166. S_W:
  9167. if TargetSize = S_L then
  9168. begin
  9169. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9170. taicpu(p).opsize := S_BL;
  9171. taicpu(p).oper[1]^.reg := ThisReg;
  9172. Result := True;
  9173. end
  9174. else
  9175. InternalError(2020112342);
  9176. else
  9177. ;
  9178. end;
  9179. end
  9180. else if not hp1_removed and not RegInUse then
  9181. begin
  9182. { If we have something like:
  9183. movzbl (oper),%regd
  9184. add x, %regd
  9185. movzbl %regb, %regd
  9186. We can reduce the register size to the input of the final
  9187. movzbl instruction. Overflows won't have any effect.
  9188. }
  9189. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9190. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9191. begin
  9192. TargetSize := S_B;
  9193. setsubreg(ThisReg, R_SUBL);
  9194. Result := True;
  9195. end
  9196. else if (taicpu(p).opsize = S_WL) and
  9197. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9198. begin
  9199. TargetSize := S_W;
  9200. setsubreg(ThisReg, R_SUBW);
  9201. Result := True;
  9202. end;
  9203. if Result then
  9204. begin
  9205. { Convert the input MOVZX to a MOV }
  9206. if (taicpu(p).oper[0]^.typ = top_reg) and
  9207. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9208. begin
  9209. { Or remove it completely! }
  9210. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9211. RemoveCurrentP(p);
  9212. p_removed := True;
  9213. end
  9214. else
  9215. begin
  9216. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9217. taicpu(p).opcode := A_MOV;
  9218. taicpu(p).oper[1]^.reg := ThisReg;
  9219. taicpu(p).opsize := TargetSize;
  9220. end;
  9221. end;
  9222. end;
  9223. end;
  9224. end;
  9225. procedure AdjustFinalLoad;
  9226. begin
  9227. if not LowerUnsignedOverflow then
  9228. begin
  9229. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9230. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9231. begin
  9232. { Convert the output MOVZX to a MOV }
  9233. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9234. begin
  9235. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9236. if (MinSize = S_B) or
  9237. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9238. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9239. begin
  9240. { Remove it completely! }
  9241. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9242. { Be careful; if p = hp1 and p was also removed, p
  9243. will become a dangling pointer }
  9244. if p = hp1 then
  9245. begin
  9246. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9247. p_removed := True;
  9248. end
  9249. else
  9250. RemoveInstruction(hp1);
  9251. hp1_removed := True;
  9252. end;
  9253. end
  9254. else
  9255. begin
  9256. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9257. taicpu(hp1).opcode := A_MOV;
  9258. taicpu(hp1).oper[0]^.reg := ThisReg;
  9259. taicpu(hp1).opsize := TargetSize;
  9260. end;
  9261. end
  9262. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9263. begin
  9264. { Need to change the size of the output }
  9265. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9266. taicpu(hp1).oper[0]^.reg := ThisReg;
  9267. taicpu(hp1).opsize := S_BL;
  9268. end;
  9269. end;
  9270. end;
  9271. function CompressInstructions: Boolean;
  9272. var
  9273. LocalIndex: Integer;
  9274. begin
  9275. Result := False;
  9276. { The objective here is to try to find a combination that
  9277. removes one of the MOV/Z instructions. }
  9278. if (
  9279. (taicpu(p).oper[0]^.typ <> top_reg) or
  9280. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9281. ) and
  9282. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9283. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9284. begin
  9285. { Make a preference to remove the second MOVZX instruction }
  9286. case taicpu(hp1).opsize of
  9287. S_BL, S_WL:
  9288. begin
  9289. TargetSize := S_L;
  9290. TargetSubReg := R_SUBD;
  9291. end;
  9292. S_BW:
  9293. begin
  9294. TargetSize := S_W;
  9295. TargetSubReg := R_SUBW;
  9296. end;
  9297. else
  9298. InternalError(2020112302);
  9299. end;
  9300. end
  9301. else
  9302. begin
  9303. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9304. begin
  9305. { Exceeded lower bound but not upper bound }
  9306. TargetSize := MaxSize;
  9307. end
  9308. else if not LowerUnsignedOverflow then
  9309. begin
  9310. { Size didn't exceed lower bound }
  9311. TargetSize := MinSize;
  9312. end
  9313. else
  9314. Exit;
  9315. end;
  9316. case TargetSize of
  9317. S_B:
  9318. TargetSubReg := R_SUBL;
  9319. S_W:
  9320. TargetSubReg := R_SUBW;
  9321. S_L:
  9322. TargetSubReg := R_SUBD;
  9323. else
  9324. InternalError(2020112350);
  9325. end;
  9326. { Update the register to its new size }
  9327. setsubreg(ThisReg, TargetSubReg);
  9328. RegInUse := False;
  9329. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9330. begin
  9331. { Check to see if the active register is used afterwards;
  9332. if not, we can change it and make a saving. }
  9333. TransferUsedRegs(TmpUsedRegs);
  9334. { The target register may be marked as in use to cross
  9335. a jump to a distant label, so exclude it }
  9336. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9337. hp2 := p;
  9338. repeat
  9339. { Explicitly check for the excluded register (don't include the first
  9340. instruction as it may be reading from here }
  9341. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9342. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9343. begin
  9344. RegInUse := True;
  9345. Break;
  9346. end;
  9347. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9348. if not GetNextInstruction(hp2, hp2) then
  9349. InternalError(2020112340);
  9350. until (hp2 = hp1);
  9351. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9352. { We might still be able to get away with this }
  9353. RegInUse := not
  9354. (
  9355. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9356. (hp2.typ = ait_instruction) and
  9357. (
  9358. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9359. instruction that doesn't actually contain ThisReg }
  9360. (cs_opt_level3 in current_settings.optimizerswitches) or
  9361. RegInInstruction(ThisReg, hp2)
  9362. ) and
  9363. RegLoadedWithNewValue(ThisReg, hp2)
  9364. );
  9365. if not RegInUse then
  9366. begin
  9367. { Force the register size to the same as this instruction so it can be removed}
  9368. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9369. begin
  9370. TargetSize := S_L;
  9371. TargetSubReg := R_SUBD;
  9372. end
  9373. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9374. begin
  9375. TargetSize := S_W;
  9376. TargetSubReg := R_SUBW;
  9377. end;
  9378. ThisReg := taicpu(hp1).oper[1]^.reg;
  9379. setsubreg(ThisReg, TargetSubReg);
  9380. RegChanged := True;
  9381. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9382. TransferUsedRegs(TmpUsedRegs);
  9383. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9384. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9385. if p = hp1 then
  9386. begin
  9387. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9388. p_removed := True;
  9389. end
  9390. else
  9391. RemoveInstruction(hp1);
  9392. hp1_removed := True;
  9393. { Instruction will become "mov %reg,%reg" }
  9394. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9395. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9396. begin
  9397. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9398. RemoveCurrentP(p);
  9399. p_removed := True;
  9400. end
  9401. else
  9402. taicpu(p).oper[1]^.reg := ThisReg;
  9403. Result := True;
  9404. end
  9405. else
  9406. begin
  9407. if TargetSize <> MaxSize then
  9408. begin
  9409. { Since the register is in use, we have to force it to
  9410. MaxSize otherwise part of it may become undefined later on }
  9411. TargetSize := MaxSize;
  9412. case TargetSize of
  9413. S_B:
  9414. TargetSubReg := R_SUBL;
  9415. S_W:
  9416. TargetSubReg := R_SUBW;
  9417. S_L:
  9418. TargetSubReg := R_SUBD;
  9419. else
  9420. InternalError(2020112351);
  9421. end;
  9422. setsubreg(ThisReg, TargetSubReg);
  9423. end;
  9424. AdjustFinalLoad;
  9425. end;
  9426. end
  9427. else
  9428. AdjustFinalLoad;
  9429. Result := AdjustInitialLoadAndSize or Result;
  9430. { Now go through every instruction we found and change the
  9431. size. If TargetSize = MaxSize, then almost no changes are
  9432. needed and Result can remain False if it hasn't been set
  9433. yet.
  9434. If RegChanged is True, then the register requires changing
  9435. and so the point about TargetSize = MaxSize doesn't apply. }
  9436. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9437. begin
  9438. for LocalIndex := 0 to InstrMax do
  9439. begin
  9440. { If p_removed is true, then the original MOV/Z was removed
  9441. and removing the AND instruction may not be safe if it
  9442. appears first }
  9443. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9444. InternalError(2020112310);
  9445. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9446. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9447. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9448. InstrList[LocalIndex].opsize := TargetSize;
  9449. end;
  9450. Result := True;
  9451. end;
  9452. end;
  9453. begin
  9454. Result := False;
  9455. p_removed := False;
  9456. hp1_removed := False;
  9457. ThisReg := taicpu(p).oper[1]^.reg;
  9458. { Check for:
  9459. movs/z ###,%ecx (or %cx or %rcx)
  9460. ...
  9461. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9462. (dealloc %ecx)
  9463. Change to:
  9464. mov ###,%cl (if ### = %cl, then remove completely)
  9465. ...
  9466. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9467. }
  9468. if (getsupreg(ThisReg) = RS_ECX) and
  9469. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9470. (hp1.typ = ait_instruction) and
  9471. (
  9472. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9473. instruction that doesn't actually contain ECX }
  9474. (cs_opt_level3 in current_settings.optimizerswitches) or
  9475. RegInInstruction(NR_ECX, hp1) or
  9476. (
  9477. { It's common for the shift/rotate's read/write register to be
  9478. initialised in between, so under -O2 and under, search ahead
  9479. one more instruction
  9480. }
  9481. GetNextInstruction(hp1, hp1) and
  9482. (hp1.typ = ait_instruction) and
  9483. RegInInstruction(NR_ECX, hp1)
  9484. )
  9485. ) and
  9486. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9487. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9488. begin
  9489. TransferUsedRegs(TmpUsedRegs);
  9490. hp2 := p;
  9491. repeat
  9492. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9493. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9494. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9495. begin
  9496. case taicpu(p).opsize of
  9497. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9498. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9499. begin
  9500. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9501. RemoveCurrentP(p);
  9502. end
  9503. else
  9504. begin
  9505. taicpu(p).opcode := A_MOV;
  9506. taicpu(p).opsize := S_B;
  9507. taicpu(p).oper[1]^.reg := NR_CL;
  9508. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9509. end;
  9510. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9511. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9512. begin
  9513. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9514. RemoveCurrentP(p);
  9515. end
  9516. else
  9517. begin
  9518. taicpu(p).opcode := A_MOV;
  9519. taicpu(p).opsize := S_W;
  9520. taicpu(p).oper[1]^.reg := NR_CX;
  9521. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9522. end;
  9523. {$ifdef x86_64}
  9524. S_LQ:
  9525. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9526. begin
  9527. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9528. RemoveCurrentP(p);
  9529. end
  9530. else
  9531. begin
  9532. taicpu(p).opcode := A_MOV;
  9533. taicpu(p).opsize := S_L;
  9534. taicpu(p).oper[1]^.reg := NR_ECX;
  9535. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9536. end;
  9537. {$endif x86_64}
  9538. else
  9539. InternalError(2021120401);
  9540. end;
  9541. Result := True;
  9542. Exit;
  9543. end;
  9544. end;
  9545. { This is anything but quick! }
  9546. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9547. Exit;
  9548. SetLength(InstrList, 0);
  9549. InstrMax := -1;
  9550. case taicpu(p).opsize of
  9551. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9552. begin
  9553. {$if defined(i386) or defined(i8086)}
  9554. { If the target size is 8-bit, make sure we can actually encode it }
  9555. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9556. Exit;
  9557. {$endif i386 or i8086}
  9558. LowerLimit := $FF;
  9559. SignedLowerLimit := $7F;
  9560. SignedLowerLimitBottom := -128;
  9561. MinSize := S_B;
  9562. if taicpu(p).opsize = S_BW then
  9563. begin
  9564. MaxSize := S_W;
  9565. UpperLimit := $FFFF;
  9566. SignedUpperLimit := $7FFF;
  9567. SignedUpperLimitBottom := -32768;
  9568. end
  9569. else
  9570. begin
  9571. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9572. MaxSize := S_L;
  9573. UpperLimit := $FFFFFFFF;
  9574. SignedUpperLimit := $7FFFFFFF;
  9575. SignedUpperLimitBottom := -2147483648;
  9576. end;
  9577. end;
  9578. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9579. begin
  9580. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9581. LowerLimit := $FFFF;
  9582. SignedLowerLimit := $7FFF;
  9583. SignedLowerLimitBottom := -32768;
  9584. UpperLimit := $FFFFFFFF;
  9585. SignedUpperLimit := $7FFFFFFF;
  9586. SignedUpperLimitBottom := -2147483648;
  9587. MinSize := S_W;
  9588. MaxSize := S_L;
  9589. end;
  9590. {$ifdef x86_64}
  9591. S_LQ:
  9592. begin
  9593. { Both the lower and upper limits are set to 32-bit. If a limit
  9594. is breached, then optimisation is impossible }
  9595. LowerLimit := $FFFFFFFF;
  9596. SignedLowerLimit := $7FFFFFFF;
  9597. SignedLowerLimitBottom := -2147483648;
  9598. UpperLimit := $FFFFFFFF;
  9599. SignedUpperLimit := $7FFFFFFF;
  9600. SignedUpperLimitBottom := -2147483648;
  9601. MinSize := S_L;
  9602. MaxSize := S_L;
  9603. end;
  9604. {$endif x86_64}
  9605. else
  9606. InternalError(2020112301);
  9607. end;
  9608. TestValMin := 0;
  9609. TestValMax := LowerLimit;
  9610. TestValSignedMax := SignedLowerLimit;
  9611. TryShiftDownLimit := LowerLimit;
  9612. TryShiftDown := S_NO;
  9613. ShiftDownOverflow := False;
  9614. RegChanged := False;
  9615. BitwiseOnly := True;
  9616. OrXorUsed := False;
  9617. UpperSignedOverflow := False;
  9618. LowerSignedOverflow := False;
  9619. UpperUnsignedOverflow := False;
  9620. LowerUnsignedOverflow := False;
  9621. hp1 := p;
  9622. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9623. (hp1.typ = ait_instruction) and
  9624. (
  9625. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9626. instruction that doesn't actually contain ThisReg }
  9627. (cs_opt_level3 in current_settings.optimizerswitches) or
  9628. { This allows this Movx optimisation to work through the SETcc instructions
  9629. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9630. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9631. skip over these SETcc instructions). }
  9632. (taicpu(hp1).opcode = A_SETcc) or
  9633. RegInInstruction(ThisReg, hp1)
  9634. ) do
  9635. begin
  9636. case taicpu(hp1).opcode of
  9637. A_INC,A_DEC:
  9638. begin
  9639. { Has to be an exact match on the register }
  9640. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9641. Break;
  9642. if taicpu(hp1).opcode = A_INC then
  9643. begin
  9644. Inc(TestValMin);
  9645. Inc(TestValMax);
  9646. Inc(TestValSignedMax);
  9647. end
  9648. else
  9649. begin
  9650. Dec(TestValMin);
  9651. Dec(TestValMax);
  9652. Dec(TestValSignedMax);
  9653. end;
  9654. end;
  9655. A_TEST, A_CMP:
  9656. begin
  9657. if (
  9658. { Too high a risk of non-linear behaviour that breaks DFA
  9659. here, unless it's cmp $0,%reg, which is equivalent to
  9660. test %reg,%reg }
  9661. OrXorUsed and
  9662. (taicpu(hp1).opcode = A_CMP) and
  9663. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9664. ) or
  9665. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9666. { Has to be an exact match on the register }
  9667. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9668. (
  9669. { Permit "test %reg,%reg" }
  9670. (taicpu(hp1).opcode = A_TEST) and
  9671. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9672. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9673. ) or
  9674. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9675. { Make sure the comparison value is not smaller than the
  9676. smallest allowed signed value for the minimum size (e.g.
  9677. -128 for 8-bit) }
  9678. not (
  9679. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9680. { Is it in the negative range? }
  9681. (
  9682. (taicpu(hp1).oper[0]^.val < 0) and
  9683. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9684. )
  9685. ) then
  9686. Break;
  9687. { Check to see if the active register is used afterwards }
  9688. TransferUsedRegs(TmpUsedRegs);
  9689. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9690. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9691. begin
  9692. { Make sure the comparison or any previous instructions
  9693. hasn't pushed the test values outside of the range of
  9694. MinSize }
  9695. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9696. begin
  9697. { Exceeded lower bound but not upper bound }
  9698. Exit;
  9699. end
  9700. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9701. begin
  9702. { Size didn't exceed lower bound }
  9703. TargetSize := MinSize;
  9704. end
  9705. else
  9706. Break;
  9707. case TargetSize of
  9708. S_B:
  9709. TargetSubReg := R_SUBL;
  9710. S_W:
  9711. TargetSubReg := R_SUBW;
  9712. S_L:
  9713. TargetSubReg := R_SUBD;
  9714. else
  9715. InternalError(2021051002);
  9716. end;
  9717. if TargetSize <> MaxSize then
  9718. begin
  9719. { Update the register to its new size }
  9720. setsubreg(ThisReg, TargetSubReg);
  9721. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9722. taicpu(hp1).oper[1]^.reg := ThisReg;
  9723. taicpu(hp1).opsize := TargetSize;
  9724. { Convert the input MOVZX to a MOV if necessary }
  9725. AdjustInitialLoadAndSize;
  9726. if (InstrMax >= 0) then
  9727. begin
  9728. for Index := 0 to InstrMax do
  9729. begin
  9730. { If p_removed is true, then the original MOV/Z was removed
  9731. and removing the AND instruction may not be safe if it
  9732. appears first }
  9733. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9734. InternalError(2020112311);
  9735. if InstrList[Index].oper[0]^.typ = top_reg then
  9736. InstrList[Index].oper[0]^.reg := ThisReg;
  9737. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9738. InstrList[Index].opsize := MinSize;
  9739. end;
  9740. end;
  9741. Result := True;
  9742. end;
  9743. Exit;
  9744. end;
  9745. end;
  9746. A_SETcc:
  9747. begin
  9748. { This allows this Movx optimisation to work through the SETcc instructions
  9749. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9750. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9751. skip over these SETcc instructions). }
  9752. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9753. { Of course, break out if the current register is used }
  9754. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9755. Break
  9756. else
  9757. { We must use Continue so the instruction doesn't get added
  9758. to InstrList }
  9759. Continue;
  9760. end;
  9761. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9762. begin
  9763. if
  9764. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9765. { Has to be an exact match on the register }
  9766. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9767. (
  9768. (
  9769. (taicpu(hp1).oper[0]^.typ = top_const) and
  9770. (
  9771. (
  9772. (taicpu(hp1).opcode = A_SHL) and
  9773. (
  9774. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9775. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9776. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9777. )
  9778. ) or (
  9779. (taicpu(hp1).opcode <> A_SHL) and
  9780. (
  9781. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9782. { Is it in the negative range? }
  9783. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9784. )
  9785. )
  9786. )
  9787. ) or (
  9788. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9789. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9790. )
  9791. ) then
  9792. Break;
  9793. { Only process OR and XOR if there are only bitwise operations,
  9794. since otherwise they can too easily fool the data flow
  9795. analysis (they can cause non-linear behaviour) }
  9796. case taicpu(hp1).opcode of
  9797. A_ADD:
  9798. begin
  9799. if OrXorUsed then
  9800. { Too high a risk of non-linear behaviour that breaks DFA here }
  9801. Break
  9802. else
  9803. BitwiseOnly := False;
  9804. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9805. begin
  9806. TestValMin := TestValMin * 2;
  9807. TestValMax := TestValMax * 2;
  9808. TestValSignedMax := TestValSignedMax * 2;
  9809. end
  9810. else
  9811. begin
  9812. WorkingValue := taicpu(hp1).oper[0]^.val;
  9813. TestValMin := TestValMin + WorkingValue;
  9814. TestValMax := TestValMax + WorkingValue;
  9815. TestValSignedMax := TestValSignedMax + WorkingValue;
  9816. end;
  9817. end;
  9818. A_SUB:
  9819. begin
  9820. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9821. begin
  9822. TestValMin := 0;
  9823. TestValMax := 0;
  9824. TestValSignedMax := 0;
  9825. end
  9826. else
  9827. begin
  9828. if OrXorUsed then
  9829. { Too high a risk of non-linear behaviour that breaks DFA here }
  9830. Break
  9831. else
  9832. BitwiseOnly := False;
  9833. WorkingValue := taicpu(hp1).oper[0]^.val;
  9834. TestValMin := TestValMin - WorkingValue;
  9835. TestValMax := TestValMax - WorkingValue;
  9836. TestValSignedMax := TestValSignedMax - WorkingValue;
  9837. end;
  9838. end;
  9839. A_AND:
  9840. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9841. begin
  9842. { we might be able to go smaller if AND appears first }
  9843. if InstrMax = -1 then
  9844. case MinSize of
  9845. S_B:
  9846. ;
  9847. S_W:
  9848. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9849. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9850. begin
  9851. TryShiftDown := S_B;
  9852. TryShiftDownLimit := $FF;
  9853. end;
  9854. S_L:
  9855. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9856. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9857. begin
  9858. TryShiftDown := S_B;
  9859. TryShiftDownLimit := $FF;
  9860. end
  9861. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9862. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9863. begin
  9864. TryShiftDown := S_W;
  9865. TryShiftDownLimit := $FFFF;
  9866. end;
  9867. else
  9868. InternalError(2020112320);
  9869. end;
  9870. WorkingValue := taicpu(hp1).oper[0]^.val;
  9871. TestValMin := TestValMin and WorkingValue;
  9872. TestValMax := TestValMax and WorkingValue;
  9873. TestValSignedMax := TestValSignedMax and WorkingValue;
  9874. end;
  9875. A_OR:
  9876. begin
  9877. if not BitwiseOnly then
  9878. Break;
  9879. OrXorUsed := True;
  9880. WorkingValue := taicpu(hp1).oper[0]^.val;
  9881. TestValMin := TestValMin or WorkingValue;
  9882. TestValMax := TestValMax or WorkingValue;
  9883. TestValSignedMax := TestValSignedMax or WorkingValue;
  9884. end;
  9885. A_XOR:
  9886. begin
  9887. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9888. begin
  9889. TestValMin := 0;
  9890. TestValMax := 0;
  9891. TestValSignedMax := 0;
  9892. end
  9893. else
  9894. begin
  9895. if not BitwiseOnly then
  9896. Break;
  9897. OrXorUsed := True;
  9898. WorkingValue := taicpu(hp1).oper[0]^.val;
  9899. TestValMin := TestValMin xor WorkingValue;
  9900. TestValMax := TestValMax xor WorkingValue;
  9901. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9902. end;
  9903. end;
  9904. A_SHL:
  9905. begin
  9906. BitwiseOnly := False;
  9907. WorkingValue := taicpu(hp1).oper[0]^.val;
  9908. TestValMin := TestValMin shl WorkingValue;
  9909. TestValMax := TestValMax shl WorkingValue;
  9910. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9911. end;
  9912. A_SHR,
  9913. { The first instruction was MOVZX, so the value won't be negative }
  9914. A_SAR:
  9915. begin
  9916. if InstrMax <> -1 then
  9917. BitwiseOnly := False
  9918. else
  9919. { we might be able to go smaller if SHR appears first }
  9920. case MinSize of
  9921. S_B:
  9922. ;
  9923. S_W:
  9924. if (taicpu(hp1).oper[0]^.val >= 8) then
  9925. begin
  9926. TryShiftDown := S_B;
  9927. TryShiftDownLimit := $FF;
  9928. TryShiftDownSignedLimit := $7F;
  9929. TryShiftDownSignedLimitLower := -128;
  9930. end;
  9931. S_L:
  9932. if (taicpu(hp1).oper[0]^.val >= 24) then
  9933. begin
  9934. TryShiftDown := S_B;
  9935. TryShiftDownLimit := $FF;
  9936. TryShiftDownSignedLimit := $7F;
  9937. TryShiftDownSignedLimitLower := -128;
  9938. end
  9939. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9940. begin
  9941. TryShiftDown := S_W;
  9942. TryShiftDownLimit := $FFFF;
  9943. TryShiftDownSignedLimit := $7FFF;
  9944. TryShiftDownSignedLimitLower := -32768;
  9945. end;
  9946. else
  9947. InternalError(2020112321);
  9948. end;
  9949. WorkingValue := taicpu(hp1).oper[0]^.val;
  9950. if taicpu(hp1).opcode = A_SAR then
  9951. begin
  9952. TestValMin := SarInt64(TestValMin, WorkingValue);
  9953. TestValMax := SarInt64(TestValMax, WorkingValue);
  9954. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9955. end
  9956. else
  9957. begin
  9958. TestValMin := TestValMin shr WorkingValue;
  9959. TestValMax := TestValMax shr WorkingValue;
  9960. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9961. end;
  9962. end;
  9963. else
  9964. InternalError(2020112303);
  9965. end;
  9966. end;
  9967. (*
  9968. A_IMUL:
  9969. case taicpu(hp1).ops of
  9970. 2:
  9971. begin
  9972. if not MatchOpType(hp1, top_reg, top_reg) or
  9973. { Has to be an exact match on the register }
  9974. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9975. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9976. Break;
  9977. TestValMin := TestValMin * TestValMin;
  9978. TestValMax := TestValMax * TestValMax;
  9979. TestValSignedMax := TestValSignedMax * TestValMax;
  9980. end;
  9981. 3:
  9982. begin
  9983. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9984. { Has to be an exact match on the register }
  9985. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9986. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9987. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9988. { Is it in the negative range? }
  9989. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9990. Break;
  9991. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9992. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9993. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9994. end;
  9995. else
  9996. Break;
  9997. end;
  9998. A_IDIV:
  9999. case taicpu(hp1).ops of
  10000. 3:
  10001. begin
  10002. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10003. { Has to be an exact match on the register }
  10004. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10005. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10006. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10007. { Is it in the negative range? }
  10008. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10009. Break;
  10010. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10011. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10012. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10013. end;
  10014. else
  10015. Break;
  10016. end;
  10017. *)
  10018. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10019. begin
  10020. { If there are no instructions in between, then we might be able to make a saving }
  10021. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10022. Break;
  10023. { We have something like:
  10024. movzbw %dl,%dx
  10025. ...
  10026. movswl %dx,%edx
  10027. Change the latter to a zero-extension then enter the
  10028. A_MOVZX case branch.
  10029. }
  10030. {$ifdef x86_64}
  10031. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10032. begin
  10033. { this becomes a zero extension from 32-bit to 64-bit, but
  10034. the upper 32 bits are already zero, so just delete the
  10035. instruction }
  10036. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10037. RemoveInstruction(hp1);
  10038. Result := True;
  10039. Exit;
  10040. end
  10041. else
  10042. {$endif x86_64}
  10043. begin
  10044. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10045. taicpu(hp1).opcode := A_MOVZX;
  10046. {$ifdef x86_64}
  10047. case taicpu(hp1).opsize of
  10048. S_BQ:
  10049. begin
  10050. taicpu(hp1).opsize := S_BL;
  10051. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10052. end;
  10053. S_WQ:
  10054. begin
  10055. taicpu(hp1).opsize := S_WL;
  10056. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10057. end;
  10058. S_LQ:
  10059. begin
  10060. taicpu(hp1).opcode := A_MOV;
  10061. taicpu(hp1).opsize := S_L;
  10062. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10063. { In this instance, we need to break out because the
  10064. instruction is no longer MOVZX or MOVSXD }
  10065. Result := True;
  10066. Exit;
  10067. end;
  10068. else
  10069. ;
  10070. end;
  10071. {$endif x86_64}
  10072. Result := CompressInstructions;
  10073. Exit;
  10074. end;
  10075. end;
  10076. A_MOVZX:
  10077. begin
  10078. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10079. Break;
  10080. if (InstrMax = -1) then
  10081. begin
  10082. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10083. begin
  10084. { Optimise around i40003 }
  10085. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10086. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10087. {$ifndef x86_64}
  10088. and (
  10089. (taicpu(p).oper[0]^.typ <> top_reg) or
  10090. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10091. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10092. )
  10093. {$endif not x86_64}
  10094. then
  10095. begin
  10096. if (taicpu(p).oper[0]^.typ = top_reg) then
  10097. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10098. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10099. taicpu(p).opsize := S_BL;
  10100. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10101. RemoveInstruction(hp1);
  10102. Result := True;
  10103. Exit;
  10104. end;
  10105. end
  10106. else
  10107. begin
  10108. { Will return false if the second parameter isn't ThisReg
  10109. (can happen on -O2 and under) }
  10110. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10111. begin
  10112. { The two MOVZX instructions are adjacent, so remove the first one }
  10113. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10114. RemoveCurrentP(p);
  10115. Result := True;
  10116. Exit;
  10117. end;
  10118. Break;
  10119. end;
  10120. end;
  10121. Result := CompressInstructions;
  10122. Exit;
  10123. end;
  10124. else
  10125. { This includes ADC, SBB and IDIV }
  10126. Break;
  10127. end;
  10128. if not CheckOverflowConditions then
  10129. Break;
  10130. { Contains highest index (so instruction count - 1) }
  10131. Inc(InstrMax);
  10132. if InstrMax > High(InstrList) then
  10133. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10134. InstrList[InstrMax] := taicpu(hp1);
  10135. end;
  10136. end;
  10137. {$pop}
  10138. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10139. var
  10140. hp1 : tai;
  10141. begin
  10142. Result:=false;
  10143. if (taicpu(p).ops >= 2) and
  10144. ((taicpu(p).oper[0]^.typ = top_const) or
  10145. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10146. (taicpu(p).oper[1]^.typ = top_reg) and
  10147. ((taicpu(p).ops = 2) or
  10148. ((taicpu(p).oper[2]^.typ = top_reg) and
  10149. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10150. GetLastInstruction(p,hp1) and
  10151. MatchInstruction(hp1,A_MOV,[]) and
  10152. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10153. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10154. begin
  10155. TransferUsedRegs(TmpUsedRegs);
  10156. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10157. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10158. { change
  10159. mov reg1,reg2
  10160. imul y,reg2 to imul y,reg1,reg2 }
  10161. begin
  10162. taicpu(p).ops := 3;
  10163. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10164. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10165. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10166. RemoveInstruction(hp1);
  10167. result:=true;
  10168. end;
  10169. end;
  10170. end;
  10171. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10172. var
  10173. ThisLabel: TAsmLabel;
  10174. begin
  10175. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10176. ThisLabel.decrefs;
  10177. taicpu(p).condition := C_None;
  10178. taicpu(p).opcode := A_RET;
  10179. taicpu(p).is_jmp := false;
  10180. taicpu(p).ops := taicpu(ret_p).ops;
  10181. case taicpu(ret_p).ops of
  10182. 0:
  10183. taicpu(p).clearop(0);
  10184. 1:
  10185. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10186. else
  10187. internalerror(2016041301);
  10188. end;
  10189. { If the original label is now dead, it might turn out that the label
  10190. immediately follows p. As a result, everything beyond it, which will
  10191. be just some final register configuration and a RET instruction, is
  10192. now dead code. [Kit] }
  10193. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10194. running RemoveDeadCodeAfterJump for each RET instruction, because
  10195. this optimisation rarely happens and most RETs appear at the end of
  10196. routines where there is nothing that can be stripped. [Kit] }
  10197. if not ThisLabel.is_used then
  10198. RemoveDeadCodeAfterJump(p);
  10199. end;
  10200. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10201. var
  10202. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10203. Unconditional, PotentialModified: Boolean;
  10204. OperPtr: POper;
  10205. NewRef: TReference;
  10206. InstrList: array of taicpu;
  10207. InstrMax, Index: Integer;
  10208. const
  10209. {$ifdef DEBUG_AOPTCPU}
  10210. SNoFlags: shortstring = ' so the flags aren''t modified';
  10211. {$else DEBUG_AOPTCPU}
  10212. SNoFlags = '';
  10213. {$endif DEBUG_AOPTCPU}
  10214. begin
  10215. Result:=false;
  10216. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10217. begin
  10218. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10219. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10220. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10221. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10222. GetNextInstruction(hp1, hp2) and
  10223. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10224. { Change from: To:
  10225. set(C) %reg j(~C) label
  10226. test %reg,%reg/cmp $0,%reg
  10227. je label
  10228. set(C) %reg j(C) label
  10229. test %reg,%reg/cmp $0,%reg
  10230. jne label
  10231. (Also do something similar with sete/setne instead of je/jne)
  10232. }
  10233. begin
  10234. { Before we do anything else, we need to check the instructions
  10235. in between SETcc and TEST to make sure they don't modify the
  10236. FLAGS register - if -O2 or under, there won't be any
  10237. instructions between SET and TEST }
  10238. TransferUsedRegs(TmpUsedRegs);
  10239. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10240. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10241. begin
  10242. next := p;
  10243. SetLength(InstrList, 0);
  10244. InstrMax := -1;
  10245. PotentialModified := False;
  10246. { Make a note of every instruction that modifies the FLAGS
  10247. register }
  10248. while GetNextInstruction(next, next) and (next <> hp1) do
  10249. begin
  10250. if next.typ <> ait_instruction then
  10251. { GetNextInstructionUsingReg should have returned False }
  10252. InternalError(2021051701);
  10253. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10254. begin
  10255. case taicpu(next).opcode of
  10256. A_SETcc,
  10257. A_CMOVcc,
  10258. A_Jcc:
  10259. begin
  10260. if PotentialModified then
  10261. { Not safe because the flags were modified earlier }
  10262. Exit
  10263. else
  10264. { Condition is the same as the initial SETcc, so this is safe
  10265. (don't add to instruction list though) }
  10266. Continue;
  10267. end;
  10268. A_ADD:
  10269. begin
  10270. if (taicpu(next).opsize = S_B) or
  10271. { LEA doesn't support 8-bit operands }
  10272. (taicpu(next).oper[1]^.typ <> top_reg) or
  10273. { Must write to a register }
  10274. (taicpu(next).oper[0]^.typ = top_ref) then
  10275. { Require a constant or a register }
  10276. Exit;
  10277. PotentialModified := True;
  10278. end;
  10279. A_SUB:
  10280. begin
  10281. if (taicpu(next).opsize = S_B) or
  10282. { LEA doesn't support 8-bit operands }
  10283. (taicpu(next).oper[1]^.typ <> top_reg) or
  10284. { Must write to a register }
  10285. (taicpu(next).oper[0]^.typ <> top_const) or
  10286. (taicpu(next).oper[0]^.val = $80000000) then
  10287. { Can't subtract a register with LEA - also
  10288. check that the value isn't -2^31, as this
  10289. can't be negated }
  10290. Exit;
  10291. PotentialModified := True;
  10292. end;
  10293. A_SAL,
  10294. A_SHL:
  10295. begin
  10296. if (taicpu(next).opsize = S_B) or
  10297. { LEA doesn't support 8-bit operands }
  10298. (taicpu(next).oper[1]^.typ <> top_reg) or
  10299. { Must write to a register }
  10300. (taicpu(next).oper[0]^.typ <> top_const) or
  10301. (taicpu(next).oper[0]^.val < 0) or
  10302. (taicpu(next).oper[0]^.val > 3) then
  10303. Exit;
  10304. PotentialModified := True;
  10305. end;
  10306. A_IMUL:
  10307. begin
  10308. if (taicpu(next).ops <> 3) or
  10309. (taicpu(next).oper[1]^.typ <> top_reg) or
  10310. { Must write to a register }
  10311. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10312. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10313. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10314. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10315. Exit
  10316. else
  10317. PotentialModified := True;
  10318. end;
  10319. else
  10320. { Don't know how to change this, so abort }
  10321. Exit;
  10322. end;
  10323. { Contains highest index (so instruction count - 1) }
  10324. Inc(InstrMax);
  10325. if InstrMax > High(InstrList) then
  10326. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10327. InstrList[InstrMax] := taicpu(next);
  10328. end;
  10329. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10330. end;
  10331. if not Assigned(next) or (next <> hp1) then
  10332. { It should be equal to hp1 }
  10333. InternalError(2021051702);
  10334. { Cycle through each instruction and check to see if we can
  10335. change them to versions that don't modify the flags }
  10336. if (InstrMax >= 0) then
  10337. begin
  10338. for Index := 0 to InstrMax do
  10339. case InstrList[Index].opcode of
  10340. A_ADD:
  10341. begin
  10342. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10343. InstrList[Index].opcode := A_LEA;
  10344. reference_reset(NewRef, 1, []);
  10345. NewRef.base := InstrList[Index].oper[1]^.reg;
  10346. if InstrList[Index].oper[0]^.typ = top_reg then
  10347. begin
  10348. NewRef.index := InstrList[Index].oper[0]^.reg;
  10349. NewRef.scalefactor := 1;
  10350. end
  10351. else
  10352. NewRef.offset := InstrList[Index].oper[0]^.val;
  10353. InstrList[Index].loadref(0, NewRef);
  10354. end;
  10355. A_SUB:
  10356. begin
  10357. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10358. InstrList[Index].opcode := A_LEA;
  10359. reference_reset(NewRef, 1, []);
  10360. NewRef.base := InstrList[Index].oper[1]^.reg;
  10361. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10362. InstrList[Index].loadref(0, NewRef);
  10363. end;
  10364. A_SHL,
  10365. A_SAL:
  10366. begin
  10367. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10368. InstrList[Index].opcode := A_LEA;
  10369. reference_reset(NewRef, 1, []);
  10370. NewRef.index := InstrList[Index].oper[1]^.reg;
  10371. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10372. InstrList[Index].loadref(0, NewRef);
  10373. end;
  10374. A_IMUL:
  10375. begin
  10376. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10377. InstrList[Index].opcode := A_LEA;
  10378. reference_reset(NewRef, 1, []);
  10379. NewRef.index := InstrList[Index].oper[1]^.reg;
  10380. case InstrList[Index].oper[0]^.val of
  10381. 2, 4, 8:
  10382. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10383. else {3, 5 and 9}
  10384. begin
  10385. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10386. NewRef.base := InstrList[Index].oper[1]^.reg;
  10387. end;
  10388. end;
  10389. InstrList[Index].loadref(0, NewRef);
  10390. end;
  10391. else
  10392. InternalError(2021051710);
  10393. end;
  10394. end;
  10395. { Mark the FLAGS register as used across this whole block }
  10396. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10397. end;
  10398. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10399. JumpC := taicpu(hp2).condition;
  10400. Unconditional := False;
  10401. if conditions_equal(JumpC, C_E) then
  10402. SetC := inverse_cond(taicpu(p).condition)
  10403. else if conditions_equal(JumpC, C_NE) then
  10404. SetC := taicpu(p).condition
  10405. else
  10406. { We've got something weird here (and inefficent) }
  10407. begin
  10408. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10409. SetC := C_NONE;
  10410. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10411. if condition_in(C_AE, JumpC) then
  10412. Unconditional := True
  10413. else
  10414. { Not sure what to do with this jump - drop out }
  10415. Exit;
  10416. end;
  10417. RemoveInstruction(hp1);
  10418. if Unconditional then
  10419. MakeUnconditional(taicpu(hp2))
  10420. else
  10421. begin
  10422. if SetC = C_NONE then
  10423. InternalError(2018061402);
  10424. taicpu(hp2).SetCondition(SetC);
  10425. end;
  10426. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10427. TmpUsedRegs }
  10428. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10429. begin
  10430. RemoveCurrentp(p, hp2);
  10431. if taicpu(hp2).opcode = A_SETcc then
  10432. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10433. else
  10434. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10435. end
  10436. else
  10437. if taicpu(hp2).opcode = A_SETcc then
  10438. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10439. else
  10440. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10441. Result := True;
  10442. end
  10443. else if
  10444. { Make sure the instructions are adjacent }
  10445. (
  10446. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10447. GetNextInstruction(p, hp1)
  10448. ) and
  10449. MatchInstruction(hp1, A_MOV, [S_B]) and
  10450. { Writing to memory is allowed }
  10451. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10452. begin
  10453. {
  10454. Watch out for sequences such as:
  10455. set(c)b %regb
  10456. movb %regb,(ref)
  10457. movb $0,1(ref)
  10458. movb $0,2(ref)
  10459. movb $0,3(ref)
  10460. Much more efficient to turn it into:
  10461. movl $0,%regl
  10462. set(c)b %regb
  10463. movl %regl,(ref)
  10464. Or:
  10465. set(c)b %regb
  10466. movzbl %regb,%regl
  10467. movl %regl,(ref)
  10468. }
  10469. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10470. GetNextInstruction(hp1, hp2) and
  10471. MatchInstruction(hp2, A_MOV, [S_B]) and
  10472. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10473. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10474. begin
  10475. { Don't do anything else except set Result to True }
  10476. end
  10477. else
  10478. begin
  10479. if taicpu(p).oper[0]^.typ = top_reg then
  10480. begin
  10481. TransferUsedRegs(TmpUsedRegs);
  10482. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10483. end;
  10484. { If it's not a register, it's a memory address }
  10485. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10486. begin
  10487. { Even if the register is still in use, we can minimise the
  10488. pipeline stall by changing the MOV into another SETcc. }
  10489. taicpu(hp1).opcode := A_SETcc;
  10490. taicpu(hp1).condition := taicpu(p).condition;
  10491. if taicpu(hp1).oper[1]^.typ = top_ref then
  10492. begin
  10493. { Swapping the operand pointers like this is probably a
  10494. bit naughty, but it is far faster than using loadoper
  10495. to transfer the reference from oper[1] to oper[0] if
  10496. you take into account the extra procedure calls and
  10497. the memory allocation and deallocation required }
  10498. OperPtr := taicpu(hp1).oper[1];
  10499. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10500. taicpu(hp1).oper[0] := OperPtr;
  10501. end
  10502. else
  10503. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10504. taicpu(hp1).clearop(1);
  10505. taicpu(hp1).ops := 1;
  10506. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10507. end
  10508. else
  10509. begin
  10510. if taicpu(hp1).oper[1]^.typ = top_reg then
  10511. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10512. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10513. RemoveInstruction(hp1);
  10514. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10515. end
  10516. end;
  10517. Result := True;
  10518. end;
  10519. end;
  10520. end;
  10521. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10522. var
  10523. hp1: tai;
  10524. Count: Integer;
  10525. OrigLabel: TAsmLabel;
  10526. begin
  10527. result := False;
  10528. { Sometimes, the optimisations below can permit this }
  10529. RemoveDeadCodeAfterJump(p);
  10530. 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
  10531. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10532. begin
  10533. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10534. { Also a side-effect of optimisations }
  10535. if CollapseZeroDistJump(p, OrigLabel) then
  10536. begin
  10537. Result := True;
  10538. Exit;
  10539. end;
  10540. hp1 := GetLabelWithSym(OrigLabel);
  10541. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10542. begin
  10543. if taicpu(hp1).opcode = A_RET then
  10544. begin
  10545. {
  10546. change
  10547. jmp .L1
  10548. ...
  10549. .L1:
  10550. ret
  10551. into
  10552. ret
  10553. }
  10554. begin
  10555. ConvertJumpToRET(p, hp1);
  10556. result:=true;
  10557. end;
  10558. end
  10559. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10560. not (cs_opt_size in current_settings.optimizerswitches) and
  10561. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10562. begin
  10563. Result := True;
  10564. Exit;
  10565. end;
  10566. end;
  10567. end;
  10568. end;
  10569. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10570. begin
  10571. Result := assigned(p) and
  10572. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10573. (taicpu(p).oper[1]^.typ = top_reg) and
  10574. (
  10575. (taicpu(p).oper[0]^.typ = top_reg) or
  10576. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10577. it is not expected that this can cause a seg. violation }
  10578. (
  10579. (taicpu(p).oper[0]^.typ = top_ref) and
  10580. { TODO: Can we detect which references become constants at this
  10581. stage so we don't have to do a blanket ban? }
  10582. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10583. (
  10584. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10585. (
  10586. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10587. not RefModified and
  10588. { If the reference also appears in the condition, then we know it's safe, otherwise
  10589. any kind of access violation would have occurred already }
  10590. Assigned(cond_p) and
  10591. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10592. (cond_p.typ = ait_instruction) and
  10593. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10594. { Just consider 2-operand comparison instructions for now to be safe }
  10595. (taicpu(cond_p).ops = 2) and
  10596. (
  10597. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10598. (
  10599. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10600. { Don't risk identical registers but different offsets, as we may have constructs
  10601. such as buffer streams with things like length fields that indicate whether
  10602. any more data follows. And there are probably some contrived examples where
  10603. writing to offsets behind the one being read also lead to access violations }
  10604. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10605. (
  10606. { Check that we're not modifying a register that appears in the reference }
  10607. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10608. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10609. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10610. )
  10611. )
  10612. )
  10613. )
  10614. )
  10615. )
  10616. );
  10617. end;
  10618. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10619. begin
  10620. { Update integer registers, ignoring deallocations }
  10621. repeat
  10622. while assigned(p) and
  10623. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10624. (p.typ = ait_label) or
  10625. ((p.typ = ait_marker) and
  10626. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10627. p := tai(p.next);
  10628. while assigned(p) and
  10629. (p.typ=ait_RegAlloc) Do
  10630. begin
  10631. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10632. begin
  10633. case tai_regalloc(p).ratype of
  10634. ra_alloc :
  10635. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10636. else
  10637. ;
  10638. end;
  10639. end;
  10640. p := tai(p.next);
  10641. end;
  10642. until not(assigned(p)) or
  10643. (not(p.typ in SkipInstr) and
  10644. not((p.typ = ait_label) and
  10645. labelCanBeSkipped(tai_label(p))));
  10646. end;
  10647. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10648. var
  10649. hp1,hp2: tai;
  10650. carryadd_opcode : TAsmOp;
  10651. symbol: TAsmSymbol;
  10652. increg, tmpreg: TRegister;
  10653. RefModified: Boolean;
  10654. {$ifndef i8086}
  10655. { Code and variables specific to CMOV optimisations }
  10656. hp3,hp4,hp5,
  10657. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10658. l, c, w, x : Longint;
  10659. condition, second_condition : TAsmCond;
  10660. FoundMatchingJump, RegMatch: Boolean;
  10661. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10662. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10663. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10664. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10665. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10666. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10667. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10668. new register to store the constant }
  10669. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10670. var
  10671. RegSize: TSubRegister;
  10672. CurrentVal: TCGInt;
  10673. ANewReg: TRegister;
  10674. X: ShortInt;
  10675. begin
  10676. Result := False;
  10677. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10678. Exit;
  10679. if StoredCount >= MAX_CMOV_REGISTERS then
  10680. { Arrays are full }
  10681. Exit;
  10682. { Remember that CMOV can't encode 8-bit registers }
  10683. case taicpu(p).opsize of
  10684. S_W:
  10685. RegSize := R_SUBW;
  10686. S_L:
  10687. RegSize := R_SUBD;
  10688. {$ifdef x86_64}
  10689. S_Q:
  10690. RegSize := R_SUBQ;
  10691. {$endif x86_64}
  10692. else
  10693. InternalError(2021100401);
  10694. end;
  10695. { See if the value has already been reserved for another CMOV instruction }
  10696. CurrentVal := taicpu(p).oper[0]^.val;
  10697. for X := 0 to StoredCount - 1 do
  10698. if ConstVals[X] = CurrentVal then
  10699. begin
  10700. ConstRegs[StoredCount] := ConstRegs[X];
  10701. ConstSizes[StoredCount] := RegSize;
  10702. ConstVals[StoredCount] := CurrentVal;
  10703. Result := True;
  10704. Inc(StoredCount);
  10705. { Don't increase CMOVCount this time, since we're re-using a register }
  10706. Exit;
  10707. end;
  10708. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10709. if ANewReg = NR_NO then
  10710. { No free registers }
  10711. Exit;
  10712. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10713. up vying for the same register }
  10714. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10715. ConstRegs[StoredCount] := ANewReg;
  10716. ConstSizes[StoredCount] := RegSize;
  10717. ConstVals[StoredCount] := CurrentVal;
  10718. Inc(StoredCount);
  10719. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10720. MOV required adds complexity and will cause diminishing returns
  10721. sooner than normal. This is more of an approximate weighting than
  10722. anything else. }
  10723. Inc(CMOVCount);
  10724. Result := True;
  10725. end;
  10726. {$endif i8086}
  10727. begin
  10728. result:=false;
  10729. if GetNextInstruction(p,hp1) then
  10730. begin
  10731. if (hp1.typ=ait_label) then
  10732. begin
  10733. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10734. Exit;
  10735. end
  10736. else if (hp1.typ<>ait_instruction) then
  10737. Exit;
  10738. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10739. if (
  10740. (
  10741. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10742. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10743. (Taicpu(hp1).oper[0]^.val=1)
  10744. ) or
  10745. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10746. ) and
  10747. GetNextInstruction(hp1,hp2) and
  10748. SkipAligns(hp2, hp2) and
  10749. (hp2.typ = ait_label) and
  10750. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10751. { jb @@1 cmc
  10752. inc/dec operand --> adc/sbb operand,0
  10753. @@1:
  10754. ... and ...
  10755. jnb @@1
  10756. inc/dec operand --> adc/sbb operand,0
  10757. @@1: }
  10758. begin
  10759. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10760. begin
  10761. case taicpu(hp1).opcode of
  10762. A_INC,
  10763. A_ADD:
  10764. carryadd_opcode:=A_ADC;
  10765. A_DEC,
  10766. A_SUB:
  10767. carryadd_opcode:=A_SBB;
  10768. else
  10769. InternalError(2021011001);
  10770. end;
  10771. Taicpu(p).clearop(0);
  10772. Taicpu(p).ops:=0;
  10773. Taicpu(p).is_jmp:=false;
  10774. Taicpu(p).opcode:=A_CMC;
  10775. Taicpu(p).condition:=C_NONE;
  10776. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10777. Taicpu(hp1).ops:=2;
  10778. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10779. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10780. else
  10781. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10782. Taicpu(hp1).loadconst(0,0);
  10783. Taicpu(hp1).opcode:=carryadd_opcode;
  10784. result:=true;
  10785. exit;
  10786. end
  10787. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10788. begin
  10789. case taicpu(hp1).opcode of
  10790. A_INC,
  10791. A_ADD:
  10792. carryadd_opcode:=A_ADC;
  10793. A_DEC,
  10794. A_SUB:
  10795. carryadd_opcode:=A_SBB;
  10796. else
  10797. InternalError(2021011002);
  10798. end;
  10799. Taicpu(hp1).ops:=2;
  10800. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10801. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10802. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10803. else
  10804. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10805. Taicpu(hp1).loadconst(0,0);
  10806. Taicpu(hp1).opcode:=carryadd_opcode;
  10807. RemoveCurrentP(p, hp1);
  10808. result:=true;
  10809. exit;
  10810. end
  10811. {
  10812. jcc @@1 setcc tmpreg
  10813. inc/dec/add/sub operand -> (movzx tmpreg)
  10814. @@1: add/sub tmpreg,operand
  10815. While this increases code size slightly, it makes the code much faster if the
  10816. jump is unpredictable
  10817. }
  10818. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10819. begin
  10820. { search for an available register which is volatile }
  10821. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10822. if increg <> NR_NO then
  10823. begin
  10824. { We don't need to check if tmpreg is in hp1 or not, because
  10825. it will be marked as in use at p (if not, this is
  10826. indictive of a compiler bug). }
  10827. TAsmLabel(symbol).decrefs;
  10828. Taicpu(p).clearop(0);
  10829. Taicpu(p).ops:=1;
  10830. Taicpu(p).is_jmp:=false;
  10831. Taicpu(p).opcode:=A_SETcc;
  10832. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10833. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10834. Taicpu(p).loadreg(0,increg);
  10835. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10836. begin
  10837. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10838. R_SUBW:
  10839. begin
  10840. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10841. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10842. end;
  10843. R_SUBD:
  10844. begin
  10845. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10846. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10847. end;
  10848. {$ifdef x86_64}
  10849. R_SUBQ:
  10850. begin
  10851. { MOVZX doesn't have a 64-bit variant, because
  10852. the 32-bit version implicitly zeroes the
  10853. upper 32-bits of the destination register }
  10854. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10855. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10856. setsubreg(tmpreg, R_SUBQ);
  10857. end;
  10858. {$endif x86_64}
  10859. else
  10860. Internalerror(2020030601);
  10861. end;
  10862. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10863. asml.InsertAfter(hp2,p);
  10864. end
  10865. else
  10866. tmpreg := increg;
  10867. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10868. begin
  10869. Taicpu(hp1).ops:=2;
  10870. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10871. end;
  10872. Taicpu(hp1).loadreg(0,tmpreg);
  10873. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10874. Result := True;
  10875. { p is no longer a Jcc instruction, so exit }
  10876. Exit;
  10877. end;
  10878. end;
  10879. end;
  10880. { Detect the following:
  10881. jmp<cond> @Lbl1
  10882. jmp @Lbl2
  10883. ...
  10884. @Lbl1:
  10885. ret
  10886. Change to:
  10887. jmp<inv_cond> @Lbl2
  10888. ret
  10889. }
  10890. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10891. begin
  10892. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10893. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10894. MatchInstruction(hp2,A_RET,[S_NO]) then
  10895. begin
  10896. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10897. { Change label address to that of the unconditional jump }
  10898. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10899. TAsmLabel(symbol).DecRefs;
  10900. taicpu(hp1).opcode := A_RET;
  10901. taicpu(hp1).is_jmp := false;
  10902. taicpu(hp1).ops := taicpu(hp2).ops;
  10903. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10904. case taicpu(hp2).ops of
  10905. 0:
  10906. taicpu(hp1).clearop(0);
  10907. 1:
  10908. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10909. else
  10910. internalerror(2016041302);
  10911. end;
  10912. end;
  10913. {$ifndef i8086}
  10914. end
  10915. {
  10916. convert
  10917. j<c> .L1
  10918. mov 1,reg
  10919. jmp .L2
  10920. .L1
  10921. mov 0,reg
  10922. .L2
  10923. into
  10924. mov 0,reg
  10925. set<not(c)> reg
  10926. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10927. would destroy the flag contents
  10928. }
  10929. else if MatchInstruction(hp1,A_MOV,[]) and
  10930. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10931. {$ifdef i386}
  10932. (
  10933. { Under i386, ESI, EDI, EBP and ESP
  10934. don't have an 8-bit representation }
  10935. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10936. ) and
  10937. {$endif i386}
  10938. (taicpu(hp1).oper[0]^.val=1) and
  10939. GetNextInstruction(hp1,hp2) and
  10940. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10941. GetNextInstruction(hp2,hp3) and
  10942. { skip align }
  10943. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10944. (hp3.typ=ait_label) and
  10945. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10946. (tai_label(hp3).labsym.getrefs=1) and
  10947. GetNextInstruction(hp3,hp4) and
  10948. MatchInstruction(hp4,A_MOV,[]) and
  10949. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10950. (taicpu(hp4).oper[0]^.val=0) and
  10951. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10952. GetNextInstruction(hp4,hp5) and
  10953. (hp5.typ=ait_label) and
  10954. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10955. (tai_label(hp5).labsym.getrefs=1) then
  10956. begin
  10957. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10958. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10959. { remove last label }
  10960. RemoveInstruction(hp5);
  10961. { remove second label }
  10962. RemoveInstruction(hp3);
  10963. { if align is present remove it }
  10964. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10965. RemoveInstruction(hp3);
  10966. { remove jmp }
  10967. RemoveInstruction(hp2);
  10968. if taicpu(hp1).opsize=S_B then
  10969. RemoveInstruction(hp1)
  10970. else
  10971. taicpu(hp1).loadconst(0,0);
  10972. taicpu(hp4).opcode:=A_SETcc;
  10973. taicpu(hp4).opsize:=S_B;
  10974. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10975. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10976. taicpu(hp4).opercnt:=1;
  10977. taicpu(hp4).ops:=1;
  10978. taicpu(hp4).freeop(1);
  10979. RemoveCurrentP(p);
  10980. Result:=true;
  10981. exit;
  10982. end
  10983. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10984. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10985. begin
  10986. { check for
  10987. jCC xxx
  10988. <several movs>
  10989. xxx:
  10990. Also spot:
  10991. Jcc xxx
  10992. <several movs>
  10993. jmp xxx
  10994. Change to:
  10995. <several cmovs with inverted condition>
  10996. jmp xxx (only for the 2nd case)
  10997. }
  10998. hp2 := p;
  10999. hp_lblxxx := hp1;
  11000. hp_flagalloc := nil;
  11001. hp_stop := nil;
  11002. FoundMatchingJump := False;
  11003. { Remember the first instruction in the first block of MOVs }
  11004. hpmov1 := hp1;
  11005. TransferUsedRegs(TmpUsedRegs);
  11006. while assigned(hp_lblxxx) and
  11007. { stop on labels }
  11008. (hp_lblxxx.typ <> ait_label) do
  11009. begin
  11010. { Keep track of all integer registers that are used }
  11011. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11012. if hp_lblxxx.typ = ait_instruction then
  11013. begin
  11014. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  11015. IsJumpToLabel(taicpu(hp_lblxxx)) then
  11016. begin
  11017. hp_stop := hp_lblxxx;
  11018. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  11019. begin
  11020. { We found Jcc xxx; <several movs>; Jmp xxx }
  11021. FoundMatchingJump := True;
  11022. Break;
  11023. end;
  11024. { If it's not the jump we're looking for, it's
  11025. possibly the "if..else" variant }
  11026. end
  11027. { Check to see if we have a valid MOV instruction instead }
  11028. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11029. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11030. Break
  11031. else
  11032. { This will be a valid MOV }
  11033. hp_stop := hp_lblxxx;
  11034. end;
  11035. hp2 := hp_lblxxx;
  11036. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11037. end;
  11038. { Just make sure the last MOV is included if there's no jump }
  11039. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11040. hp_stop := hp_lblxxx;
  11041. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11042. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11043. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11044. jmp yyy; xxx:; movs; yyy:" variation }
  11045. if assigned(hp_lblxxx) and
  11046. (
  11047. { If we found JMP xxx, we don't actually need a label
  11048. (hp_lblxxx is the JMP instruction instead) }
  11049. FoundMatchingJump or
  11050. { Make sure we actually have the right label }
  11051. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11052. ) then
  11053. begin
  11054. { Use TmpUsedRegs to track registers that we reserve }
  11055. { When allocating temporary registers, try to look one
  11056. instruction back, as defining them before a CMP or TEST
  11057. instruction will be faster, and also avoid picking a
  11058. register that was only just deallocated }
  11059. if GetLastInstruction(p, hp_prev) and
  11060. 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
  11061. begin
  11062. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11063. for l := 0 to 1 do
  11064. with taicpu(hp_prev).oper[l]^ do
  11065. case typ of
  11066. top_reg:
  11067. if getregtype(reg) = R_INTREGISTER then
  11068. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11069. top_ref:
  11070. begin
  11071. if
  11072. {$ifdef x86_64}
  11073. (ref^.base <> NR_RIP) and
  11074. {$endif x86_64}
  11075. (ref^.base <> NR_NO) then
  11076. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11077. if (ref^.index <> NR_NO) then
  11078. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11079. end
  11080. else
  11081. ;
  11082. end;
  11083. { When inserting instructions before hp_prev, try to insert
  11084. them before the allocation of the FLAGS register }
  11085. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11086. { If not found, set it equal to hp_prev so it's something sensible }
  11087. hp_flagalloc := hp_prev;
  11088. hp_prev2 := nil;
  11089. { When dealing with a comparison against zero, take
  11090. note of the instruction before it to see if we can
  11091. move instructions further back in order to benefit
  11092. PostPeepholeOptTestOr.
  11093. }
  11094. if (
  11095. (
  11096. (taicpu(hp_prev).opcode = A_CMP) and
  11097. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11098. ) or
  11099. (
  11100. (taicpu(hp_prev).opcode = A_TEST) and
  11101. (
  11102. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11103. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11104. )
  11105. )
  11106. ) and
  11107. GetLastInstruction(hp_prev, hp_prev2) then
  11108. begin
  11109. if (hp_prev2.typ = ait_instruction) and
  11110. { These instructions set the zero flag if the result is zero }
  11111. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11112. begin
  11113. { Also mark all the registers in this previous instruction
  11114. as 'in use', even if they've just been deallocated }
  11115. for l := 0 to 1 do
  11116. with taicpu(hp_prev2).oper[l]^ do
  11117. case typ of
  11118. top_reg:
  11119. if getregtype(reg) = R_INTREGISTER then
  11120. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11121. top_ref:
  11122. begin
  11123. if
  11124. {$ifdef x86_64}
  11125. (ref^.base <> NR_RIP) and
  11126. {$endif x86_64}
  11127. (ref^.base <> NR_NO) then
  11128. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11129. if (ref^.index <> NR_NO) then
  11130. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11131. end
  11132. else
  11133. ;
  11134. end;
  11135. end
  11136. else
  11137. { Unsuitable instruction }
  11138. hp_prev2 := nil;
  11139. end;
  11140. end
  11141. else
  11142. begin
  11143. hp_prev := p;
  11144. { When inserting instructions before hp_prev, try to insert
  11145. them before the allocation of the FLAGS register }
  11146. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11147. { If not found, set it equal to p so it's something sensible }
  11148. hp_flagalloc := p;
  11149. hp_prev2 := nil;
  11150. end;
  11151. l := 0;
  11152. c := 0;
  11153. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11154. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11155. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11156. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11157. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11158. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11159. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11160. RefModified := False;
  11161. while assigned(hp1) and
  11162. { Stop on the label we found }
  11163. (hp1 <> hp_lblxxx) do
  11164. begin
  11165. case hp1.typ of
  11166. ait_instruction:
  11167. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11168. begin
  11169. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11170. begin
  11171. Inc(l);
  11172. { MOV instruction will be writing to a register }
  11173. if Assigned(hp_prev) and
  11174. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11175. (hp_prev.typ = ait_instruction) and
  11176. (taicpu(hp_prev).ops = 2) and
  11177. (
  11178. (
  11179. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11180. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11181. ) or
  11182. (
  11183. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11184. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11185. )
  11186. ) then
  11187. { It is no longer safe to use the reference in the condition.
  11188. this prevents problems such as:
  11189. mov (%reg),%reg
  11190. mov (%reg),...
  11191. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11192. (fixes #40165)
  11193. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11194. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11195. }
  11196. RefModified := True;
  11197. end
  11198. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11199. { CMOV with constants grows the code size }
  11200. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11201. begin
  11202. { Register was reserved by TryCMOVConst and
  11203. stored on ConstRegs[c] }
  11204. end
  11205. else
  11206. Break;
  11207. end
  11208. else
  11209. Break;
  11210. else
  11211. ;
  11212. end;
  11213. GetNextInstruction(hp1,hp1);
  11214. end;
  11215. if (hp1 = hp_lblxxx) then
  11216. begin
  11217. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11218. begin
  11219. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11220. TmpUsedRegs[R_INTREGISTER].Clear;
  11221. x := 0;
  11222. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11223. condition := inverse_cond(taicpu(p).condition);
  11224. UpdateUsedRegs(tai(p.next));
  11225. hp1 := hpmov1;
  11226. repeat
  11227. if not Assigned(hp1) then
  11228. InternalError(2018062900);
  11229. if (hp1.typ = ait_instruction) then
  11230. begin
  11231. { Extra safeguard }
  11232. if (taicpu(hp1).opcode <> A_MOV) then
  11233. InternalError(2018062901);
  11234. if taicpu(hp1).oper[0]^.typ = top_const then
  11235. begin
  11236. if x >= MAX_CMOV_REGISTERS then
  11237. InternalError(2021100410);
  11238. { If it's in TmpUsedRegs, then this register
  11239. is being used more than once and hence has
  11240. already had its value defined (it gets
  11241. added to UsedRegs through AllocRegBetween
  11242. below) }
  11243. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11244. begin
  11245. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11246. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11247. asml.InsertBefore(hp_new, hp_flagalloc);
  11248. if Assigned(hp_prev2) then
  11249. TrySwapMovOp(hp_prev2, hp_new);
  11250. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11251. ConstMovs[X] := hp_new;
  11252. end
  11253. else
  11254. { We just need an instruction between hp_prev and hp1
  11255. where we know the register is marked as in use }
  11256. hp_new := hpmov1;
  11257. { Keep track of largest write for this register so it can be optimised later }
  11258. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11259. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11260. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11261. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11262. Inc(x);
  11263. end;
  11264. taicpu(hp1).opcode := A_CMOVcc;
  11265. taicpu(hp1).condition := condition;
  11266. end;
  11267. UpdateUsedRegs(tai(hp1.next));
  11268. GetNextInstruction(hp1, hp1);
  11269. until (hp1 = hp_lblxxx);
  11270. { Update initialisation MOVs to the smallest possible size }
  11271. for c := 0 to x - 1 do
  11272. if Assigned(ConstMovs[c]) then
  11273. begin
  11274. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11275. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11276. end;
  11277. hp2 := hp_lblxxx;
  11278. repeat
  11279. if not Assigned(hp2) then
  11280. InternalError(2018062910);
  11281. case hp2.typ of
  11282. ait_label:
  11283. { What we expected - break out of the loop (it won't be a dead label at the top of
  11284. a cluster because that was optimised at an earlier stage) }
  11285. Break;
  11286. ait_align:
  11287. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11288. begin
  11289. hp2 := tai(hp2.Next);
  11290. Continue;
  11291. end;
  11292. ait_instruction:
  11293. begin
  11294. if taicpu(hp2).opcode<>A_JMP then
  11295. InternalError(2018062912);
  11296. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11297. Break;
  11298. end
  11299. else
  11300. begin
  11301. { Might be a comment or temporary allocation entry }
  11302. if not (hp2.typ in SkipInstr) then
  11303. InternalError(2018062911);
  11304. hp2 := tai(hp2.Next);
  11305. Continue;
  11306. end;
  11307. end;
  11308. until False;
  11309. { Now we can safely decrement the reference count }
  11310. tasmlabel(symbol).decrefs;
  11311. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11312. { Remove the original jump }
  11313. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11314. if hp2.typ=ait_instruction then
  11315. begin
  11316. p := hp2;
  11317. Result := True;
  11318. end
  11319. else
  11320. begin
  11321. UpdateUsedRegs(tai(hp2.next));
  11322. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11323. { Remove the label if this is its final reference }
  11324. if (tasmlabel(symbol).getrefs=0) then
  11325. begin
  11326. { Make sure the aligns get stripped too }
  11327. hp1 := tai(hp_lblxxx.Previous);
  11328. while Assigned(hp1) and (hp1.typ = ait_align) do
  11329. begin
  11330. hp_lblxxx := hp1;
  11331. hp1 := tai(hp_lblxxx.Previous);
  11332. end;
  11333. StripLabelFast(hp_lblxxx);
  11334. end;
  11335. end;
  11336. Exit;
  11337. end;
  11338. end
  11339. else if assigned(hp_lblxxx) and
  11340. { check further for
  11341. jCC xxx
  11342. <several movs 1>
  11343. jmp yyy
  11344. xxx:
  11345. <several movs 2>
  11346. yyy:
  11347. }
  11348. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11349. { hp1 should be pointing to jmp yyy }
  11350. MatchInstruction(hp1, A_JMP, []) and
  11351. { real label and jump, no further references to the
  11352. label are allowed }
  11353. (TAsmLabel(symbol).getrefs=1) and
  11354. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11355. begin
  11356. hp_jump := hp1;
  11357. { Don't set c to zero }
  11358. l := 0;
  11359. w := 0;
  11360. GetNextInstruction(hp_lblxxx, hpmov2);
  11361. hp2 := hp_lblxxx;
  11362. hp_lblyyy := hpmov2;
  11363. while assigned(hp_lblyyy) and
  11364. { stop on labels }
  11365. (hp_lblyyy.typ <> ait_label) do
  11366. begin
  11367. { Keep track of all integer registers that are used }
  11368. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11369. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11370. Break;
  11371. hp2 := hp_lblyyy;
  11372. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11373. end;
  11374. { Analyse the second batch of MOVs to see if the setup is valid }
  11375. RefModified := False;
  11376. hp1 := hpmov2;
  11377. while assigned(hp1) and
  11378. (hp1 <> hp_lblyyy) do
  11379. begin
  11380. case hp1.typ of
  11381. ait_instruction:
  11382. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11383. begin
  11384. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11385. begin
  11386. Inc(l);
  11387. { MOV instruction will be writing to a register }
  11388. if Assigned(hp_prev) and
  11389. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11390. (hp_prev.typ = ait_instruction) and
  11391. (taicpu(hp_prev).ops = 2) and
  11392. (
  11393. (
  11394. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11395. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11396. ) or
  11397. (
  11398. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11399. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11400. )
  11401. ) then
  11402. { It is no longer safe to use the reference in the condition.
  11403. this prevents problems such as:
  11404. mov (%reg),%reg
  11405. mov (%reg),...
  11406. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11407. (fixes #40165)
  11408. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11409. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11410. }
  11411. RefModified := True;
  11412. end
  11413. else if not (cs_opt_size in current_settings.optimizerswitches)
  11414. { CMOV with constants grows the code size }
  11415. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11416. begin
  11417. { Register was reserved by TryCMOVConst and
  11418. stored on ConstRegs[c] }
  11419. end
  11420. else
  11421. Break;
  11422. end
  11423. else
  11424. Break;
  11425. else
  11426. ;
  11427. end;
  11428. GetNextInstruction(hp1,hp1);
  11429. end;
  11430. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11431. TmpUsedRegs[R_INTREGISTER].Clear;
  11432. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11433. (hp1 = hp_lblyyy) and
  11434. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11435. begin
  11436. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11437. second_condition := taicpu(p).condition;
  11438. condition := inverse_cond(taicpu(p).condition);
  11439. UpdateUsedRegs(tai(p.next));
  11440. { Scan through the first set of MOVs to update UsedRegs,
  11441. but don't process them yet }
  11442. hp1 := hpmov1;
  11443. repeat
  11444. if not Assigned(hp1) then
  11445. InternalError(2018062901);
  11446. UpdateUsedRegs(tai(hp1.next));
  11447. GetNextInstruction(hp1, hp1);
  11448. until (hp1 = hp_lblxxx);
  11449. UpdateUsedRegs(tai(hp_lblxxx.next));
  11450. { Process the second set of MOVs first,
  11451. because if a destination register is
  11452. shared between the first and second MOV
  11453. sets, it is more efficient to turn the
  11454. first one into a MOV instruction and place
  11455. it before the CMP if possible, but we
  11456. won't know which registers are shared
  11457. until we've processed at least one list,
  11458. so we might as well make it the second
  11459. one since that won't be modified again. }
  11460. hp1 := hpmov2;
  11461. repeat
  11462. if not Assigned(hp1) then
  11463. InternalError(2018062902);
  11464. if (hp1.typ = ait_instruction) then
  11465. begin
  11466. { Extra safeguard }
  11467. if (taicpu(hp1).opcode <> A_MOV) then
  11468. InternalError(2018062903);
  11469. if taicpu(hp1).oper[0]^.typ = top_const then
  11470. begin
  11471. RegMatch := False;
  11472. for x := 0 to c - 1 do
  11473. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11474. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11475. begin
  11476. RegMatch := True;
  11477. { If it's in TmpUsedRegs, then this register
  11478. is being used more than once and hence has
  11479. already had its value defined (it gets
  11480. added to UsedRegs through AllocRegBetween
  11481. below) }
  11482. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11483. begin
  11484. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11485. asml.InsertBefore(hp_new, hp_flagalloc);
  11486. if Assigned(hp_prev2) then
  11487. TrySwapMovOp(hp_prev2, hp_new);
  11488. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11489. ConstMovs[X] := hp_new;
  11490. end
  11491. else
  11492. { We just need an instruction between hp_prev and hp1
  11493. where we know the register is marked as in use }
  11494. hp_new := hpmov2;
  11495. { Keep track of largest write for this register so it can be optimised later }
  11496. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11497. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11498. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11499. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11500. Break;
  11501. end;
  11502. if not RegMatch then
  11503. InternalError(2021100411);
  11504. end;
  11505. taicpu(hp1).opcode := A_CMOVcc;
  11506. taicpu(hp1).condition := second_condition;
  11507. { Store these writes to search for
  11508. duplicates later on }
  11509. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11510. Inc(w);
  11511. end;
  11512. UpdateUsedRegs(tai(hp1.next));
  11513. GetNextInstruction(hp1, hp1);
  11514. until (hp1 = hp_lblyyy);
  11515. { Now do the first set of MOVs }
  11516. hp1 := hpmov1;
  11517. repeat
  11518. if not Assigned(hp1) then
  11519. InternalError(2018062904);
  11520. if (hp1.typ = ait_instruction) then
  11521. begin
  11522. RegMatch := False;
  11523. { Extra safeguard }
  11524. if (taicpu(hp1).opcode <> A_MOV) then
  11525. InternalError(2018062905);
  11526. { Search through the RegWrites list to see
  11527. if there are any opposing CMOV pairs that
  11528. write to the same register }
  11529. for x := 0 to w - 1 do
  11530. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11531. begin
  11532. { We have a match. Keep this as a MOV }
  11533. { Move ahead in preparation }
  11534. GetNextInstruction(hp1, hp1);
  11535. RegMatch := True;
  11536. Break;
  11537. end;
  11538. if RegMatch then
  11539. Continue;
  11540. if taicpu(hp1).oper[0]^.typ = top_const then
  11541. begin
  11542. RegMatch := False;
  11543. for x := 0 to c - 1 do
  11544. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11545. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11546. begin
  11547. RegMatch := True;
  11548. { If it's in TmpUsedRegs, then this register
  11549. is being used more than once and hence has
  11550. already had its value defined (it gets
  11551. added to UsedRegs through AllocRegBetween
  11552. below) }
  11553. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11554. begin
  11555. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11556. asml.InsertBefore(hp_new, hp_flagalloc);
  11557. if Assigned(hp_prev2) then
  11558. TrySwapMovOp(hp_prev2, hp_new);
  11559. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11560. ConstMovs[X] := hp_new;
  11561. end
  11562. else
  11563. { We just need an instruction between hp_prev and hp1
  11564. where we know the register is marked as in use }
  11565. hp_new := hpmov1;
  11566. { Keep track of largest write for this register so it can be optimised later }
  11567. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11568. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11569. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11570. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11571. Break;
  11572. end;
  11573. if not RegMatch then
  11574. InternalError(2021100412);
  11575. end;
  11576. taicpu(hp1).opcode := A_CMOVcc;
  11577. taicpu(hp1).condition := condition;
  11578. end;
  11579. GetNextInstruction(hp1, hp1);
  11580. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11581. { Update initialisation MOVs to the smallest possible size }
  11582. for x := 0 to c - 1 do
  11583. if Assigned(ConstMovs[x]) then
  11584. begin
  11585. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11586. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11587. end;
  11588. UpdateUsedRegs(tai(hp_jump.next));
  11589. UpdateUsedRegs(tai(hp_lblyyy.next));
  11590. { Get first instruction after label }
  11591. hp1 := p;
  11592. GetNextInstruction(hp_lblyyy, p);
  11593. { Don't dereference yet, as doing so will cause
  11594. GetNextInstruction to skip the label and
  11595. optional align marker. [Kit] }
  11596. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11597. { remove Jcc }
  11598. RemoveInstruction(hp1);
  11599. { Now we can safely decrement it }
  11600. tasmlabel(symbol).decrefs;
  11601. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11602. { Make sure the aligns get stripped too }
  11603. hp1 := tai(hp_lblxxx.Previous);
  11604. while Assigned(hp1) and (hp1.typ = ait_align) do
  11605. begin
  11606. hp_lblxxx := hp1;
  11607. hp1 := tai(hp_lblxxx.Previous);
  11608. end;
  11609. StripLabelFast(hp_lblxxx);
  11610. { remove jmp }
  11611. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11612. RemoveInstruction(hp_jump);
  11613. { As before, now we can safely decrement it }
  11614. TAsmLabel(symbol).decrefs;
  11615. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11616. if TAsmLabel(symbol).getrefs = 0 then
  11617. begin
  11618. { Make sure the aligns get stripped too }
  11619. hp1 := tai(hp_lblyyy.Previous);
  11620. while Assigned(hp1) and (hp1.typ = ait_align) do
  11621. begin
  11622. hp_lblyyy := hp1;
  11623. hp1 := tai(hp_lblyyy.Previous);
  11624. end;
  11625. StripLabelFast(hp_lblyyy);
  11626. end;
  11627. if Assigned(p) then
  11628. result := True;
  11629. exit;
  11630. end;
  11631. end;
  11632. end;
  11633. {$endif i8086}
  11634. end;
  11635. end;
  11636. end;
  11637. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11638. var
  11639. hp1,hp2,hp3: tai;
  11640. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11641. NewSize: TOpSize;
  11642. NewRegSize: TSubRegister;
  11643. Limit: TCgInt;
  11644. SwapOper: POper;
  11645. begin
  11646. result:=false;
  11647. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11648. GetNextInstruction(p,hp1) and
  11649. (hp1.typ = ait_instruction);
  11650. if reg_and_hp1_is_instr and
  11651. (
  11652. (taicpu(hp1).opcode <> A_LEA) or
  11653. { If the LEA instruction can be converted into an arithmetic instruction,
  11654. it may be possible to then fold it. }
  11655. (
  11656. { If the flags register is in use, don't change the instruction
  11657. to an ADD otherwise this will scramble the flags. [Kit] }
  11658. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11659. ConvertLEA(taicpu(hp1))
  11660. )
  11661. ) and
  11662. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11663. GetNextInstruction(hp1,hp2) and
  11664. MatchInstruction(hp2,A_MOV,[]) and
  11665. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11666. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11667. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11668. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11669. {$ifdef i386}
  11670. { not all registers have byte size sub registers on i386 }
  11671. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11672. {$endif i386}
  11673. (((taicpu(hp1).ops=2) and
  11674. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11675. ((taicpu(hp1).ops=1) and
  11676. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11677. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11678. begin
  11679. { change movsX/movzX reg/ref, reg2
  11680. add/sub/or/... reg3/$const, reg2
  11681. mov reg2 reg/ref
  11682. to add/sub/or/... reg3/$const, reg/ref }
  11683. { by example:
  11684. movswl %si,%eax movswl %si,%eax p
  11685. decl %eax addl %edx,%eax hp1
  11686. movw %ax,%si movw %ax,%si hp2
  11687. ->
  11688. movswl %si,%eax movswl %si,%eax p
  11689. decw %eax addw %edx,%eax hp1
  11690. movw %ax,%si movw %ax,%si hp2
  11691. }
  11692. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11693. {
  11694. ->
  11695. movswl %si,%eax movswl %si,%eax p
  11696. decw %si addw %dx,%si hp1
  11697. movw %ax,%si movw %ax,%si hp2
  11698. }
  11699. case taicpu(hp1).ops of
  11700. 1:
  11701. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11702. 2:
  11703. begin
  11704. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11705. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11706. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11707. end;
  11708. else
  11709. internalerror(2008042702);
  11710. end;
  11711. {
  11712. ->
  11713. decw %si addw %dx,%si p
  11714. }
  11715. DebugMsg(SPeepholeOptimization + 'var3',p);
  11716. RemoveCurrentP(p, hp1);
  11717. RemoveInstruction(hp2);
  11718. Result := True;
  11719. Exit;
  11720. end;
  11721. if reg_and_hp1_is_instr and
  11722. (taicpu(hp1).opcode = A_MOV) and
  11723. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11724. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11725. {$ifdef x86_64}
  11726. { check for implicit extension to 64 bit }
  11727. or
  11728. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11729. (taicpu(hp1).opsize=S_Q) and
  11730. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11731. )
  11732. {$endif x86_64}
  11733. )
  11734. then
  11735. begin
  11736. { change
  11737. movx %reg1,%reg2
  11738. mov %reg2,%reg3
  11739. dealloc %reg2
  11740. into
  11741. movx %reg,%reg3
  11742. }
  11743. TransferUsedRegs(TmpUsedRegs);
  11744. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11745. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11746. begin
  11747. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11748. {$ifdef x86_64}
  11749. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11750. (taicpu(hp1).opsize=S_Q) then
  11751. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11752. else
  11753. {$endif x86_64}
  11754. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11755. RemoveInstruction(hp1);
  11756. Result := True;
  11757. Exit;
  11758. end;
  11759. end;
  11760. if reg_and_hp1_is_instr and
  11761. ((taicpu(hp1).opcode=A_MOV) or
  11762. (taicpu(hp1).opcode=A_ADD) or
  11763. (taicpu(hp1).opcode=A_SUB) or
  11764. (taicpu(hp1).opcode=A_CMP) or
  11765. (taicpu(hp1).opcode=A_OR) or
  11766. (taicpu(hp1).opcode=A_XOR) or
  11767. (taicpu(hp1).opcode=A_AND)
  11768. ) and
  11769. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11770. begin
  11771. AndTest := (taicpu(hp1).opcode=A_AND) and
  11772. GetNextInstruction(hp1, hp2) and
  11773. (hp2.typ = ait_instruction) and
  11774. (
  11775. (
  11776. (taicpu(hp2).opcode=A_TEST) and
  11777. (
  11778. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11779. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11780. (
  11781. { If the AND and TEST instructions share a constant, this is also valid }
  11782. (taicpu(hp1).oper[0]^.typ = top_const) and
  11783. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11784. )
  11785. ) and
  11786. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11787. ) or
  11788. (
  11789. (taicpu(hp2).opcode=A_CMP) and
  11790. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11791. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11792. )
  11793. );
  11794. { change
  11795. movx (oper),%reg2
  11796. and $x,%reg2
  11797. test %reg2,%reg2
  11798. dealloc %reg2
  11799. into
  11800. op %reg1,%reg3
  11801. if the second op accesses only the bits stored in reg1
  11802. }
  11803. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11804. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11805. (taicpu(hp1).oper[0]^.typ = top_const) and
  11806. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11807. AndTest then
  11808. begin
  11809. { Check if the AND constant is in range }
  11810. case taicpu(p).opsize of
  11811. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11812. begin
  11813. NewSize := S_B;
  11814. Limit := $FF;
  11815. end;
  11816. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11817. begin
  11818. NewSize := S_W;
  11819. Limit := $FFFF;
  11820. end;
  11821. {$ifdef x86_64}
  11822. S_LQ:
  11823. begin
  11824. NewSize := S_L;
  11825. Limit := $FFFFFFFF;
  11826. end;
  11827. {$endif x86_64}
  11828. else
  11829. InternalError(2021120303);
  11830. end;
  11831. if (
  11832. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11833. { Check for negative operands }
  11834. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11835. ) and
  11836. GetNextInstruction(hp2,hp3) and
  11837. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11838. (taicpu(hp3).condition in [C_E,C_NE]) then
  11839. begin
  11840. TransferUsedRegs(TmpUsedRegs);
  11841. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11842. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11843. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11844. begin
  11845. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11846. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11847. taicpu(hp1).opcode := A_TEST;
  11848. taicpu(hp1).opsize := NewSize;
  11849. RemoveInstruction(hp2);
  11850. RemoveCurrentP(p, hp1);
  11851. Result:=true;
  11852. exit;
  11853. end;
  11854. end;
  11855. end;
  11856. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11857. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11858. (taicpu(hp1).opsize=S_B)) or
  11859. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11860. (taicpu(hp1).opsize=S_W))
  11861. {$ifdef x86_64}
  11862. or ((taicpu(p).opsize=S_LQ) and
  11863. (taicpu(hp1).opsize=S_L))
  11864. {$endif x86_64}
  11865. ) and
  11866. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11867. begin
  11868. { change
  11869. movx %reg1,%reg2
  11870. op %reg2,%reg3
  11871. dealloc %reg2
  11872. into
  11873. op %reg1,%reg3
  11874. if the second op accesses only the bits stored in reg1
  11875. }
  11876. TransferUsedRegs(TmpUsedRegs);
  11877. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11878. if AndTest then
  11879. begin
  11880. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11881. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11882. end
  11883. else
  11884. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11885. if not RegUsed then
  11886. begin
  11887. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11888. if taicpu(p).oper[0]^.typ=top_reg then
  11889. begin
  11890. case taicpu(hp1).opsize of
  11891. S_B:
  11892. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11893. S_W:
  11894. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11895. S_L:
  11896. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11897. else
  11898. Internalerror(2020102301);
  11899. end;
  11900. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11901. end
  11902. else
  11903. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11904. RemoveCurrentP(p);
  11905. if AndTest then
  11906. RemoveInstruction(hp2);
  11907. result:=true;
  11908. exit;
  11909. end;
  11910. end
  11911. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11912. (
  11913. { Bitwise operations only }
  11914. (taicpu(hp1).opcode=A_AND) or
  11915. (taicpu(hp1).opcode=A_TEST) or
  11916. (
  11917. (taicpu(hp1).oper[0]^.typ = top_const) and
  11918. (
  11919. (taicpu(hp1).opcode=A_OR) or
  11920. (taicpu(hp1).opcode=A_XOR)
  11921. )
  11922. )
  11923. ) and
  11924. (
  11925. (taicpu(hp1).oper[0]^.typ = top_const) or
  11926. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11927. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11928. ) then
  11929. begin
  11930. { change
  11931. movx %reg2,%reg2
  11932. op const,%reg2
  11933. into
  11934. op const,%reg2 (smaller version)
  11935. movx %reg2,%reg2
  11936. also change
  11937. movx %reg1,%reg2
  11938. and/test (oper),%reg2
  11939. dealloc %reg2
  11940. into
  11941. and/test (oper),%reg1
  11942. }
  11943. case taicpu(p).opsize of
  11944. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11945. begin
  11946. NewSize := S_B;
  11947. NewRegSize := R_SUBL;
  11948. Limit := $FF;
  11949. end;
  11950. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11951. begin
  11952. NewSize := S_W;
  11953. NewRegSize := R_SUBW;
  11954. Limit := $FFFF;
  11955. end;
  11956. {$ifdef x86_64}
  11957. S_LQ:
  11958. begin
  11959. NewSize := S_L;
  11960. NewRegSize := R_SUBD;
  11961. Limit := $FFFFFFFF;
  11962. end;
  11963. {$endif x86_64}
  11964. else
  11965. Internalerror(2021120302);
  11966. end;
  11967. TransferUsedRegs(TmpUsedRegs);
  11968. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11969. if AndTest then
  11970. begin
  11971. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11972. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11973. end
  11974. else
  11975. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11976. if
  11977. (
  11978. (taicpu(p).opcode = A_MOVZX) and
  11979. (
  11980. (taicpu(hp1).opcode=A_AND) or
  11981. (taicpu(hp1).opcode=A_TEST)
  11982. ) and
  11983. not (
  11984. { If both are references, then the final instruction will have
  11985. both operands as references, which is not allowed }
  11986. (taicpu(p).oper[0]^.typ = top_ref) and
  11987. (taicpu(hp1).oper[0]^.typ = top_ref)
  11988. ) and
  11989. not RegUsed
  11990. ) or
  11991. (
  11992. (
  11993. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11994. not RegUsed
  11995. ) and
  11996. (taicpu(p).oper[0]^.typ = top_reg) and
  11997. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11998. (taicpu(hp1).oper[0]^.typ = top_const) and
  11999. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12000. ) then
  12001. begin
  12002. {$if defined(i386) or defined(i8086)}
  12003. { If the target size is 8-bit, make sure we can actually encode it }
  12004. 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
  12005. Exit;
  12006. {$endif i386 or i8086}
  12007. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12008. taicpu(hp1).opsize := NewSize;
  12009. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12010. if AndTest then
  12011. begin
  12012. RemoveInstruction(hp2);
  12013. if not RegUsed then
  12014. begin
  12015. taicpu(hp1).opcode := A_TEST;
  12016. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12017. begin
  12018. { Make sure the reference is the second operand }
  12019. SwapOper := taicpu(hp1).oper[0];
  12020. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12021. taicpu(hp1).oper[1] := SwapOper;
  12022. end;
  12023. end;
  12024. end;
  12025. case taicpu(hp1).oper[0]^.typ of
  12026. top_reg:
  12027. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12028. top_const:
  12029. { For the AND/TEST case }
  12030. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12031. else
  12032. ;
  12033. end;
  12034. if RegUsed then
  12035. begin
  12036. AsmL.Remove(p);
  12037. AsmL.InsertAfter(p, hp1);
  12038. p := hp1;
  12039. end
  12040. else
  12041. RemoveCurrentP(p, hp1);
  12042. result:=true;
  12043. exit;
  12044. end;
  12045. end;
  12046. end;
  12047. if reg_and_hp1_is_instr and
  12048. (taicpu(p).oper[0]^.typ = top_reg) and
  12049. (
  12050. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12051. ) and
  12052. (taicpu(hp1).oper[0]^.typ = top_const) and
  12053. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12054. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12055. { Minimum shift value allowed is the bit difference between the sizes }
  12056. (taicpu(hp1).oper[0]^.val >=
  12057. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12058. 8 * (
  12059. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12060. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12061. )
  12062. ) then
  12063. begin
  12064. { For:
  12065. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12066. shl/sal ##, %reg1
  12067. Remove the movsx/movzx instruction if the shift overwrites the
  12068. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12069. }
  12070. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12071. RemoveCurrentP(p, hp1);
  12072. Result := True;
  12073. Exit;
  12074. end
  12075. else if reg_and_hp1_is_instr and
  12076. (taicpu(p).oper[0]^.typ = top_reg) and
  12077. (
  12078. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12079. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12080. ) and
  12081. (taicpu(hp1).oper[0]^.typ = top_const) and
  12082. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12083. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12084. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12085. (taicpu(hp1).oper[0]^.val <
  12086. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12087. 8 * (
  12088. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12089. )
  12090. ) then
  12091. begin
  12092. { For:
  12093. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12094. sar ##, %reg1 shr ##, %reg1
  12095. Move the shift to before the movx instruction if the shift value
  12096. is not too large.
  12097. }
  12098. asml.Remove(hp1);
  12099. asml.InsertBefore(hp1, p);
  12100. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12101. case taicpu(p).opsize of
  12102. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12103. taicpu(hp1).opsize := S_B;
  12104. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12105. taicpu(hp1).opsize := S_W;
  12106. {$ifdef x86_64}
  12107. S_LQ:
  12108. taicpu(hp1).opsize := S_L;
  12109. {$endif}
  12110. else
  12111. InternalError(2020112401);
  12112. end;
  12113. if (taicpu(hp1).opcode = A_SHR) then
  12114. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12115. else
  12116. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12117. Result := True;
  12118. end;
  12119. if reg_and_hp1_is_instr and
  12120. (taicpu(p).oper[0]^.typ = top_reg) and
  12121. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12122. (
  12123. (taicpu(hp1).opcode = taicpu(p).opcode)
  12124. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12125. {$ifdef x86_64}
  12126. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12127. {$endif x86_64}
  12128. ) then
  12129. begin
  12130. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12131. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12132. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12133. begin
  12134. {
  12135. For example:
  12136. movzbw %al,%ax
  12137. movzwl %ax,%eax
  12138. Compress into:
  12139. movzbl %al,%eax
  12140. }
  12141. RegUsed := False;
  12142. case taicpu(p).opsize of
  12143. S_BW:
  12144. case taicpu(hp1).opsize of
  12145. S_WL:
  12146. begin
  12147. taicpu(p).opsize := S_BL;
  12148. RegUsed := True;
  12149. end;
  12150. {$ifdef x86_64}
  12151. S_WQ:
  12152. begin
  12153. if taicpu(p).opcode = A_MOVZX then
  12154. begin
  12155. taicpu(p).opsize := S_BL;
  12156. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12157. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12158. end
  12159. else
  12160. taicpu(p).opsize := S_BQ;
  12161. RegUsed := True;
  12162. end;
  12163. {$endif x86_64}
  12164. else
  12165. ;
  12166. end;
  12167. {$ifdef x86_64}
  12168. S_BL:
  12169. case taicpu(hp1).opsize of
  12170. S_LQ:
  12171. begin
  12172. if taicpu(p).opcode = A_MOVZX then
  12173. begin
  12174. taicpu(p).opsize := S_BL;
  12175. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12176. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12177. end
  12178. else
  12179. taicpu(p).opsize := S_BQ;
  12180. RegUsed := True;
  12181. end;
  12182. else
  12183. ;
  12184. end;
  12185. S_WL:
  12186. case taicpu(hp1).opsize of
  12187. S_LQ:
  12188. begin
  12189. if taicpu(p).opcode = A_MOVZX then
  12190. begin
  12191. taicpu(p).opsize := S_WL;
  12192. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12193. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12194. end
  12195. else
  12196. taicpu(p).opsize := S_WQ;
  12197. RegUsed := True;
  12198. end;
  12199. else
  12200. ;
  12201. end;
  12202. {$endif x86_64}
  12203. else
  12204. ;
  12205. end;
  12206. if RegUsed then
  12207. begin
  12208. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12209. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12210. RemoveInstruction(hp1);
  12211. Result := True;
  12212. Exit;
  12213. end;
  12214. end;
  12215. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12216. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12217. GetNextInstruction(hp1, hp2) and
  12218. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12219. (
  12220. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12221. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12222. {$ifdef x86_64}
  12223. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12224. {$endif x86_64}
  12225. ) and
  12226. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12227. (
  12228. (
  12229. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12230. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12231. ) or
  12232. (
  12233. { Only allow the operands in reverse order for TEST instructions }
  12234. (taicpu(hp2).opcode = A_TEST) and
  12235. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12236. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12237. )
  12238. ) then
  12239. begin
  12240. {
  12241. For example:
  12242. movzbl %al,%eax
  12243. movzbl (ref),%edx
  12244. andl %edx,%eax
  12245. (%edx deallocated)
  12246. Change to:
  12247. andb (ref),%al
  12248. movzbl %al,%eax
  12249. Rules are:
  12250. - First two instructions have the same opcode and opsize
  12251. - First instruction's operands are the same super-register
  12252. - Second instruction operates on a different register
  12253. - Third instruction is AND, OR, XOR or TEST
  12254. - Third instruction's operands are the destination registers of the first two instructions
  12255. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12256. - Second instruction's destination register is deallocated afterwards
  12257. }
  12258. TransferUsedRegs(TmpUsedRegs);
  12259. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12260. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12261. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12262. begin
  12263. case taicpu(p).opsize of
  12264. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12265. NewSize := S_B;
  12266. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12267. NewSize := S_W;
  12268. {$ifdef x86_64}
  12269. S_LQ:
  12270. NewSize := S_L;
  12271. {$endif x86_64}
  12272. else
  12273. InternalError(2021120301);
  12274. end;
  12275. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12276. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12277. taicpu(hp2).opsize := NewSize;
  12278. RemoveInstruction(hp1);
  12279. { With TEST, it's best to keep the MOVX instruction at the top }
  12280. if (taicpu(hp2).opcode <> A_TEST) then
  12281. begin
  12282. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12283. asml.Remove(p);
  12284. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12285. asml.InsertAfter(p, hp2);
  12286. p := hp2;
  12287. end
  12288. else
  12289. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12290. Result := True;
  12291. Exit;
  12292. end;
  12293. end;
  12294. end;
  12295. if taicpu(p).opcode=A_MOVZX then
  12296. begin
  12297. { removes superfluous And's after movzx's }
  12298. if reg_and_hp1_is_instr and
  12299. (taicpu(hp1).opcode = A_AND) and
  12300. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12301. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12302. {$ifdef x86_64}
  12303. { check for implicit extension to 64 bit }
  12304. or
  12305. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12306. (taicpu(hp1).opsize=S_Q) and
  12307. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12308. )
  12309. {$endif x86_64}
  12310. )
  12311. then
  12312. begin
  12313. case taicpu(p).opsize Of
  12314. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12315. if (taicpu(hp1).oper[0]^.val = $ff) then
  12316. begin
  12317. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12318. RemoveInstruction(hp1);
  12319. Result:=true;
  12320. exit;
  12321. end;
  12322. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12323. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12324. begin
  12325. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12326. RemoveInstruction(hp1);
  12327. Result:=true;
  12328. exit;
  12329. end;
  12330. {$ifdef x86_64}
  12331. S_LQ:
  12332. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12333. begin
  12334. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12335. RemoveInstruction(hp1);
  12336. Result:=true;
  12337. exit;
  12338. end;
  12339. {$endif x86_64}
  12340. else
  12341. ;
  12342. end;
  12343. { we cannot get rid of the and, but can we get rid of the movz ?}
  12344. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12345. begin
  12346. case taicpu(p).opsize Of
  12347. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12348. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12349. begin
  12350. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12351. RemoveCurrentP(p,hp1);
  12352. Result:=true;
  12353. exit;
  12354. end;
  12355. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12356. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12357. begin
  12358. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12359. RemoveCurrentP(p,hp1);
  12360. Result:=true;
  12361. exit;
  12362. end;
  12363. {$ifdef x86_64}
  12364. S_LQ:
  12365. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12366. begin
  12367. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12368. RemoveCurrentP(p,hp1);
  12369. Result:=true;
  12370. exit;
  12371. end;
  12372. {$endif x86_64}
  12373. else
  12374. ;
  12375. end;
  12376. end;
  12377. end;
  12378. { changes some movzx constructs to faster synonyms (all examples
  12379. are given with eax/ax, but are also valid for other registers)}
  12380. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12381. begin
  12382. case taicpu(p).opsize of
  12383. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12384. (the machine code is equivalent to movzbl %al,%eax), but the
  12385. code generator still generates that assembler instruction and
  12386. it is silently converted. This should probably be checked.
  12387. [Kit] }
  12388. S_BW:
  12389. begin
  12390. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12391. (
  12392. not IsMOVZXAcceptable
  12393. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12394. or (
  12395. (cs_opt_size in current_settings.optimizerswitches) and
  12396. (taicpu(p).oper[1]^.reg = NR_AX)
  12397. )
  12398. ) then
  12399. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12400. begin
  12401. DebugMsg(SPeepholeOptimization + 'var7',p);
  12402. taicpu(p).opcode := A_AND;
  12403. taicpu(p).changeopsize(S_W);
  12404. taicpu(p).loadConst(0,$ff);
  12405. Result := True;
  12406. end
  12407. else if not IsMOVZXAcceptable and
  12408. GetNextInstruction(p, hp1) and
  12409. (tai(hp1).typ = ait_instruction) and
  12410. (taicpu(hp1).opcode = A_AND) and
  12411. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12412. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12413. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12414. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12415. begin
  12416. DebugMsg(SPeepholeOptimization + 'var8',p);
  12417. taicpu(p).opcode := A_MOV;
  12418. taicpu(p).changeopsize(S_W);
  12419. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12420. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12421. Result := True;
  12422. end;
  12423. end;
  12424. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12425. S_BL:
  12426. if not IsMOVZXAcceptable then
  12427. begin
  12428. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12429. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12430. begin
  12431. DebugMsg(SPeepholeOptimization + 'var9',p);
  12432. taicpu(p).opcode := A_AND;
  12433. taicpu(p).changeopsize(S_L);
  12434. taicpu(p).loadConst(0,$ff);
  12435. Result := True;
  12436. end
  12437. else if GetNextInstruction(p, hp1) and
  12438. (tai(hp1).typ = ait_instruction) and
  12439. (taicpu(hp1).opcode = A_AND) and
  12440. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12441. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12442. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12443. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12444. begin
  12445. DebugMsg(SPeepholeOptimization + 'var10',p);
  12446. taicpu(p).opcode := A_MOV;
  12447. taicpu(p).changeopsize(S_L);
  12448. { do not use R_SUBWHOLE
  12449. as movl %rdx,%eax
  12450. is invalid in assembler PM }
  12451. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12452. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12453. Result := True;
  12454. end;
  12455. end;
  12456. {$endif i8086}
  12457. S_WL:
  12458. if not IsMOVZXAcceptable then
  12459. begin
  12460. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12461. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12462. begin
  12463. DebugMsg(SPeepholeOptimization + 'var11',p);
  12464. taicpu(p).opcode := A_AND;
  12465. taicpu(p).changeopsize(S_L);
  12466. taicpu(p).loadConst(0,$ffff);
  12467. Result := True;
  12468. end
  12469. else if GetNextInstruction(p, hp1) and
  12470. (tai(hp1).typ = ait_instruction) and
  12471. (taicpu(hp1).opcode = A_AND) and
  12472. (taicpu(hp1).oper[0]^.typ = top_const) and
  12473. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12474. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12475. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12476. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12477. begin
  12478. DebugMsg(SPeepholeOptimization + 'var12',p);
  12479. taicpu(p).opcode := A_MOV;
  12480. taicpu(p).changeopsize(S_L);
  12481. { do not use R_SUBWHOLE
  12482. as movl %rdx,%eax
  12483. is invalid in assembler PM }
  12484. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12485. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12486. Result := True;
  12487. end;
  12488. end;
  12489. else
  12490. InternalError(2017050705);
  12491. end;
  12492. end
  12493. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12494. begin
  12495. if GetNextInstruction(p, hp1) and
  12496. (tai(hp1).typ = ait_instruction) and
  12497. (taicpu(hp1).opcode = A_AND) and
  12498. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12499. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12500. begin
  12501. //taicpu(p).opcode := A_MOV;
  12502. case taicpu(p).opsize Of
  12503. S_BL:
  12504. begin
  12505. DebugMsg(SPeepholeOptimization + 'var13',p);
  12506. taicpu(hp1).changeopsize(S_L);
  12507. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12508. end;
  12509. S_WL:
  12510. begin
  12511. DebugMsg(SPeepholeOptimization + 'var14',p);
  12512. taicpu(hp1).changeopsize(S_L);
  12513. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12514. end;
  12515. S_BW:
  12516. begin
  12517. DebugMsg(SPeepholeOptimization + 'var15',p);
  12518. taicpu(hp1).changeopsize(S_W);
  12519. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12520. end;
  12521. else
  12522. Internalerror(2017050704)
  12523. end;
  12524. Result := True;
  12525. end;
  12526. end;
  12527. end;
  12528. end;
  12529. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12530. var
  12531. hp1, hp2 : tai;
  12532. MaskLength : Cardinal;
  12533. MaskedBits : TCgInt;
  12534. ActiveReg : TRegister;
  12535. begin
  12536. Result:=false;
  12537. { There are no optimisations for reference targets }
  12538. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12539. Exit;
  12540. while GetNextInstruction(p, hp1) and
  12541. (hp1.typ = ait_instruction) do
  12542. begin
  12543. if (taicpu(p).oper[0]^.typ = top_const) then
  12544. begin
  12545. case taicpu(hp1).opcode of
  12546. A_AND:
  12547. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12548. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12549. { the second register must contain the first one, so compare their subreg types }
  12550. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12551. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12552. { change
  12553. and const1, reg
  12554. and const2, reg
  12555. to
  12556. and (const1 and const2), reg
  12557. }
  12558. begin
  12559. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12560. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12561. RemoveCurrentP(p, hp1);
  12562. Result:=true;
  12563. exit;
  12564. end;
  12565. A_CMP:
  12566. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12567. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12568. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12569. { Just check that the condition on the next instruction is compatible }
  12570. GetNextInstruction(hp1, hp2) and
  12571. (hp2.typ = ait_instruction) and
  12572. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12573. then
  12574. { change
  12575. and 2^n, reg
  12576. cmp 2^n, reg
  12577. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12578. to
  12579. and 2^n, reg
  12580. test reg, reg
  12581. j(~c) / set(~c) / cmov(~c)
  12582. }
  12583. begin
  12584. { Keep TEST instruction in, rather than remove it, because
  12585. it may trigger other optimisations such as MovAndTest2Test }
  12586. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12587. taicpu(hp1).opcode := A_TEST;
  12588. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12589. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12590. Result := True;
  12591. Exit;
  12592. end
  12593. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12594. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12595. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12596. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12597. { change
  12598. and $ff/$ff/$ffff, reg
  12599. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12600. dealloc reg
  12601. to
  12602. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12603. }
  12604. begin
  12605. TransferUsedRegs(TmpUsedRegs);
  12606. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12607. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12608. begin
  12609. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12610. case taicpu(p).oper[0]^.val of
  12611. $ff:
  12612. begin
  12613. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12614. taicpu(hp1).opsize:=S_B;
  12615. end;
  12616. $ffff:
  12617. begin
  12618. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12619. taicpu(hp1).opsize:=S_W;
  12620. end;
  12621. $ffffffff:
  12622. begin
  12623. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12624. taicpu(hp1).opsize:=S_L;
  12625. end;
  12626. else
  12627. Internalerror(2023030401);
  12628. end;
  12629. RemoveCurrentP(p);
  12630. Result := True;
  12631. Exit;
  12632. end;
  12633. end;
  12634. A_MOVZX:
  12635. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12636. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12637. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12638. (
  12639. (
  12640. (taicpu(p).opsize=S_W) and
  12641. (taicpu(hp1).opsize=S_BW)
  12642. ) or
  12643. (
  12644. (taicpu(p).opsize=S_L) and
  12645. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12646. )
  12647. {$ifdef x86_64}
  12648. or
  12649. (
  12650. (taicpu(p).opsize=S_Q) and
  12651. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12652. )
  12653. {$endif x86_64}
  12654. ) then
  12655. begin
  12656. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12657. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12658. ) or
  12659. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12660. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12661. then
  12662. begin
  12663. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12664. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12665. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12666. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12667. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12668. }
  12669. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12670. RemoveInstruction(hp1);
  12671. { See if there are other optimisations possible }
  12672. Continue;
  12673. end;
  12674. end;
  12675. A_SHL:
  12676. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12677. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12678. begin
  12679. {$ifopt R+}
  12680. {$define RANGE_WAS_ON}
  12681. {$R-}
  12682. {$endif}
  12683. { get length of potential and mask }
  12684. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12685. { really a mask? }
  12686. {$ifdef RANGE_WAS_ON}
  12687. {$R+}
  12688. {$endif}
  12689. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12690. { unmasked part shifted out? }
  12691. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12692. begin
  12693. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12694. RemoveCurrentP(p, hp1);
  12695. Result:=true;
  12696. exit;
  12697. end;
  12698. end;
  12699. A_SHR:
  12700. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12701. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12702. (taicpu(hp1).oper[0]^.val <= 63) then
  12703. begin
  12704. { Does SHR combined with the AND cover all the bits?
  12705. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12706. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12707. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12708. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12709. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12710. begin
  12711. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12712. RemoveCurrentP(p, hp1);
  12713. Result := True;
  12714. Exit;
  12715. end;
  12716. end;
  12717. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12718. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12719. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12720. begin
  12721. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12722. (
  12723. (
  12724. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12725. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12726. ) or (
  12727. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12728. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12729. {$ifdef x86_64}
  12730. ) or (
  12731. (taicpu(hp1).opsize = S_LQ) and
  12732. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12733. {$endif x86_64}
  12734. )
  12735. ) then
  12736. begin
  12737. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12738. begin
  12739. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12740. RemoveInstruction(hp1);
  12741. { See if there are other optimisations possible }
  12742. Continue;
  12743. end;
  12744. { The super-registers are the same though.
  12745. Note that this change by itself doesn't improve
  12746. code speed, but it opens up other optimisations. }
  12747. {$ifdef x86_64}
  12748. { Convert 64-bit register to 32-bit }
  12749. case taicpu(hp1).opsize of
  12750. S_BQ:
  12751. begin
  12752. taicpu(hp1).opsize := S_BL;
  12753. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12754. end;
  12755. S_WQ:
  12756. begin
  12757. taicpu(hp1).opsize := S_WL;
  12758. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12759. end
  12760. else
  12761. ;
  12762. end;
  12763. {$endif x86_64}
  12764. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12765. taicpu(hp1).opcode := A_MOVZX;
  12766. { See if there are other optimisations possible }
  12767. Continue;
  12768. end;
  12769. end;
  12770. else
  12771. ;
  12772. end;
  12773. end
  12774. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12775. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12776. begin
  12777. {$ifdef x86_64}
  12778. if (taicpu(p).opsize = S_Q) then
  12779. begin
  12780. { Never necessary }
  12781. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12782. RemoveCurrentP(p, hp1);
  12783. Result := True;
  12784. Exit;
  12785. end;
  12786. {$endif x86_64}
  12787. { Forward check to determine necessity of and %reg,%reg }
  12788. TransferUsedRegs(TmpUsedRegs);
  12789. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12790. { Saves on a bunch of dereferences }
  12791. ActiveReg := taicpu(p).oper[1]^.reg;
  12792. case taicpu(hp1).opcode of
  12793. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12794. if (
  12795. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12796. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12797. ) and
  12798. (
  12799. (taicpu(hp1).opcode <> A_MOV) or
  12800. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12801. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12802. ) and
  12803. not (
  12804. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12805. (taicpu(hp1).opcode = A_MOV) and
  12806. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12807. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12808. ) and
  12809. (
  12810. (
  12811. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12812. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12813. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12814. ) or
  12815. (
  12816. {$ifdef x86_64}
  12817. (
  12818. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12819. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12820. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12821. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12822. ) and
  12823. {$endif x86_64}
  12824. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12825. )
  12826. ) then
  12827. begin
  12828. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12829. RemoveCurrentP(p, hp1);
  12830. Result := True;
  12831. Exit;
  12832. end;
  12833. A_ADD,
  12834. A_AND,
  12835. A_BSF,
  12836. A_BSR,
  12837. A_BTC,
  12838. A_BTR,
  12839. A_BTS,
  12840. A_OR,
  12841. A_SUB,
  12842. A_XOR:
  12843. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12844. if (
  12845. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12846. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12847. ) and
  12848. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12849. begin
  12850. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12851. RemoveCurrentP(p, hp1);
  12852. Result := True;
  12853. Exit;
  12854. end;
  12855. A_CMP,
  12856. A_TEST:
  12857. if (
  12858. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12859. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12860. ) and
  12861. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12862. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12863. begin
  12864. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12865. RemoveCurrentP(p, hp1);
  12866. Result := True;
  12867. Exit;
  12868. end;
  12869. A_BSWAP,
  12870. A_NEG,
  12871. A_NOT:
  12872. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12873. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12874. begin
  12875. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12876. RemoveCurrentP(p, hp1);
  12877. Result := True;
  12878. Exit;
  12879. end;
  12880. else
  12881. ;
  12882. end;
  12883. end;
  12884. if (taicpu(hp1).is_jmp) and
  12885. (taicpu(hp1).opcode<>A_JMP) and
  12886. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12887. begin
  12888. { change
  12889. and x, reg
  12890. jxx
  12891. to
  12892. test x, reg
  12893. jxx
  12894. if reg is deallocated before the
  12895. jump, but only if it's a conditional jump (PFV)
  12896. }
  12897. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12898. taicpu(p).opcode := A_TEST;
  12899. Exit;
  12900. end;
  12901. Break;
  12902. end;
  12903. { Lone AND tests }
  12904. if (taicpu(p).oper[0]^.typ = top_const) then
  12905. begin
  12906. {
  12907. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12908. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12909. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12910. }
  12911. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12912. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12913. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12914. begin
  12915. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12916. if taicpu(p).opsize = S_L then
  12917. begin
  12918. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12919. Result := True;
  12920. end;
  12921. end;
  12922. end;
  12923. { Backward check to determine necessity of and %reg,%reg }
  12924. if (taicpu(p).oper[0]^.typ = top_reg) and
  12925. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12926. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12927. GetLastInstruction(p, hp2) and
  12928. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12929. { Check size of adjacent instruction to determine if the AND is
  12930. effectively a null operation }
  12931. (
  12932. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12933. { Note: Don't include S_Q }
  12934. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12935. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12936. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12937. ) then
  12938. begin
  12939. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12940. { If GetNextInstruction returned False, hp1 will be nil }
  12941. RemoveCurrentP(p, hp1);
  12942. Result := True;
  12943. Exit;
  12944. end;
  12945. end;
  12946. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12947. var
  12948. hp1, hp2: tai;
  12949. NewRef: TReference;
  12950. Distance: Cardinal;
  12951. TempTracking: TAllUsedRegs;
  12952. { This entire nested function is used in an if-statement below, but we
  12953. want to avoid all the used reg transfers and GetNextInstruction calls
  12954. until we really have to check }
  12955. function MemRegisterNotUsedLater: Boolean; inline;
  12956. var
  12957. hp2: tai;
  12958. begin
  12959. TransferUsedRegs(TmpUsedRegs);
  12960. hp2 := p;
  12961. repeat
  12962. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12963. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12964. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12965. end;
  12966. begin
  12967. Result := False;
  12968. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12969. (taicpu(p).oper[1]^.typ = top_reg) then
  12970. begin
  12971. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12972. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12973. (hp1.typ <> ait_instruction) or
  12974. not
  12975. (
  12976. (cs_opt_level3 in current_settings.optimizerswitches) or
  12977. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12978. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12979. ) then
  12980. Exit;
  12981. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12982. addq $x, %rax
  12983. movq %rax, %rdx
  12984. sarq $63, %rdx
  12985. (%rax still in use)
  12986. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12987. leaq $x(%rax),%rdx
  12988. addq $x, %rax
  12989. sarq $63, %rdx
  12990. ...which is okay since it breaks the dependency chain between
  12991. addq and movq, but if OptPass2MOV is called first:
  12992. addq $x, %rax
  12993. cqto
  12994. ...which is better in all ways, taking only 2 cycles to execute
  12995. and much smaller in code size.
  12996. }
  12997. { The extra register tracking is quite strenuous }
  12998. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12999. MatchInstruction(hp1, A_MOV, []) then
  13000. begin
  13001. { Update the register tracking to the MOV instruction }
  13002. CopyUsedRegs(TempTracking);
  13003. hp2 := p;
  13004. repeat
  13005. UpdateUsedRegs(tai(hp2.Next));
  13006. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13007. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13008. OptPass2ADD get called again }
  13009. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13010. begin
  13011. { Reset the tracking to the current instruction }
  13012. RestoreUsedRegs(TempTracking);
  13013. ReleaseUsedRegs(TempTracking);
  13014. Result := True;
  13015. Exit;
  13016. end;
  13017. { Reset the tracking to the current instruction }
  13018. RestoreUsedRegs(TempTracking);
  13019. ReleaseUsedRegs(TempTracking);
  13020. { If OptPass2MOV returned True, we don't need to set Result to
  13021. True if hp1 didn't change because the ADD instruction didn't
  13022. get modified and we'll be evaluating hp1 again when the
  13023. peephole optimizer reaches it }
  13024. end;
  13025. { Change:
  13026. add %reg2,%reg1
  13027. (%reg2 not modified in between)
  13028. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13029. To:
  13030. mov/s/z #(%reg1,%reg2),%reg1
  13031. }
  13032. if (taicpu(p).oper[0]^.typ = top_reg) and
  13033. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13034. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13035. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13036. (
  13037. (
  13038. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13039. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13040. { r/esp cannot be an index }
  13041. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13042. ) or (
  13043. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13044. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13045. )
  13046. ) and (
  13047. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13048. (
  13049. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13050. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13051. MemRegisterNotUsedLater
  13052. )
  13053. ) then
  13054. begin
  13055. if (
  13056. { Instructions are guaranteed to be adjacent on -O2 and under }
  13057. (cs_opt_level3 in current_settings.optimizerswitches) and
  13058. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13059. ) then
  13060. begin
  13061. { If the other register is used in between, move the MOV
  13062. instruction to right after the ADD instruction so a
  13063. saving can still be made }
  13064. Asml.Remove(hp1);
  13065. Asml.InsertAfter(hp1, p);
  13066. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13067. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13068. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13069. RemoveCurrentp(p, hp1);
  13070. end
  13071. else
  13072. begin
  13073. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13074. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13075. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13076. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13077. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13078. { hp1 may not be the immediate next instruction under -O3 }
  13079. RemoveCurrentp(p)
  13080. else
  13081. RemoveCurrentp(p, hp1);
  13082. end;
  13083. Result := True;
  13084. Exit;
  13085. end;
  13086. { Change:
  13087. addl/q $x,%reg1
  13088. movl/q %reg1,%reg2
  13089. To:
  13090. leal/q $x(%reg1),%reg2
  13091. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13092. Breaks the dependency chain.
  13093. }
  13094. if (taicpu(p).oper[0]^.typ = top_const) and
  13095. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13096. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13097. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13098. (
  13099. { Instructions are guaranteed to be adjacent on -O2 and under }
  13100. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13101. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13102. ) then
  13103. begin
  13104. TransferUsedRegs(TmpUsedRegs);
  13105. hp2 := p;
  13106. repeat
  13107. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13108. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13109. if (
  13110. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13111. not (cs_opt_size in current_settings.optimizerswitches) or
  13112. (
  13113. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13114. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13115. )
  13116. ) then
  13117. begin
  13118. { Change the MOV instruction to a LEA instruction, and update the
  13119. first operand }
  13120. reference_reset(NewRef, 1, []);
  13121. NewRef.base := taicpu(p).oper[1]^.reg;
  13122. NewRef.scalefactor := 1;
  13123. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13124. taicpu(hp1).opcode := A_LEA;
  13125. taicpu(hp1).loadref(0, NewRef);
  13126. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13127. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13128. begin
  13129. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13130. { Move what is now the LEA instruction to before the ADD instruction }
  13131. Asml.Remove(hp1);
  13132. Asml.InsertBefore(hp1, p);
  13133. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13134. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13135. p := hp1;
  13136. end
  13137. else
  13138. begin
  13139. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13140. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13141. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13142. { hp1 may not be the immediate next instruction under -O3 }
  13143. RemoveCurrentp(p)
  13144. else
  13145. RemoveCurrentp(p, hp1);
  13146. end;
  13147. Result := True;
  13148. end;
  13149. end;
  13150. end;
  13151. end;
  13152. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13153. var
  13154. SubReg: TSubRegister;
  13155. begin
  13156. Result:=false;
  13157. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13158. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13159. with taicpu(p).oper[0]^.ref^ do
  13160. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13161. begin
  13162. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13163. begin
  13164. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13165. taicpu(p).opcode := A_ADD;
  13166. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13167. Result := True;
  13168. end
  13169. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13170. begin
  13171. if (base <> NR_NO) then
  13172. begin
  13173. if (scalefactor <= 1) then
  13174. begin
  13175. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13176. taicpu(p).opcode := A_ADD;
  13177. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13178. Result := True;
  13179. end;
  13180. end
  13181. else
  13182. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13183. if (scalefactor in [2, 4, 8]) then
  13184. begin
  13185. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13186. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13187. taicpu(p).opcode := A_SHL;
  13188. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13189. Result := True;
  13190. end;
  13191. end;
  13192. end;
  13193. end;
  13194. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13195. var
  13196. hp1, hp2: tai;
  13197. NewRef: TReference;
  13198. Distance: Cardinal;
  13199. TempTracking: TAllUsedRegs;
  13200. begin
  13201. Result := False;
  13202. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13203. MatchOpType(taicpu(p),top_const,top_reg) then
  13204. begin
  13205. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13206. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13207. (hp1.typ <> ait_instruction) or
  13208. not
  13209. (
  13210. (cs_opt_level3 in current_settings.optimizerswitches) or
  13211. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13212. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13213. ) then
  13214. Exit;
  13215. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13216. subq $x, %rax
  13217. movq %rax, %rdx
  13218. sarq $63, %rdx
  13219. (%rax still in use)
  13220. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13221. leaq $-x(%rax),%rdx
  13222. movq $x, %rax
  13223. sarq $63, %rdx
  13224. ...which is okay since it breaks the dependency chain between
  13225. subq and movq, but if OptPass2MOV is called first:
  13226. subq $x, %rax
  13227. cqto
  13228. ...which is better in all ways, taking only 2 cycles to execute
  13229. and much smaller in code size.
  13230. }
  13231. { The extra register tracking is quite strenuous }
  13232. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13233. MatchInstruction(hp1, A_MOV, []) then
  13234. begin
  13235. { Update the register tracking to the MOV instruction }
  13236. CopyUsedRegs(TempTracking);
  13237. hp2 := p;
  13238. repeat
  13239. UpdateUsedRegs(tai(hp2.Next));
  13240. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13241. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13242. OptPass2SUB get called again }
  13243. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13244. begin
  13245. { Reset the tracking to the current instruction }
  13246. RestoreUsedRegs(TempTracking);
  13247. ReleaseUsedRegs(TempTracking);
  13248. Result := True;
  13249. Exit;
  13250. end;
  13251. { Reset the tracking to the current instruction }
  13252. RestoreUsedRegs(TempTracking);
  13253. ReleaseUsedRegs(TempTracking);
  13254. { If OptPass2MOV returned True, we don't need to set Result to
  13255. True if hp1 didn't change because the SUB instruction didn't
  13256. get modified and we'll be evaluating hp1 again when the
  13257. peephole optimizer reaches it }
  13258. end;
  13259. { Change:
  13260. subl/q $x,%reg1
  13261. movl/q %reg1,%reg2
  13262. To:
  13263. leal/q $-x(%reg1),%reg2
  13264. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13265. Breaks the dependency chain and potentially permits the removal of
  13266. a CMP instruction if one follows.
  13267. }
  13268. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13269. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13270. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13271. (
  13272. { Instructions are guaranteed to be adjacent on -O2 and under }
  13273. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13274. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13275. ) then
  13276. begin
  13277. TransferUsedRegs(TmpUsedRegs);
  13278. hp2 := p;
  13279. repeat
  13280. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13281. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13282. if (
  13283. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13284. not (cs_opt_size in current_settings.optimizerswitches) or
  13285. (
  13286. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13287. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13288. )
  13289. ) then
  13290. begin
  13291. { Change the MOV instruction to a LEA instruction, and update the
  13292. first operand }
  13293. reference_reset(NewRef, 1, []);
  13294. NewRef.base := taicpu(p).oper[1]^.reg;
  13295. NewRef.scalefactor := 1;
  13296. NewRef.offset := -taicpu(p).oper[0]^.val;
  13297. taicpu(hp1).opcode := A_LEA;
  13298. taicpu(hp1).loadref(0, NewRef);
  13299. TransferUsedRegs(TmpUsedRegs);
  13300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13301. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13302. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13303. begin
  13304. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13305. { Move what is now the LEA instruction to before the SUB instruction }
  13306. Asml.Remove(hp1);
  13307. Asml.InsertBefore(hp1, p);
  13308. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13309. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13310. p := hp1;
  13311. end
  13312. else
  13313. begin
  13314. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13315. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13316. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13317. { hp1 may not be the immediate next instruction under -O3 }
  13318. RemoveCurrentp(p)
  13319. else
  13320. RemoveCurrentp(p, hp1);
  13321. end;
  13322. Result := True;
  13323. end;
  13324. end;
  13325. end;
  13326. end;
  13327. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13328. begin
  13329. { we can skip all instructions not messing with the stack pointer }
  13330. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13331. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13332. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13333. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13334. ({(taicpu(hp1).ops=0) or }
  13335. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13336. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13337. ) and }
  13338. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13339. )
  13340. ) do
  13341. GetNextInstruction(hp1,hp1);
  13342. Result:=assigned(hp1);
  13343. end;
  13344. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13345. var
  13346. hp1, hp2, hp3, hp4, hp5: tai;
  13347. begin
  13348. Result:=false;
  13349. hp5:=nil;
  13350. { replace
  13351. leal(q) x(<stackpointer>),<stackpointer>
  13352. call procname
  13353. leal(q) -x(<stackpointer>),<stackpointer>
  13354. ret
  13355. by
  13356. jmp procname
  13357. but do it only on level 4 because it destroys stack back traces
  13358. }
  13359. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13360. MatchOpType(taicpu(p),top_ref,top_reg) and
  13361. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13362. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13363. { the -8 or -24 are not required, but bail out early if possible,
  13364. higher values are unlikely }
  13365. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13366. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13367. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13368. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13369. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13370. GetNextInstruction(p, hp1) and
  13371. { Take a copy of hp1 }
  13372. SetAndTest(hp1, hp4) and
  13373. { trick to skip label }
  13374. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13375. SkipSimpleInstructions(hp1) and
  13376. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13377. GetNextInstruction(hp1, hp2) and
  13378. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13379. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13380. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13381. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13382. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13383. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13384. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13385. { Segment register will be NR_NO }
  13386. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13387. GetNextInstruction(hp2, hp3) and
  13388. { trick to skip label }
  13389. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13390. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13391. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13392. SetAndTest(hp3,hp5) and
  13393. GetNextInstruction(hp3,hp3) and
  13394. MatchInstruction(hp3,A_RET,[S_NO])
  13395. )
  13396. ) and
  13397. (taicpu(hp3).ops=0) then
  13398. begin
  13399. taicpu(hp1).opcode := A_JMP;
  13400. taicpu(hp1).is_jmp := true;
  13401. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13402. RemoveCurrentP(p, hp4);
  13403. RemoveInstruction(hp2);
  13404. RemoveInstruction(hp3);
  13405. if Assigned(hp5) then
  13406. begin
  13407. AsmL.Remove(hp5);
  13408. ASmL.InsertBefore(hp5,hp1)
  13409. end;
  13410. Result:=true;
  13411. end;
  13412. end;
  13413. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13414. {$ifdef x86_64}
  13415. var
  13416. hp1, hp2, hp3, hp4, hp5: tai;
  13417. {$endif x86_64}
  13418. begin
  13419. Result:=false;
  13420. {$ifdef x86_64}
  13421. hp5:=nil;
  13422. { replace
  13423. push %rax
  13424. call procname
  13425. pop %rcx
  13426. ret
  13427. by
  13428. jmp procname
  13429. but do it only on level 4 because it destroys stack back traces
  13430. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13431. for all supported calling conventions
  13432. }
  13433. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13434. MatchOpType(taicpu(p),top_reg) and
  13435. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13436. GetNextInstruction(p, hp1) and
  13437. { Take a copy of hp1 }
  13438. SetAndTest(hp1, hp4) and
  13439. { trick to skip label }
  13440. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13441. SkipSimpleInstructions(hp1) and
  13442. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13443. GetNextInstruction(hp1, hp2) and
  13444. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13445. MatchOpType(taicpu(hp2),top_reg) and
  13446. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13447. GetNextInstruction(hp2, hp3) and
  13448. { trick to skip label }
  13449. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13450. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13451. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13452. SetAndTest(hp3,hp5) and
  13453. GetNextInstruction(hp3,hp3) and
  13454. MatchInstruction(hp3,A_RET,[S_NO])
  13455. )
  13456. ) and
  13457. (taicpu(hp3).ops=0) then
  13458. begin
  13459. taicpu(hp1).opcode := A_JMP;
  13460. taicpu(hp1).is_jmp := true;
  13461. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13462. RemoveCurrentP(p, hp4);
  13463. RemoveInstruction(hp2);
  13464. RemoveInstruction(hp3);
  13465. if Assigned(hp5) then
  13466. begin
  13467. AsmL.Remove(hp5);
  13468. ASmL.InsertBefore(hp5,hp1)
  13469. end;
  13470. Result:=true;
  13471. end;
  13472. {$endif x86_64}
  13473. end;
  13474. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13475. var
  13476. Value, RegName: string;
  13477. begin
  13478. Result:=false;
  13479. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13480. begin
  13481. case taicpu(p).oper[0]^.val of
  13482. 0:
  13483. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13484. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13485. begin
  13486. { change "mov $0,%reg" into "xor %reg,%reg" }
  13487. taicpu(p).opcode := A_XOR;
  13488. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13489. Result := True;
  13490. {$ifdef x86_64}
  13491. end
  13492. else if (taicpu(p).opsize = S_Q) then
  13493. begin
  13494. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13495. { The actual optimization }
  13496. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13497. taicpu(p).changeopsize(S_L);
  13498. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13499. Result := True;
  13500. end;
  13501. $1..$FFFFFFFF:
  13502. begin
  13503. { Code size reduction by J. Gareth "Kit" Moreton }
  13504. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13505. case taicpu(p).opsize of
  13506. S_Q:
  13507. begin
  13508. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13509. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13510. { The actual optimization }
  13511. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13512. taicpu(p).changeopsize(S_L);
  13513. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13514. Result := True;
  13515. end;
  13516. else
  13517. { Do nothing };
  13518. end;
  13519. {$endif x86_64}
  13520. end;
  13521. -1:
  13522. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13523. if (cs_opt_size in current_settings.optimizerswitches) and
  13524. (taicpu(p).opsize <> S_B) and
  13525. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13526. begin
  13527. { change "mov $-1,%reg" into "or $-1,%reg" }
  13528. { NOTES:
  13529. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13530. - This operation creates a false dependency on the register, so only do it when optimising for size
  13531. - 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
  13532. }
  13533. taicpu(p).opcode := A_OR;
  13534. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13535. Result := True;
  13536. end;
  13537. else
  13538. { Do nothing };
  13539. end;
  13540. end;
  13541. end;
  13542. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13543. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13544. begin
  13545. Result := False;
  13546. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13547. Exit;
  13548. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13549. so don't bother optimising }
  13550. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13551. Exit;
  13552. if (taicpu(p).oper[0]^.typ <> top_const) or
  13553. { If the value can fit into an 8-bit signed integer, a smaller
  13554. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13555. falls within this range }
  13556. (
  13557. (taicpu(p).oper[0]^.val > -128) and
  13558. (taicpu(p).oper[0]^.val <= 127)
  13559. ) then
  13560. Exit;
  13561. { If we're optimising for size, this is acceptable }
  13562. if (cs_opt_size in current_settings.optimizerswitches) then
  13563. Exit(True);
  13564. if (taicpu(p).oper[1]^.typ = top_reg) and
  13565. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13566. Exit(True);
  13567. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13568. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13569. Exit(True);
  13570. end;
  13571. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13572. var
  13573. hp1: tai;
  13574. Value: TCGInt;
  13575. begin
  13576. Result := False;
  13577. if MatchOpType(taicpu(p), top_const, top_reg) then
  13578. begin
  13579. { Detect:
  13580. andw x, %ax (0 <= x < $8000)
  13581. ...
  13582. movzwl %ax,%eax
  13583. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13584. }
  13585. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13586. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13587. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13588. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13589. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13590. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13591. begin
  13592. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13593. taicpu(hp1).opcode := A_CWDE;
  13594. taicpu(hp1).clearop(0);
  13595. taicpu(hp1).clearop(1);
  13596. taicpu(hp1).ops := 0;
  13597. { A change was made, but not with p, so don't set Result, but
  13598. notify the compiler that a change was made }
  13599. Include(OptsToCheck, aoc_ForceNewIteration);
  13600. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13601. end;
  13602. end;
  13603. { If "not x" is a power of 2 (popcnt = 1), change:
  13604. and $x, %reg/ref
  13605. To:
  13606. btr lb(x), %reg/ref
  13607. }
  13608. if IsBTXAcceptable(p) and
  13609. (
  13610. { Make sure a TEST doesn't follow that plays with the register }
  13611. not GetNextInstruction(p, hp1) or
  13612. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13613. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13614. ) then
  13615. begin
  13616. {$push}{$R-}{$Q-}
  13617. { Value is a sign-extended 32-bit integer - just correct it
  13618. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13619. checks to see if this operand is an immediate. }
  13620. Value := not taicpu(p).oper[0]^.val;
  13621. {$pop}
  13622. {$ifdef x86_64}
  13623. if taicpu(p).opsize = S_L then
  13624. {$endif x86_64}
  13625. Value := Value and $FFFFFFFF;
  13626. if (PopCnt(QWord(Value)) = 1) then
  13627. begin
  13628. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13629. taicpu(p).opcode := A_BTR;
  13630. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13631. Result := True;
  13632. Exit;
  13633. end;
  13634. end;
  13635. end;
  13636. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13637. begin
  13638. Result := False;
  13639. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13640. Exit;
  13641. { Convert:
  13642. movswl %ax,%eax -> cwtl
  13643. movslq %eax,%rax -> cdqe
  13644. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13645. refer to the same opcode and depends only on the assembler's
  13646. current operand-size attribute. [Kit]
  13647. }
  13648. with taicpu(p) do
  13649. case opsize of
  13650. S_WL:
  13651. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13652. begin
  13653. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13654. opcode := A_CWDE;
  13655. clearop(0);
  13656. clearop(1);
  13657. ops := 0;
  13658. Result := True;
  13659. end;
  13660. {$ifdef x86_64}
  13661. S_LQ:
  13662. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13663. begin
  13664. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13665. opcode := A_CDQE;
  13666. clearop(0);
  13667. clearop(1);
  13668. ops := 0;
  13669. Result := True;
  13670. end;
  13671. {$endif x86_64}
  13672. else
  13673. ;
  13674. end;
  13675. end;
  13676. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13677. var
  13678. hp1, hp2: tai;
  13679. IdentityMask, Shift: TCGInt;
  13680. LimitSize: Topsize;
  13681. DoNotMerge: Boolean;
  13682. begin
  13683. Result := False;
  13684. { All these optimisations work on "shr const,%reg" }
  13685. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13686. Exit;
  13687. DoNotMerge := False;
  13688. Shift := taicpu(p).oper[0]^.val;
  13689. LimitSize := taicpu(p).opsize;
  13690. hp1 := p;
  13691. repeat
  13692. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13693. Break;
  13694. { Detect:
  13695. shr x, %reg
  13696. and y, %reg
  13697. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13698. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13699. }
  13700. case taicpu(hp1).opcode of
  13701. A_AND:
  13702. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13703. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13704. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13705. begin
  13706. { Make sure the FLAGS register isn't in use }
  13707. TransferUsedRegs(TmpUsedRegs);
  13708. hp2 := p;
  13709. repeat
  13710. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13711. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13712. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13713. begin
  13714. { Generate the identity mask }
  13715. case taicpu(p).opsize of
  13716. S_B:
  13717. IdentityMask := $FF shr Shift;
  13718. S_W:
  13719. IdentityMask := $FFFF shr Shift;
  13720. S_L:
  13721. IdentityMask := $FFFFFFFF shr Shift;
  13722. {$ifdef x86_64}
  13723. S_Q:
  13724. { We need to force the operands to be unsigned 64-bit
  13725. integers otherwise the wrong value is generated }
  13726. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13727. {$endif x86_64}
  13728. else
  13729. InternalError(2022081501);
  13730. end;
  13731. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13732. begin
  13733. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13734. { All the possible 1 bits are covered, so we can remove the AND }
  13735. hp2 := tai(hp1.Previous);
  13736. RemoveInstruction(hp1);
  13737. { p wasn't actually changed, so don't set Result to True,
  13738. but a change was nonetheless made elsewhere }
  13739. Include(OptsToCheck, aoc_ForceNewIteration);
  13740. { Do another pass in case other AND or MOVZX instructions
  13741. follow }
  13742. hp1 := hp2;
  13743. Continue;
  13744. end;
  13745. end;
  13746. end;
  13747. A_TEST, A_CMP, A_Jcc:
  13748. { Skip over conditional jumps and relevant comparisons }
  13749. Continue;
  13750. A_MOVZX:
  13751. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13752. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13753. begin
  13754. { Since the original register is being read as is, subsequent
  13755. SHRs must not be merged at this point }
  13756. DoNotMerge := True;
  13757. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13758. begin
  13759. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13760. begin
  13761. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13762. { All the possible 1 bits are covered, so we can remove the AND }
  13763. hp2 := tai(hp1.Previous);
  13764. RemoveInstruction(hp1);
  13765. hp1 := hp2;
  13766. end
  13767. else { Different register target }
  13768. begin
  13769. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13770. taicpu(hp1).opcode := A_MOV;
  13771. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13772. case taicpu(hp1).opsize of
  13773. S_BW:
  13774. taicpu(hp1).opsize := S_W;
  13775. S_BL, S_WL:
  13776. taicpu(hp1).opsize := S_L;
  13777. else
  13778. InternalError(2022081503);
  13779. end;
  13780. end;
  13781. end
  13782. else if (Shift > 0) and
  13783. (taicpu(p).opsize = S_W) and
  13784. (taicpu(hp1).opsize = S_WL) and
  13785. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13786. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13787. begin
  13788. { Detect:
  13789. shr x, %ax (x > 0)
  13790. ...
  13791. movzwl %ax,%eax
  13792. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13793. }
  13794. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13795. taicpu(hp1).opcode := A_CWDE;
  13796. taicpu(hp1).clearop(0);
  13797. taicpu(hp1).clearop(1);
  13798. taicpu(hp1).ops := 0;
  13799. end;
  13800. { Move onto the next instruction }
  13801. Continue;
  13802. end;
  13803. A_SHL, A_SAL, A_SHR:
  13804. if (taicpu(hp1).opsize <= LimitSize) and
  13805. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13806. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13807. begin
  13808. { Make sure the sizes don't exceed the register size limit
  13809. (measured by the shift value falling below the limit) }
  13810. if taicpu(hp1).opsize < LimitSize then
  13811. LimitSize := taicpu(hp1).opsize;
  13812. if taicpu(hp1).opcode = A_SHR then
  13813. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13814. else
  13815. begin
  13816. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13817. DoNotMerge := True;
  13818. end;
  13819. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13820. Break;
  13821. { Since we've established that the combined shift is within
  13822. limits, we can actually combine the adjacent SHR
  13823. instructions even if they're different sizes }
  13824. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13825. begin
  13826. hp2 := tai(hp1.Previous);
  13827. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13828. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13829. RemoveInstruction(hp1);
  13830. hp1 := hp2;
  13831. end;
  13832. { Move onto the next instruction }
  13833. Continue;
  13834. end;
  13835. else
  13836. ;
  13837. end;
  13838. Break;
  13839. until False;
  13840. { Detect the following (looking backwards):
  13841. shr %cl,%reg
  13842. shr x, %reg
  13843. Swap the two SHR instructions to minimise a pipeline stall.
  13844. }
  13845. if GetLastInstruction(p, hp1) and
  13846. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13847. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13848. { First operand will be %cl }
  13849. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13850. { Just to be sure }
  13851. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13852. begin
  13853. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13854. { Moving the entries this way ensures the register tracking remains correct }
  13855. Asml.Remove(p);
  13856. Asml.InsertBefore(p, hp1);
  13857. p := hp1;
  13858. { Don't set Result to True because the current instruction is now
  13859. "shr %cl,%reg" and there's nothing more we can do with it }
  13860. end;
  13861. end;
  13862. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13863. var
  13864. hp1, hp2: tai;
  13865. Opposite, SecondOpposite: TAsmOp;
  13866. NewCond: TAsmCond;
  13867. begin
  13868. Result := False;
  13869. { Change:
  13870. add/sub 128,(dest)
  13871. To:
  13872. sub/add -128,(dest)
  13873. This generaally takes fewer bytes to encode because -128 can be stored
  13874. in a signed byte, whereas +128 cannot.
  13875. }
  13876. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13877. begin
  13878. if taicpu(p).opcode = A_ADD then
  13879. Opposite := A_SUB
  13880. else
  13881. Opposite := A_ADD;
  13882. { Be careful if the flags are in use, because the CF flag inverts
  13883. when changing from ADD to SUB and vice versa }
  13884. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13885. GetNextInstruction(p, hp1) then
  13886. begin
  13887. TransferUsedRegs(TmpUsedRegs);
  13888. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13889. hp2 := hp1;
  13890. { Scan ahead to check if everything's safe }
  13891. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13892. begin
  13893. if (hp1.typ <> ait_instruction) then
  13894. { Probably unsafe since the flags are still in use }
  13895. Exit;
  13896. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13897. { Stop searching at an unconditional jump }
  13898. Break;
  13899. if not
  13900. (
  13901. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13902. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13903. ) and
  13904. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13905. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13906. Exit;
  13907. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13908. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13909. { Move to the next instruction }
  13910. GetNextInstruction(hp1, hp1);
  13911. end;
  13912. while Assigned(hp2) and (hp2 <> hp1) do
  13913. begin
  13914. NewCond := C_None;
  13915. case taicpu(hp2).condition of
  13916. C_A, C_NBE:
  13917. NewCond := C_BE;
  13918. C_B, C_C, C_NAE:
  13919. NewCond := C_AE;
  13920. C_AE, C_NB, C_NC:
  13921. NewCond := C_B;
  13922. C_BE, C_NA:
  13923. NewCond := C_A;
  13924. else
  13925. { No change needed };
  13926. end;
  13927. if NewCond <> C_None then
  13928. begin
  13929. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13930. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13931. taicpu(hp2).condition := NewCond;
  13932. end
  13933. else
  13934. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13935. begin
  13936. { Because of the flipping of the carry bit, to ensure
  13937. the operation remains equivalent, ADC becomes SBB
  13938. and vice versa, and the constant is not-inverted.
  13939. If multiple ADCs or SBBs appear in a row, each one
  13940. changed causes the carry bit to invert, so they all
  13941. need to be flipped }
  13942. if taicpu(hp2).opcode = A_ADC then
  13943. SecondOpposite := A_SBB
  13944. else
  13945. SecondOpposite := A_ADC;
  13946. if taicpu(hp2).oper[0]^.typ <> top_const then
  13947. { Should have broken out of this optimisation already }
  13948. InternalError(2021112901);
  13949. 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]^) + ' -> ' +
  13950. 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);
  13951. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13952. taicpu(hp2).opcode := SecondOpposite;
  13953. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13954. end;
  13955. { Move to the next instruction }
  13956. GetNextInstruction(hp2, hp2);
  13957. end;
  13958. if (hp2 <> hp1) then
  13959. InternalError(2021111501);
  13960. end;
  13961. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13962. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13963. taicpu(p).opcode := Opposite;
  13964. taicpu(p).oper[0]^.val := -128;
  13965. { No further optimisations can be made on this instruction, so move
  13966. onto the next one to save time }
  13967. p := tai(p.Next);
  13968. UpdateUsedRegs(p);
  13969. Result := True;
  13970. Exit;
  13971. end;
  13972. { Detect:
  13973. add/sub %reg2,(dest)
  13974. add/sub x, (dest)
  13975. (dest can be a register or a reference)
  13976. Swap the instructions to minimise a pipeline stall. This reverses the
  13977. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13978. optimisations could be made.
  13979. }
  13980. if (taicpu(p).oper[0]^.typ = top_reg) and
  13981. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13982. (
  13983. (
  13984. (taicpu(p).oper[1]^.typ = top_reg) and
  13985. { We can try searching further ahead if we're writing to a register }
  13986. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13987. ) or
  13988. (
  13989. (taicpu(p).oper[1]^.typ = top_ref) and
  13990. GetNextInstruction(p, hp1)
  13991. )
  13992. ) and
  13993. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13994. (taicpu(hp1).oper[0]^.typ = top_const) and
  13995. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13996. begin
  13997. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13998. TransferUsedRegs(TmpUsedRegs);
  13999. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14000. hp2 := p;
  14001. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14002. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14003. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14004. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14005. begin
  14006. asml.remove(hp1);
  14007. asml.InsertBefore(hp1, p);
  14008. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14009. Result := True;
  14010. end;
  14011. end;
  14012. end;
  14013. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14014. var
  14015. hp1: tai;
  14016. begin
  14017. Result:=false;
  14018. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14019. while GetNextInstruction(p, hp1) and
  14020. TrySwapMovCmp(p, hp1) do
  14021. begin
  14022. if MatchInstruction(hp1, A_MOV, []) then
  14023. begin
  14024. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14025. begin
  14026. { A little hacky, but since CMP doesn't read the flags, only
  14027. modify them, it's safe if they get scrambled by MOV -> XOR }
  14028. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14029. Result := PostPeepholeOptMov(hp1);
  14030. {$ifdef x86_64}
  14031. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14032. { Used to shrink instruction size }
  14033. PostPeepholeOptXor(hp1);
  14034. {$endif x86_64}
  14035. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14036. end
  14037. else
  14038. begin
  14039. Result := PostPeepholeOptMov(hp1);
  14040. {$ifdef x86_64}
  14041. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14042. { Used to shrink instruction size }
  14043. PostPeepholeOptXor(hp1);
  14044. {$endif x86_64}
  14045. end;
  14046. end;
  14047. { Enabling this flag is actually a null operation, but it marks
  14048. the code as 'modified' during this pass }
  14049. Include(OptsToCheck, aoc_ForceNewIteration);
  14050. end;
  14051. { change "cmp $0, %reg" to "test %reg, %reg" }
  14052. if MatchOpType(taicpu(p),top_const,top_reg) and
  14053. (taicpu(p).oper[0]^.val = 0) then
  14054. begin
  14055. taicpu(p).opcode := A_TEST;
  14056. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14057. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14058. Result:=true;
  14059. end;
  14060. end;
  14061. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14062. var
  14063. IsTestConstX, IsValid : Boolean;
  14064. hp1,hp2 : tai;
  14065. begin
  14066. Result:=false;
  14067. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14068. if (taicpu(p).opcode = A_TEST) then
  14069. while GetNextInstruction(p, hp1) and
  14070. TrySwapMovCmp(p, hp1) do
  14071. begin
  14072. if MatchInstruction(hp1, A_MOV, []) then
  14073. begin
  14074. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14075. begin
  14076. { A little hacky, but since TEST doesn't read the flags, only
  14077. modify them, it's safe if they get scrambled by MOV -> XOR }
  14078. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14079. Result := PostPeepholeOptMov(hp1);
  14080. {$ifdef x86_64}
  14081. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14082. { Used to shrink instruction size }
  14083. PostPeepholeOptXor(hp1);
  14084. {$endif x86_64}
  14085. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14086. end
  14087. else
  14088. begin
  14089. Result := PostPeepholeOptMov(hp1);
  14090. {$ifdef x86_64}
  14091. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14092. { Used to shrink instruction size }
  14093. PostPeepholeOptXor(hp1);
  14094. {$endif x86_64}
  14095. end;
  14096. end;
  14097. { Enabling this flag is actually a null operation, but it marks
  14098. the code as 'modified' during this pass }
  14099. Include(OptsToCheck, aoc_ForceNewIteration);
  14100. end;
  14101. { If x is a power of 2 (popcnt = 1), change:
  14102. or $x, %reg/ref
  14103. To:
  14104. bts lb(x), %reg/ref
  14105. }
  14106. if (taicpu(p).opcode = A_OR) and
  14107. IsBTXAcceptable(p) and
  14108. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14109. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14110. (
  14111. { Don't optimise if a test instruction follows }
  14112. not GetNextInstruction(p, hp1) or
  14113. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14114. ) then
  14115. begin
  14116. 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);
  14117. taicpu(p).opcode := A_BTS;
  14118. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14119. Result := True;
  14120. Exit;
  14121. end;
  14122. { If x is a power of 2 (popcnt = 1), change:
  14123. test $x, %reg/ref
  14124. je / sete / cmove (or jne / setne)
  14125. To:
  14126. bt lb(x), %reg/ref
  14127. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14128. }
  14129. if (taicpu(p).opcode = A_TEST) and
  14130. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14131. (taicpu(p).oper[0]^.typ = top_const) and
  14132. (
  14133. (cs_opt_size in current_settings.optimizerswitches) or
  14134. (
  14135. (taicpu(p).oper[1]^.typ = top_reg) and
  14136. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14137. ) or
  14138. (
  14139. (taicpu(p).oper[1]^.typ <> top_reg) and
  14140. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14141. )
  14142. ) and
  14143. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14144. { For sizes less than S_L, the byte size is equal or larger with BT,
  14145. so don't bother optimising }
  14146. (taicpu(p).opsize >= S_L) then
  14147. begin
  14148. IsValid := True;
  14149. { Check the next set of instructions, watching the FLAGS register
  14150. and the conditions used }
  14151. TransferUsedRegs(TmpUsedRegs);
  14152. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14153. hp1 := p;
  14154. hp2 := nil;
  14155. while GetNextInstruction(hp1, hp1) do
  14156. begin
  14157. if not Assigned(hp2) then
  14158. { The first instruction after TEST }
  14159. hp2 := hp1;
  14160. if (hp1.typ <> ait_instruction) then
  14161. begin
  14162. { If the flags are no longer in use, everything is fine }
  14163. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14164. IsValid := False;
  14165. Break;
  14166. end;
  14167. case taicpu(hp1).condition of
  14168. C_None:
  14169. begin
  14170. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14171. { Something is not quite normal, so play safe and don't change }
  14172. IsValid := False;
  14173. Break;
  14174. end;
  14175. C_E, C_Z, C_NE, C_NZ:
  14176. { This is fine };
  14177. else
  14178. begin
  14179. { Unsupported condition }
  14180. IsValid := False;
  14181. Break;
  14182. end;
  14183. end;
  14184. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14185. end;
  14186. if IsValid then
  14187. begin
  14188. while hp2 <> hp1 do
  14189. begin
  14190. case taicpu(hp2).condition of
  14191. C_Z, C_E:
  14192. taicpu(hp2).condition := C_NC;
  14193. C_NZ, C_NE:
  14194. taicpu(hp2).condition := C_C;
  14195. else
  14196. { Should not get this by this point }
  14197. InternalError(2022110701);
  14198. end;
  14199. GetNextInstruction(hp2, hp2);
  14200. end;
  14201. 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);
  14202. taicpu(p).opcode := A_BT;
  14203. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14204. Result := True;
  14205. Exit;
  14206. end;
  14207. end;
  14208. { removes the line marked with (x) from the sequence
  14209. and/or/xor/add/sub/... $x, %y
  14210. test/or %y, %y | test $-1, %y (x)
  14211. j(n)z _Label
  14212. as the first instruction already adjusts the ZF
  14213. %y operand may also be a reference }
  14214. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14215. MatchOperand(taicpu(p).oper[0]^,-1);
  14216. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14217. GetLastInstruction(p, hp1) and
  14218. (tai(hp1).typ = ait_instruction) and
  14219. GetNextInstruction(p,hp2) and
  14220. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14221. case taicpu(hp1).opcode Of
  14222. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14223. { These two instructions set the zero flag if the result is zero }
  14224. A_POPCNT, A_LZCNT:
  14225. begin
  14226. if (
  14227. { With POPCNT, an input of zero will set the zero flag
  14228. because the population count of zero is zero }
  14229. (taicpu(hp1).opcode = A_POPCNT) and
  14230. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14231. (
  14232. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14233. { Faster than going through the second half of the 'or'
  14234. condition below }
  14235. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14236. )
  14237. ) or (
  14238. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14239. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14240. { and in case of carry for A(E)/B(E)/C/NC }
  14241. (
  14242. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14243. (
  14244. (taicpu(hp1).opcode <> A_ADD) and
  14245. (taicpu(hp1).opcode <> A_SUB) and
  14246. (taicpu(hp1).opcode <> A_LZCNT)
  14247. )
  14248. )
  14249. ) then
  14250. begin
  14251. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14252. RemoveCurrentP(p, hp2);
  14253. Result:=true;
  14254. Exit;
  14255. end;
  14256. end;
  14257. A_SHL, A_SAL, A_SHR, A_SAR:
  14258. begin
  14259. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14260. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14261. { therefore, it's only safe to do this optimization for }
  14262. { shifts by a (nonzero) constant }
  14263. (taicpu(hp1).oper[0]^.typ = top_const) and
  14264. (taicpu(hp1).oper[0]^.val <> 0) and
  14265. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14266. { and in case of carry for A(E)/B(E)/C/NC }
  14267. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14268. begin
  14269. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14270. RemoveCurrentP(p, hp2);
  14271. Result:=true;
  14272. Exit;
  14273. end;
  14274. end;
  14275. A_DEC, A_INC, A_NEG:
  14276. begin
  14277. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14278. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14279. { and in case of carry for A(E)/B(E)/C/NC }
  14280. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14281. begin
  14282. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14283. RemoveCurrentP(p, hp2);
  14284. Result:=true;
  14285. Exit;
  14286. end;
  14287. end;
  14288. A_ANDN, A_BZHI:
  14289. begin
  14290. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14291. { Only the zero and sign flags are consistent with what the result is }
  14292. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14293. begin
  14294. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14295. RemoveCurrentP(p, hp2);
  14296. Result:=true;
  14297. Exit;
  14298. end;
  14299. end;
  14300. A_BEXTR:
  14301. begin
  14302. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14303. { Only the zero flag is set }
  14304. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14305. begin
  14306. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14307. RemoveCurrentP(p, hp2);
  14308. Result:=true;
  14309. Exit;
  14310. end;
  14311. end;
  14312. else
  14313. ;
  14314. end; { case }
  14315. { change "test $-1,%reg" into "test %reg,%reg" }
  14316. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14317. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14318. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14319. if MatchInstruction(p, A_OR, []) and
  14320. { Can only match if they're both registers }
  14321. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14322. begin
  14323. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14324. taicpu(p).opcode := A_TEST;
  14325. { No need to set Result to True, as we've done all the optimisations we can }
  14326. end;
  14327. end;
  14328. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14329. var
  14330. hp1,hp3 : tai;
  14331. {$ifndef x86_64}
  14332. hp2 : taicpu;
  14333. {$endif x86_64}
  14334. begin
  14335. Result:=false;
  14336. hp3:=nil;
  14337. {$ifndef x86_64}
  14338. { don't do this on modern CPUs, this really hurts them due to
  14339. broken call/ret pairing }
  14340. if (current_settings.optimizecputype < cpu_Pentium2) and
  14341. not(cs_create_pic in current_settings.moduleswitches) and
  14342. GetNextInstruction(p, hp1) and
  14343. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14344. MatchOpType(taicpu(hp1),top_ref) and
  14345. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14346. begin
  14347. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14348. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14349. InsertLLItem(p.previous, p, hp2);
  14350. taicpu(p).opcode := A_JMP;
  14351. taicpu(p).is_jmp := true;
  14352. RemoveInstruction(hp1);
  14353. Result:=true;
  14354. end
  14355. else
  14356. {$endif x86_64}
  14357. { replace
  14358. call procname
  14359. ret
  14360. by
  14361. jmp procname
  14362. but do it only on level 4 because it destroys stack back traces
  14363. else if the subroutine is marked as no return, remove the ret
  14364. }
  14365. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14366. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14367. GetNextInstruction(p, hp1) and
  14368. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14369. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14370. SetAndTest(hp1,hp3) and
  14371. GetNextInstruction(hp1,hp1) and
  14372. MatchInstruction(hp1,A_RET,[S_NO])
  14373. )
  14374. ) and
  14375. (taicpu(hp1).ops=0) then
  14376. begin
  14377. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14378. { we might destroy stack alignment here if we do not do a call }
  14379. (target_info.stackalign<=sizeof(SizeUInt)) then
  14380. begin
  14381. taicpu(p).opcode := A_JMP;
  14382. taicpu(p).is_jmp := true;
  14383. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14384. end
  14385. else
  14386. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14387. RemoveInstruction(hp1);
  14388. if Assigned(hp3) then
  14389. begin
  14390. AsmL.Remove(hp3);
  14391. AsmL.InsertBefore(hp3,p)
  14392. end;
  14393. Result:=true;
  14394. end;
  14395. end;
  14396. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14397. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14398. begin
  14399. case OpSize of
  14400. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14401. Result := (Val <= $FF) and (Val >= -128);
  14402. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14403. Result := (Val <= $FFFF) and (Val >= -32768);
  14404. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14405. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14406. else
  14407. Result := True;
  14408. end;
  14409. end;
  14410. var
  14411. hp1, hp2 : tai;
  14412. SizeChange: Boolean;
  14413. PreMessage: string;
  14414. begin
  14415. Result := False;
  14416. if (taicpu(p).oper[0]^.typ = top_reg) and
  14417. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14418. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14419. begin
  14420. { Change (using movzbl %al,%eax as an example):
  14421. movzbl %al, %eax movzbl %al, %eax
  14422. cmpl x, %eax testl %eax,%eax
  14423. To:
  14424. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14425. movzbl %al, %eax movzbl %al, %eax
  14426. Smaller instruction and minimises pipeline stall as the CPU
  14427. doesn't have to wait for the register to get zero-extended. [Kit]
  14428. Also allow if the smaller of the two registers is being checked,
  14429. as this still removes the false dependency.
  14430. }
  14431. if
  14432. (
  14433. (
  14434. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14435. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14436. ) or (
  14437. { If MatchOperand returns True, they must both be registers }
  14438. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14439. )
  14440. ) and
  14441. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14442. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14443. begin
  14444. 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);
  14445. asml.Remove(hp1);
  14446. asml.InsertBefore(hp1, p);
  14447. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14448. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14449. begin
  14450. taicpu(hp1).opcode := A_TEST;
  14451. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14452. end;
  14453. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14454. case taicpu(p).opsize of
  14455. S_BW, S_BL:
  14456. begin
  14457. SizeChange := taicpu(hp1).opsize <> S_B;
  14458. taicpu(hp1).changeopsize(S_B);
  14459. end;
  14460. S_WL:
  14461. begin
  14462. SizeChange := taicpu(hp1).opsize <> S_W;
  14463. taicpu(hp1).changeopsize(S_W);
  14464. end
  14465. else
  14466. InternalError(2020112701);
  14467. end;
  14468. UpdateUsedRegs(tai(p.Next));
  14469. { Check if the register is used aferwards - if not, we can
  14470. remove the movzx instruction completely }
  14471. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14472. begin
  14473. { Hp1 is a better position than p for debugging purposes }
  14474. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14475. RemoveCurrentp(p, hp1);
  14476. Result := True;
  14477. end;
  14478. if SizeChange then
  14479. DebugMsg(SPeepholeOptimization + PreMessage +
  14480. 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)
  14481. else
  14482. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14483. Exit;
  14484. end;
  14485. { Change (using movzwl %ax,%eax as an example):
  14486. movzwl %ax, %eax
  14487. movb %al, (dest) (Register is smaller than read register in movz)
  14488. To:
  14489. movb %al, (dest) (Move one back to avoid a false dependency)
  14490. movzwl %ax, %eax
  14491. }
  14492. if (taicpu(hp1).opcode = A_MOV) and
  14493. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14494. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14495. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14496. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14497. begin
  14498. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14499. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14500. asml.Remove(hp1);
  14501. asml.InsertBefore(hp1, p);
  14502. if taicpu(hp1).oper[1]^.typ = top_reg then
  14503. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14504. { Check if the register is used aferwards - if not, we can
  14505. remove the movzx instruction completely }
  14506. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14507. begin
  14508. { Hp1 is a better position than p for debugging purposes }
  14509. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14510. RemoveCurrentp(p, hp1);
  14511. Result := True;
  14512. end;
  14513. Exit;
  14514. end;
  14515. end;
  14516. end;
  14517. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14518. var
  14519. hp1: tai;
  14520. {$ifdef x86_64}
  14521. PreMessage, RegName: string;
  14522. {$endif x86_64}
  14523. begin
  14524. Result := False;
  14525. { If x is a power of 2 (popcnt = 1), change:
  14526. xor $x, %reg/ref
  14527. To:
  14528. btc lb(x), %reg/ref
  14529. }
  14530. if IsBTXAcceptable(p) and
  14531. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14532. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14533. (
  14534. { Don't optimise if a test instruction follows }
  14535. not GetNextInstruction(p, hp1) or
  14536. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14537. ) then
  14538. begin
  14539. 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);
  14540. taicpu(p).opcode := A_BTC;
  14541. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14542. Result := True;
  14543. Exit;
  14544. end;
  14545. {$ifdef x86_64}
  14546. { Code size reduction by J. Gareth "Kit" Moreton }
  14547. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14548. as this removes the REX prefix }
  14549. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14550. Exit;
  14551. if taicpu(p).oper[0]^.typ <> top_reg then
  14552. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14553. InternalError(2018011500);
  14554. case taicpu(p).opsize of
  14555. S_Q:
  14556. begin
  14557. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14558. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14559. { The actual optimization }
  14560. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14561. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14562. taicpu(p).changeopsize(S_L);
  14563. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14564. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14565. end;
  14566. else
  14567. ;
  14568. end;
  14569. {$endif x86_64}
  14570. end;
  14571. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14572. var
  14573. XReg: TRegister;
  14574. begin
  14575. Result := False;
  14576. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14577. Smaller encoding and slightly faster on some platforms (also works for
  14578. ZMM-sized registers) }
  14579. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14580. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14581. begin
  14582. XReg := taicpu(p).oper[0]^.reg;
  14583. if (taicpu(p).oper[1]^.reg = XReg) then
  14584. begin
  14585. taicpu(p).changeopsize(S_XMM);
  14586. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14587. if (cs_opt_size in current_settings.optimizerswitches) then
  14588. begin
  14589. { Change input registers to %xmm0 to reduce size. Note that
  14590. there's a risk of a false dependency doing this, so only
  14591. optimise for size here }
  14592. XReg := NR_XMM0;
  14593. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14594. end
  14595. else
  14596. begin
  14597. setsubreg(XReg, R_SUBMMX);
  14598. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14599. end;
  14600. taicpu(p).oper[0]^.reg := XReg;
  14601. taicpu(p).oper[1]^.reg := XReg;
  14602. Result := True;
  14603. end;
  14604. end;
  14605. end;
  14606. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14607. var
  14608. OperIdx: Integer;
  14609. begin
  14610. for OperIdx := 0 to p.ops - 1 do
  14611. if p.oper[OperIdx]^.typ = top_ref then
  14612. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14613. end;
  14614. end.