aoptx86.pas 701 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224
  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_instruction) and is_calljmp(taicpu(Next).opcode) then
  492. if is_calljmpuncondret(taicpu(Next).opcode) then
  493. begin
  494. if (taicpu(Next).opcode = A_JMP) and
  495. { Remove dead code now to save time }
  496. RemoveDeadCodeAfterJump(taicpu(Next)) then
  497. { A jump was removed, but not the current instruction, and
  498. Result doesn't necessarily translate into an optimisation
  499. routine's Result, so use the "Force New Iteration" flag so
  500. mark a new pass }
  501. Include(OptsToCheck, aoc_ForceNewIteration);
  502. if not Assigned(JumpTracking) then
  503. begin
  504. { Cross-label optimisations often causes other optimisations
  505. to perform worse because they're not given the chance to
  506. optimise locally. In this case, don't do the cross-label
  507. optimisations yet, but flag them as a potential possibility
  508. for the next iteration of Pass 1 }
  509. if not NotFirstIteration then
  510. Include(OptsToCheck, aoc_ForceNewIteration);
  511. end
  512. else if IsJumpToLabel(taicpu(Next)) and
  513. GetNextInstruction(Next, Next_Label) then
  514. begin
  515. { If we have JMP .lbl, and the label after it has all of its
  516. references tracked, then this is probably an if-else style of
  517. block and we can keep tracking. If the label for this jump
  518. then appears later and is fully tracked, then it's the end
  519. of the if-else blocks and the code paths converge (thus
  520. marking the end of the cross-jump) }
  521. if (Next_Label.typ = ait_label) then
  522. begin
  523. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  524. begin
  525. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  526. Next := Next_Label;
  527. { CrossJump gets set to false by LabelAccountedFor if the
  528. list is completely emptied (as it indicates that all
  529. code paths have converged). We could avoid this nuance
  530. by moving the TrackJump call to before the
  531. LabelAccountedFor call, but this is slower in situations
  532. where LabelAccountedFor would return False due to the
  533. creation of a new object that is not used and destroyed
  534. soon after. }
  535. CrossJump := True;
  536. Continue;
  537. end;
  538. end
  539. else if (Next_Label.typ <> ait_marker) then
  540. { We just did a RemoveDeadCodeAfterJump, so either we find
  541. a label, the end of the procedure or some kind of marker}
  542. InternalError(2022041720);
  543. end;
  544. Result := False;
  545. Exit;
  546. end
  547. else
  548. begin
  549. if not Assigned(JumpTracking) then
  550. begin
  551. { Cross-label optimisations often causes other optimisations
  552. to perform worse because they're not given the chance to
  553. optimise locally. In this case, don't do the cross-label
  554. optimisations yet, but flag them as a potential possibility
  555. for the next iteration of Pass 1 }
  556. if not NotFirstIteration then
  557. Include(OptsToCheck, aoc_ForceNewIteration);
  558. end
  559. else if IsJumpToLabel(taicpu(Next)) then
  560. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  561. else
  562. { Conditional jumps should always be a jump to label }
  563. InternalError(2022041701);
  564. CrossJump := True;
  565. Continue;
  566. end;
  567. if Next.typ = ait_label then
  568. begin
  569. if not Assigned(JumpTracking) then
  570. begin
  571. { Cross-label optimisations often causes other optimisations
  572. to perform worse because they're not given the chance to
  573. optimise locally. In this case, don't do the cross-label
  574. optimisations yet, but flag them as a potential possibility
  575. for the next iteration of Pass 1 }
  576. if not NotFirstIteration then
  577. Include(OptsToCheck, aoc_ForceNewIteration);
  578. end
  579. else if LabelAccountedFor(tai_label(Next).labsym) then
  580. Continue;
  581. { If we reach here, we're at a label that hasn't been seen before
  582. (or JumpTracking was nil) }
  583. Break;
  584. end;
  585. until not Result or
  586. not (cs_opt_level3 in current_settings.optimizerswitches) or
  587. not (Next.typ in [ait_label, ait_instruction]) or
  588. RegInInstruction(reg,Next);
  589. end;
  590. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  591. begin
  592. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  593. begin
  594. Result:=GetNextInstruction(Current,Next);
  595. exit;
  596. end;
  597. Next:=tai(Current.Next);
  598. Result:=false;
  599. while assigned(Next) do
  600. begin
  601. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  602. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  603. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  604. exit
  605. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  606. begin
  607. Result:=true;
  608. exit;
  609. end;
  610. Next:=tai(Next.Next);
  611. end;
  612. end;
  613. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  614. begin
  615. Result:=RegReadByInstruction(reg,hp);
  616. end;
  617. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  618. var
  619. p: taicpu;
  620. opcount: longint;
  621. begin
  622. RegReadByInstruction := false;
  623. if hp.typ <> ait_instruction then
  624. exit;
  625. p := taicpu(hp);
  626. case p.opcode of
  627. A_CALL:
  628. regreadbyinstruction := true;
  629. A_IMUL:
  630. case p.ops of
  631. 1:
  632. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  633. (
  634. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  635. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  636. );
  637. 2,3:
  638. regReadByInstruction :=
  639. reginop(reg,p.oper[0]^) or
  640. reginop(reg,p.oper[1]^);
  641. else
  642. InternalError(2019112801);
  643. end;
  644. A_MUL:
  645. begin
  646. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  647. (
  648. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  649. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  650. );
  651. end;
  652. A_IDIV,A_DIV:
  653. begin
  654. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  655. (
  656. (getregtype(reg)=R_INTREGISTER) and
  657. (
  658. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  659. )
  660. );
  661. end;
  662. else
  663. begin
  664. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  665. begin
  666. RegReadByInstruction := false;
  667. exit;
  668. end;
  669. for opcount := 0 to p.ops-1 do
  670. if (p.oper[opCount]^.typ = top_ref) and
  671. RegInRef(reg,p.oper[opcount]^.ref^) then
  672. begin
  673. RegReadByInstruction := true;
  674. exit
  675. end;
  676. { special handling for SSE MOVSD }
  677. if (p.opcode=A_MOVSD) and (p.ops>0) then
  678. begin
  679. if p.ops<>2 then
  680. internalerror(2017042702);
  681. regReadByInstruction := reginop(reg,p.oper[0]^) or
  682. (
  683. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  684. );
  685. exit;
  686. end;
  687. with insprop[p.opcode] do
  688. begin
  689. case getregtype(reg) of
  690. R_INTREGISTER:
  691. begin
  692. case getsupreg(reg) of
  693. RS_EAX:
  694. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  695. begin
  696. RegReadByInstruction := true;
  697. exit
  698. end;
  699. RS_ECX:
  700. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  701. begin
  702. RegReadByInstruction := true;
  703. exit
  704. end;
  705. RS_EDX:
  706. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  707. begin
  708. RegReadByInstruction := true;
  709. exit
  710. end;
  711. RS_EBX:
  712. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  713. begin
  714. RegReadByInstruction := true;
  715. exit
  716. end;
  717. RS_ESP:
  718. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  719. begin
  720. RegReadByInstruction := true;
  721. exit
  722. end;
  723. RS_EBP:
  724. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  725. begin
  726. RegReadByInstruction := true;
  727. exit
  728. end;
  729. RS_ESI:
  730. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  731. begin
  732. RegReadByInstruction := true;
  733. exit
  734. end;
  735. RS_EDI:
  736. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  737. begin
  738. RegReadByInstruction := true;
  739. exit
  740. end;
  741. end;
  742. end;
  743. R_MMREGISTER:
  744. begin
  745. case getsupreg(reg) of
  746. RS_XMM0:
  747. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  748. begin
  749. RegReadByInstruction := true;
  750. exit
  751. end;
  752. end;
  753. end;
  754. else
  755. ;
  756. end;
  757. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  758. begin
  759. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  760. begin
  761. case p.condition of
  762. C_A,C_NBE, { CF=0 and ZF=0 }
  763. C_BE,C_NA: { CF=1 or ZF=1 }
  764. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  765. C_AE,C_NB,C_NC, { CF=0 }
  766. C_B,C_NAE,C_C: { CF=1 }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  768. C_NE,C_NZ, { ZF=0 }
  769. C_E,C_Z: { ZF=1 }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  771. C_G,C_NLE, { ZF=0 and SF=OF }
  772. C_LE,C_NG: { ZF=1 or SF<>OF }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  774. C_GE,C_NL, { SF=OF }
  775. C_L,C_NGE: { SF<>OF }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  777. C_NO, { OF=0 }
  778. C_O: { OF=1 }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  780. C_NP,C_PO, { PF=0 }
  781. C_P,C_PE: { PF=1 }
  782. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  783. C_NS, { SF=0 }
  784. C_S: { SF=1 }
  785. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  786. else
  787. internalerror(2017042701);
  788. end;
  789. if RegReadByInstruction then
  790. exit;
  791. end;
  792. case getsubreg(reg) of
  793. R_SUBW,R_SUBD,R_SUBQ:
  794. RegReadByInstruction :=
  795. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  796. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  797. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  798. R_SUBFLAGCARRY:
  799. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  800. R_SUBFLAGPARITY:
  801. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGAUXILIARY:
  803. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGZERO:
  805. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGSIGN:
  807. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGOVERFLOW:
  809. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGINTERRUPT:
  811. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGDIRECTION:
  813. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. else
  815. internalerror(2017042601);
  816. end;
  817. exit;
  818. end;
  819. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  820. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  821. (p.oper[0]^.reg=p.oper[1]^.reg) then
  822. exit;
  823. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  824. begin
  825. RegReadByInstruction := true;
  826. exit
  827. end;
  828. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  829. begin
  830. RegReadByInstruction := true;
  831. exit
  832. end;
  833. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  834. begin
  835. RegReadByInstruction := true;
  836. exit
  837. end;
  838. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  839. begin
  840. RegReadByInstruction := true;
  841. exit
  842. end;
  843. end;
  844. end;
  845. end;
  846. end;
  847. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  848. begin
  849. result:=false;
  850. if p1.typ<>ait_instruction then
  851. exit;
  852. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  853. exit(true);
  854. if (getregtype(reg)=R_INTREGISTER) and
  855. { change information for xmm movsd are not correct }
  856. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  857. begin
  858. { Handle instructions that behave differently depending on the size and operand count }
  859. case taicpu(p1).opcode of
  860. A_MUL, A_DIV, A_IDIV:
  861. if taicpu(p1).opsize = S_B then
  862. Result := (getsupreg(Reg) = RS_EAX)
  863. else
  864. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  865. A_IMUL:
  866. if taicpu(p1).ops = 1 then
  867. begin
  868. if taicpu(p1).opsize = S_B then
  869. Result := (getsupreg(Reg) = RS_EAX)
  870. else
  871. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  872. end;
  873. { If ops are greater than 1, call inherited method }
  874. else
  875. case getsupreg(reg) of
  876. { RS_EAX = RS_RAX on x86-64 }
  877. RS_EAX:
  878. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. RS_ECX:
  880. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_EDX:
  882. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EBX:
  884. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_ESP:
  886. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_EBP:
  888. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_ESI:
  890. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_EDI:
  892. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. end;
  897. if result then
  898. exit;
  899. end
  900. else if getregtype(reg)=R_MMREGISTER then
  901. begin
  902. case getsupreg(reg) of
  903. RS_XMM0:
  904. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  905. else
  906. ;
  907. end;
  908. if result then
  909. exit;
  910. end
  911. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  912. begin
  913. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  914. exit(true);
  915. case getsubreg(reg) of
  916. R_SUBFLAGCARRY:
  917. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  918. R_SUBFLAGPARITY:
  919. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGAUXILIARY:
  921. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGZERO:
  923. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGSIGN:
  925. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGOVERFLOW:
  927. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGINTERRUPT:
  929. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGDIRECTION:
  931. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBW,R_SUBD,R_SUBQ:
  933. { Everything except the direction bits }
  934. Result:=
  935. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  936. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  937. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  938. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  939. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  940. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  941. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  942. else
  943. ;
  944. end;
  945. if result then
  946. exit;
  947. end
  948. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  949. exit(true);
  950. Result:=inherited RegInInstruction(Reg, p1);
  951. end;
  952. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  953. const
  954. WriteOps: array[0..3] of set of TInsChange =
  955. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  956. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  957. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  958. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  959. var
  960. OperIdx: Integer;
  961. begin
  962. Result := False;
  963. if p1.typ <> ait_instruction then
  964. exit;
  965. with insprop[taicpu(p1).opcode] do
  966. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  967. begin
  968. case getsubreg(reg) of
  969. R_SUBW,R_SUBD,R_SUBQ:
  970. Result :=
  971. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  972. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  973. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  974. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  975. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  976. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  977. R_SUBFLAGCARRY:
  978. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGPARITY:
  980. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGAUXILIARY:
  982. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGZERO:
  984. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGSIGN:
  986. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGOVERFLOW:
  988. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGINTERRUPT:
  990. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGDIRECTION:
  992. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. else
  994. internalerror(2017042602);
  995. end;
  996. exit;
  997. end;
  998. case taicpu(p1).opcode of
  999. A_CALL:
  1000. { We could potentially set Result to False if the register in
  1001. question is non-volatile for the subroutine's calling convention,
  1002. but this would require detecting the calling convention in use and
  1003. also assuming that the routine doesn't contain malformed assembly
  1004. language, for example... so it could only be done under -O4 as it
  1005. would be considered a side-effect. [Kit] }
  1006. Result := True;
  1007. A_MOVSD:
  1008. { special handling for SSE MOVSD }
  1009. if (taicpu(p1).ops>0) then
  1010. begin
  1011. if taicpu(p1).ops<>2 then
  1012. internalerror(2017042703);
  1013. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1014. end;
  1015. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1016. so fix it here (FK)
  1017. }
  1018. A_VMOVSS,
  1019. A_VMOVSD:
  1020. begin
  1021. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1022. exit;
  1023. end;
  1024. A_MUL, A_DIV, A_IDIV:
  1025. begin
  1026. if taicpu(p1).opsize = S_B then
  1027. Result := (getsupreg(Reg) = RS_EAX)
  1028. else
  1029. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1030. end;
  1031. A_IMUL:
  1032. begin
  1033. if taicpu(p1).ops = 1 then
  1034. begin
  1035. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1036. end
  1037. else
  1038. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1039. Exit;
  1040. end;
  1041. else
  1042. ;
  1043. end;
  1044. if Result then
  1045. exit;
  1046. with insprop[taicpu(p1).opcode] do
  1047. begin
  1048. if getregtype(reg)=R_INTREGISTER then
  1049. begin
  1050. case getsupreg(reg) of
  1051. RS_EAX:
  1052. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1053. begin
  1054. Result := True;
  1055. exit
  1056. end;
  1057. RS_ECX:
  1058. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1059. begin
  1060. Result := True;
  1061. exit
  1062. end;
  1063. RS_EDX:
  1064. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1065. begin
  1066. Result := True;
  1067. exit
  1068. end;
  1069. RS_EBX:
  1070. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1071. begin
  1072. Result := True;
  1073. exit
  1074. end;
  1075. RS_ESP:
  1076. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1077. begin
  1078. Result := True;
  1079. exit
  1080. end;
  1081. RS_EBP:
  1082. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1083. begin
  1084. Result := True;
  1085. exit
  1086. end;
  1087. RS_ESI:
  1088. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1089. begin
  1090. Result := True;
  1091. exit
  1092. end;
  1093. RS_EDI:
  1094. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1095. begin
  1096. Result := True;
  1097. exit
  1098. end;
  1099. end;
  1100. end;
  1101. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1102. if (WriteOps[OperIdx]*Ch<>[]) and
  1103. { The register doesn't get modified inside a reference }
  1104. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1105. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1106. begin
  1107. Result := true;
  1108. exit
  1109. end;
  1110. end;
  1111. end;
  1112. {$ifdef DEBUG_AOPTCPU}
  1113. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1114. begin
  1115. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1116. end;
  1117. function debug_tostr(i: tcgint): string; inline;
  1118. begin
  1119. Result := tostr(i);
  1120. end;
  1121. function debug_hexstr(i: tcgint): string;
  1122. begin
  1123. Result := '0x';
  1124. case i of
  1125. 0..$FF:
  1126. Result := Result + hexstr(i, 2);
  1127. $100..$FFFF:
  1128. Result := Result + hexstr(i, 4);
  1129. $10000..$FFFFFF:
  1130. Result := Result + hexstr(i, 6);
  1131. $1000000..$FFFFFFFF:
  1132. Result := Result + hexstr(i, 8);
  1133. else
  1134. Result := Result + hexstr(i, 16);
  1135. end;
  1136. end;
  1137. function debug_regname(r: TRegister): string; inline;
  1138. begin
  1139. Result := '%' + std_regname(r);
  1140. end;
  1141. { Debug output function - creates a string representation of an operator }
  1142. function debug_operstr(oper: TOper): string;
  1143. begin
  1144. case oper.typ of
  1145. top_const:
  1146. Result := '$' + debug_tostr(oper.val);
  1147. top_reg:
  1148. Result := debug_regname(oper.reg);
  1149. top_ref:
  1150. begin
  1151. if oper.ref^.offset <> 0 then
  1152. Result := debug_tostr(oper.ref^.offset) + '('
  1153. else
  1154. Result := '(';
  1155. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1156. begin
  1157. Result := Result + debug_regname(oper.ref^.base);
  1158. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1159. Result := Result + ',' + debug_regname(oper.ref^.index);
  1160. end
  1161. else
  1162. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1163. Result := Result + debug_regname(oper.ref^.index);
  1164. if (oper.ref^.scalefactor > 1) then
  1165. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1166. else
  1167. Result := Result + ')';
  1168. end;
  1169. else
  1170. Result := '[UNKNOWN]';
  1171. end;
  1172. end;
  1173. function debug_op2str(opcode: tasmop): string; inline;
  1174. begin
  1175. Result := std_op2str[opcode];
  1176. end;
  1177. function debug_opsize2str(opsize: topsize): string; inline;
  1178. begin
  1179. Result := gas_opsize2str[opsize];
  1180. end;
  1181. {$else DEBUG_AOPTCPU}
  1182. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1183. begin
  1184. end;
  1185. function debug_tostr(i: tcgint): string; inline;
  1186. begin
  1187. Result := '';
  1188. end;
  1189. function debug_hexstr(i: tcgint): string; inline;
  1190. begin
  1191. Result := '';
  1192. end;
  1193. function debug_regname(r: TRegister): string; inline;
  1194. begin
  1195. Result := '';
  1196. end;
  1197. function debug_operstr(oper: TOper): string; inline;
  1198. begin
  1199. Result := '';
  1200. end;
  1201. function debug_op2str(opcode: tasmop): string; inline;
  1202. begin
  1203. Result := '';
  1204. end;
  1205. function debug_opsize2str(opsize: topsize): string; inline;
  1206. begin
  1207. Result := '';
  1208. end;
  1209. {$endif DEBUG_AOPTCPU}
  1210. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1211. begin
  1212. {$ifdef x86_64}
  1213. { Always fine on x86-64 }
  1214. Result := True;
  1215. {$else x86_64}
  1216. Result :=
  1217. {$ifdef i8086}
  1218. (current_settings.cputype >= cpu_386) and
  1219. {$endif i8086}
  1220. (
  1221. { Always accept if optimising for size }
  1222. (cs_opt_size in current_settings.optimizerswitches) or
  1223. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1224. (current_settings.optimizecputype >= cpu_Pentium2)
  1225. );
  1226. {$endif x86_64}
  1227. end;
  1228. { Attempts to allocate a volatile integer register for use between p and hp,
  1229. using AUsedRegs for the current register usage information. Returns NR_NO
  1230. if no free register could be found }
  1231. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1232. var
  1233. RegSet: TCPURegisterSet;
  1234. CurrentSuperReg: Integer;
  1235. CurrentReg: TRegister;
  1236. Currentp: tai;
  1237. Breakout: Boolean;
  1238. begin
  1239. Result := NR_NO;
  1240. RegSet :=
  1241. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1242. current_procinfo.saved_regs_int;
  1243. (*
  1244. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1245. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1246. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1247. *)
  1248. for CurrentSuperReg in RegSet do
  1249. begin
  1250. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1251. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1252. {$if defined(i386) or defined(i8086)}
  1253. { If the target size is 8-bit, make sure we can actually encode it }
  1254. and (
  1255. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1256. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1257. )
  1258. {$endif i386 or i8086}
  1259. then
  1260. begin
  1261. Currentp := p;
  1262. Breakout := False;
  1263. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1264. begin
  1265. case Currentp.typ of
  1266. ait_instruction:
  1267. begin
  1268. if RegInInstruction(CurrentReg, Currentp) then
  1269. begin
  1270. Breakout := True;
  1271. Break;
  1272. end;
  1273. { Cannot allocate across an unconditional jump }
  1274. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1275. Exit;
  1276. end;
  1277. ait_marker:
  1278. { Don't try anything more if a marker is hit }
  1279. Exit;
  1280. ait_regalloc:
  1281. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1282. begin
  1283. Breakout := True;
  1284. Break;
  1285. end;
  1286. else
  1287. ;
  1288. end;
  1289. end;
  1290. if Breakout then
  1291. { Try the next register }
  1292. Continue;
  1293. { We have a free register available }
  1294. Result := CurrentReg;
  1295. if not DontAlloc then
  1296. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1297. Exit;
  1298. end;
  1299. end;
  1300. end;
  1301. { Attempts to allocate a volatile MM register for use between p and hp,
  1302. using AUsedRegs for the current register usage information. Returns NR_NO
  1303. if no free register could be found }
  1304. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1305. var
  1306. RegSet: TCPURegisterSet;
  1307. CurrentSuperReg: Integer;
  1308. CurrentReg: TRegister;
  1309. Currentp: tai;
  1310. Breakout: Boolean;
  1311. begin
  1312. Result := NR_NO;
  1313. RegSet :=
  1314. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1315. current_procinfo.saved_regs_mm;
  1316. for CurrentSuperReg in RegSet do
  1317. begin
  1318. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1319. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1320. begin
  1321. Currentp := p;
  1322. Breakout := False;
  1323. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1324. begin
  1325. case Currentp.typ of
  1326. ait_instruction:
  1327. begin
  1328. if RegInInstruction(CurrentReg, Currentp) then
  1329. begin
  1330. Breakout := True;
  1331. Break;
  1332. end;
  1333. { Cannot allocate across an unconditional jump }
  1334. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1335. Exit;
  1336. end;
  1337. ait_marker:
  1338. { Don't try anything more if a marker is hit }
  1339. Exit;
  1340. ait_regalloc:
  1341. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1342. begin
  1343. Breakout := True;
  1344. Break;
  1345. end;
  1346. else
  1347. ;
  1348. end;
  1349. end;
  1350. if Breakout then
  1351. { Try the next register }
  1352. Continue;
  1353. { We have a free register available }
  1354. Result := CurrentReg;
  1355. if not DontAlloc then
  1356. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1357. Exit;
  1358. end;
  1359. end;
  1360. end;
  1361. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1362. begin
  1363. if not SuperRegistersEqual(reg1,reg2) then
  1364. exit(false);
  1365. if getregtype(reg1)<>R_INTREGISTER then
  1366. exit(true); {because SuperRegisterEqual is true}
  1367. case getsubreg(reg1) of
  1368. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1369. higher, it preserves the high bits, so the new value depends on
  1370. reg2's previous value. In other words, it is equivalent to doing:
  1371. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1372. R_SUBL:
  1373. exit(getsubreg(reg2)=R_SUBL);
  1374. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1375. higher, it actually does a:
  1376. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1377. R_SUBH:
  1378. exit(getsubreg(reg2)=R_SUBH);
  1379. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1380. bits of reg2:
  1381. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1382. R_SUBW:
  1383. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1384. { a write to R_SUBD always overwrites every other subregister,
  1385. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1386. R_SUBD,
  1387. R_SUBQ:
  1388. exit(true);
  1389. else
  1390. internalerror(2017042801);
  1391. end;
  1392. end;
  1393. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1394. begin
  1395. if not SuperRegistersEqual(reg1,reg2) then
  1396. exit(false);
  1397. if getregtype(reg1)<>R_INTREGISTER then
  1398. exit(true); {because SuperRegisterEqual is true}
  1399. case getsubreg(reg1) of
  1400. R_SUBL:
  1401. exit(getsubreg(reg2)<>R_SUBH);
  1402. R_SUBH:
  1403. exit(getsubreg(reg2)<>R_SUBL);
  1404. R_SUBW,
  1405. R_SUBD,
  1406. R_SUBQ:
  1407. exit(true);
  1408. else
  1409. internalerror(2017042802);
  1410. end;
  1411. end;
  1412. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1413. var
  1414. hp1 : tai;
  1415. l : TCGInt;
  1416. begin
  1417. result:=false;
  1418. if not(GetNextInstruction(p, hp1)) then
  1419. exit;
  1420. { changes the code sequence
  1421. shr/sar const1, x
  1422. shl const2, x
  1423. to
  1424. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1425. if (taicpu(p).oper[0]^.typ = top_const) and
  1426. MatchInstruction(hp1,A_SHL,[]) and
  1427. (taicpu(hp1).oper[0]^.typ = top_const) and
  1428. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1429. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1430. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1431. begin
  1432. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1433. not(cs_opt_size in current_settings.optimizerswitches) then
  1434. begin
  1435. { shr/sar const1, %reg
  1436. shl const2, %reg
  1437. with const1 > const2 }
  1438. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1439. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1440. taicpu(hp1).opcode := A_AND;
  1441. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1442. case taicpu(p).opsize Of
  1443. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1444. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1445. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1446. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1447. else
  1448. Internalerror(2017050703)
  1449. end;
  1450. end
  1451. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1452. not(cs_opt_size in current_settings.optimizerswitches) then
  1453. begin
  1454. { shr/sar const1, %reg
  1455. shl const2, %reg
  1456. with const1 < const2 }
  1457. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1458. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1459. taicpu(p).opcode := A_AND;
  1460. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1461. case taicpu(p).opsize Of
  1462. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1463. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1464. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1465. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1466. else
  1467. Internalerror(2017050702)
  1468. end;
  1469. end
  1470. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1471. begin
  1472. { shr/sar const1, %reg
  1473. shl const2, %reg
  1474. with const1 = const2 }
  1475. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1476. taicpu(p).opcode := A_AND;
  1477. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1478. case taicpu(p).opsize Of
  1479. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1480. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1481. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1482. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1483. else
  1484. Internalerror(2017050701)
  1485. end;
  1486. RemoveInstruction(hp1);
  1487. end;
  1488. end;
  1489. end;
  1490. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1491. var
  1492. opsize : topsize;
  1493. hp1, hp2 : tai;
  1494. tmpref : treference;
  1495. ShiftValue : Cardinal;
  1496. BaseValue : TCGInt;
  1497. begin
  1498. result:=false;
  1499. opsize:=taicpu(p).opsize;
  1500. { changes certain "imul const, %reg"'s to lea sequences }
  1501. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1502. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1503. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1504. if (taicpu(p).oper[0]^.val = 1) then
  1505. if (taicpu(p).ops = 2) then
  1506. { remove "imul $1, reg" }
  1507. begin
  1508. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1509. Result := RemoveCurrentP(p);
  1510. end
  1511. else
  1512. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1513. begin
  1514. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1515. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1516. asml.InsertAfter(hp1, p);
  1517. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1518. RemoveCurrentP(p, hp1);
  1519. Result := True;
  1520. end
  1521. else if ((taicpu(p).ops <= 2) or
  1522. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1523. not(cs_opt_size in current_settings.optimizerswitches) and
  1524. (not(GetNextInstruction(p, hp1)) or
  1525. not((tai(hp1).typ = ait_instruction) and
  1526. ((taicpu(hp1).opcode=A_Jcc) and
  1527. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1528. begin
  1529. {
  1530. imul X, reg1, reg2 to
  1531. lea (reg1,reg1,Y), reg2
  1532. shl ZZ,reg2
  1533. imul XX, reg1 to
  1534. lea (reg1,reg1,YY), reg1
  1535. shl ZZ,reg2
  1536. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1537. it does not exist as a separate optimization target in FPC though.
  1538. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1539. at most two zeros
  1540. }
  1541. reference_reset(tmpref,1,[]);
  1542. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1543. begin
  1544. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1545. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1546. TmpRef.base := taicpu(p).oper[1]^.reg;
  1547. TmpRef.index := taicpu(p).oper[1]^.reg;
  1548. if not(BaseValue in [3,5,9]) then
  1549. Internalerror(2018110101);
  1550. TmpRef.ScaleFactor := BaseValue-1;
  1551. if (taicpu(p).ops = 2) then
  1552. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1553. else
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1555. AsmL.InsertAfter(hp1,p);
  1556. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1557. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1558. RemoveCurrentP(p, hp1);
  1559. if ShiftValue>0 then
  1560. begin
  1561. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1562. AsmL.InsertAfter(hp2,hp1);
  1563. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1564. end;
  1565. Result := True;
  1566. end;
  1567. end;
  1568. end;
  1569. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1570. begin
  1571. Result := False;
  1572. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1573. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1574. begin
  1575. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1576. taicpu(p).opcode := A_MOV;
  1577. Result := True;
  1578. end;
  1579. end;
  1580. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1581. var
  1582. p: taicpu absolute hp; { Implicit typecast }
  1583. i: Integer;
  1584. begin
  1585. Result := False;
  1586. if not assigned(hp) or
  1587. (hp.typ <> ait_instruction) then
  1588. Exit;
  1589. Prefetch(insprop[p.opcode]);
  1590. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1591. with insprop[p.opcode] do
  1592. begin
  1593. case getsubreg(reg) of
  1594. R_SUBW,R_SUBD,R_SUBQ:
  1595. Result:=
  1596. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1597. uncommon flags are checked first }
  1598. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1599. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1600. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1601. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1604. R_SUBFLAGCARRY:
  1605. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1606. R_SUBFLAGPARITY:
  1607. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGAUXILIARY:
  1609. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGZERO:
  1611. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGSIGN:
  1613. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGOVERFLOW:
  1615. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGINTERRUPT:
  1617. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGDIRECTION:
  1619. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1620. else
  1621. internalerror(2017050501);
  1622. end;
  1623. exit;
  1624. end;
  1625. { Handle special cases first }
  1626. case p.opcode of
  1627. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1628. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1629. begin
  1630. Result :=
  1631. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1632. (p.oper[1]^.typ = top_reg) and
  1633. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1634. (
  1635. (p.oper[0]^.typ = top_const) or
  1636. (
  1637. (p.oper[0]^.typ = top_reg) and
  1638. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1639. ) or (
  1640. (p.oper[0]^.typ = top_ref) and
  1641. not RegInRef(reg,p.oper[0]^.ref^)
  1642. )
  1643. );
  1644. end;
  1645. A_MUL, A_IMUL:
  1646. Result :=
  1647. (
  1648. (p.ops=3) and { IMUL only }
  1649. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1650. (
  1651. (
  1652. (p.oper[1]^.typ=top_reg) and
  1653. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1654. ) or (
  1655. (p.oper[1]^.typ=top_ref) and
  1656. not RegInRef(reg,p.oper[1]^.ref^)
  1657. )
  1658. )
  1659. ) or (
  1660. (
  1661. (p.ops=1) and
  1662. (
  1663. (
  1664. (
  1665. (p.oper[0]^.typ=top_reg) and
  1666. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1667. )
  1668. ) or (
  1669. (p.oper[0]^.typ=top_ref) and
  1670. not RegInRef(reg,p.oper[0]^.ref^)
  1671. )
  1672. ) and (
  1673. (
  1674. (p.opsize=S_B) and
  1675. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1676. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1677. ) or (
  1678. (p.opsize=S_W) and
  1679. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1680. ) or (
  1681. (p.opsize=S_L) and
  1682. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1683. {$ifdef x86_64}
  1684. ) or (
  1685. (p.opsize=S_Q) and
  1686. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1687. {$endif x86_64}
  1688. )
  1689. )
  1690. )
  1691. );
  1692. A_CBW:
  1693. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1694. {$ifndef x86_64}
  1695. A_LDS:
  1696. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1697. A_LES:
  1698. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. {$endif not x86_64}
  1700. A_LFS:
  1701. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1702. A_LGS:
  1703. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LSS:
  1705. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1707. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1708. A_LODSB:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1710. A_LODSW:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1712. {$ifdef x86_64}
  1713. A_LODSQ:
  1714. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1715. {$endif x86_64}
  1716. A_LODSD:
  1717. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1718. A_FSTSW, A_FNSTSW:
  1719. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1720. else
  1721. begin
  1722. with insprop[p.opcode] do
  1723. begin
  1724. if (
  1725. { xor %reg,%reg etc. is classed as a new value }
  1726. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1727. MatchOpType(p, top_reg, top_reg) and
  1728. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1729. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1730. ) then
  1731. begin
  1732. Result := True;
  1733. Exit;
  1734. end;
  1735. { Make sure the entire register is overwritten }
  1736. if (getregtype(reg) = R_INTREGISTER) then
  1737. begin
  1738. if (p.ops > 0) then
  1739. begin
  1740. if RegInOp(reg, p.oper[0]^) then
  1741. begin
  1742. if (p.oper[0]^.typ = top_ref) then
  1743. begin
  1744. if RegInRef(reg, p.oper[0]^.ref^) then
  1745. begin
  1746. Result := False;
  1747. Exit;
  1748. end;
  1749. end
  1750. else if (p.oper[0]^.typ = top_reg) then
  1751. begin
  1752. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1753. begin
  1754. Result := False;
  1755. Exit;
  1756. end
  1757. else if ([Ch_WOp1]*Ch<>[]) then
  1758. begin
  1759. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1760. Result := True
  1761. else
  1762. begin
  1763. Result := False;
  1764. Exit;
  1765. end;
  1766. end;
  1767. end;
  1768. end;
  1769. if (p.ops > 1) then
  1770. begin
  1771. if RegInOp(reg, p.oper[1]^) then
  1772. begin
  1773. if (p.oper[1]^.typ = top_ref) then
  1774. begin
  1775. if RegInRef(reg, p.oper[1]^.ref^) then
  1776. begin
  1777. Result := False;
  1778. Exit;
  1779. end;
  1780. end
  1781. else if (p.oper[1]^.typ = top_reg) then
  1782. begin
  1783. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1784. begin
  1785. Result := False;
  1786. Exit;
  1787. end
  1788. else if ([Ch_WOp2]*Ch<>[]) then
  1789. begin
  1790. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1791. Result := True
  1792. else
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end;
  1798. end;
  1799. end;
  1800. if (p.ops > 2) then
  1801. begin
  1802. if RegInOp(reg, p.oper[2]^) then
  1803. begin
  1804. if (p.oper[2]^.typ = top_ref) then
  1805. begin
  1806. if RegInRef(reg, p.oper[2]^.ref^) then
  1807. begin
  1808. Result := False;
  1809. Exit;
  1810. end;
  1811. end
  1812. else if (p.oper[2]^.typ = top_reg) then
  1813. begin
  1814. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1815. begin
  1816. Result := False;
  1817. Exit;
  1818. end
  1819. else if ([Ch_WOp3]*Ch<>[]) then
  1820. begin
  1821. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1822. Result := True
  1823. else
  1824. begin
  1825. Result := False;
  1826. Exit;
  1827. end;
  1828. end;
  1829. end;
  1830. end;
  1831. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1832. begin
  1833. if (p.oper[3]^.typ = top_ref) then
  1834. begin
  1835. if RegInRef(reg, p.oper[3]^.ref^) then
  1836. begin
  1837. Result := False;
  1838. Exit;
  1839. end;
  1840. end
  1841. else if (p.oper[3]^.typ = top_reg) then
  1842. begin
  1843. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1844. begin
  1845. Result := False;
  1846. Exit;
  1847. end
  1848. else if ([Ch_WOp4]*Ch<>[]) then
  1849. begin
  1850. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1851. Result := True
  1852. else
  1853. begin
  1854. Result := False;
  1855. Exit;
  1856. end;
  1857. end;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1864. case getsupreg(reg) of
  1865. RS_EAX:
  1866. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1867. begin
  1868. Result := True;
  1869. Exit;
  1870. end;
  1871. RS_ECX:
  1872. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1873. begin
  1874. Result := True;
  1875. Exit;
  1876. end;
  1877. RS_EDX:
  1878. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1879. begin
  1880. Result := True;
  1881. Exit;
  1882. end;
  1883. RS_EBX:
  1884. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1885. begin
  1886. Result := True;
  1887. Exit;
  1888. end;
  1889. RS_ESP:
  1890. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1891. begin
  1892. Result := True;
  1893. Exit;
  1894. end;
  1895. RS_EBP:
  1896. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1897. begin
  1898. Result := True;
  1899. Exit;
  1900. end;
  1901. RS_ESI:
  1902. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1903. begin
  1904. Result := True;
  1905. Exit;
  1906. end;
  1907. RS_EDI:
  1908. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1909. begin
  1910. Result := True;
  1911. Exit;
  1912. end;
  1913. else
  1914. ;
  1915. end;
  1916. end;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1922. var
  1923. hp2,hp3 : tai;
  1924. begin
  1925. { some x86-64 issue a NOP before the real exit code }
  1926. if MatchInstruction(p,A_NOP,[]) then
  1927. GetNextInstruction(p,p);
  1928. result:=assigned(p) and (p.typ=ait_instruction) and
  1929. ((taicpu(p).opcode = A_RET) or
  1930. ((taicpu(p).opcode=A_LEAVE) and
  1931. GetNextInstruction(p,hp2) and
  1932. MatchInstruction(hp2,A_RET,[S_NO])
  1933. ) or
  1934. (((taicpu(p).opcode=A_LEA) and
  1935. MatchOpType(taicpu(p),top_ref,top_reg) and
  1936. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1937. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1938. ) and
  1939. GetNextInstruction(p,hp2) and
  1940. MatchInstruction(hp2,A_RET,[S_NO])
  1941. ) or
  1942. ((((taicpu(p).opcode=A_MOV) and
  1943. MatchOpType(taicpu(p),top_reg,top_reg) and
  1944. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1945. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1946. ((taicpu(p).opcode=A_LEA) and
  1947. MatchOpType(taicpu(p),top_ref,top_reg) and
  1948. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1949. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1950. )
  1951. ) and
  1952. GetNextInstruction(p,hp2) and
  1953. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1954. MatchOpType(taicpu(hp2),top_reg) and
  1955. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1956. GetNextInstruction(hp2,hp3) and
  1957. MatchInstruction(hp3,A_RET,[S_NO])
  1958. )
  1959. );
  1960. end;
  1961. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1962. begin
  1963. isFoldableArithOp := False;
  1964. case hp1.opcode of
  1965. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1966. isFoldableArithOp :=
  1967. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1968. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1969. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1970. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[1]^.reg = reg);
  1972. A_INC,A_DEC,A_NEG,A_NOT:
  1973. isFoldableArithOp :=
  1974. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1975. (taicpu(hp1).oper[0]^.reg = reg);
  1976. else
  1977. ;
  1978. end;
  1979. end;
  1980. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1981. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1982. var
  1983. hp2: tai;
  1984. begin
  1985. hp2 := p;
  1986. repeat
  1987. hp2 := tai(hp2.previous);
  1988. if assigned(hp2) and
  1989. (hp2.typ = ait_regalloc) and
  1990. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1991. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1992. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1993. begin
  1994. RemoveInstruction(hp2);
  1995. break;
  1996. end;
  1997. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1998. end;
  1999. begin
  2000. case current_procinfo.procdef.returndef.typ of
  2001. arraydef,recorddef,pointerdef,
  2002. stringdef,enumdef,procdef,objectdef,errordef,
  2003. filedef,setdef,procvardef,
  2004. classrefdef,forwarddef:
  2005. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2006. orddef:
  2007. if current_procinfo.procdef.returndef.size <> 0 then
  2008. begin
  2009. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2010. { for int64/qword }
  2011. if current_procinfo.procdef.returndef.size = 8 then
  2012. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2013. end;
  2014. else
  2015. ;
  2016. end;
  2017. end;
  2018. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2019. var
  2020. hp1,hp2 : tai;
  2021. begin
  2022. result:=false;
  2023. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2024. begin
  2025. { vmova* reg1,reg1
  2026. =>
  2027. <nop> }
  2028. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2029. begin
  2030. RemoveCurrentP(p);
  2031. result:=true;
  2032. exit;
  2033. end;
  2034. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2035. (hp1.typ = ait_instruction) and
  2036. (
  2037. { Under -O2 and below, the instructions are always adjacent }
  2038. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2039. (taicpu(hp1).ops <= 1) or
  2040. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2041. { If reg1 = reg3, reg1 must not be modified in between }
  2042. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2043. ) then
  2044. begin
  2045. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2046. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2047. begin
  2048. { vmova* reg1,reg2
  2049. ...
  2050. vmova* reg2,reg3
  2051. dealloc reg2
  2052. =>
  2053. vmova* reg1,reg3 }
  2054. TransferUsedRegs(TmpUsedRegs);
  2055. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2056. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2057. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2058. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2059. begin
  2060. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2061. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2064. RemoveInstruction(hp1);
  2065. result:=true;
  2066. exit;
  2067. end;
  2068. { special case:
  2069. vmova* reg1,<op>
  2070. ...
  2071. vmova* <op>,reg1
  2072. =>
  2073. vmova* reg1,<op> }
  2074. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2075. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2076. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2077. ) then
  2078. begin
  2079. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2080. RemoveInstruction(hp1);
  2081. result:=true;
  2082. exit;
  2083. end
  2084. end
  2085. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2086. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2087. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2088. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2089. ) and
  2090. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2091. begin
  2092. { vmova* reg1,reg2
  2093. ...
  2094. vmovs* reg2,<op>
  2095. dealloc reg2
  2096. =>
  2097. vmovs* reg1,<op> }
  2098. TransferUsedRegs(TmpUsedRegs);
  2099. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2100. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2101. begin
  2102. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2103. taicpu(p).opcode:=taicpu(hp1).opcode;
  2104. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2105. TransferUsedRegs(TmpUsedRegs);
  2106. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2107. RemoveInstruction(hp1);
  2108. result:=true;
  2109. exit;
  2110. end
  2111. end;
  2112. if MatchInstruction(hp1,[A_VFMADDPD,
  2113. A_VFMADD132PD,
  2114. A_VFMADD132PS,
  2115. A_VFMADD132SD,
  2116. A_VFMADD132SS,
  2117. A_VFMADD213PD,
  2118. A_VFMADD213PS,
  2119. A_VFMADD213SD,
  2120. A_VFMADD213SS,
  2121. A_VFMADD231PD,
  2122. A_VFMADD231PS,
  2123. A_VFMADD231SD,
  2124. A_VFMADD231SS,
  2125. A_VFMADDSUB132PD,
  2126. A_VFMADDSUB132PS,
  2127. A_VFMADDSUB213PD,
  2128. A_VFMADDSUB213PS,
  2129. A_VFMADDSUB231PD,
  2130. A_VFMADDSUB231PS,
  2131. A_VFMSUB132PD,
  2132. A_VFMSUB132PS,
  2133. A_VFMSUB132SD,
  2134. A_VFMSUB132SS,
  2135. A_VFMSUB213PD,
  2136. A_VFMSUB213PS,
  2137. A_VFMSUB213SD,
  2138. A_VFMSUB213SS,
  2139. A_VFMSUB231PD,
  2140. A_VFMSUB231PS,
  2141. A_VFMSUB231SD,
  2142. A_VFMSUB231SS,
  2143. A_VFMSUBADD132PD,
  2144. A_VFMSUBADD132PS,
  2145. A_VFMSUBADD213PD,
  2146. A_VFMSUBADD213PS,
  2147. A_VFMSUBADD231PD,
  2148. A_VFMSUBADD231PS,
  2149. A_VFNMADD132PD,
  2150. A_VFNMADD132PS,
  2151. A_VFNMADD132SD,
  2152. A_VFNMADD132SS,
  2153. A_VFNMADD213PD,
  2154. A_VFNMADD213PS,
  2155. A_VFNMADD213SD,
  2156. A_VFNMADD213SS,
  2157. A_VFNMADD231PD,
  2158. A_VFNMADD231PS,
  2159. A_VFNMADD231SD,
  2160. A_VFNMADD231SS,
  2161. A_VFNMSUB132PD,
  2162. A_VFNMSUB132PS,
  2163. A_VFNMSUB132SD,
  2164. A_VFNMSUB132SS,
  2165. A_VFNMSUB213PD,
  2166. A_VFNMSUB213PS,
  2167. A_VFNMSUB213SD,
  2168. A_VFNMSUB213SS,
  2169. A_VFNMSUB231PD,
  2170. A_VFNMSUB231PS,
  2171. A_VFNMSUB231SD,
  2172. A_VFNMSUB231SS],[S_NO]) and
  2173. { we mix single and double opperations here because we assume that the compiler
  2174. generates vmovapd only after double operations and vmovaps only after single operations }
  2175. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2176. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2177. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2178. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2179. begin
  2180. TransferUsedRegs(TmpUsedRegs);
  2181. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2182. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2183. begin
  2184. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2185. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2186. RemoveCurrentP(p)
  2187. else
  2188. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2189. RemoveInstruction(hp2);
  2190. end;
  2191. end
  2192. else if (hp1.typ = ait_instruction) and
  2193. (((taicpu(p).opcode=A_MOVAPS) and
  2194. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2195. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2196. ((taicpu(p).opcode=A_MOVAPD) and
  2197. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2198. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2199. ) and
  2200. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2201. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2202. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2203. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2204. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2205. { change
  2206. movapX reg,reg2
  2207. addsX/subsX/... reg3, reg2
  2208. movapX reg2,reg
  2209. to
  2210. addsX/subsX/... reg3,reg
  2211. }
  2212. begin
  2213. TransferUsedRegs(TmpUsedRegs);
  2214. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2215. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2216. begin
  2217. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2218. debug_op2str(taicpu(p).opcode)+' '+
  2219. debug_op2str(taicpu(hp1).opcode)+' '+
  2220. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2221. { we cannot eliminate the first move if
  2222. the operations uses the same register for source and dest }
  2223. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2224. { Remember that hp1 is not necessarily the immediate
  2225. next instruction }
  2226. RemoveCurrentP(p);
  2227. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2228. RemoveInstruction(hp2);
  2229. result:=true;
  2230. end;
  2231. end
  2232. else if (hp1.typ = ait_instruction) and
  2233. (((taicpu(p).opcode=A_VMOVAPD) and
  2234. (taicpu(hp1).opcode=A_VCOMISD)) or
  2235. ((taicpu(p).opcode=A_VMOVAPS) and
  2236. ((taicpu(hp1).opcode=A_VCOMISS))
  2237. )
  2238. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2239. { change
  2240. movapX reg,reg1
  2241. vcomisX reg1,reg1
  2242. to
  2243. vcomisX reg,reg
  2244. }
  2245. begin
  2246. TransferUsedRegs(TmpUsedRegs);
  2247. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2248. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2249. begin
  2250. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2251. debug_op2str(taicpu(p).opcode)+' '+
  2252. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2253. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2254. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2255. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2256. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2257. RemoveCurrentP(p);
  2258. result:=true;
  2259. exit;
  2260. end;
  2261. end
  2262. end;
  2263. end;
  2264. end;
  2265. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2266. var
  2267. hp1 : tai;
  2268. begin
  2269. result:=false;
  2270. { replace
  2271. V<Op>X %mreg1,%mreg2,%mreg3
  2272. VMovX %mreg3,%mreg4
  2273. dealloc %mreg3
  2274. by
  2275. V<Op>X %mreg1,%mreg2,%mreg4
  2276. ?
  2277. }
  2278. if GetNextInstruction(p,hp1) and
  2279. { we mix single and double operations here because we assume that the compiler
  2280. generates vmovapd only after double operations and vmovaps only after single operations }
  2281. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2282. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2283. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2284. begin
  2285. TransferUsedRegs(TmpUsedRegs);
  2286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2287. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2288. begin
  2289. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2290. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2291. RemoveInstruction(hp1);
  2292. result:=true;
  2293. end;
  2294. end;
  2295. end;
  2296. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2297. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2298. begin
  2299. Result := False;
  2300. { For safety reasons, only check for exact register matches }
  2301. { Check base register }
  2302. if (ref.base = AOldReg) then
  2303. begin
  2304. ref.base := ANewReg;
  2305. Result := True;
  2306. end;
  2307. { Check index register }
  2308. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2309. begin
  2310. ref.index := ANewReg;
  2311. Result := True;
  2312. end;
  2313. end;
  2314. { Replaces all references to AOldReg in an operand to ANewReg }
  2315. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2316. var
  2317. OldSupReg, NewSupReg: TSuperRegister;
  2318. OldSubReg, NewSubReg: TSubRegister;
  2319. OldRegType: TRegisterType;
  2320. ThisOper: POper;
  2321. begin
  2322. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2323. Result := False;
  2324. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2325. InternalError(2020011801);
  2326. OldSupReg := getsupreg(AOldReg);
  2327. OldSubReg := getsubreg(AOldReg);
  2328. OldRegType := getregtype(AOldReg);
  2329. NewSupReg := getsupreg(ANewReg);
  2330. NewSubReg := getsubreg(ANewReg);
  2331. if OldRegType <> getregtype(ANewReg) then
  2332. InternalError(2020011802);
  2333. if OldSubReg <> NewSubReg then
  2334. InternalError(2020011803);
  2335. case ThisOper^.typ of
  2336. top_reg:
  2337. if (
  2338. (ThisOper^.reg = AOldReg) or
  2339. (
  2340. (OldRegType = R_INTREGISTER) and
  2341. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2342. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2343. (
  2344. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2345. {$ifndef x86_64}
  2346. and (
  2347. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2348. don't have an 8-bit representation }
  2349. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2350. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2351. )
  2352. {$endif x86_64}
  2353. )
  2354. )
  2355. ) then
  2356. begin
  2357. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2358. Result := True;
  2359. end;
  2360. top_ref:
  2361. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2362. Result := True;
  2363. else
  2364. ;
  2365. end;
  2366. end;
  2367. { Replaces all references to AOldReg in an instruction to ANewReg }
  2368. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2369. const
  2370. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2371. var
  2372. OperIdx: Integer;
  2373. begin
  2374. Result := False;
  2375. for OperIdx := 0 to p.ops - 1 do
  2376. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2377. begin
  2378. { The shift and rotate instructions can only use CL }
  2379. if not (
  2380. (OperIdx = 0) and
  2381. { This second condition just helps to avoid unnecessarily
  2382. calling MatchInstruction for 10 different opcodes }
  2383. (p.oper[0]^.reg = NR_CL) and
  2384. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2385. ) then
  2386. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2387. end
  2388. else if p.oper[OperIdx]^.typ = top_ref then
  2389. { It's okay to replace registers in references that get written to }
  2390. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2391. end;
  2392. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2393. begin
  2394. Result :=
  2395. (ref^.index = NR_NO) and
  2396. (
  2397. {$ifdef x86_64}
  2398. (
  2399. (ref^.base = NR_RIP) and
  2400. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2401. ) or
  2402. {$endif x86_64}
  2403. (ref^.refaddr = addr_full) or
  2404. (ref^.base = NR_STACK_POINTER_REG) or
  2405. (ref^.base = current_procinfo.framepointer)
  2406. );
  2407. end;
  2408. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2409. var
  2410. l: asizeint;
  2411. begin
  2412. Result := False;
  2413. { Should have been checked previously }
  2414. if p.opcode <> A_LEA then
  2415. InternalError(2020072501);
  2416. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2417. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2418. not(cs_opt_size in current_settings.optimizerswitches) then
  2419. exit;
  2420. with p.oper[0]^.ref^ do
  2421. begin
  2422. if (base <> p.oper[1]^.reg) or
  2423. (index <> NR_NO) or
  2424. assigned(symbol) then
  2425. exit;
  2426. l:=offset;
  2427. if (l=1) and UseIncDec then
  2428. begin
  2429. p.opcode:=A_INC;
  2430. p.loadreg(0,p.oper[1]^.reg);
  2431. p.ops:=1;
  2432. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2433. end
  2434. else if (l=-1) and UseIncDec then
  2435. begin
  2436. p.opcode:=A_DEC;
  2437. p.loadreg(0,p.oper[1]^.reg);
  2438. p.ops:=1;
  2439. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2440. end
  2441. else
  2442. begin
  2443. if (l<0) and (l<>-2147483648) then
  2444. begin
  2445. p.opcode:=A_SUB;
  2446. p.loadConst(0,-l);
  2447. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2448. end
  2449. else
  2450. begin
  2451. p.opcode:=A_ADD;
  2452. p.loadConst(0,l);
  2453. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2454. end;
  2455. end;
  2456. end;
  2457. Result := True;
  2458. end;
  2459. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2460. var
  2461. CurrentReg, ReplaceReg: TRegister;
  2462. begin
  2463. Result := False;
  2464. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2465. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2466. case hp.opcode of
  2467. A_FSTSW, A_FNSTSW,
  2468. A_IN, A_INS, A_OUT, A_OUTS,
  2469. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2470. { These routines have explicit operands, but they are restricted in
  2471. what they can be (e.g. IN and OUT can only read from AL, AX or
  2472. EAX. }
  2473. Exit;
  2474. A_IMUL:
  2475. begin
  2476. { The 1-operand version writes to implicit registers
  2477. The 2-operand version reads from the first operator, and reads
  2478. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2479. the 3-operand version reads from a register that it doesn't write to
  2480. }
  2481. case hp.ops of
  2482. 1:
  2483. if (
  2484. (
  2485. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2486. ) or
  2487. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2488. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2489. begin
  2490. Result := True;
  2491. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2492. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2493. end;
  2494. 2:
  2495. { Only modify the first parameter }
  2496. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2497. begin
  2498. Result := True;
  2499. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2500. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2501. end;
  2502. 3:
  2503. { Only modify the second parameter }
  2504. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. else
  2511. InternalError(2020012901);
  2512. end;
  2513. end;
  2514. else
  2515. if (hp.ops > 0) and
  2516. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2517. begin
  2518. Result := True;
  2519. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2520. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2521. end;
  2522. end;
  2523. end;
  2524. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2525. var
  2526. hp2: tai;
  2527. p_SourceReg, p_TargetReg: TRegister;
  2528. begin
  2529. Result := False;
  2530. { Backward optimisation. If we have:
  2531. func. %reg1,%reg2
  2532. mov %reg2,%reg3
  2533. (dealloc %reg2)
  2534. Change to:
  2535. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2536. Perform similar optimisations with 1, 3 and 4-operand instructions
  2537. that only have one output.
  2538. }
  2539. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2540. begin
  2541. p_SourceReg := taicpu(p).oper[0]^.reg;
  2542. p_TargetReg := taicpu(p).oper[1]^.reg;
  2543. TransferUsedRegs(TmpUsedRegs);
  2544. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2545. GetLastInstruction(p, hp2) and
  2546. (hp2.typ = ait_instruction) and
  2547. { Have to make sure it's an instruction that only reads from
  2548. the first operands and only writes (not reads or modifies) to
  2549. the last one; in essence, a pure function such as BSR, POPCNT
  2550. or ANDN }
  2551. (
  2552. (
  2553. (taicpu(hp2).ops = 1) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2555. ) or
  2556. (
  2557. (taicpu(hp2).ops = 2) and
  2558. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2559. ) or
  2560. (
  2561. (taicpu(hp2).ops = 3) and
  2562. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2563. ) or
  2564. (
  2565. (taicpu(hp2).ops = 4) and
  2566. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2567. )
  2568. ) and
  2569. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2570. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2571. begin
  2572. case taicpu(hp2).opcode of
  2573. A_FSTSW, A_FNSTSW,
  2574. A_IN, A_INS, A_OUT, A_OUTS,
  2575. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2576. { These routines have explicit operands, but they are restricted in
  2577. what they can be (e.g. IN and OUT can only read from AL, AX or
  2578. EAX. }
  2579. ;
  2580. else
  2581. begin
  2582. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2583. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2584. if not RegInInstruction(p_TargetReg, hp2) then
  2585. begin
  2586. { Since we're allocating from an earlier point, we
  2587. need to remove the register from the tracking }
  2588. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2589. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2590. end;
  2591. RemoveCurrentp(p, hp1);
  2592. { If the Func was another MOV instruction, we might get
  2593. "mov %reg,%reg" that doesn't get removed in Pass 2
  2594. otherwise, so deal with it here (also do something
  2595. similar with lea (%reg),%reg}
  2596. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2597. begin
  2598. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2599. if p = hp2 then
  2600. RemoveCurrentp(p)
  2601. else
  2602. RemoveInstruction(hp2);
  2603. end;
  2604. Result := True;
  2605. Exit;
  2606. end;
  2607. end;
  2608. end;
  2609. end;
  2610. end;
  2611. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2612. begin
  2613. Result := False;
  2614. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2615. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2616. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2617. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2618. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2619. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2620. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2621. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2622. begin
  2623. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2624. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2625. Result := True;
  2626. end;
  2627. end;
  2628. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2629. var
  2630. hp1, hp2, hp3, hp4: tai;
  2631. DoOptimisation, TempBool: Boolean;
  2632. {$ifdef x86_64}
  2633. NewConst: TCGInt;
  2634. {$endif x86_64}
  2635. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2636. begin
  2637. if taicpu(hp1).opcode = signed_movop then
  2638. begin
  2639. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2640. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2641. end
  2642. else
  2643. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2644. end;
  2645. function TryConstMerge(var p1, p2: tai): Boolean;
  2646. var
  2647. ThisRef: TReference;
  2648. begin
  2649. Result := False;
  2650. ThisRef := taicpu(p2).oper[1]^.ref^;
  2651. { Only permit writes to the stack, since we can guarantee alignment with that }
  2652. if (ThisRef.index = NR_NO) and
  2653. (
  2654. (ThisRef.base = NR_STACK_POINTER_REG) or
  2655. (ThisRef.base = current_procinfo.framepointer)
  2656. ) then
  2657. begin
  2658. case taicpu(p).opsize of
  2659. S_B:
  2660. begin
  2661. { Word writes must be on a 2-byte boundary }
  2662. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2663. begin
  2664. { Reduce offset of second reference to see if it is sequential with the first }
  2665. Dec(ThisRef.offset, 1);
  2666. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2667. begin
  2668. { Make sure the constants aren't represented as a
  2669. negative number, as these won't merge properly }
  2670. taicpu(p1).opsize := S_W;
  2671. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2672. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2673. RemoveInstruction(p2);
  2674. Result := True;
  2675. end;
  2676. end;
  2677. end;
  2678. S_W:
  2679. begin
  2680. { Longword writes must be on a 4-byte boundary }
  2681. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2682. begin
  2683. { Reduce offset of second reference to see if it is sequential with the first }
  2684. Dec(ThisRef.offset, 2);
  2685. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2686. begin
  2687. { Make sure the constants aren't represented as a
  2688. negative number, as these won't merge properly }
  2689. taicpu(p1).opsize := S_L;
  2690. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2691. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2692. RemoveInstruction(p2);
  2693. Result := True;
  2694. end;
  2695. end;
  2696. end;
  2697. {$ifdef x86_64}
  2698. S_L:
  2699. begin
  2700. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2701. see if the constants can be encoded this way. }
  2702. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2703. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2704. { Quadword writes must be on an 8-byte boundary }
  2705. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2706. begin
  2707. { Reduce offset of second reference to see if it is sequential with the first }
  2708. Dec(ThisRef.offset, 4);
  2709. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2710. begin
  2711. { Make sure the constants aren't represented as a
  2712. negative number, as these won't merge properly }
  2713. taicpu(p1).opsize := S_Q;
  2714. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2715. taicpu(p1).oper[0]^.val := NewConst;
  2716. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2717. RemoveInstruction(p2);
  2718. Result := True;
  2719. end;
  2720. end;
  2721. end;
  2722. {$endif x86_64}
  2723. else
  2724. ;
  2725. end;
  2726. end;
  2727. end;
  2728. var
  2729. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2730. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2731. NewSize: topsize; NewOffset: asizeint;
  2732. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2733. SourceRef, TargetRef: TReference;
  2734. MovAligned, MovUnaligned: TAsmOp;
  2735. ThisRef: TReference;
  2736. JumpTracking: TLinkedList;
  2737. begin
  2738. Result:=false;
  2739. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2740. { remove mov reg1,reg1? }
  2741. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2742. then
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2745. { take care of the register (de)allocs following p }
  2746. RemoveCurrentP(p, hp1);
  2747. Result:=true;
  2748. exit;
  2749. end;
  2750. { All the next optimisations require a next instruction }
  2751. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2752. Exit;
  2753. { Prevent compiler warnings }
  2754. p_TargetReg := NR_NO;
  2755. if taicpu(p).oper[1]^.typ = top_reg then
  2756. begin
  2757. { Saves on a large number of dereferences }
  2758. p_TargetReg := taicpu(p).oper[1]^.reg;
  2759. { Look for:
  2760. mov %reg1,%reg2
  2761. ??? %reg2,r/m
  2762. Change to:
  2763. mov %reg1,%reg2
  2764. ??? %reg1,r/m
  2765. }
  2766. if taicpu(p).oper[0]^.typ = top_reg then
  2767. begin
  2768. if RegReadByInstruction(p_TargetReg, hp1) and
  2769. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2770. begin
  2771. { A change has occurred, just not in p }
  2772. Result := True;
  2773. TransferUsedRegs(TmpUsedRegs);
  2774. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2775. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2776. { Just in case something didn't get modified (e.g. an
  2777. implicit register) }
  2778. not RegReadByInstruction(p_TargetReg, hp1) then
  2779. begin
  2780. { We can remove the original MOV }
  2781. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2782. RemoveCurrentp(p, hp1);
  2783. { UsedRegs got updated by RemoveCurrentp }
  2784. Result := True;
  2785. Exit;
  2786. end;
  2787. { If we know a MOV instruction has become a null operation, we might as well
  2788. get rid of it now to save time. }
  2789. if (taicpu(hp1).opcode = A_MOV) and
  2790. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2791. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2792. { Just being a register is enough to confirm it's a null operation }
  2793. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2794. begin
  2795. Result := True;
  2796. { Speed-up to reduce a pipeline stall... if we had something like...
  2797. movl %eax,%edx
  2798. movw %dx,%ax
  2799. ... the second instruction would change to movw %ax,%ax, but
  2800. given that it is now %ax that's active rather than %eax,
  2801. penalties might occur due to a partial register write, so instead,
  2802. change it to a MOVZX instruction when optimising for speed.
  2803. }
  2804. if not (cs_opt_size in current_settings.optimizerswitches) and
  2805. IsMOVZXAcceptable and
  2806. (taicpu(hp1).opsize < taicpu(p).opsize)
  2807. {$ifdef x86_64}
  2808. { operations already implicitly set the upper 64 bits to zero }
  2809. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2810. {$endif x86_64}
  2811. then
  2812. begin
  2813. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2814. case taicpu(p).opsize of
  2815. S_W:
  2816. if taicpu(hp1).opsize = S_B then
  2817. taicpu(hp1).opsize := S_BL
  2818. else
  2819. InternalError(2020012911);
  2820. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2821. case taicpu(hp1).opsize of
  2822. S_B:
  2823. taicpu(hp1).opsize := S_BL;
  2824. S_W:
  2825. taicpu(hp1).opsize := S_WL;
  2826. else
  2827. InternalError(2020012912);
  2828. end;
  2829. else
  2830. InternalError(2020012910);
  2831. end;
  2832. taicpu(hp1).opcode := A_MOVZX;
  2833. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2834. end
  2835. else
  2836. begin
  2837. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2838. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2839. RemoveInstruction(hp1);
  2840. { The instruction after what was hp1 is now the immediate next instruction,
  2841. so we can continue to make optimisations if it's present }
  2842. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2843. Exit;
  2844. hp1 := hp2;
  2845. end;
  2846. end;
  2847. end;
  2848. end;
  2849. end;
  2850. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2851. overwrites the original destination register. e.g.
  2852. movl ###,%reg2d
  2853. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2854. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2855. }
  2856. if (taicpu(p).oper[1]^.typ = top_reg) and
  2857. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2858. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2859. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2860. begin
  2861. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2862. begin
  2863. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2864. case taicpu(p).oper[0]^.typ of
  2865. top_const:
  2866. { We have something like:
  2867. movb $x, %regb
  2868. movzbl %regb,%regd
  2869. Change to:
  2870. movl $x, %regd
  2871. }
  2872. begin
  2873. case taicpu(hp1).opsize of
  2874. S_BW:
  2875. begin
  2876. convert_mov_value(A_MOVSX, $FF);
  2877. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2878. taicpu(p).opsize := S_W;
  2879. end;
  2880. S_BL:
  2881. begin
  2882. convert_mov_value(A_MOVSX, $FF);
  2883. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2884. taicpu(p).opsize := S_L;
  2885. end;
  2886. S_WL:
  2887. begin
  2888. convert_mov_value(A_MOVSX, $FFFF);
  2889. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2890. taicpu(p).opsize := S_L;
  2891. end;
  2892. {$ifdef x86_64}
  2893. S_BQ:
  2894. begin
  2895. convert_mov_value(A_MOVSX, $FF);
  2896. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2897. taicpu(p).opsize := S_Q;
  2898. end;
  2899. S_WQ:
  2900. begin
  2901. convert_mov_value(A_MOVSX, $FFFF);
  2902. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2903. taicpu(p).opsize := S_Q;
  2904. end;
  2905. S_LQ:
  2906. begin
  2907. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2908. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2909. taicpu(p).opsize := S_Q;
  2910. end;
  2911. {$endif x86_64}
  2912. else
  2913. { If hp1 was a MOV instruction, it should have been
  2914. optimised already }
  2915. InternalError(2020021001);
  2916. end;
  2917. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2918. RemoveInstruction(hp1);
  2919. Result := True;
  2920. Exit;
  2921. end;
  2922. top_ref:
  2923. begin
  2924. { We have something like:
  2925. movb mem, %regb
  2926. movzbl %regb,%regd
  2927. Change to:
  2928. movzbl mem, %regd
  2929. }
  2930. ThisRef := taicpu(p).oper[0]^.ref^;
  2931. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2932. begin
  2933. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2934. taicpu(hp1).loadref(0, ThisRef);
  2935. { Make sure any registers in the references are properly tracked }
  2936. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2937. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2938. if (ThisRef.index <> NR_NO) then
  2939. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2940. RemoveCurrentP(p, hp1);
  2941. Result := True;
  2942. Exit;
  2943. end;
  2944. end;
  2945. else
  2946. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2947. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2948. Exit;
  2949. end;
  2950. end
  2951. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2952. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2953. optimised }
  2954. else
  2955. begin
  2956. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2957. RemoveCurrentP(p, hp1);
  2958. Result := True;
  2959. Exit;
  2960. end;
  2961. end;
  2962. if (taicpu(hp1).opcode = A_AND) and
  2963. (taicpu(p).oper[1]^.typ = top_reg) and
  2964. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2965. begin
  2966. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2967. begin
  2968. case taicpu(p).opsize of
  2969. S_L:
  2970. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2971. begin
  2972. { Optimize out:
  2973. mov x, %reg
  2974. and ffffffffh, %reg
  2975. }
  2976. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2977. RemoveInstruction(hp1);
  2978. Result:=true;
  2979. exit;
  2980. end;
  2981. S_Q: { TODO: Confirm if this is even possible }
  2982. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2983. begin
  2984. { Optimize out:
  2985. mov x, %reg
  2986. and ffffffffffffffffh, %reg
  2987. }
  2988. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2989. RemoveInstruction(hp1);
  2990. Result:=true;
  2991. exit;
  2992. end;
  2993. else
  2994. ;
  2995. end;
  2996. if (
  2997. (taicpu(p).oper[0]^.typ=top_reg) or
  2998. (
  2999. (taicpu(p).oper[0]^.typ=top_ref) and
  3000. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3001. )
  3002. ) and
  3003. GetNextInstruction(hp1,hp2) and
  3004. MatchInstruction(hp2,A_TEST,[]) and
  3005. (
  3006. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3007. (
  3008. { If the register being tested is smaller than the one
  3009. that received a bitwise AND, permit it if the constant
  3010. fits into the smaller size }
  3011. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3012. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3013. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3014. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3015. (
  3016. (
  3017. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3018. (taicpu(hp1).oper[0]^.val <= $FF)
  3019. ) or
  3020. (
  3021. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3022. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3023. {$ifdef x86_64}
  3024. ) or
  3025. (
  3026. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3027. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3028. {$endif x86_64}
  3029. )
  3030. )
  3031. )
  3032. ) and
  3033. (
  3034. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3035. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3036. ) and
  3037. GetNextInstruction(hp2,hp3) and
  3038. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3039. (taicpu(hp3).condition in [C_E,C_NE]) then
  3040. begin
  3041. TransferUsedRegs(TmpUsedRegs);
  3042. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3043. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3044. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3045. begin
  3046. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3047. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3048. taicpu(hp1).opcode:=A_TEST;
  3049. { Shrink the TEST instruction down to the smallest possible size }
  3050. case taicpu(hp1).oper[0]^.val of
  3051. 0..255:
  3052. if (taicpu(hp1).opsize <> S_B)
  3053. {$ifndef x86_64}
  3054. and (
  3055. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3056. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3057. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3058. )
  3059. {$endif x86_64}
  3060. then
  3061. begin
  3062. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3063. { Only print debug message if the TEST instruction
  3064. is a different size before and after }
  3065. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3066. taicpu(hp1).opsize := S_B;
  3067. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3068. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3069. end;
  3070. 256..65535:
  3071. if (taicpu(hp1).opsize <> S_W) then
  3072. begin
  3073. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3074. { Only print debug message if the TEST instruction
  3075. is a different size before and after }
  3076. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3077. taicpu(hp1).opsize := S_W;
  3078. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3079. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3080. end;
  3081. {$ifdef x86_64}
  3082. 65536..$7FFFFFFF:
  3083. if (taicpu(hp1).opsize <> S_L) then
  3084. begin
  3085. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3086. { Only print debug message if the TEST instruction
  3087. is a different size before and after }
  3088. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3089. taicpu(hp1).opsize := S_L;
  3090. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3091. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3092. end;
  3093. {$endif x86_64}
  3094. else
  3095. ;
  3096. end;
  3097. RemoveInstruction(hp2);
  3098. RemoveCurrentP(p, hp1);
  3099. Result:=true;
  3100. exit;
  3101. end;
  3102. end;
  3103. end
  3104. else if IsMOVZXAcceptable and
  3105. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3106. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3107. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3108. then
  3109. begin
  3110. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3111. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3112. case taicpu(p).opsize of
  3113. S_B:
  3114. if (taicpu(hp1).oper[0]^.val = $ff) then
  3115. begin
  3116. { Convert:
  3117. movb x, %regl movb x, %regl
  3118. andw ffh, %regw andl ffh, %regd
  3119. To:
  3120. movzbw x, %regd movzbl x, %regd
  3121. (Identical registers, just different sizes)
  3122. }
  3123. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3124. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3125. case taicpu(hp1).opsize of
  3126. S_W: NewSize := S_BW;
  3127. S_L: NewSize := S_BL;
  3128. {$ifdef x86_64}
  3129. S_Q: NewSize := S_BQ;
  3130. {$endif x86_64}
  3131. else
  3132. InternalError(2018011510);
  3133. end;
  3134. end
  3135. else
  3136. NewSize := S_NO;
  3137. S_W:
  3138. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3139. begin
  3140. { Convert:
  3141. movw x, %regw
  3142. andl ffffh, %regd
  3143. To:
  3144. movzwl x, %regd
  3145. (Identical registers, just different sizes)
  3146. }
  3147. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3148. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3149. case taicpu(hp1).opsize of
  3150. S_L: NewSize := S_WL;
  3151. {$ifdef x86_64}
  3152. S_Q: NewSize := S_WQ;
  3153. {$endif x86_64}
  3154. else
  3155. InternalError(2018011511);
  3156. end;
  3157. end
  3158. else
  3159. NewSize := S_NO;
  3160. else
  3161. NewSize := S_NO;
  3162. end;
  3163. if NewSize <> S_NO then
  3164. begin
  3165. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3166. { The actual optimization }
  3167. taicpu(p).opcode := A_MOVZX;
  3168. taicpu(p).changeopsize(NewSize);
  3169. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3170. { Safeguard if "and" is followed by a conditional command }
  3171. TransferUsedRegs(TmpUsedRegs);
  3172. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3173. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3174. begin
  3175. { At this point, the "and" command is effectively equivalent to
  3176. "test %reg,%reg". This will be handled separately by the
  3177. Peephole Optimizer. [Kit] }
  3178. DebugMsg(SPeepholeOptimization + PreMessage +
  3179. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3180. end
  3181. else
  3182. begin
  3183. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3184. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3185. RemoveInstruction(hp1);
  3186. end;
  3187. Result := True;
  3188. Exit;
  3189. end;
  3190. end;
  3191. end;
  3192. if (taicpu(hp1).opcode = A_OR) and
  3193. (taicpu(p).oper[1]^.typ = top_reg) and
  3194. MatchOperand(taicpu(p).oper[0]^, 0) and
  3195. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3196. begin
  3197. { mov 0, %reg
  3198. or ###,%reg
  3199. Change to (only if the flags are not used):
  3200. mov ###,%reg
  3201. }
  3202. TransferUsedRegs(TmpUsedRegs);
  3203. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3204. DoOptimisation := True;
  3205. { Even if the flags are used, we might be able to do the optimisation
  3206. if the conditions are predictable }
  3207. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3208. begin
  3209. { Only perform if ### = %reg (the same register) or equal to 0,
  3210. so %reg is guaranteed to still have a value of zero }
  3211. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3212. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3213. begin
  3214. hp2 := hp1;
  3215. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3216. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3217. GetNextInstruction(hp2, hp3) do
  3218. begin
  3219. { Don't continue modifying if the flags state is getting changed }
  3220. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3221. Break;
  3222. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3223. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3224. begin
  3225. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3226. begin
  3227. { Condition is always true }
  3228. case taicpu(hp3).opcode of
  3229. A_Jcc:
  3230. begin
  3231. { Check for jump shortcuts before we destroy the condition }
  3232. hp4 := hp3;
  3233. DoJumpOptimizations(hp3, TempBool);
  3234. { Make sure hp3 hasn't changed }
  3235. if (hp4 = hp3) then
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3238. MakeUnconditional(taicpu(hp3));
  3239. end;
  3240. Result := True;
  3241. end;
  3242. A_CMOVcc:
  3243. begin
  3244. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3245. taicpu(hp3).opcode := A_MOV;
  3246. taicpu(hp3).condition := C_None;
  3247. Result := True;
  3248. end;
  3249. A_SETcc:
  3250. begin
  3251. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3252. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3253. taicpu(hp3).opcode := A_MOV;
  3254. taicpu(hp3).ops := 2;
  3255. taicpu(hp3).condition := C_None;
  3256. taicpu(hp3).opsize := S_B;
  3257. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3258. taicpu(hp3).loadconst(0, 1);
  3259. Result := True;
  3260. end;
  3261. else
  3262. InternalError(2021090701);
  3263. end;
  3264. end
  3265. 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
  3266. begin
  3267. { Condition is always false }
  3268. case taicpu(hp3).opcode of
  3269. A_Jcc:
  3270. begin
  3271. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3272. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3273. RemoveInstruction(hp3);
  3274. Result := True;
  3275. { Since hp3 was deleted, hp2 must not be updated }
  3276. Continue;
  3277. end;
  3278. A_CMOVcc:
  3279. begin
  3280. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3281. RemoveInstruction(hp3);
  3282. Result := True;
  3283. { Since hp3 was deleted, hp2 must not be updated }
  3284. Continue;
  3285. end;
  3286. A_SETcc:
  3287. begin
  3288. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3289. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3290. taicpu(hp3).opcode := A_MOV;
  3291. taicpu(hp3).ops := 2;
  3292. taicpu(hp3).condition := C_None;
  3293. taicpu(hp3).opsize := S_B;
  3294. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3295. taicpu(hp3).loadconst(0, 0);
  3296. Result := True;
  3297. end;
  3298. else
  3299. InternalError(2021090702);
  3300. end;
  3301. end
  3302. else
  3303. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3304. DoOptimisation := False;
  3305. end;
  3306. hp2 := hp3;
  3307. end;
  3308. { Flags are still in use - don't optimise }
  3309. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3310. DoOptimisation := False;
  3311. end
  3312. else
  3313. DoOptimisation := False;
  3314. end;
  3315. if DoOptimisation then
  3316. begin
  3317. {$ifdef x86_64}
  3318. { OR only supports 32-bit sign-extended constants for 64-bit
  3319. instructions, so compensate for this if the constant is
  3320. encoded as a value greater than or equal to 2^31 }
  3321. if (taicpu(hp1).opsize = S_Q) and
  3322. (taicpu(hp1).oper[0]^.typ = top_const) and
  3323. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3324. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3325. {$endif x86_64}
  3326. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3327. taicpu(hp1).opcode := A_MOV;
  3328. RemoveCurrentP(p, hp1);
  3329. Result := True;
  3330. Exit;
  3331. end;
  3332. end;
  3333. { Next instruction is also a MOV ? }
  3334. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3335. begin
  3336. if MatchOpType(taicpu(p), top_const, top_ref) and
  3337. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3338. TryConstMerge(p, hp1) then
  3339. begin
  3340. Result := True;
  3341. { In case we have four byte writes in a row, check for 2 more
  3342. right now so we don't have to wait for another iteration of
  3343. pass 1
  3344. }
  3345. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3346. case taicpu(p).opsize of
  3347. S_W:
  3348. begin
  3349. if GetNextInstruction(p, hp1) and
  3350. MatchInstruction(hp1, A_MOV, [S_B]) and
  3351. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3352. GetNextInstruction(hp1, hp2) and
  3353. MatchInstruction(hp2, A_MOV, [S_B]) and
  3354. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3355. { Try to merge the two bytes }
  3356. TryConstMerge(hp1, hp2) then
  3357. { Now try to merge the two words (hp2 will get deleted) }
  3358. TryConstMerge(p, hp1);
  3359. end;
  3360. S_L:
  3361. begin
  3362. { Though this only really benefits x86_64 and not i386, it
  3363. gets a potential optimisation done faster and hence
  3364. reduces the number of times OptPass1MOV is entered }
  3365. if GetNextInstruction(p, hp1) and
  3366. MatchInstruction(hp1, A_MOV, [S_W]) and
  3367. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3368. GetNextInstruction(hp1, hp2) and
  3369. MatchInstruction(hp2, A_MOV, [S_W]) and
  3370. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3371. { Try to merge the two words }
  3372. TryConstMerge(hp1, hp2) then
  3373. { This will always fail on i386, so don't bother
  3374. calling it unless we're doing x86_64 }
  3375. {$ifdef x86_64}
  3376. { Now try to merge the two longwords (hp2 will get deleted) }
  3377. TryConstMerge(p, hp1)
  3378. {$endif x86_64}
  3379. ;
  3380. end;
  3381. else
  3382. ;
  3383. end;
  3384. Exit;
  3385. end;
  3386. if (taicpu(p).oper[1]^.typ = top_reg) and
  3387. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3388. begin
  3389. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3390. TransferUsedRegs(TmpUsedRegs);
  3391. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3392. { we have
  3393. mov x, %treg
  3394. mov %treg, y
  3395. }
  3396. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3397. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3398. { we've got
  3399. mov x, %treg
  3400. mov %treg, y
  3401. with %treg is not used after }
  3402. case taicpu(p).oper[0]^.typ Of
  3403. { top_reg is covered by DeepMOVOpt }
  3404. top_const:
  3405. begin
  3406. { change
  3407. mov const, %treg
  3408. mov %treg, y
  3409. to
  3410. mov const, y
  3411. }
  3412. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3413. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3414. begin
  3415. if taicpu(hp1).oper[1]^.typ=top_reg then
  3416. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3417. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3418. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3419. RemoveInstruction(hp1);
  3420. Result:=true;
  3421. Exit;
  3422. end;
  3423. end;
  3424. top_ref:
  3425. case taicpu(hp1).oper[1]^.typ of
  3426. top_reg:
  3427. begin
  3428. { change
  3429. mov mem, %treg
  3430. mov %treg, %reg
  3431. to
  3432. mov mem, %reg"
  3433. }
  3434. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3435. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3436. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3437. RemoveInstruction(hp1);
  3438. Result:=true;
  3439. Exit;
  3440. end;
  3441. top_ref:
  3442. begin
  3443. {$ifdef x86_64}
  3444. { Look for the following to simplify:
  3445. mov x(mem1), %reg
  3446. mov %reg, y(mem2)
  3447. mov x+8(mem1), %reg
  3448. mov %reg, y+8(mem2)
  3449. Change to:
  3450. movdqu x(mem1), %xmmreg
  3451. movdqu %xmmreg, y(mem2)
  3452. ...but only as long as the memory blocks don't overlap
  3453. }
  3454. SourceRef := taicpu(p).oper[0]^.ref^;
  3455. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3456. if (taicpu(p).opsize = S_Q) and
  3457. GetNextInstruction(hp1, hp2) and
  3458. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3459. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3460. begin
  3461. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3462. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3463. Inc(SourceRef.offset, 8);
  3464. if UseAVX then
  3465. begin
  3466. MovAligned := A_VMOVDQA;
  3467. MovUnaligned := A_VMOVDQU;
  3468. end
  3469. else
  3470. begin
  3471. MovAligned := A_MOVDQA;
  3472. MovUnaligned := A_MOVDQU;
  3473. end;
  3474. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3475. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3476. begin
  3477. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3478. Inc(TargetRef.offset, 8);
  3479. if GetNextInstruction(hp2, hp3) and
  3480. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3481. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3482. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3483. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3484. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3485. begin
  3486. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3487. if NewMMReg <> NR_NO then
  3488. begin
  3489. { Remember that the offsets are 8 ahead }
  3490. if ((SourceRef.offset mod 16) = 8) and
  3491. (
  3492. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3493. (SourceRef.base = current_procinfo.framepointer) or
  3494. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3495. ) then
  3496. taicpu(p).opcode := MovAligned
  3497. else
  3498. taicpu(p).opcode := MovUnaligned;
  3499. taicpu(p).opsize := S_XMM;
  3500. taicpu(p).oper[1]^.reg := NewMMReg;
  3501. if ((TargetRef.offset mod 16) = 8) and
  3502. (
  3503. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3504. (TargetRef.base = current_procinfo.framepointer) or
  3505. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3506. ) then
  3507. taicpu(hp1).opcode := MovAligned
  3508. else
  3509. taicpu(hp1).opcode := MovUnaligned;
  3510. taicpu(hp1).opsize := S_XMM;
  3511. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3512. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3513. RemoveInstruction(hp2);
  3514. RemoveInstruction(hp3);
  3515. Result := True;
  3516. Exit;
  3517. end;
  3518. end;
  3519. end
  3520. else
  3521. begin
  3522. { See if the next references are 8 less rather than 8 greater }
  3523. Dec(SourceRef.offset, 16); { -8 the other way }
  3524. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3525. begin
  3526. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3527. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3528. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3529. GetNextInstruction(hp2, hp3) and
  3530. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3531. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3532. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3533. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3534. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3535. begin
  3536. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3537. if NewMMReg <> NR_NO then
  3538. begin
  3539. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3540. if ((SourceRef.offset mod 16) = 0) and
  3541. (
  3542. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3543. (SourceRef.base = current_procinfo.framepointer) or
  3544. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3545. ) then
  3546. taicpu(hp2).opcode := MovAligned
  3547. else
  3548. taicpu(hp2).opcode := MovUnaligned;
  3549. taicpu(hp2).opsize := S_XMM;
  3550. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3551. if ((TargetRef.offset mod 16) = 0) and
  3552. (
  3553. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3554. (TargetRef.base = current_procinfo.framepointer) or
  3555. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3556. ) then
  3557. taicpu(hp3).opcode := MovAligned
  3558. else
  3559. taicpu(hp3).opcode := MovUnaligned;
  3560. taicpu(hp3).opsize := S_XMM;
  3561. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3562. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3563. RemoveInstruction(hp1);
  3564. RemoveCurrentP(p, hp2);
  3565. Result := True;
  3566. Exit;
  3567. end;
  3568. end;
  3569. end;
  3570. end;
  3571. end;
  3572. {$endif x86_64}
  3573. end;
  3574. else
  3575. { The write target should be a reg or a ref }
  3576. InternalError(2021091601);
  3577. end;
  3578. else
  3579. ;
  3580. end
  3581. else
  3582. { %treg is used afterwards, but all eventualities
  3583. other than the first MOV instruction being a constant
  3584. are covered by DeepMOVOpt, so only check for that }
  3585. if (taicpu(p).oper[0]^.typ = top_const) and
  3586. (
  3587. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3588. not (cs_opt_size in current_settings.optimizerswitches) or
  3589. (taicpu(hp1).opsize = S_B)
  3590. ) and
  3591. (
  3592. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3593. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3594. ) then
  3595. begin
  3596. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3597. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3598. end;
  3599. end;
  3600. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3601. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3602. { mov reg1, mem1 or mov mem1, reg1
  3603. mov mem2, reg2 mov reg2, mem2}
  3604. begin
  3605. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3606. { mov reg1, mem1 or mov mem1, reg1
  3607. mov mem2, reg1 mov reg2, mem1}
  3608. begin
  3609. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3610. { Removes the second statement from
  3611. mov reg1, mem1/reg2
  3612. mov mem1/reg2, reg1 }
  3613. begin
  3614. if taicpu(p).oper[0]^.typ=top_reg then
  3615. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3616. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3617. RemoveInstruction(hp1);
  3618. Result:=true;
  3619. exit;
  3620. end
  3621. else
  3622. begin
  3623. TransferUsedRegs(TmpUsedRegs);
  3624. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3625. if (taicpu(p).oper[1]^.typ = top_ref) and
  3626. { mov reg1, mem1
  3627. mov mem2, reg1 }
  3628. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3629. GetNextInstruction(hp1, hp2) and
  3630. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3631. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3632. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3633. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3634. { change to
  3635. mov reg1, mem1 mov reg1, mem1
  3636. mov mem2, reg1 cmp reg1, mem2
  3637. cmp mem1, reg1
  3638. }
  3639. begin
  3640. RemoveInstruction(hp2);
  3641. taicpu(hp1).opcode := A_CMP;
  3642. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3643. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3644. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3645. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3646. end;
  3647. end;
  3648. end
  3649. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3650. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3651. begin
  3652. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3653. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3654. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3655. end
  3656. else
  3657. begin
  3658. TransferUsedRegs(TmpUsedRegs);
  3659. if GetNextInstruction(hp1, hp2) and
  3660. MatchOpType(taicpu(p),top_ref,top_reg) and
  3661. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3662. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3663. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3664. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3665. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3666. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3667. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3668. { mov mem1, %reg1
  3669. mov %reg1, mem2
  3670. mov mem2, reg2
  3671. to:
  3672. mov mem1, reg2
  3673. mov reg2, mem2}
  3674. begin
  3675. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3676. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3677. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3678. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3679. RemoveInstruction(hp2);
  3680. Result := True;
  3681. end
  3682. {$ifdef i386}
  3683. { this is enabled for i386 only, as the rules to create the reg sets below
  3684. are too complicated for x86-64, so this makes this code too error prone
  3685. on x86-64
  3686. }
  3687. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3688. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3689. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3690. { mov mem1, reg1 mov mem1, reg1
  3691. mov reg1, mem2 mov reg1, mem2
  3692. mov mem2, reg2 mov mem2, reg1
  3693. to: to:
  3694. mov mem1, reg1 mov mem1, reg1
  3695. mov mem1, reg2 mov reg1, mem2
  3696. mov reg1, mem2
  3697. or (if mem1 depends on reg1
  3698. and/or if mem2 depends on reg2)
  3699. to:
  3700. mov mem1, reg1
  3701. mov reg1, mem2
  3702. mov reg1, reg2
  3703. }
  3704. begin
  3705. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3706. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3707. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3708. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3709. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3710. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3711. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3712. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3713. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3714. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3715. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3716. end
  3717. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3718. begin
  3719. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3720. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3721. end
  3722. else
  3723. begin
  3724. RemoveInstruction(hp2);
  3725. end
  3726. {$endif i386}
  3727. ;
  3728. end;
  3729. end
  3730. { movl [mem1],reg1
  3731. movl [mem1],reg2
  3732. to
  3733. movl [mem1],reg1
  3734. movl reg1,reg2
  3735. }
  3736. else if not CheckMovMov2MovMov2(p, hp1) and
  3737. { movl const1,[mem1]
  3738. movl [mem1],reg1
  3739. to
  3740. movl const1,reg1
  3741. movl reg1,[mem1]
  3742. }
  3743. MatchOpType(Taicpu(p),top_const,top_ref) and
  3744. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3745. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3746. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3747. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3748. begin
  3749. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3750. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3751. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3752. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3753. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3754. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3755. Result:=true;
  3756. exit;
  3757. end;
  3758. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3759. { Change:
  3760. movl %reg1,%reg2
  3761. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3762. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3763. To:
  3764. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3765. movl x(%reg1),%reg1
  3766. movl %reg1,%regX
  3767. }
  3768. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3769. begin
  3770. p_SourceReg := taicpu(p).oper[0]^.reg;
  3771. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3772. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3773. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3774. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3775. GetNextInstruction(hp1, hp2) and
  3776. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3777. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3778. begin
  3779. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3780. if RegInRef(p_TargetReg, SourceRef) and
  3781. { If %reg1 also appears in the second reference, then it will
  3782. not refer to the same memory block as the first reference }
  3783. not RegInRef(p_SourceReg, SourceRef) then
  3784. begin
  3785. { Check to see if the references match if %reg2 is changed to %reg1 }
  3786. if SourceRef.base = p_TargetReg then
  3787. SourceRef.base := p_SourceReg;
  3788. if SourceRef.index = p_TargetReg then
  3789. SourceRef.index := p_SourceReg;
  3790. { RefsEqual also checks to ensure both references are non-volatile }
  3791. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3792. begin
  3793. taicpu(hp2).loadreg(0, p_SourceReg);
  3794. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3795. Result := True;
  3796. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3797. begin
  3798. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3799. RemoveCurrentP(p, hp1);
  3800. Exit;
  3801. end
  3802. else
  3803. begin
  3804. { Check to see if %reg2 is no longer in use }
  3805. TransferUsedRegs(TmpUsedRegs);
  3806. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3807. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3808. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3809. begin
  3810. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3811. RemoveCurrentP(p, hp1);
  3812. Exit;
  3813. end;
  3814. end;
  3815. { If we reach this point, p and hp1 weren't actually modified,
  3816. so we can do a bit more work on this pass }
  3817. end;
  3818. end;
  3819. end;
  3820. end;
  3821. end;
  3822. {$ifdef x86_64}
  3823. { Change:
  3824. movl %reg1l,%reg2l
  3825. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3826. To:
  3827. movl %reg1l,%reg2l
  3828. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3829. If %reg1 = %reg3, convert to:
  3830. movl %reg1l,%reg2l
  3831. andl %reg1l,%reg1l
  3832. }
  3833. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3834. MatchOpType(taicpu(p), top_reg, top_reg) and
  3835. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3836. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3837. begin
  3838. TransferUsedRegs(TmpUsedRegs);
  3839. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3840. taicpu(hp1).opsize := S_L;
  3841. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3842. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3843. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3844. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3845. begin
  3846. { %reg1 = %reg3 }
  3847. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3848. taicpu(hp1).opcode := A_AND;
  3849. end
  3850. else
  3851. begin
  3852. { %reg1 <> %reg3 }
  3853. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3854. end;
  3855. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3856. begin
  3857. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3858. RemoveCurrentP(p, hp1);
  3859. Result := True;
  3860. Exit;
  3861. end
  3862. else
  3863. begin
  3864. { Initial instruction wasn't actually changed }
  3865. Include(OptsToCheck, aoc_ForceNewIteration);
  3866. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3867. appears below since %reg1 has technically changed }
  3868. if taicpu(hp1).opcode = A_AND then
  3869. Exit;
  3870. end;
  3871. end;
  3872. {$endif x86_64}
  3873. { search further than the next instruction for a mov (as long as it's not a jump) }
  3874. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3875. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3876. (taicpu(p).oper[1]^.typ = top_reg) and
  3877. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3878. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3879. begin
  3880. { we work with hp2 here, so hp1 can be still used later on when
  3881. checking for GetNextInstruction_p }
  3882. hp3 := hp1;
  3883. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3884. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3885. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3888. if NotFirstIteration then
  3889. JumpTracking := TLinkedList.Create
  3890. else
  3891. JumpTracking := nil;
  3892. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3893. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3894. (hp2.typ=ait_instruction) do
  3895. begin
  3896. case taicpu(hp2).opcode of
  3897. A_POP:
  3898. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3899. begin
  3900. if not CrossJump and
  3901. not RegUsedBetween(p_TargetReg, p, hp2) then
  3902. begin
  3903. { We can remove the original MOV since the register
  3904. wasn't used between it and its popping from the stack }
  3905. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3906. RemoveCurrentp(p, hp1);
  3907. Result := True;
  3908. JumpTracking.Free;
  3909. Exit;
  3910. end;
  3911. { Can't go any further }
  3912. Break;
  3913. end;
  3914. A_MOV:
  3915. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3916. ((taicpu(p).oper[0]^.typ=top_const) or
  3917. ((taicpu(p).oper[0]^.typ=top_reg) and
  3918. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3919. )
  3920. ) then
  3921. begin
  3922. { we have
  3923. mov x, %treg
  3924. mov %treg, y
  3925. }
  3926. { We don't need to call UpdateUsedRegs for every instruction between
  3927. p and hp2 because the register we're concerned about will not
  3928. become deallocated (otherwise GetNextInstructionUsingReg would
  3929. have stopped at an earlier instruction). [Kit] }
  3930. TempRegUsed :=
  3931. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3932. RegReadByInstruction(p_TargetReg, hp3) or
  3933. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3934. case taicpu(p).oper[0]^.typ Of
  3935. top_reg:
  3936. begin
  3937. { change
  3938. mov %reg, %treg
  3939. mov %treg, y
  3940. to
  3941. mov %reg, y
  3942. }
  3943. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3944. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3945. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3946. begin
  3947. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3948. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3949. if TempRegUsed then
  3950. begin
  3951. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3952. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3953. { Set the start of the next GetNextInstructionUsingRegCond search
  3954. to start at the entry right before hp2 (which is about to be removed) }
  3955. hp3 := tai(hp2.Previous);
  3956. RemoveInstruction(hp2);
  3957. Include(OptsToCheck, aoc_ForceNewIteration);
  3958. { See if there's more we can optimise }
  3959. Continue;
  3960. end
  3961. else
  3962. begin
  3963. RemoveInstruction(hp2);
  3964. { We can remove the original MOV too }
  3965. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3966. RemoveCurrentP(p, hp1);
  3967. Result:=true;
  3968. JumpTracking.Free;
  3969. Exit;
  3970. end;
  3971. end
  3972. else
  3973. begin
  3974. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3975. taicpu(hp2).loadReg(0, p_SourceReg);
  3976. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3977. { Check to see if the register also appears in the reference }
  3978. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3979. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3980. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3981. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3982. begin
  3983. { Don't remove the first instruction if the temporary register is in use }
  3984. if not TempRegUsed then
  3985. begin
  3986. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3987. RemoveCurrentP(p, hp1);
  3988. Result:=true;
  3989. JumpTracking.Free;
  3990. Exit;
  3991. end;
  3992. { No need to set Result to True here. If there's another instruction later
  3993. on that can be optimised, it will be detected when the main Pass 1 loop
  3994. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3995. hp3 := hp2;
  3996. Continue;
  3997. end;
  3998. end;
  3999. end;
  4000. top_const:
  4001. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4002. begin
  4003. { change
  4004. mov const, %treg
  4005. mov %treg, y
  4006. to
  4007. mov const, y
  4008. }
  4009. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4010. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4011. begin
  4012. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4013. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4014. if TempRegUsed then
  4015. begin
  4016. { Don't remove the first instruction if the temporary register is in use }
  4017. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4018. { No need to set Result to True. If there's another instruction later on
  4019. that can be optimised, it will be detected when the main Pass 1 loop
  4020. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4021. end
  4022. else
  4023. begin
  4024. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4025. RemoveCurrentP(p, hp1);
  4026. Result:=true;
  4027. Exit;
  4028. end;
  4029. end;
  4030. end;
  4031. else
  4032. Internalerror(2019103001);
  4033. end;
  4034. end
  4035. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4036. begin
  4037. if not CrossJump and
  4038. not RegUsedBetween(p_TargetReg, p, hp2) and
  4039. not RegReadByInstruction(p_TargetReg, hp2) then
  4040. begin
  4041. { Register is not used before it is overwritten }
  4042. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4043. RemoveCurrentp(p, hp1);
  4044. Result := True;
  4045. Exit;
  4046. end;
  4047. if (taicpu(p).oper[0]^.typ = top_const) and
  4048. (taicpu(hp2).oper[0]^.typ = top_const) then
  4049. begin
  4050. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4051. begin
  4052. { Same value - register hasn't changed }
  4053. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4054. RemoveInstruction(hp2);
  4055. Include(OptsToCheck, aoc_ForceNewIteration);
  4056. { See if there's more we can optimise }
  4057. Continue;
  4058. end;
  4059. end;
  4060. {$ifdef x86_64}
  4061. end
  4062. { Change:
  4063. movl %reg1l,%reg2l
  4064. ...
  4065. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4066. To:
  4067. movl %reg1l,%reg2l
  4068. ...
  4069. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4070. If %reg1 = %reg3, convert to:
  4071. movl %reg1l,%reg2l
  4072. ...
  4073. andl %reg1l,%reg1l
  4074. }
  4075. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4076. (taicpu(p).oper[0]^.typ = top_reg) and
  4077. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4078. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4079. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4080. begin
  4081. TempRegUsed :=
  4082. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4083. RegReadByInstruction(p_TargetReg, hp3) or
  4084. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4085. taicpu(hp2).opsize := S_L;
  4086. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4087. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4088. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4089. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4090. begin
  4091. { %reg1 = %reg3 }
  4092. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4093. taicpu(hp2).opcode := A_AND;
  4094. end
  4095. else
  4096. begin
  4097. { %reg1 <> %reg3 }
  4098. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4099. end;
  4100. if not TempRegUsed then
  4101. begin
  4102. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4103. RemoveCurrentP(p, hp1);
  4104. Result := True;
  4105. Exit;
  4106. end
  4107. else
  4108. begin
  4109. { Initial instruction wasn't actually changed }
  4110. Include(OptsToCheck, aoc_ForceNewIteration);
  4111. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4112. appears below since %reg1 has technically changed }
  4113. if taicpu(hp2).opcode = A_AND then
  4114. Break;
  4115. end;
  4116. {$endif x86_64}
  4117. end
  4118. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4119. GetNextInstruction(hp2, hp4) and
  4120. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4121. { Optimise the following first:
  4122. movl [mem1],reg1
  4123. movl [mem1],reg2
  4124. to
  4125. movl [mem1],reg1
  4126. movl reg1,reg2
  4127. If [mem1] contains the target register and reg1 is the
  4128. the source register, this optimisation will get missed
  4129. and produce less efficient code later on.
  4130. }
  4131. if CheckMovMov2MovMov2(hp2, hp4) then
  4132. { Initial instruction wasn't actually changed }
  4133. Include(OptsToCheck, aoc_ForceNewIteration);
  4134. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4135. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4136. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4137. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4138. begin
  4139. {
  4140. Change from:
  4141. mov ###, %reg
  4142. ...
  4143. movs/z %reg,%reg (Same register, just different sizes)
  4144. To:
  4145. movs/z ###, %reg (Longer version)
  4146. ...
  4147. (remove)
  4148. }
  4149. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4150. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4151. { Keep the first instruction as mov if ### is a constant }
  4152. if taicpu(p).oper[0]^.typ = top_const then
  4153. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4154. else
  4155. begin
  4156. taicpu(p).opcode := taicpu(hp2).opcode;
  4157. taicpu(p).opsize := taicpu(hp2).opsize;
  4158. end;
  4159. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4160. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4161. RemoveInstruction(hp2);
  4162. Result := True;
  4163. JumpTracking.Free;
  4164. Exit;
  4165. end;
  4166. else
  4167. { Move down to the if-block below };
  4168. end;
  4169. { Also catches MOV/S/Z instructions that aren't modified }
  4170. if taicpu(p).oper[0]^.typ = top_reg then
  4171. begin
  4172. p_SourceReg := taicpu(p).oper[0]^.reg;
  4173. if
  4174. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4175. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4176. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4177. begin
  4178. Result := True;
  4179. { Just in case something didn't get modified (e.g. an
  4180. implicit register). Also, if it does read from this
  4181. register, then there's no longer an advantage to
  4182. changing the register on subsequent instructions.}
  4183. if not RegReadByInstruction(p_TargetReg, hp2) then
  4184. begin
  4185. { If a conditional jump was crossed, do not delete
  4186. the original MOV no matter what }
  4187. if not CrossJump and
  4188. { RegEndOfLife returns True if the register is
  4189. deallocated before the next instruction or has
  4190. been loaded with a new value }
  4191. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4192. begin
  4193. { We can remove the original MOV }
  4194. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4195. RemoveCurrentp(p, hp1);
  4196. JumpTracking.Free;
  4197. Result := True;
  4198. Exit;
  4199. end;
  4200. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4201. begin
  4202. { See if there's more we can optimise }
  4203. hp3 := hp2;
  4204. Continue;
  4205. end;
  4206. end;
  4207. end;
  4208. end;
  4209. { Break out of the while loop under normal circumstances }
  4210. Break;
  4211. end;
  4212. JumpTracking.Free;
  4213. end;
  4214. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4215. (taicpu(p).oper[1]^.typ = top_reg) and
  4216. (taicpu(p).opsize = S_L) and
  4217. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4218. (hp2.typ = ait_instruction) and
  4219. (taicpu(hp2).opcode = A_AND) and
  4220. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4221. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4222. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4223. ) then
  4224. begin
  4225. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4226. begin
  4227. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4228. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4229. begin
  4230. { Optimize out:
  4231. mov x, %reg
  4232. and ffffffffh, %reg
  4233. }
  4234. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4235. RemoveInstruction(hp2);
  4236. Result:=true;
  4237. exit;
  4238. end;
  4239. end;
  4240. end;
  4241. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4242. x >= RetOffset) as it doesn't do anything (it writes either to a
  4243. parameter or to the temporary storage room for the function
  4244. result)
  4245. }
  4246. if IsExitCode(hp1) and
  4247. (taicpu(p).oper[1]^.typ = top_ref) and
  4248. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4249. (
  4250. (
  4251. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4252. not (
  4253. assigned(current_procinfo.procdef.funcretsym) and
  4254. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4255. )
  4256. ) or
  4257. { Also discard writes to the stack that are below the base pointer,
  4258. as this is temporary storage rather than a function result on the
  4259. stack, say. }
  4260. (
  4261. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4262. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4263. )
  4264. ) then
  4265. begin
  4266. RemoveCurrentp(p, hp1);
  4267. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4268. RemoveLastDeallocForFuncRes(p);
  4269. Result:=true;
  4270. exit;
  4271. end;
  4272. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4273. begin
  4274. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4275. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4276. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4277. begin
  4278. { change
  4279. mov reg1, mem1
  4280. test/cmp x, mem1
  4281. to
  4282. mov reg1, mem1
  4283. test/cmp x, reg1
  4284. }
  4285. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4286. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4287. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4288. Result := True;
  4289. Exit;
  4290. end;
  4291. if DoMovCmpMemOpt(p, hp1) then
  4292. begin
  4293. Result := True;
  4294. Exit;
  4295. end;
  4296. end;
  4297. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4298. { If the flags register is in use, don't change the instruction to an
  4299. ADD otherwise this will scramble the flags. [Kit] }
  4300. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4301. begin
  4302. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4303. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4304. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4305. ) or
  4306. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4307. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4308. )
  4309. ) then
  4310. { mov reg1,ref
  4311. lea reg2,[reg1,reg2]
  4312. to
  4313. add reg2,ref}
  4314. begin
  4315. TransferUsedRegs(TmpUsedRegs);
  4316. { reg1 may not be used afterwards }
  4317. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4318. begin
  4319. Taicpu(hp1).opcode:=A_ADD;
  4320. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4321. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4322. RemoveCurrentp(p, hp1);
  4323. result:=true;
  4324. exit;
  4325. end;
  4326. end;
  4327. { If the LEA instruction can be converted into an arithmetic instruction,
  4328. it may be possible to then fold it in the next optimisation, otherwise
  4329. there's nothing more that can be optimised here. }
  4330. if not ConvertLEA(taicpu(hp1)) then
  4331. Exit;
  4332. end;
  4333. if (taicpu(p).oper[1]^.typ = top_reg) and
  4334. (hp1.typ = ait_instruction) and
  4335. GetNextInstruction(hp1, hp2) and
  4336. MatchInstruction(hp2,A_MOV,[]) and
  4337. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4338. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4339. (
  4340. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4341. {$ifdef x86_64}
  4342. or
  4343. (
  4344. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4345. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4346. )
  4347. {$endif x86_64}
  4348. ) then
  4349. begin
  4350. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4351. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4352. { change movsX/movzX reg/ref, reg2
  4353. add/sub/or/... reg3/$const, reg2
  4354. mov reg2 reg/ref
  4355. dealloc reg2
  4356. to
  4357. add/sub/or/... reg3/$const, reg/ref }
  4358. begin
  4359. TransferUsedRegs(TmpUsedRegs);
  4360. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4361. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4362. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4363. begin
  4364. { by example:
  4365. movswl %si,%eax movswl %si,%eax p
  4366. decl %eax addl %edx,%eax hp1
  4367. movw %ax,%si movw %ax,%si hp2
  4368. ->
  4369. movswl %si,%eax movswl %si,%eax p
  4370. decw %eax addw %edx,%eax hp1
  4371. movw %ax,%si movw %ax,%si hp2
  4372. }
  4373. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4374. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4375. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4376. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4377. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4378. {
  4379. ->
  4380. movswl %si,%eax movswl %si,%eax p
  4381. decw %si addw %dx,%si hp1
  4382. movw %ax,%si movw %ax,%si hp2
  4383. }
  4384. case taicpu(hp1).ops of
  4385. 1:
  4386. begin
  4387. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4388. if taicpu(hp1).oper[0]^.typ=top_reg then
  4389. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4390. end;
  4391. 2:
  4392. begin
  4393. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4394. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4395. (taicpu(hp1).opcode<>A_SHL) and
  4396. (taicpu(hp1).opcode<>A_SHR) and
  4397. (taicpu(hp1).opcode<>A_SAR) then
  4398. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4399. end;
  4400. else
  4401. internalerror(2008042701);
  4402. end;
  4403. {
  4404. ->
  4405. decw %si addw %dx,%si p
  4406. }
  4407. RemoveInstruction(hp2);
  4408. RemoveCurrentP(p, hp1);
  4409. Result:=True;
  4410. Exit;
  4411. end;
  4412. end;
  4413. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4414. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4415. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4416. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4417. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4418. )
  4419. {$ifdef i386}
  4420. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4421. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4422. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4423. {$endif i386}
  4424. then
  4425. { change movsX/movzX reg/ref, reg2
  4426. add/sub/or/... regX/$const, reg2
  4427. mov reg2, reg3
  4428. dealloc reg2
  4429. to
  4430. movsX/movzX reg/ref, reg3
  4431. add/sub/or/... reg3/$const, reg3
  4432. }
  4433. begin
  4434. TransferUsedRegs(TmpUsedRegs);
  4435. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4436. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4437. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4438. begin
  4439. { by example:
  4440. movswl %si,%eax movswl %si,%eax p
  4441. decl %eax addl %edx,%eax hp1
  4442. movw %ax,%si movw %ax,%si hp2
  4443. ->
  4444. movswl %si,%eax movswl %si,%eax p
  4445. decw %eax addw %edx,%eax hp1
  4446. movw %ax,%si movw %ax,%si hp2
  4447. }
  4448. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4449. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4450. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4451. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4452. { limit size of constants as well to avoid assembler errors, but
  4453. check opsize to avoid overflow when left shifting the 1 }
  4454. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4455. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4456. {$ifdef x86_64}
  4457. { Be careful of, for example:
  4458. movl %reg1,%reg2
  4459. addl %reg3,%reg2
  4460. movq %reg2,%reg4
  4461. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4462. }
  4463. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4464. begin
  4465. taicpu(hp2).changeopsize(S_L);
  4466. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4467. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4468. end;
  4469. {$endif x86_64}
  4470. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4471. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4472. if taicpu(p).oper[0]^.typ=top_reg then
  4473. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4474. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4475. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4476. {
  4477. ->
  4478. movswl %si,%eax movswl %si,%eax p
  4479. decw %si addw %dx,%si hp1
  4480. movw %ax,%si movw %ax,%si hp2
  4481. }
  4482. case taicpu(hp1).ops of
  4483. 1:
  4484. begin
  4485. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4486. if taicpu(hp1).oper[0]^.typ=top_reg then
  4487. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4488. end;
  4489. 2:
  4490. begin
  4491. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4492. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4493. (taicpu(hp1).opcode<>A_SHL) and
  4494. (taicpu(hp1).opcode<>A_SHR) and
  4495. (taicpu(hp1).opcode<>A_SAR) then
  4496. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4497. end;
  4498. else
  4499. internalerror(2018111801);
  4500. end;
  4501. {
  4502. ->
  4503. decw %si addw %dx,%si p
  4504. }
  4505. RemoveInstruction(hp2);
  4506. end;
  4507. end;
  4508. end;
  4509. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4510. GetNextInstruction(hp1, hp2) and
  4511. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4512. MatchOperand(Taicpu(p).oper[0]^,0) and
  4513. (Taicpu(p).oper[1]^.typ = top_reg) and
  4514. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4515. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4516. { mov reg1,0
  4517. bts reg1,operand1 --> mov reg1,operand2
  4518. or reg1,operand2 bts reg1,operand1}
  4519. begin
  4520. Taicpu(hp2).opcode:=A_MOV;
  4521. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4522. asml.remove(hp1);
  4523. insertllitem(hp2,hp2.next,hp1);
  4524. RemoveCurrentp(p, hp1);
  4525. Result:=true;
  4526. exit;
  4527. end;
  4528. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4529. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4530. GetNextInstruction(hp1, hp2) and
  4531. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4532. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4533. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4534. { change
  4535. mov reg1,reg2
  4536. sub reg3,reg2
  4537. cmp reg3,reg1
  4538. into
  4539. mov reg1,reg2
  4540. sub reg3,reg2
  4541. }
  4542. begin
  4543. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4544. RemoveInstruction(hp2);
  4545. Result:=true;
  4546. exit;
  4547. end;
  4548. {
  4549. mov ref,reg0
  4550. <op> reg0,reg1
  4551. dealloc reg0
  4552. to
  4553. <op> ref,reg1
  4554. }
  4555. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4556. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4557. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4558. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4559. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4560. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4561. begin
  4562. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4563. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4564. RemoveCurrentp(p, hp1);
  4565. Result:=true;
  4566. exit;
  4567. end;
  4568. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4569. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4570. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4571. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4572. begin
  4573. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4574. {$ifdef x86_64}
  4575. { Convert:
  4576. movq x(ref),%reg64
  4577. shrq y,%reg64
  4578. To:
  4579. movl x+4(ref),%reg32
  4580. shrl y-32,%reg32 (Remove if y = 32)
  4581. }
  4582. if (taicpu(p).opsize = S_Q) and
  4583. (taicpu(hp1).opcode = A_SHR) and
  4584. (taicpu(hp1).oper[0]^.val >= 32) then
  4585. begin
  4586. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4587. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4588. { Convert to 32-bit }
  4589. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4590. taicpu(p).opsize := S_L;
  4591. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4592. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4593. if (taicpu(hp1).oper[0]^.val = 32) then
  4594. begin
  4595. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4596. RemoveInstruction(hp1);
  4597. end
  4598. else
  4599. begin
  4600. { This will potentially open up more arithmetic operations since
  4601. the peephole optimizer now has a big hint that only the lower
  4602. 32 bits are currently in use (and opcodes are smaller in size) }
  4603. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4604. taicpu(hp1).opsize := S_L;
  4605. Dec(taicpu(hp1).oper[0]^.val, 32);
  4606. DebugMsg(SPeepholeOptimization + PreMessage +
  4607. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4608. end;
  4609. Result := True;
  4610. Exit;
  4611. end;
  4612. {$endif x86_64}
  4613. { Convert:
  4614. movl x(ref),%reg
  4615. shrl $24,%reg
  4616. To:
  4617. movzbl x+3(ref),%reg
  4618. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4619. Also accept sar instead of shr, but convert to movsx instead of movzx
  4620. }
  4621. if taicpu(hp1).opcode = A_SHR then
  4622. MovUnaligned := A_MOVZX
  4623. else
  4624. MovUnaligned := A_MOVSX;
  4625. NewSize := S_NO;
  4626. NewOffset := 0;
  4627. case taicpu(p).opsize of
  4628. S_B:
  4629. { No valid combinations };
  4630. S_W:
  4631. if (taicpu(hp1).oper[0]^.val = 8) then
  4632. begin
  4633. NewSize := S_BW;
  4634. NewOffset := 1;
  4635. end;
  4636. S_L:
  4637. case taicpu(hp1).oper[0]^.val of
  4638. 16:
  4639. begin
  4640. NewSize := S_WL;
  4641. NewOffset := 2;
  4642. end;
  4643. 24:
  4644. begin
  4645. NewSize := S_BL;
  4646. NewOffset := 3;
  4647. end;
  4648. else
  4649. ;
  4650. end;
  4651. {$ifdef x86_64}
  4652. S_Q:
  4653. case taicpu(hp1).oper[0]^.val of
  4654. 32:
  4655. begin
  4656. if taicpu(hp1).opcode = A_SAR then
  4657. begin
  4658. { 32-bit to 64-bit is a distinct instruction }
  4659. MovUnaligned := A_MOVSXD;
  4660. NewSize := S_LQ;
  4661. NewOffset := 4;
  4662. end
  4663. else
  4664. { Should have been handled by MovShr2Mov above }
  4665. InternalError(2022081811);
  4666. end;
  4667. 48:
  4668. begin
  4669. NewSize := S_WQ;
  4670. NewOffset := 6;
  4671. end;
  4672. 56:
  4673. begin
  4674. NewSize := S_BQ;
  4675. NewOffset := 7;
  4676. end;
  4677. else
  4678. ;
  4679. end;
  4680. {$endif x86_64}
  4681. else
  4682. InternalError(2022081810);
  4683. end;
  4684. if (NewSize <> S_NO) and
  4685. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4686. begin
  4687. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4688. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4689. debug_op2str(MovUnaligned);
  4690. {$ifdef x86_64}
  4691. if MovUnaligned <> A_MOVSXD then
  4692. { Don't add size suffix for MOVSXD }
  4693. {$endif x86_64}
  4694. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4695. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4696. taicpu(p).opcode := MovUnaligned;
  4697. taicpu(p).opsize := NewSize;
  4698. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4699. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4700. RemoveInstruction(hp1);
  4701. Result := True;
  4702. Exit;
  4703. end;
  4704. end;
  4705. { Backward optimisation shared with OptPass2MOV }
  4706. if FuncMov2Func(p, hp1) then
  4707. begin
  4708. Result := True;
  4709. Exit;
  4710. end;
  4711. end;
  4712. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4713. var
  4714. hp1 : tai;
  4715. begin
  4716. Result:=false;
  4717. if taicpu(p).ops <> 2 then
  4718. exit;
  4719. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4720. GetNextInstruction(p,hp1) then
  4721. begin
  4722. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4723. (taicpu(hp1).ops = 2) then
  4724. begin
  4725. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4726. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4727. { movXX reg1, mem1 or movXX mem1, reg1
  4728. movXX mem2, reg2 movXX reg2, mem2}
  4729. begin
  4730. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4731. { movXX reg1, mem1 or movXX mem1, reg1
  4732. movXX mem2, reg1 movXX reg2, mem1}
  4733. begin
  4734. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4735. begin
  4736. { Removes the second statement from
  4737. movXX reg1, mem1/reg2
  4738. movXX mem1/reg2, reg1
  4739. }
  4740. if taicpu(p).oper[0]^.typ=top_reg then
  4741. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4742. { Removes the second statement from
  4743. movXX mem1/reg1, reg2
  4744. movXX reg2, mem1/reg1
  4745. }
  4746. if (taicpu(p).oper[1]^.typ=top_reg) and
  4747. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4748. begin
  4749. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4750. RemoveInstruction(hp1);
  4751. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4752. Result:=true;
  4753. exit;
  4754. end
  4755. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4756. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4757. begin
  4758. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4759. RemoveInstruction(hp1);
  4760. Result:=true;
  4761. exit;
  4762. end;
  4763. end
  4764. end;
  4765. end;
  4766. end;
  4767. end;
  4768. end;
  4769. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4770. var
  4771. hp1 : tai;
  4772. begin
  4773. result:=false;
  4774. { replace
  4775. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4776. MovX %mreg2,%mreg1
  4777. dealloc %mreg2
  4778. by
  4779. <Op>X %mreg2,%mreg1
  4780. ?
  4781. }
  4782. if GetNextInstruction(p,hp1) and
  4783. { we mix single and double opperations here because we assume that the compiler
  4784. generates vmovapd only after double operations and vmovaps only after single operations }
  4785. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4786. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4787. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4788. (taicpu(p).oper[0]^.typ=top_reg) then
  4789. begin
  4790. TransferUsedRegs(TmpUsedRegs);
  4791. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4792. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4793. begin
  4794. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4795. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4796. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4797. RemoveInstruction(hp1);
  4798. result:=true;
  4799. end;
  4800. end;
  4801. end;
  4802. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4803. var
  4804. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4805. JumpLabel, JumpLabel_dist: TAsmLabel;
  4806. FirstValue, SecondValue: TCGInt;
  4807. function OptimizeJump(var InputP: tai): Boolean;
  4808. var
  4809. TempBool: Boolean;
  4810. begin
  4811. Result := False;
  4812. TempBool := True;
  4813. if DoJumpOptimizations(InputP, TempBool) or
  4814. not TempBool then
  4815. begin
  4816. Result := True;
  4817. if Assigned(InputP) then
  4818. begin
  4819. { CollapseZeroDistJump will be set to the label or an align
  4820. before it after the jump if it optimises, whether or not
  4821. the label is live or dead }
  4822. if (InputP.typ = ait_align) or
  4823. (
  4824. (InputP.typ = ait_label) and
  4825. not (tai_label(InputP).labsym.is_used)
  4826. ) then
  4827. GetNextInstruction(InputP, InputP);
  4828. end;
  4829. Exit;
  4830. end;
  4831. end;
  4832. begin
  4833. Result := False;
  4834. if (taicpu(p).oper[0]^.typ = top_const) and
  4835. (taicpu(p).oper[0]^.val <> -1) then
  4836. begin
  4837. { Convert unsigned maximum constants to -1 to aid optimisation }
  4838. case taicpu(p).opsize of
  4839. S_B:
  4840. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4841. begin
  4842. taicpu(p).oper[0]^.val := -1;
  4843. Result := True;
  4844. Exit;
  4845. end;
  4846. S_W:
  4847. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4848. begin
  4849. taicpu(p).oper[0]^.val := -1;
  4850. Result := True;
  4851. Exit;
  4852. end;
  4853. S_L:
  4854. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4855. begin
  4856. taicpu(p).oper[0]^.val := -1;
  4857. Result := True;
  4858. Exit;
  4859. end;
  4860. {$ifdef x86_64}
  4861. S_Q:
  4862. { Storing anything greater than $7FFFFFFF is not possible so do
  4863. nothing };
  4864. {$endif x86_64}
  4865. else
  4866. InternalError(2021121001);
  4867. end;
  4868. end;
  4869. if GetNextInstruction(p, hp1) and
  4870. TrySwapMovCmp(p, hp1) then
  4871. begin
  4872. Result := True;
  4873. Exit;
  4874. end;
  4875. p_label := nil;
  4876. JumpLabel := nil;
  4877. if MatchInstruction(hp1, A_Jcc, []) then
  4878. begin
  4879. if OptimizeJump(hp1) then
  4880. begin
  4881. Result := True;
  4882. if Assigned(hp1) then
  4883. begin
  4884. { CollapseZeroDistJump will be set to the label or an align
  4885. before it after the jump if it optimises, whether or not
  4886. the label is live or dead }
  4887. if (hp1.typ = ait_align) or
  4888. (
  4889. (hp1.typ = ait_label) and
  4890. not (tai_label(hp1).labsym.is_used)
  4891. ) then
  4892. GetNextInstruction(hp1, hp1);
  4893. end;
  4894. TransferUsedRegs(TmpUsedRegs);
  4895. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4896. if not Assigned(hp1) or
  4897. (
  4898. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4899. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4900. ) then
  4901. begin
  4902. { No more conditional jumps; conditional statement is no longer required }
  4903. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4904. RemoveCurrentP(p);
  4905. end;
  4906. Exit;
  4907. end;
  4908. if IsJumpToLabel(taicpu(hp1)) then
  4909. begin
  4910. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4911. if Assigned(JumpLabel) then
  4912. p_label := getlabelwithsym(JumpLabel);
  4913. end;
  4914. end;
  4915. { Search for:
  4916. test $x,(reg/ref)
  4917. jne @lbl1
  4918. test $y,(reg/ref) (same register or reference)
  4919. jne @lbl1
  4920. Change to:
  4921. test $(x or y),(reg/ref)
  4922. jne @lbl1
  4923. (Note, this doesn't work with je instead of jne)
  4924. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4925. Also search for:
  4926. test $x,(reg/ref)
  4927. je @lbl1
  4928. ...
  4929. test $y,(reg/ref)
  4930. je/jne @lbl2
  4931. If (x or y) = x, then the second jump is deterministic
  4932. }
  4933. if (
  4934. (
  4935. (taicpu(p).oper[0]^.typ = top_const) or
  4936. (
  4937. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4938. (taicpu(p).oper[0]^.typ = top_reg) and
  4939. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4940. )
  4941. ) and
  4942. MatchInstruction(hp1, A_JCC, [])
  4943. ) then
  4944. begin
  4945. if (taicpu(p).oper[0]^.typ = top_reg) and
  4946. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4947. FirstValue := -1
  4948. else
  4949. FirstValue := taicpu(p).oper[0]^.val;
  4950. { If we have several test/jne's in a row, it might be the case that
  4951. the second label doesn't go to the same location, but the one
  4952. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4953. so accommodate for this with a while loop.
  4954. }
  4955. hp1_last := hp1;
  4956. while (
  4957. (
  4958. (taicpu(p).oper[1]^.typ = top_reg) and
  4959. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4960. ) or GetNextInstruction(hp1_last, p_dist)
  4961. ) and (p_dist.typ = ait_instruction) do
  4962. begin
  4963. if (
  4964. (
  4965. (taicpu(p_dist).opcode = A_TEST) and
  4966. (
  4967. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4968. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4969. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4970. )
  4971. ) or
  4972. (
  4973. { cmp 0,%reg = test %reg,%reg }
  4974. (taicpu(p_dist).opcode = A_CMP) and
  4975. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4976. )
  4977. ) and
  4978. { Make sure the destination operands are actually the same }
  4979. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4980. GetNextInstruction(p_dist, hp1_dist) and
  4981. MatchInstruction(hp1_dist, A_JCC, []) then
  4982. begin
  4983. if OptimizeJump(hp1_dist) then
  4984. begin
  4985. Result := True;
  4986. Exit;
  4987. end;
  4988. if
  4989. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4990. (
  4991. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4992. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4993. ) then
  4994. SecondValue := -1
  4995. else
  4996. SecondValue := taicpu(p_dist).oper[0]^.val;
  4997. { If both of the TEST constants are identical, delete the
  4998. second TEST that is unnecessary (be careful though, just
  4999. in case the flags are modified in between) }
  5000. if (FirstValue = SecondValue) then
  5001. begin
  5002. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5003. begin
  5004. { Since the second jump's condition is a subset of the first, we
  5005. know it will never branch because the first jump dominates it.
  5006. Get it out of the way now rather than wait for the jump
  5007. optimisations for a speed boost. }
  5008. if IsJumpToLabel(taicpu(hp1_dist)) then
  5009. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5010. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5011. RemoveInstruction(hp1_dist);
  5012. Result := True;
  5013. end
  5014. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5015. begin
  5016. { If the inverse of the first condition is a subset of the second,
  5017. the second one will definitely branch if the first one doesn't }
  5018. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5019. { We can remove the TEST instruction too }
  5020. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5021. RemoveInstruction(p_dist);
  5022. MakeUnconditional(taicpu(hp1_dist));
  5023. RemoveDeadCodeAfterJump(hp1_dist);
  5024. { Since the jump is now unconditional, we can't
  5025. continue any further with this particular
  5026. optimisation. The original TEST is still intact
  5027. though, so there might be something else we can
  5028. do }
  5029. Include(OptsToCheck, aoc_ForceNewIteration);
  5030. Break;
  5031. end;
  5032. if Result or
  5033. { If a jump wasn't removed or made unconditional, only
  5034. remove the identical TEST instruction if the flags
  5035. weren't modified }
  5036. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5037. begin
  5038. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5039. RemoveInstruction(p_dist);
  5040. { If the jump was removed or made unconditional, we
  5041. don't need to allocate NR_DEFAULTFLAGS over the
  5042. entire range }
  5043. if not Result then
  5044. begin
  5045. { Mark the flags as 'in use' over the entire range }
  5046. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5047. { Speed gain - continue search from the Jcc instruction }
  5048. hp1_last := hp1_dist;
  5049. { Only the TEST instruction was removed, and the
  5050. original was unchanged, so we can safely do
  5051. another iteration of the while loop }
  5052. Include(OptsToCheck, aoc_ForceNewIteration);
  5053. Continue;
  5054. end;
  5055. Exit;
  5056. end;
  5057. end;
  5058. hp1_last := nil;
  5059. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5060. (
  5061. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5062. { Always adjacent under -O2 and under }
  5063. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5064. (
  5065. GetNextInstruction(hp1, hp1_last) and
  5066. (hp1_last = p_dist)
  5067. )
  5068. ) and
  5069. (
  5070. (
  5071. { Test the following variant:
  5072. test $x,(reg/ref)
  5073. jne @lbl1
  5074. test $y,(reg/ref)
  5075. je @lbl2
  5076. @lbl1:
  5077. Becomes:
  5078. test $(x or y),(reg/ref)
  5079. je @lbl2
  5080. @lbl1: (may become a dead label)
  5081. }
  5082. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5083. GetNextInstruction(hp1_dist, hp1_last) and
  5084. (hp1_last = p_label)
  5085. ) or
  5086. (
  5087. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5088. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5089. then the second jump will never branch, so it can also be
  5090. removed regardless of where it goes }
  5091. (
  5092. (FirstValue = -1) or
  5093. (SecondValue = -1) or
  5094. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5095. )
  5096. )
  5097. ) then
  5098. begin
  5099. { Same jump location... can be a register since nothing's changed }
  5100. { If any of the entries are equivalent to test %reg,%reg, then the
  5101. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5102. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5103. if (hp1_last = p_label) then
  5104. begin
  5105. { Variant }
  5106. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5107. RemoveInstruction(p_dist);
  5108. if Assigned(JumpLabel) then
  5109. JumpLabel.decrefs;
  5110. RemoveInstruction(hp1);
  5111. end
  5112. else
  5113. begin
  5114. { Only remove the second test if no jumps or other conditional instructions follow }
  5115. TransferUsedRegs(TmpUsedRegs);
  5116. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5117. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5118. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5119. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5120. begin
  5121. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5122. RemoveInstruction(p_dist);
  5123. { Remove the first jump, not the second, to keep
  5124. any register deallocations between the second
  5125. TEST/JNE pair in the same place. Aids future
  5126. optimisation. }
  5127. if Assigned(JumpLabel) then
  5128. JumpLabel.decrefs;
  5129. RemoveInstruction(hp1);
  5130. end
  5131. else
  5132. begin
  5133. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5134. if IsJumpToLabel(taicpu(hp1_dist)) then
  5135. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5136. { Remove second jump in this instance }
  5137. RemoveInstruction(hp1_dist);
  5138. end;
  5139. end;
  5140. Result := True;
  5141. Exit;
  5142. end;
  5143. end;
  5144. if { If -O2 and under, it may stop on any old instruction }
  5145. (cs_opt_level3 in current_settings.optimizerswitches) and
  5146. (taicpu(p).oper[1]^.typ = top_reg) and
  5147. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5148. begin
  5149. hp1_last := p_dist;
  5150. Continue;
  5151. end;
  5152. Break;
  5153. end;
  5154. end;
  5155. { Search for:
  5156. test %reg,%reg
  5157. j(c1) @lbl1
  5158. ...
  5159. @lbl:
  5160. test %reg,%reg (same register)
  5161. j(c2) @lbl2
  5162. If c2 is a subset of c1, change to:
  5163. test %reg,%reg
  5164. j(c1) @lbl2
  5165. (@lbl1 may become a dead label as a result)
  5166. }
  5167. if (taicpu(p).oper[1]^.typ = top_reg) and
  5168. (taicpu(p).oper[0]^.typ = top_reg) and
  5169. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5170. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5171. Assigned(p_label) and
  5172. GetNextInstruction(p_label, p_dist) and
  5173. MatchInstruction(p_dist, A_TEST, []) and
  5174. { It's fine if the second test uses smaller sub-registers }
  5175. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5176. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5177. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5178. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5179. GetNextInstruction(p_dist, hp1_dist) and
  5180. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5181. begin
  5182. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5183. if JumpLabel = JumpLabel_dist then
  5184. { This is an infinite loop }
  5185. Exit;
  5186. { Best optimisation when the first condition is a subset (or equal) of the second }
  5187. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5188. begin
  5189. { Any registers used here will already be allocated }
  5190. if Assigned(JumpLabel) then
  5191. JumpLabel.DecRefs;
  5192. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5193. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5194. Result := True;
  5195. Exit;
  5196. end;
  5197. end;
  5198. end;
  5199. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5200. var
  5201. hp1, hp2: tai;
  5202. ActiveReg: TRegister;
  5203. OldOffset: asizeint;
  5204. ThisConst: TCGInt;
  5205. function RegDeallocated: Boolean;
  5206. begin
  5207. TransferUsedRegs(TmpUsedRegs);
  5208. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5209. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5210. end;
  5211. begin
  5212. result:=false;
  5213. hp1 := nil;
  5214. { replace
  5215. addX const,%reg1
  5216. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5217. dealloc %reg1
  5218. by
  5219. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5220. }
  5221. if MatchOpType(taicpu(p),top_const,top_reg) then
  5222. begin
  5223. ActiveReg := taicpu(p).oper[1]^.reg;
  5224. { Ensures the entire register was updated }
  5225. if (taicpu(p).opsize >= S_L) and
  5226. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5227. MatchInstruction(hp1,A_LEA,[]) and
  5228. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5229. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5230. (
  5231. { Cover the case where the register in the reference is also the destination register }
  5232. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5233. (
  5234. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5235. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5236. RegDeallocated
  5237. )
  5238. ) then
  5239. begin
  5240. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5241. {$push}
  5242. {$R-}{$Q-}
  5243. { Explicitly disable overflow checking for these offset calculation
  5244. as those do not matter for the final result }
  5245. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5246. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5247. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5248. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5249. {$pop}
  5250. {$ifdef x86_64}
  5251. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5252. begin
  5253. { Overflow; abort }
  5254. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5255. end
  5256. else
  5257. {$endif x86_64}
  5258. begin
  5259. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5260. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5261. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5262. RemoveCurrentP(p, hp1)
  5263. else
  5264. RemoveCurrentP(p);
  5265. result:=true;
  5266. Exit;
  5267. end;
  5268. end;
  5269. if (
  5270. { Save calling GetNextInstructionUsingReg again }
  5271. Assigned(hp1) or
  5272. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5273. ) and
  5274. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5275. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5276. begin
  5277. if taicpu(hp1).oper[0]^.typ = top_const then
  5278. begin
  5279. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5280. if taicpu(hp1).opcode = A_ADD then
  5281. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5282. else
  5283. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5284. Result := True;
  5285. { Handle any overflows }
  5286. case taicpu(p).opsize of
  5287. S_B:
  5288. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5289. S_W:
  5290. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5291. S_L:
  5292. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5293. {$ifdef x86_64}
  5294. S_Q:
  5295. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5296. { Overflow; abort }
  5297. Result := False
  5298. else
  5299. taicpu(p).oper[0]^.val := ThisConst;
  5300. {$endif x86_64}
  5301. else
  5302. InternalError(2021102610);
  5303. end;
  5304. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5305. if Result then
  5306. begin
  5307. if (taicpu(p).oper[0]^.val < 0) and
  5308. (
  5309. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5310. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5311. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5312. ) then
  5313. begin
  5314. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5315. taicpu(p).opcode := A_SUB;
  5316. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5317. end
  5318. else
  5319. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5320. RemoveInstruction(hp1);
  5321. end;
  5322. end
  5323. else
  5324. begin
  5325. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5326. TransferUsedRegs(TmpUsedRegs);
  5327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5328. hp2 := p;
  5329. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5330. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5331. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5332. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5333. begin
  5334. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5335. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5336. Asml.Remove(p);
  5337. Asml.InsertAfter(p, hp1);
  5338. p := hp1;
  5339. Result := True;
  5340. Exit;
  5341. end;
  5342. end;
  5343. end;
  5344. if DoArithCombineOpt(p) then
  5345. Result:=true;
  5346. end;
  5347. end;
  5348. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5349. var
  5350. hp1, hp2: tai;
  5351. ref: Integer;
  5352. saveref: treference;
  5353. offsetcalc: Int64;
  5354. TempReg: TRegister;
  5355. Multiple: TCGInt;
  5356. Adjacent, IntermediateRegDiscarded: Boolean;
  5357. begin
  5358. Result:=false;
  5359. { play save and throw an error if LEA uses a seg register prefix,
  5360. this is most likely an error somewhere else }
  5361. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5362. internalerror(2022022001);
  5363. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5364. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5365. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5366. (
  5367. { do not mess with leas accessing the stack pointer
  5368. unless it's a null operation }
  5369. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5370. (
  5371. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5372. (taicpu(p).oper[0]^.ref^.offset = 0)
  5373. )
  5374. ) and
  5375. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5376. begin
  5377. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5378. begin
  5379. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5380. begin
  5381. taicpu(p).opcode := A_MOV;
  5382. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5383. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5384. end
  5385. else
  5386. begin
  5387. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5388. RemoveCurrentP(p);
  5389. end;
  5390. Result:=true;
  5391. exit;
  5392. end
  5393. else if (
  5394. { continue to use lea to adjust the stack pointer,
  5395. it is the recommended way, but only if not optimizing for size }
  5396. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5397. (cs_opt_size in current_settings.optimizerswitches)
  5398. ) and
  5399. { If the flags register is in use, don't change the instruction
  5400. to an ADD otherwise this will scramble the flags. [Kit] }
  5401. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5402. ConvertLEA(taicpu(p)) then
  5403. begin
  5404. Result:=true;
  5405. exit;
  5406. end;
  5407. end;
  5408. { Don't optimise if the stack or frame pointer is the destination register }
  5409. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5410. Exit;
  5411. if GetNextInstruction(p,hp1) and
  5412. (hp1.typ=ait_instruction) then
  5413. begin
  5414. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5415. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5416. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5417. begin
  5418. TransferUsedRegs(TmpUsedRegs);
  5419. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5420. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5421. begin
  5422. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5423. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5424. RemoveInstruction(hp1);
  5425. result:=true;
  5426. exit;
  5427. end;
  5428. end;
  5429. { changes
  5430. lea <ref1>, reg1
  5431. <op> ...,<ref. with reg1>,...
  5432. to
  5433. <op> ...,<ref1>,... }
  5434. { find a reference which uses reg1 }
  5435. 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
  5436. ref:=0
  5437. 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
  5438. ref:=1
  5439. else
  5440. ref:=-1;
  5441. if (ref<>-1) and
  5442. { reg1 must be either the base or the index }
  5443. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5444. begin
  5445. { reg1 can be removed from the reference }
  5446. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5447. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5448. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5449. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5450. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5451. else
  5452. Internalerror(2019111201);
  5453. { check if the can insert all data of the lea into the second instruction }
  5454. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5455. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5456. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5457. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5458. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5459. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5460. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5461. {$ifdef x86_64}
  5462. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5463. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5464. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5465. )
  5466. {$endif x86_64}
  5467. then
  5468. begin
  5469. { reg1 might not used by the second instruction after it is remove from the reference }
  5470. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5471. begin
  5472. TransferUsedRegs(TmpUsedRegs);
  5473. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5474. { reg1 is not updated so it might not be used afterwards }
  5475. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5476. begin
  5477. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5478. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5479. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5480. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5481. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5482. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5483. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5484. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5485. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5486. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5487. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5488. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5489. RemoveCurrentP(p, hp1);
  5490. result:=true;
  5491. exit;
  5492. end
  5493. end;
  5494. end;
  5495. { recover }
  5496. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5497. end;
  5498. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5499. if Adjacent or
  5500. { Check further ahead (up to 2 instructions ahead for -O2) }
  5501. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5502. begin
  5503. { Check common LEA/LEA conditions }
  5504. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5505. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5506. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5507. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5508. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5509. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5510. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5511. (
  5512. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5513. calling it (since it calls GetNextInstruction) }
  5514. Adjacent or
  5515. (
  5516. (
  5517. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5518. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5519. ) and (
  5520. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5521. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5522. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5523. )
  5524. )
  5525. ) then
  5526. begin
  5527. TransferUsedRegs(TmpUsedRegs);
  5528. hp2 := p;
  5529. repeat
  5530. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5531. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5532. IntermediateRegDiscarded :=
  5533. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5534. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5535. { changes
  5536. lea offset1(regX,scale), reg1
  5537. lea offset2(reg1,reg1), reg2
  5538. to
  5539. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5540. and
  5541. lea offset1(regX,scale1), reg1
  5542. lea offset2(reg1,scale2), reg2
  5543. to
  5544. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5545. and
  5546. lea offset1(regX,scale1), reg1
  5547. lea offset2(reg3,reg1,scale2), reg2
  5548. to
  5549. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5550. ... so long as the final scale does not exceed 8
  5551. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5552. }
  5553. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5554. (
  5555. { Don't optimise if size is a concern and the intermediate register remains in use }
  5556. IntermediateRegDiscarded or
  5557. not (cs_opt_size in current_settings.optimizerswitches)
  5558. ) and
  5559. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5560. (
  5561. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5562. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5563. ) and (
  5564. (
  5565. { lea (reg1,scale2), reg2 variant }
  5566. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5567. (
  5568. Adjacent or
  5569. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5570. ) and
  5571. (
  5572. (
  5573. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5574. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5575. ) or (
  5576. { lea (regX,regX), reg1 variant }
  5577. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5578. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5579. )
  5580. )
  5581. ) or (
  5582. { lea (reg1,reg1), reg1 variant }
  5583. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5584. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5585. )
  5586. ) then
  5587. begin
  5588. { Make everything homogeneous to make calculations easier }
  5589. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5590. begin
  5591. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5592. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5593. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5594. else
  5595. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5596. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5597. end;
  5598. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5599. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5600. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5601. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5602. begin
  5603. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5604. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5605. begin
  5606. { Put the register to change in the index register }
  5607. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5608. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5609. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5610. end;
  5611. { Change lea (reg,reg) to lea(,reg,2) }
  5612. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5613. begin
  5614. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5615. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5616. end;
  5617. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5618. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5619. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5620. { Just to prevent miscalculations }
  5621. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5622. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5623. else
  5624. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5625. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5626. if IntermediateRegDiscarded then
  5627. begin
  5628. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5629. RemoveCurrentP(p);
  5630. end
  5631. else
  5632. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5633. result:=true;
  5634. exit;
  5635. end;
  5636. end;
  5637. { changes
  5638. lea offset1(regX), reg1
  5639. lea offset2(reg1), reg2
  5640. to
  5641. lea offset1+offset2(regX), reg2 }
  5642. if (
  5643. { Don't optimise if size is a concern and the intermediate register remains in use }
  5644. IntermediateRegDiscarded or
  5645. not (cs_opt_size in current_settings.optimizerswitches)
  5646. ) and
  5647. (
  5648. (
  5649. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5650. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5651. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5652. ) or (
  5653. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5654. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5655. (
  5656. (
  5657. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5658. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5659. ) or (
  5660. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5661. (
  5662. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5663. (
  5664. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5665. (
  5666. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5667. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5668. )
  5669. )
  5670. )
  5671. )
  5672. )
  5673. )
  5674. ) then
  5675. begin
  5676. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5677. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5678. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5679. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5680. begin
  5681. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5682. begin
  5683. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5684. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5685. { if the register is used as index and base, we have to increase for base as well
  5686. and adapt base }
  5687. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5688. begin
  5689. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5690. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5691. end;
  5692. end
  5693. else
  5694. begin
  5695. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5696. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5697. end;
  5698. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5699. begin
  5700. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5701. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5702. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5703. end;
  5704. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5705. if IntermediateRegDiscarded then
  5706. begin
  5707. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5708. RemoveCurrentP(p);
  5709. end
  5710. else
  5711. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5712. result:=true;
  5713. exit;
  5714. end;
  5715. end;
  5716. end;
  5717. { Change:
  5718. leal/q $x(%reg1),%reg2
  5719. ...
  5720. shll/q $y,%reg2
  5721. To:
  5722. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5723. }
  5724. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5725. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5726. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5727. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5728. (taicpu(hp1).oper[0]^.val <= 3) then
  5729. begin
  5730. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5731. TransferUsedRegs(TmpUsedRegs);
  5732. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5733. if
  5734. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5735. (this works even if scalefactor is zero) }
  5736. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5737. { Ensure offset doesn't go out of bounds }
  5738. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5739. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5740. (
  5741. (
  5742. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5743. (
  5744. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5745. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5746. (
  5747. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5748. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5749. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5750. )
  5751. )
  5752. ) or (
  5753. (
  5754. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5755. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5756. ) and
  5757. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5758. )
  5759. ) then
  5760. begin
  5761. repeat
  5762. with taicpu(p).oper[0]^.ref^ do
  5763. begin
  5764. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5765. if index = base then
  5766. begin
  5767. if Multiple > 4 then
  5768. { Optimisation will no longer work because resultant
  5769. scale factor will exceed 8 }
  5770. Break;
  5771. base := NR_NO;
  5772. scalefactor := 2;
  5773. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5774. end
  5775. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5776. begin
  5777. { Scale factor only works on the index register }
  5778. index := base;
  5779. base := NR_NO;
  5780. end;
  5781. { For safety }
  5782. if scalefactor <= 1 then
  5783. begin
  5784. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5785. scalefactor := Multiple;
  5786. end
  5787. else
  5788. begin
  5789. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5790. scalefactor := scalefactor * Multiple;
  5791. end;
  5792. offset := offset * Multiple;
  5793. end;
  5794. RemoveInstruction(hp1);
  5795. Result := True;
  5796. Exit;
  5797. { This repeat..until loop exists for the benefit of Break }
  5798. until True;
  5799. end;
  5800. end;
  5801. end;
  5802. end;
  5803. end;
  5804. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5805. var
  5806. hp1 : tai;
  5807. SubInstr: Boolean;
  5808. ThisConst: TCGInt;
  5809. const
  5810. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5811. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5812. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5813. begin
  5814. Result := False;
  5815. if taicpu(p).oper[0]^.typ <> top_const then
  5816. { Should have been confirmed before calling }
  5817. InternalError(2021102601);
  5818. SubInstr := (taicpu(p).opcode = A_SUB);
  5819. if GetLastInstruction(p, hp1) and
  5820. (hp1.typ = ait_instruction) and
  5821. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5822. begin
  5823. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5824. { Bad size }
  5825. InternalError(2022042001);
  5826. case taicpu(hp1).opcode Of
  5827. A_INC:
  5828. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5829. begin
  5830. if SubInstr then
  5831. ThisConst := taicpu(p).oper[0]^.val - 1
  5832. else
  5833. ThisConst := taicpu(p).oper[0]^.val + 1;
  5834. end
  5835. else
  5836. Exit;
  5837. A_DEC:
  5838. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5839. begin
  5840. if SubInstr then
  5841. ThisConst := taicpu(p).oper[0]^.val + 1
  5842. else
  5843. ThisConst := taicpu(p).oper[0]^.val - 1;
  5844. end
  5845. else
  5846. Exit;
  5847. A_SUB:
  5848. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5849. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5850. begin
  5851. if SubInstr then
  5852. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5853. else
  5854. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5855. end
  5856. else
  5857. Exit;
  5858. A_ADD:
  5859. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5860. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5861. begin
  5862. if SubInstr then
  5863. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5864. else
  5865. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5866. end
  5867. else
  5868. Exit;
  5869. else
  5870. Exit;
  5871. end;
  5872. { Check that the values are in range }
  5873. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5874. { Overflow; abort }
  5875. Exit;
  5876. if (ThisConst = 0) then
  5877. begin
  5878. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5879. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5880. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5881. RemoveInstruction(hp1);
  5882. hp1 := tai(p.next);
  5883. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5884. if not GetLastInstruction(hp1, p) then
  5885. p := hp1;
  5886. end
  5887. else
  5888. begin
  5889. if taicpu(hp1).opercnt=1 then
  5890. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5891. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5892. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5893. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5894. else
  5895. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5896. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5897. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5898. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5899. RemoveInstruction(hp1);
  5900. taicpu(p).loadconst(0, ThisConst);
  5901. end;
  5902. Result := True;
  5903. end;
  5904. end;
  5905. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5906. begin
  5907. Result := False;
  5908. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5909. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5910. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5911. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5912. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5913. (
  5914. (
  5915. (taicpu(hp1).opcode = A_TEST)
  5916. ) or (
  5917. (taicpu(hp1).opcode = A_CMP) and
  5918. { A sanity check more than anything }
  5919. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5920. )
  5921. ) then
  5922. begin
  5923. { change
  5924. mov mem, %reg
  5925. ...
  5926. cmp/test x, %reg / test %reg,%reg
  5927. (reg deallocated)
  5928. to
  5929. cmp/test x, mem / cmp 0, mem
  5930. }
  5931. TransferUsedRegs(TmpUsedRegs);
  5932. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5933. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5934. begin
  5935. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5936. if (taicpu(hp1).opcode = A_TEST) and
  5937. (
  5938. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5939. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5940. ) then
  5941. begin
  5942. taicpu(hp1).opcode := A_CMP;
  5943. taicpu(hp1).loadconst(0, 0);
  5944. end;
  5945. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5946. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5947. RemoveCurrentP(p);
  5948. if (p <> hp1) then
  5949. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5950. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5951. { Make sure the flags are allocated across the CMP instruction }
  5952. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5953. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5954. Result := True;
  5955. Exit;
  5956. end;
  5957. end;
  5958. end;
  5959. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5960. var
  5961. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5962. ThisReg, SecondReg: TRegister;
  5963. JumpLoc: TAsmLabel;
  5964. NewSize: TOpSize;
  5965. begin
  5966. Result := False;
  5967. {
  5968. Convert:
  5969. j<c> .L1
  5970. .L2:
  5971. mov 1,reg
  5972. jmp .L3 (or ret, although it might not be a RET yet)
  5973. .L1:
  5974. mov 0,reg
  5975. jmp .L3 (or ret)
  5976. ( As long as .L3 <> .L1 or .L2)
  5977. To:
  5978. mov 0,reg
  5979. set<not(c)> reg
  5980. jmp .L3 (or ret)
  5981. .L2:
  5982. mov 1,reg
  5983. jmp .L3 (or ret)
  5984. .L1:
  5985. mov 0,reg
  5986. jmp .L3 (or ret)
  5987. }
  5988. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5989. Exit;
  5990. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5991. if GetNextInstruction(hp_label, hp2) and
  5992. MatchInstruction(hp2,A_MOV,[]) and
  5993. (taicpu(hp2).oper[0]^.typ = top_const) and
  5994. (
  5995. (
  5996. (taicpu(hp2).oper[1]^.typ = top_reg)
  5997. {$ifdef i386}
  5998. { Under i386, ESI, EDI, EBP and ESP
  5999. don't have an 8-bit representation }
  6000. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6001. {$endif i386}
  6002. ) or (
  6003. {$ifdef i386}
  6004. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6005. {$endif i386}
  6006. (taicpu(hp2).opsize = S_B)
  6007. )
  6008. ) and
  6009. GetNextInstruction(hp2, hp3) and
  6010. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6011. (
  6012. (taicpu(hp3).opcode=A_RET) or
  6013. (
  6014. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6015. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6016. )
  6017. ) and
  6018. GetNextInstruction(hp3, hp4) and
  6019. (hp4.typ=ait_label) and
  6020. (tai_label(hp4).labsym=JumpLoc) and
  6021. (
  6022. not (cs_opt_size in current_settings.optimizerswitches) or
  6023. { If the initial jump is the label's only reference, then it will
  6024. become a dead label if the other conditions are met and hence
  6025. remove at least 2 instructions, including a jump }
  6026. (JumpLoc.getrefs = 1)
  6027. ) and
  6028. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6029. that will be optimised out }
  6030. GetNextInstruction(hp4, hp5) and
  6031. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6032. (taicpu(hp5).oper[0]^.typ = top_const) and
  6033. (
  6034. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6035. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6036. ) and
  6037. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6038. GetNextInstruction(hp5,hp6) and
  6039. (
  6040. (hp6.typ<>ait_label) or
  6041. SkipLabels(hp6, hp6)
  6042. ) and
  6043. (hp6.typ=ait_instruction) then
  6044. begin
  6045. { First, let's look at the two jumps that are hp3 and hp6 }
  6046. if not
  6047. (
  6048. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6049. (
  6050. (taicpu(hp6).opcode=A_RET) or
  6051. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6052. )
  6053. ) then
  6054. { If condition is False, then the JMP/RET instructions matched conventionally }
  6055. begin
  6056. { See if one of the jumps can be instantly converted into a RET }
  6057. if (taicpu(hp3).opcode=A_JMP) then
  6058. begin
  6059. { Reuse hp5 }
  6060. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6061. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6062. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6063. Exit;
  6064. if MatchInstruction(hp5, A_RET, []) then
  6065. begin
  6066. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6067. ConvertJumpToRET(hp3, hp5);
  6068. Result := True;
  6069. end
  6070. else
  6071. Exit;
  6072. end;
  6073. if (taicpu(hp6).opcode=A_JMP) then
  6074. begin
  6075. { Reuse hp5 }
  6076. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6077. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6078. Exit;
  6079. if MatchInstruction(hp5, A_RET, []) then
  6080. begin
  6081. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6082. ConvertJumpToRET(hp6, hp5);
  6083. Result := True;
  6084. end
  6085. else
  6086. Exit;
  6087. end;
  6088. if not
  6089. (
  6090. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6091. (
  6092. (taicpu(hp6).opcode=A_RET) or
  6093. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6094. )
  6095. ) then
  6096. { Still doesn't match }
  6097. Exit;
  6098. end;
  6099. if (taicpu(hp2).oper[0]^.val = 1) then
  6100. begin
  6101. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6102. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6103. end
  6104. else
  6105. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6106. if taicpu(hp2).opsize=S_B then
  6107. begin
  6108. if taicpu(hp2).oper[1]^.typ = top_reg then
  6109. begin
  6110. SecondReg := taicpu(hp2).oper[1]^.reg;
  6111. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6112. end
  6113. else
  6114. begin
  6115. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6116. SecondReg := NR_NO;
  6117. end;
  6118. hp_pos := p;
  6119. hp_allocstart := hp4;
  6120. end
  6121. else
  6122. begin
  6123. { Will be a register because the size can't be S_B otherwise }
  6124. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6125. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6126. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6127. if (cs_opt_size in current_settings.optimizerswitches) then
  6128. begin
  6129. { Favour using MOVZX when optimising for size }
  6130. case taicpu(hp2).opsize of
  6131. S_W:
  6132. NewSize := S_BW;
  6133. S_L:
  6134. NewSize := S_BL;
  6135. {$ifdef x86_64}
  6136. S_Q:
  6137. begin
  6138. NewSize := S_BL;
  6139. { Will implicitly zero-extend to 64-bit }
  6140. setsubreg(SecondReg, R_SUBD);
  6141. end;
  6142. {$endif x86_64}
  6143. else
  6144. InternalError(2022101301);
  6145. end;
  6146. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6147. { Inserting it right before p will guarantee that the flags are also tracked }
  6148. Asml.InsertBefore(hp5, p);
  6149. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6150. hp_pos := hp5;
  6151. hp_allocstart := hp4;
  6152. end
  6153. else
  6154. begin
  6155. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6156. { Inserting it right before p will guarantee that the flags are also tracked }
  6157. Asml.InsertBefore(hp5, p);
  6158. hp_pos := p;
  6159. hp_allocstart := hp5;
  6160. end;
  6161. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6162. end;
  6163. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6164. taicpu(hp4).condition := taicpu(p).condition;
  6165. asml.InsertBefore(hp4, hp_pos);
  6166. if taicpu(hp3).is_jmp then
  6167. begin
  6168. JumpLoc.decrefs;
  6169. MakeUnconditional(taicpu(p));
  6170. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6171. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6172. end
  6173. else
  6174. ConvertJumpToRET(p, hp3);
  6175. if SecondReg <> NR_NO then
  6176. { Ensure the destination register is allocated over this region }
  6177. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6178. if (JumpLoc.getrefs = 0) then
  6179. RemoveDeadCodeAfterJump(hp3);
  6180. Result:=true;
  6181. exit;
  6182. end;
  6183. end;
  6184. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6185. var
  6186. hp1, hp2: tai;
  6187. ActiveReg: TRegister;
  6188. OldOffset: asizeint;
  6189. ThisConst: TCGInt;
  6190. function RegDeallocated: Boolean;
  6191. begin
  6192. TransferUsedRegs(TmpUsedRegs);
  6193. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6194. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6195. end;
  6196. begin
  6197. Result:=false;
  6198. hp1 := nil;
  6199. { replace
  6200. subX const,%reg1
  6201. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6202. dealloc %reg1
  6203. by
  6204. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6205. }
  6206. if MatchOpType(taicpu(p),top_const,top_reg) then
  6207. begin
  6208. ActiveReg := taicpu(p).oper[1]^.reg;
  6209. { Ensures the entire register was updated }
  6210. if (taicpu(p).opsize >= S_L) and
  6211. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6212. MatchInstruction(hp1,A_LEA,[]) and
  6213. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6214. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6215. (
  6216. { Cover the case where the register in the reference is also the destination register }
  6217. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6218. (
  6219. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6220. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6221. RegDeallocated
  6222. )
  6223. ) then
  6224. begin
  6225. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6226. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6227. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6228. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6229. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6230. {$ifdef x86_64}
  6231. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6232. begin
  6233. { Overflow; abort }
  6234. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6235. end
  6236. else
  6237. {$endif x86_64}
  6238. begin
  6239. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6240. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6241. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6242. RemoveCurrentP(p, hp1)
  6243. else
  6244. RemoveCurrentP(p);
  6245. result:=true;
  6246. Exit;
  6247. end;
  6248. end;
  6249. if (
  6250. { Save calling GetNextInstructionUsingReg again }
  6251. Assigned(hp1) or
  6252. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6253. ) and
  6254. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6255. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6256. begin
  6257. if taicpu(hp1).oper[0]^.typ = top_const then
  6258. begin
  6259. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6260. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6261. Result := True;
  6262. { Handle any overflows }
  6263. case taicpu(p).opsize of
  6264. S_B:
  6265. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6266. S_W:
  6267. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6268. S_L:
  6269. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6270. {$ifdef x86_64}
  6271. S_Q:
  6272. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6273. { Overflow; abort }
  6274. Result := False
  6275. else
  6276. taicpu(p).oper[0]^.val := ThisConst;
  6277. {$endif x86_64}
  6278. else
  6279. InternalError(2021102611);
  6280. end;
  6281. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6282. if Result then
  6283. begin
  6284. if (taicpu(p).oper[0]^.val < 0) and
  6285. (
  6286. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6287. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6288. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6289. ) then
  6290. begin
  6291. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6292. taicpu(p).opcode := A_SUB;
  6293. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6294. end
  6295. else
  6296. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6297. RemoveInstruction(hp1);
  6298. end;
  6299. end
  6300. else
  6301. begin
  6302. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6303. TransferUsedRegs(TmpUsedRegs);
  6304. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6305. hp2 := p;
  6306. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6307. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6308. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6309. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6310. begin
  6311. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6312. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6313. Asml.Remove(p);
  6314. Asml.InsertAfter(p, hp1);
  6315. p := hp1;
  6316. Result := True;
  6317. Exit;
  6318. end;
  6319. end;
  6320. end;
  6321. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6322. { * change "sub/add const1, reg" or "dec reg" followed by
  6323. "sub const2, reg" to one "sub ..., reg" }
  6324. {$ifdef i386}
  6325. if (taicpu(p).oper[0]^.val = 2) and
  6326. (ActiveReg = NR_ESP) and
  6327. { Don't do the sub/push optimization if the sub }
  6328. { comes from setting up the stack frame (JM) }
  6329. (not(GetLastInstruction(p,hp1)) or
  6330. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6331. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6332. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6333. begin
  6334. hp1 := tai(p.next);
  6335. while Assigned(hp1) and
  6336. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6337. not RegReadByInstruction(NR_ESP,hp1) and
  6338. not RegModifiedByInstruction(NR_ESP,hp1) do
  6339. hp1 := tai(hp1.next);
  6340. if Assigned(hp1) and
  6341. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6342. begin
  6343. taicpu(hp1).changeopsize(S_L);
  6344. if taicpu(hp1).oper[0]^.typ=top_reg then
  6345. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6346. hp1 := tai(p.next);
  6347. RemoveCurrentp(p, hp1);
  6348. Result:=true;
  6349. exit;
  6350. end;
  6351. end;
  6352. {$endif i386}
  6353. if DoArithCombineOpt(p) then
  6354. Result:=true;
  6355. end;
  6356. end;
  6357. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6358. var
  6359. TmpBool1,TmpBool2 : Boolean;
  6360. tmpref : treference;
  6361. hp1,hp2: tai;
  6362. mask, shiftval: tcgint;
  6363. begin
  6364. Result:=false;
  6365. { All these optimisations work on "shl/sal const,%reg" }
  6366. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6367. Exit;
  6368. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6369. (taicpu(p).oper[0]^.val <= 3) then
  6370. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6371. begin
  6372. { should we check the next instruction? }
  6373. TmpBool1 := True;
  6374. { have we found an add/sub which could be
  6375. integrated in the lea? }
  6376. TmpBool2 := False;
  6377. reference_reset(tmpref,2,[]);
  6378. TmpRef.index := taicpu(p).oper[1]^.reg;
  6379. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6380. while TmpBool1 and
  6381. GetNextInstruction(p, hp1) and
  6382. (tai(hp1).typ = ait_instruction) and
  6383. ((((taicpu(hp1).opcode = A_ADD) or
  6384. (taicpu(hp1).opcode = A_SUB)) and
  6385. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6386. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6387. (((taicpu(hp1).opcode = A_INC) or
  6388. (taicpu(hp1).opcode = A_DEC)) and
  6389. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6390. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6391. ((taicpu(hp1).opcode = A_LEA) and
  6392. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6393. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6394. (not GetNextInstruction(hp1,hp2) or
  6395. not instrReadsFlags(hp2)) Do
  6396. begin
  6397. TmpBool1 := False;
  6398. if taicpu(hp1).opcode=A_LEA then
  6399. begin
  6400. if (TmpRef.base = NR_NO) and
  6401. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6402. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6403. { Segment register isn't a concern here }
  6404. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6405. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6406. begin
  6407. TmpBool1 := True;
  6408. TmpBool2 := True;
  6409. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6410. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6411. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6412. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6413. RemoveInstruction(hp1);
  6414. end
  6415. end
  6416. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6417. begin
  6418. TmpBool1 := True;
  6419. TmpBool2 := True;
  6420. case taicpu(hp1).opcode of
  6421. A_ADD:
  6422. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6423. A_SUB:
  6424. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6425. else
  6426. internalerror(2019050536);
  6427. end;
  6428. RemoveInstruction(hp1);
  6429. end
  6430. else
  6431. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6432. (((taicpu(hp1).opcode = A_ADD) and
  6433. (TmpRef.base = NR_NO)) or
  6434. (taicpu(hp1).opcode = A_INC) or
  6435. (taicpu(hp1).opcode = A_DEC)) then
  6436. begin
  6437. TmpBool1 := True;
  6438. TmpBool2 := True;
  6439. case taicpu(hp1).opcode of
  6440. A_ADD:
  6441. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6442. A_INC:
  6443. inc(TmpRef.offset);
  6444. A_DEC:
  6445. dec(TmpRef.offset);
  6446. else
  6447. internalerror(2019050535);
  6448. end;
  6449. RemoveInstruction(hp1);
  6450. end;
  6451. end;
  6452. if TmpBool2
  6453. {$ifndef x86_64}
  6454. or
  6455. ((current_settings.optimizecputype < cpu_Pentium2) and
  6456. (taicpu(p).oper[0]^.val <= 3) and
  6457. not(cs_opt_size in current_settings.optimizerswitches))
  6458. {$endif x86_64}
  6459. then
  6460. begin
  6461. if not(TmpBool2) and
  6462. (taicpu(p).oper[0]^.val=1) then
  6463. begin
  6464. taicpu(p).opcode := A_ADD;
  6465. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6466. end
  6467. else
  6468. begin
  6469. taicpu(p).opcode := A_LEA;
  6470. taicpu(p).loadref(0, TmpRef);
  6471. end;
  6472. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6473. Result := True;
  6474. end;
  6475. end
  6476. {$ifndef x86_64}
  6477. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6478. begin
  6479. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6480. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6481. (unlike shl, which is only Tairable in the U pipe) }
  6482. if taicpu(p).oper[0]^.val=1 then
  6483. begin
  6484. taicpu(p).opcode := A_ADD;
  6485. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6486. Result := True;
  6487. end
  6488. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6489. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6490. else if (taicpu(p).opsize = S_L) and
  6491. (taicpu(p).oper[0]^.val<= 3) then
  6492. begin
  6493. reference_reset(tmpref,2,[]);
  6494. TmpRef.index := taicpu(p).oper[1]^.reg;
  6495. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6496. taicpu(p).opcode := A_LEA;
  6497. taicpu(p).loadref(0, TmpRef);
  6498. Result := True;
  6499. end;
  6500. end
  6501. {$endif x86_64}
  6502. else if
  6503. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6504. (
  6505. (
  6506. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6507. SetAndTest(hp1, hp2)
  6508. {$ifdef x86_64}
  6509. ) or
  6510. (
  6511. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6512. GetNextInstruction(hp1, hp2) and
  6513. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6514. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6515. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6516. {$endif x86_64}
  6517. )
  6518. ) and
  6519. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6520. begin
  6521. { Change:
  6522. shl x, %reg1
  6523. mov -(1<<x), %reg2
  6524. and %reg2, %reg1
  6525. Or:
  6526. shl x, %reg1
  6527. and -(1<<x), %reg1
  6528. To just:
  6529. shl x, %reg1
  6530. Since the and operation only zeroes bits that are already zero from the shl operation
  6531. }
  6532. case taicpu(p).oper[0]^.val of
  6533. 8:
  6534. mask:=$FFFFFFFFFFFFFF00;
  6535. 16:
  6536. mask:=$FFFFFFFFFFFF0000;
  6537. 32:
  6538. mask:=$FFFFFFFF00000000;
  6539. 63:
  6540. { Constant pre-calculated to prevent overflow errors with Int64 }
  6541. mask:=$8000000000000000;
  6542. else
  6543. begin
  6544. if taicpu(p).oper[0]^.val >= 64 then
  6545. { Shouldn't happen realistically, since the register
  6546. is guaranteed to be set to zero at this point }
  6547. mask := 0
  6548. else
  6549. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6550. end;
  6551. end;
  6552. if taicpu(hp1).oper[0]^.val = mask then
  6553. begin
  6554. { Everything checks out, perform the optimisation, as long as
  6555. the FLAGS register isn't being used}
  6556. TransferUsedRegs(TmpUsedRegs);
  6557. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6558. {$ifdef x86_64}
  6559. if (hp1 <> hp2) then
  6560. begin
  6561. { "shl/mov/and" version }
  6562. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6563. { Don't do the optimisation if the FLAGS register is in use }
  6564. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6565. begin
  6566. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6567. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6568. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6569. begin
  6570. RemoveInstruction(hp1);
  6571. Result := True;
  6572. end;
  6573. { Only set Result to True if the 'mov' instruction was removed }
  6574. RemoveInstruction(hp2);
  6575. end;
  6576. end
  6577. else
  6578. {$endif x86_64}
  6579. begin
  6580. { "shl/and" version }
  6581. { Don't do the optimisation if the FLAGS register is in use }
  6582. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6583. begin
  6584. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6585. RemoveInstruction(hp1);
  6586. Result := True;
  6587. end;
  6588. end;
  6589. Exit;
  6590. end
  6591. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6592. begin
  6593. { Even if the mask doesn't allow for its removal, we might be
  6594. able to optimise the mask for the "shl/and" version, which
  6595. may permit other peephole optimisations }
  6596. {$ifdef DEBUG_AOPTCPU}
  6597. mask := taicpu(hp1).oper[0]^.val and mask;
  6598. if taicpu(hp1).oper[0]^.val <> mask then
  6599. begin
  6600. DebugMsg(
  6601. SPeepholeOptimization +
  6602. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6603. ' to $' + debug_tostr(mask) +
  6604. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6605. taicpu(hp1).oper[0]^.val := mask;
  6606. end;
  6607. {$else DEBUG_AOPTCPU}
  6608. { If debugging is off, just set the operand even if it's the same }
  6609. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6610. {$endif DEBUG_AOPTCPU}
  6611. end;
  6612. end;
  6613. {
  6614. change
  6615. shl/sal const,reg
  6616. <op> ...(...,reg,1),...
  6617. into
  6618. <op> ...(...,reg,1 shl const),...
  6619. if const in 1..3
  6620. }
  6621. if MatchOpType(taicpu(p), top_const, top_reg) and
  6622. (taicpu(p).oper[0]^.val in [1..3]) and
  6623. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6624. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6625. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6626. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6627. MatchOpType(taicpu(hp1),top_ref))
  6628. ) and
  6629. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6630. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6631. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6632. begin
  6633. TransferUsedRegs(TmpUsedRegs);
  6634. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6635. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6636. begin
  6637. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6638. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6639. RemoveCurrentP(p);
  6640. Result:=true;
  6641. exit;
  6642. end;
  6643. end;
  6644. if MatchOpType(taicpu(p), top_const, top_reg) and
  6645. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6646. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6647. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6648. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6649. begin
  6650. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6651. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6652. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6653. {$ifdef x86_64}
  6654. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6655. {$endif x86_64}
  6656. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6657. begin
  6658. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6659. taicpu(hp1).opcode:=A_MOV;
  6660. taicpu(hp1).oper[0]^.val:=0;
  6661. end
  6662. else
  6663. begin
  6664. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6665. taicpu(hp1).oper[0]^.val:=shiftval;
  6666. end;
  6667. RemoveCurrentP(p);
  6668. Result:=true;
  6669. exit;
  6670. end;
  6671. end;
  6672. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6673. begin
  6674. case shr_size of
  6675. S_B:
  6676. { No valid combinations }
  6677. Result := False;
  6678. S_W:
  6679. Result := (Shift >= 8) and (movz_size = S_BW);
  6680. S_L:
  6681. Result :=
  6682. (Shift >= 24) { Any opsize is valid for this shift } or
  6683. ((Shift >= 16) and (movz_size = S_WL));
  6684. {$ifdef x86_64}
  6685. S_Q:
  6686. Result :=
  6687. (Shift >= 56) { Any opsize is valid for this shift } or
  6688. ((Shift >= 48) and (movz_size = S_WL));
  6689. {$endif x86_64}
  6690. else
  6691. InternalError(2022081510);
  6692. end;
  6693. end;
  6694. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6695. var
  6696. hp1, hp2: tai;
  6697. Shift: TCGInt;
  6698. LimitSize: Topsize;
  6699. DoNotMerge: Boolean;
  6700. begin
  6701. Result := False;
  6702. { All these optimisations work on "shr const,%reg" }
  6703. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6704. Exit;
  6705. DoNotMerge := False;
  6706. Shift := taicpu(p).oper[0]^.val;
  6707. LimitSize := taicpu(p).opsize;
  6708. hp1 := p;
  6709. repeat
  6710. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6711. Exit;
  6712. case taicpu(hp1).opcode of
  6713. A_TEST, A_CMP, A_Jcc:
  6714. { Skip over conditional jumps and relevant comparisons }
  6715. Continue;
  6716. A_MOVZX:
  6717. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6718. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6719. begin
  6720. { Since the original register is being read as is, subsequent
  6721. SHRs must not be merged at this point }
  6722. DoNotMerge := True;
  6723. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6724. begin
  6725. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6726. begin
  6727. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6728. taicpu(hp1).opcode := A_MOV;
  6729. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6730. case taicpu(hp1).opsize of
  6731. S_BW:
  6732. taicpu(hp1).opsize := S_W;
  6733. S_BL, S_WL:
  6734. taicpu(hp1).opsize := S_L;
  6735. else
  6736. InternalError(2022081503);
  6737. end;
  6738. { p itself hasn't changed, so no need to set Result to True }
  6739. Include(OptsToCheck, aoc_ForceNewIteration);
  6740. { See if there's anything afterwards that can be
  6741. optimised, since the input register hasn't changed }
  6742. Continue;
  6743. end;
  6744. { NOTE: If the MOVZX instruction reads and writes the same
  6745. register, defer this to the post-peephole optimisation stage }
  6746. Exit;
  6747. end;
  6748. end;
  6749. A_SHL, A_SAL, A_SHR:
  6750. if (taicpu(hp1).opsize <= LimitSize) and
  6751. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6752. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6753. begin
  6754. { Make sure the sizes don't exceed the register size limit
  6755. (measured by the shift value falling below the limit) }
  6756. if taicpu(hp1).opsize < LimitSize then
  6757. LimitSize := taicpu(hp1).opsize;
  6758. if taicpu(hp1).opcode = A_SHR then
  6759. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6760. else
  6761. begin
  6762. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6763. DoNotMerge := True;
  6764. end;
  6765. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6766. Exit;
  6767. { Since we've established that the combined shift is within
  6768. limits, we can actually combine the adjacent SHR
  6769. instructions even if they're different sizes }
  6770. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6771. begin
  6772. hp2 := tai(hp1.Previous);
  6773. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6774. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6775. RemoveInstruction(hp1);
  6776. hp1 := hp2;
  6777. { Though p has changed, only the constant has, and its
  6778. effects can still be detected on the next iteration of
  6779. the repeat..until loop }
  6780. Include(OptsToCheck, aoc_ForceNewIteration);
  6781. end;
  6782. { Move onto the next instruction }
  6783. Continue;
  6784. end;
  6785. else
  6786. ;
  6787. end;
  6788. Break;
  6789. until False;
  6790. end;
  6791. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6792. var
  6793. CurrentRef: TReference;
  6794. FullReg: TRegister;
  6795. hp1, hp2: tai;
  6796. begin
  6797. Result := False;
  6798. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6799. Exit;
  6800. { We assume you've checked if the operand is actually a reference by
  6801. this point. If it isn't, you'll most likely get an access violation }
  6802. CurrentRef := first_mov.oper[1]^.ref^;
  6803. { Memory must be aligned }
  6804. if (CurrentRef.offset mod 4) <> 0 then
  6805. Exit;
  6806. Inc(CurrentRef.offset);
  6807. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6808. if MatchOperand(second_mov.oper[0]^, 0) and
  6809. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6810. GetNextInstruction(second_mov, hp1) and
  6811. (hp1.typ = ait_instruction) and
  6812. (taicpu(hp1).opcode = A_MOV) and
  6813. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6814. (taicpu(hp1).oper[0]^.val = 0) then
  6815. begin
  6816. Inc(CurrentRef.offset);
  6817. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6818. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6819. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6820. begin
  6821. case taicpu(hp1).opsize of
  6822. S_B:
  6823. if GetNextInstruction(hp1, hp2) and
  6824. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6825. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6826. (taicpu(hp2).oper[0]^.val = 0) then
  6827. begin
  6828. Inc(CurrentRef.offset);
  6829. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6830. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6831. (taicpu(hp2).opsize = S_B) then
  6832. begin
  6833. RemoveInstruction(hp1);
  6834. RemoveInstruction(hp2);
  6835. first_mov.opsize := S_L;
  6836. if first_mov.oper[0]^.typ = top_reg then
  6837. begin
  6838. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6839. { Reuse second_mov as a MOVZX instruction }
  6840. second_mov.opcode := A_MOVZX;
  6841. second_mov.opsize := S_BL;
  6842. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6843. second_mov.loadreg(1, FullReg);
  6844. first_mov.oper[0]^.reg := FullReg;
  6845. asml.Remove(second_mov);
  6846. asml.InsertBefore(second_mov, first_mov);
  6847. end
  6848. else
  6849. { It's a value }
  6850. begin
  6851. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6852. RemoveInstruction(second_mov);
  6853. end;
  6854. Result := True;
  6855. Exit;
  6856. end;
  6857. end;
  6858. S_W:
  6859. begin
  6860. RemoveInstruction(hp1);
  6861. first_mov.opsize := S_L;
  6862. if first_mov.oper[0]^.typ = top_reg then
  6863. begin
  6864. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6865. { Reuse second_mov as a MOVZX instruction }
  6866. second_mov.opcode := A_MOVZX;
  6867. second_mov.opsize := S_BL;
  6868. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6869. second_mov.loadreg(1, FullReg);
  6870. first_mov.oper[0]^.reg := FullReg;
  6871. asml.Remove(second_mov);
  6872. asml.InsertBefore(second_mov, first_mov);
  6873. end
  6874. else
  6875. { It's a value }
  6876. begin
  6877. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6878. RemoveInstruction(second_mov);
  6879. end;
  6880. Result := True;
  6881. Exit;
  6882. end;
  6883. else
  6884. ;
  6885. end;
  6886. end;
  6887. end;
  6888. end;
  6889. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6890. { returns true if a "continue" should be done after this optimization }
  6891. var
  6892. hp1, hp2, hp3: tai;
  6893. begin
  6894. Result := false;
  6895. hp3 := nil;
  6896. if MatchOpType(taicpu(p),top_ref) and
  6897. GetNextInstruction(p, hp1) and
  6898. (hp1.typ = ait_instruction) and
  6899. (((taicpu(hp1).opcode = A_FLD) and
  6900. (taicpu(p).opcode = A_FSTP)) or
  6901. ((taicpu(p).opcode = A_FISTP) and
  6902. (taicpu(hp1).opcode = A_FILD))) and
  6903. MatchOpType(taicpu(hp1),top_ref) and
  6904. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6905. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6906. begin
  6907. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6908. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6909. GetNextInstruction(hp1, hp2) and
  6910. (((hp2.typ = ait_instruction) and
  6911. IsExitCode(hp2) and
  6912. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6913. not(assigned(current_procinfo.procdef.funcretsym) and
  6914. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6915. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6916. { fstp <temp>
  6917. fld <temp>
  6918. <dealloc> <temp>
  6919. }
  6920. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6921. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6922. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6923. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6924. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6925. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6926. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6927. )
  6928. )
  6929. ) then
  6930. begin
  6931. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6932. RemoveInstruction(hp1);
  6933. RemoveCurrentP(p, hp2);
  6934. { first case: exit code }
  6935. if hp2.typ = ait_instruction then
  6936. RemoveLastDeallocForFuncRes(p);
  6937. Result := true;
  6938. end
  6939. else
  6940. { we can do this only in fast math mode as fstp is rounding ...
  6941. ... still disabled as it breaks the compiler and/or rtl }
  6942. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6943. { ... or if another fstp equal to the first one follows }
  6944. GetNextInstruction(hp1,hp2) and
  6945. (hp2.typ = ait_instruction) and
  6946. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6947. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6948. begin
  6949. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6950. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6951. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6952. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6953. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6954. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6955. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6956. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6957. ) then
  6958. begin
  6959. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6960. RemoveCurrentP(p,hp2);
  6961. RemoveInstruction(hp1);
  6962. Result := true;
  6963. end
  6964. else if { fst can't store an extended/comp value }
  6965. (taicpu(p).opsize <> S_FX) and
  6966. (taicpu(p).opsize <> S_IQ) then
  6967. begin
  6968. if (taicpu(p).opcode = A_FSTP) then
  6969. taicpu(p).opcode := A_FST
  6970. else
  6971. taicpu(p).opcode := A_FIST;
  6972. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6973. RemoveInstruction(hp1);
  6974. Result := true;
  6975. end;
  6976. end;
  6977. end;
  6978. end;
  6979. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6980. var
  6981. hp1, hp2, hp3: tai;
  6982. begin
  6983. result:=false;
  6984. if MatchOpType(taicpu(p),top_reg) and
  6985. GetNextInstruction(p, hp1) and
  6986. (hp1.typ = Ait_Instruction) and
  6987. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6988. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6989. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6990. { change to
  6991. fld reg fxxx reg,st
  6992. fxxxp st, st1 (hp1)
  6993. Remark: non commutative operations must be reversed!
  6994. }
  6995. begin
  6996. case taicpu(hp1).opcode Of
  6997. A_FMULP,A_FADDP,
  6998. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6999. begin
  7000. case taicpu(hp1).opcode Of
  7001. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7002. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7003. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7004. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7005. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7006. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7007. else
  7008. internalerror(2019050534);
  7009. end;
  7010. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7011. taicpu(hp1).oper[1]^.reg := NR_ST;
  7012. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7013. RemoveCurrentP(p, hp1);
  7014. Result:=true;
  7015. exit;
  7016. end;
  7017. else
  7018. ;
  7019. end;
  7020. end
  7021. else
  7022. if MatchOpType(taicpu(p),top_ref) and
  7023. GetNextInstruction(p, hp2) and
  7024. (hp2.typ = Ait_Instruction) and
  7025. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7026. (taicpu(p).opsize in [S_FS, S_FL]) and
  7027. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7028. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7029. if GetLastInstruction(p, hp1) and
  7030. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7031. MatchOpType(taicpu(hp1),top_ref) and
  7032. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7033. if ((taicpu(hp2).opcode = A_FMULP) or
  7034. (taicpu(hp2).opcode = A_FADDP)) then
  7035. { change to
  7036. fld/fst mem1 (hp1) fld/fst mem1
  7037. fld mem1 (p) fadd/
  7038. faddp/ fmul st, st
  7039. fmulp st, st1 (hp2) }
  7040. begin
  7041. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7042. RemoveCurrentP(p, hp1);
  7043. if (taicpu(hp2).opcode = A_FADDP) then
  7044. taicpu(hp2).opcode := A_FADD
  7045. else
  7046. taicpu(hp2).opcode := A_FMUL;
  7047. taicpu(hp2).oper[1]^.reg := NR_ST;
  7048. end
  7049. else
  7050. { change to
  7051. fld/fst mem1 (hp1) fld/fst mem1
  7052. fld mem1 (p) fld st
  7053. }
  7054. begin
  7055. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7056. taicpu(p).changeopsize(S_FL);
  7057. taicpu(p).loadreg(0,NR_ST);
  7058. end
  7059. else
  7060. begin
  7061. case taicpu(hp2).opcode Of
  7062. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7063. { change to
  7064. fld/fst mem1 (hp1) fld/fst mem1
  7065. fld mem2 (p) fxxx mem2
  7066. fxxxp st, st1 (hp2) }
  7067. begin
  7068. case taicpu(hp2).opcode Of
  7069. A_FADDP: taicpu(p).opcode := A_FADD;
  7070. A_FMULP: taicpu(p).opcode := A_FMUL;
  7071. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7072. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7073. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7074. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7075. else
  7076. internalerror(2019050533);
  7077. end;
  7078. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7079. RemoveInstruction(hp2);
  7080. end
  7081. else
  7082. ;
  7083. end
  7084. end
  7085. end;
  7086. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7087. begin
  7088. Result := condition_in(cond1, cond2) or
  7089. { Not strictly subsets due to the actual flags checked, but because we're
  7090. comparing integers, E is a subset of AE and GE and their aliases }
  7091. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7092. end;
  7093. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7094. var
  7095. v: TCGInt;
  7096. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7097. FirstMatch, TempBool: Boolean;
  7098. NewReg: TRegister;
  7099. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7100. begin
  7101. Result:=false;
  7102. { All these optimisations need a next instruction }
  7103. if not GetNextInstruction(p, hp1) then
  7104. Exit;
  7105. { Search for:
  7106. cmp ###,###
  7107. j(c1) @lbl1
  7108. ...
  7109. @lbl:
  7110. cmp ###,### (same comparison as above)
  7111. j(c2) @lbl2
  7112. If c1 is a subset of c2, change to:
  7113. cmp ###,###
  7114. j(c1) @lbl2
  7115. (@lbl1 may become a dead label as a result)
  7116. }
  7117. { Also handle cases where there are multiple jumps in a row }
  7118. p_jump := hp1;
  7119. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7120. begin
  7121. if IsJumpToLabel(taicpu(p_jump)) then
  7122. begin
  7123. { Do jump optimisations first in case the condition becomes
  7124. unnecessary }
  7125. TempBool := True;
  7126. if DoJumpOptimizations(p_jump, TempBool) or
  7127. not TempBool then
  7128. begin
  7129. if Assigned(p_jump) then
  7130. begin
  7131. { CollapseZeroDistJump will be set to the label or an align
  7132. before it after the jump if it optimises, whether or not
  7133. the label is live or dead }
  7134. if (p_jump.typ = ait_align) or
  7135. (
  7136. (p_jump.typ = ait_label) and
  7137. not (tai_label(p_jump).labsym.is_used)
  7138. ) then
  7139. GetNextInstruction(p_jump, p_jump);
  7140. end;
  7141. TransferUsedRegs(TmpUsedRegs);
  7142. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7143. if not Assigned(p_jump) or
  7144. (
  7145. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7146. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7147. ) then
  7148. begin
  7149. { No more conditional jumps; conditional statement is no longer required }
  7150. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7151. RemoveCurrentP(p);
  7152. Result := True;
  7153. Exit;
  7154. end;
  7155. hp1 := p_jump;
  7156. Include(OptsToCheck, aoc_ForceNewIteration);
  7157. Continue;
  7158. end;
  7159. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7160. if GetNextInstruction(p_jump, hp2) and
  7161. (
  7162. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7163. not TempBool
  7164. ) then
  7165. begin
  7166. hp1 := p_jump;
  7167. Include(OptsToCheck, aoc_ForceNewIteration);
  7168. Continue;
  7169. end;
  7170. p_label := nil;
  7171. if Assigned(JumpLabel) then
  7172. p_label := getlabelwithsym(JumpLabel);
  7173. if Assigned(p_label) and
  7174. GetNextInstruction(p_label, p_dist) and
  7175. MatchInstruction(p_dist, A_CMP, []) and
  7176. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7177. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7178. GetNextInstruction(p_dist, hp1_dist) and
  7179. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7180. begin
  7181. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7182. if JumpLabel = JumpLabel_dist then
  7183. { This is an infinite loop }
  7184. Exit;
  7185. { Best optimisation when the first condition is a subset (or equal) of the second }
  7186. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7187. begin
  7188. { Any registers used here will already be allocated }
  7189. if Assigned(JumpLabel) then
  7190. JumpLabel.DecRefs;
  7191. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7192. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7193. Result := True;
  7194. { Don't exit yet. Since p and p_jump haven't actually been
  7195. removed, we can check for more on this iteration }
  7196. end
  7197. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7198. GetNextInstruction(hp1_dist, hp1_label) and
  7199. (hp1_label.typ = ait_label) then
  7200. begin
  7201. JumpLabel_far := tai_label(hp1_label).labsym;
  7202. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7203. { This is an infinite loop }
  7204. Exit;
  7205. if Assigned(JumpLabel_far) then
  7206. begin
  7207. { In this situation, if the first jump branches, the second one will never,
  7208. branch so change the destination label to after the second jump }
  7209. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7210. if Assigned(JumpLabel) then
  7211. JumpLabel.DecRefs;
  7212. JumpLabel_far.IncRefs;
  7213. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7214. Result := True;
  7215. { Don't exit yet. Since p and p_jump haven't actually been
  7216. removed, we can check for more on this iteration }
  7217. Continue;
  7218. end;
  7219. end;
  7220. end;
  7221. end;
  7222. { Search for:
  7223. cmp ###,###
  7224. j(c1) @lbl1
  7225. cmp ###,### (same as first)
  7226. Remove second cmp
  7227. }
  7228. if GetNextInstruction(p_jump, hp2) and
  7229. (
  7230. (
  7231. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7232. (
  7233. (
  7234. MatchOpType(taicpu(p), top_const, top_reg) and
  7235. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7236. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7237. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7238. ) or (
  7239. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7240. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7241. )
  7242. )
  7243. ) or (
  7244. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7245. MatchOperand(taicpu(p).oper[0]^, 0) and
  7246. (taicpu(p).oper[1]^.typ = top_reg) and
  7247. MatchInstruction(hp2, A_TEST, []) and
  7248. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7249. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7250. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7251. )
  7252. ) then
  7253. begin
  7254. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7255. RemoveInstruction(hp2);
  7256. Result := True;
  7257. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7258. end;
  7259. GetNextInstruction(p_jump, p_jump);
  7260. end;
  7261. if (
  7262. { Don't call GetNextInstruction again if we already have it }
  7263. (hp1 = p_jump) or
  7264. GetNextInstruction(p, hp1)
  7265. ) and
  7266. MatchInstruction(hp1, A_Jcc, []) and
  7267. IsJumpToLabel(taicpu(hp1)) and
  7268. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7269. GetNextInstruction(hp1, hp2) then
  7270. begin
  7271. {
  7272. cmp x, y (or "cmp y, x")
  7273. je @lbl
  7274. mov x, y
  7275. @lbl:
  7276. (x and y can be constants, registers or references)
  7277. Change to:
  7278. mov x, y (x and y will always be equal in the end)
  7279. @lbl: (may beceome a dead label)
  7280. Also:
  7281. cmp x, y (or "cmp y, x")
  7282. jne @lbl
  7283. mov x, y
  7284. @lbl:
  7285. (x and y can be constants, registers or references)
  7286. Change to:
  7287. Absolutely nothing! (Except @lbl if it's still live)
  7288. }
  7289. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7290. (
  7291. (
  7292. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7293. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7294. ) or (
  7295. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7296. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7297. )
  7298. ) and
  7299. GetNextInstruction(hp2, hp1_label) and
  7300. (hp1_label.typ = ait_label) and
  7301. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7302. begin
  7303. tai_label(hp1_label).labsym.DecRefs;
  7304. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7305. begin
  7306. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7307. RemoveInstruction(hp2);
  7308. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7309. end
  7310. else
  7311. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7312. RemoveInstruction(hp1);
  7313. RemoveCurrentp(p, hp2);
  7314. Result := True;
  7315. Exit;
  7316. end;
  7317. {
  7318. Try to optimise the following:
  7319. cmp $x,### ($x and $y can be registers or constants)
  7320. je @lbl1 (only reference)
  7321. cmp $y,### (### are identical)
  7322. @Lbl:
  7323. sete %reg1
  7324. Change to:
  7325. cmp $x,###
  7326. sete %reg2 (allocate new %reg2)
  7327. cmp $y,###
  7328. sete %reg1
  7329. orb %reg2,%reg1
  7330. (dealloc %reg2)
  7331. This adds an instruction (so don't perform under -Os), but it removes
  7332. a conditional branch.
  7333. }
  7334. if not (cs_opt_size in current_settings.optimizerswitches) and
  7335. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7336. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7337. { The first operand of CMP instructions can only be a register or
  7338. immediate anyway, so no need to check }
  7339. GetNextInstruction(hp2, p_label) and
  7340. (p_label.typ = ait_label) and
  7341. (tai_label(p_label).labsym.getrefs = 1) and
  7342. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7343. GetNextInstruction(p_label, p_dist) and
  7344. MatchInstruction(p_dist, A_SETcc, []) and
  7345. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7346. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7347. begin
  7348. TransferUsedRegs(TmpUsedRegs);
  7349. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7350. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7351. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7352. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7353. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7354. { Get the instruction after the SETcc instruction so we can
  7355. allocate a new register over the entire range }
  7356. GetNextInstruction(p_dist, hp1_dist) then
  7357. begin
  7358. { Register can appear in p if it's not used afterwards, so only
  7359. allocate between hp1 and hp1_dist }
  7360. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7361. if NewReg <> NR_NO then
  7362. begin
  7363. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7364. { Change the jump instruction into a SETcc instruction }
  7365. taicpu(hp1).opcode := A_SETcc;
  7366. taicpu(hp1).opsize := S_B;
  7367. taicpu(hp1).loadreg(0, NewReg);
  7368. { This is now a dead label }
  7369. tai_label(p_label).labsym.decrefs;
  7370. { Prefer adding before the next instruction so the FLAGS
  7371. register is deallicated first }
  7372. AsmL.InsertBefore(
  7373. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7374. hp1_dist
  7375. );
  7376. Result := True;
  7377. { Don't exit yet, as p wasn't changed and hp1, while
  7378. modified, is still intact and might be optimised by the
  7379. SETcc optimisation below }
  7380. end;
  7381. end;
  7382. end;
  7383. end;
  7384. if taicpu(p).oper[0]^.typ = top_const then
  7385. begin
  7386. if (taicpu(p).oper[0]^.val = 0) and
  7387. (taicpu(p).oper[1]^.typ = top_reg) and
  7388. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7389. begin
  7390. hp2 := p;
  7391. FirstMatch := True;
  7392. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7393. anything meaningful once it's converted to "test %reg,%reg";
  7394. additionally, some jumps will always (or never) branch, so
  7395. evaluate every jump immediately following the
  7396. comparison, optimising the conditions if possible.
  7397. Similarly with SETcc... those that are always set to 0 or 1
  7398. are changed to MOV instructions }
  7399. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7400. (
  7401. GetNextInstruction(hp2, hp1) and
  7402. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7403. ) do
  7404. begin
  7405. FirstMatch := False;
  7406. case taicpu(hp1).condition of
  7407. C_B, C_C, C_NAE, C_O:
  7408. { For B/NAE:
  7409. Will never branch since an unsigned integer can never be below zero
  7410. For C/O:
  7411. Result cannot overflow because 0 is being subtracted
  7412. }
  7413. begin
  7414. if taicpu(hp1).opcode = A_Jcc then
  7415. begin
  7416. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7417. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7418. RemoveInstruction(hp1);
  7419. { Since hp1 was deleted, hp2 must not be updated }
  7420. Continue;
  7421. end
  7422. else
  7423. begin
  7424. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7425. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7426. taicpu(hp1).opcode := A_MOV;
  7427. taicpu(hp1).ops := 2;
  7428. taicpu(hp1).condition := C_None;
  7429. taicpu(hp1).opsize := S_B;
  7430. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7431. taicpu(hp1).loadconst(0, 0);
  7432. end;
  7433. end;
  7434. C_BE, C_NA:
  7435. begin
  7436. { Will only branch if equal to zero }
  7437. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7438. taicpu(hp1).condition := C_E;
  7439. end;
  7440. C_A, C_NBE:
  7441. begin
  7442. { Will only branch if not equal to zero }
  7443. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7444. taicpu(hp1).condition := C_NE;
  7445. end;
  7446. C_AE, C_NB, C_NC, C_NO:
  7447. begin
  7448. { Will always branch }
  7449. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7450. if taicpu(hp1).opcode = A_Jcc then
  7451. begin
  7452. MakeUnconditional(taicpu(hp1));
  7453. { Any jumps/set that follow will now be dead code }
  7454. RemoveDeadCodeAfterJump(taicpu(hp1));
  7455. Break;
  7456. end
  7457. else
  7458. begin
  7459. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7460. taicpu(hp1).opcode := A_MOV;
  7461. taicpu(hp1).ops := 2;
  7462. taicpu(hp1).condition := C_None;
  7463. taicpu(hp1).opsize := S_B;
  7464. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7465. taicpu(hp1).loadconst(0, 1);
  7466. end;
  7467. end;
  7468. C_None:
  7469. InternalError(2020012201);
  7470. C_P, C_PE, C_NP, C_PO:
  7471. { We can't handle parity checks and they should never be generated
  7472. after a general-purpose CMP (it's used in some floating-point
  7473. comparisons that don't use CMP) }
  7474. InternalError(2020012202);
  7475. else
  7476. { Zero/Equality, Sign, their complements and all of the
  7477. signed comparisons do not need to be converted };
  7478. end;
  7479. hp2 := hp1;
  7480. end;
  7481. { Convert the instruction to a TEST }
  7482. taicpu(p).opcode := A_TEST;
  7483. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7484. Result := True;
  7485. Exit;
  7486. end
  7487. else if (taicpu(p).oper[0]^.val = 1) and
  7488. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7489. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7490. begin
  7491. { Convert; To:
  7492. cmp $1,r/m cmp $0,r/m
  7493. jl @lbl jle @lbl
  7494. (Also do inverted conditions)
  7495. }
  7496. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7497. taicpu(p).oper[0]^.val := 0;
  7498. if taicpu(hp1).condition in [C_L, C_NGE] then
  7499. taicpu(hp1).condition := C_LE
  7500. else
  7501. taicpu(hp1).condition := C_NLE;
  7502. { If the instruction is now "cmp $0,%reg", convert it to a
  7503. TEST (and effectively do the work of the "cmp $0,%reg" in
  7504. the block above)
  7505. }
  7506. if (taicpu(p).oper[1]^.typ = top_reg) then
  7507. begin
  7508. taicpu(p).opcode := A_TEST;
  7509. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7510. end;
  7511. Result := True;
  7512. Exit;
  7513. end
  7514. else if (taicpu(p).oper[1]^.typ = top_reg)
  7515. {$ifdef x86_64}
  7516. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7517. {$endif x86_64}
  7518. then
  7519. begin
  7520. { cmp register,$8000 neg register
  7521. je target --> jo target
  7522. .... only if register is deallocated before jump.}
  7523. case Taicpu(p).opsize of
  7524. S_B: v:=$80;
  7525. S_W: v:=$8000;
  7526. S_L: v:=qword($80000000);
  7527. else
  7528. internalerror(2013112905);
  7529. end;
  7530. if (taicpu(p).oper[0]^.val=v) and
  7531. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7532. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7533. begin
  7534. TransferUsedRegs(TmpUsedRegs);
  7535. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7536. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7537. begin
  7538. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7539. Taicpu(p).opcode:=A_NEG;
  7540. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7541. Taicpu(p).clearop(1);
  7542. Taicpu(p).ops:=1;
  7543. if Taicpu(hp1).condition=C_E then
  7544. Taicpu(hp1).condition:=C_O
  7545. else
  7546. Taicpu(hp1).condition:=C_NO;
  7547. Result:=true;
  7548. exit;
  7549. end;
  7550. end;
  7551. end;
  7552. end;
  7553. if TrySwapMovCmp(p, hp1) then
  7554. begin
  7555. Result := True;
  7556. Exit;
  7557. end;
  7558. end;
  7559. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7560. var
  7561. hp1: tai;
  7562. begin
  7563. {
  7564. remove the second (v)pxor from
  7565. pxor reg,reg
  7566. ...
  7567. pxor reg,reg
  7568. }
  7569. Result:=false;
  7570. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7571. MatchOpType(taicpu(p),top_reg,top_reg) and
  7572. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7573. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7574. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7575. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7576. begin
  7577. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7578. RemoveInstruction(hp1);
  7579. Result:=true;
  7580. Exit;
  7581. end
  7582. {
  7583. replace
  7584. pxor reg1,reg1
  7585. movapd/s reg1,reg2
  7586. dealloc reg1
  7587. by
  7588. pxor reg2,reg2
  7589. }
  7590. else if GetNextInstruction(p,hp1) and
  7591. { we mix single and double opperations here because we assume that the compiler
  7592. generates vmovapd only after double operations and vmovaps only after single operations }
  7593. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7594. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7595. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7596. (taicpu(p).oper[0]^.typ=top_reg) then
  7597. begin
  7598. TransferUsedRegs(TmpUsedRegs);
  7599. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7600. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7601. begin
  7602. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7603. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7604. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7605. RemoveInstruction(hp1);
  7606. result:=true;
  7607. end;
  7608. end;
  7609. end;
  7610. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7611. var
  7612. hp1: tai;
  7613. begin
  7614. {
  7615. remove the second (v)pxor from
  7616. (v)pxor reg,reg
  7617. ...
  7618. (v)pxor reg,reg
  7619. }
  7620. Result:=false;
  7621. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7622. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7623. begin
  7624. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7625. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7626. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7627. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7628. begin
  7629. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7630. RemoveInstruction(hp1);
  7631. Result:=true;
  7632. Exit;
  7633. end;
  7634. {$ifdef x86_64}
  7635. {
  7636. replace
  7637. vpxor reg1,reg1,reg1
  7638. vmov reg,mem
  7639. by
  7640. movq $0,mem
  7641. }
  7642. if GetNextInstruction(p,hp1) and
  7643. MatchInstruction(hp1,A_VMOVSD,[]) and
  7644. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7645. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7646. begin
  7647. TransferUsedRegs(TmpUsedRegs);
  7648. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7649. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7650. begin
  7651. taicpu(hp1).loadconst(0,0);
  7652. taicpu(hp1).opcode:=A_MOV;
  7653. taicpu(hp1).opsize:=S_Q;
  7654. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7655. RemoveCurrentP(p);
  7656. result:=true;
  7657. Exit;
  7658. end;
  7659. end;
  7660. {$endif x86_64}
  7661. end
  7662. {
  7663. replace
  7664. vpxor reg1,reg1,reg2
  7665. by
  7666. vpxor reg2,reg2,reg2
  7667. to avoid unncessary data dependencies
  7668. }
  7669. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7670. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7671. begin
  7672. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7673. { avoid unncessary data dependency }
  7674. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7675. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7676. result:=true;
  7677. exit;
  7678. end;
  7679. Result:=OptPass1VOP(p);
  7680. end;
  7681. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7682. var
  7683. hp1 : tai;
  7684. begin
  7685. result:=false;
  7686. { replace
  7687. IMul const,%mreg1,%mreg2
  7688. Mov %reg2,%mreg3
  7689. dealloc %mreg3
  7690. by
  7691. Imul const,%mreg1,%mreg23
  7692. }
  7693. if (taicpu(p).ops=3) and
  7694. GetNextInstruction(p,hp1) and
  7695. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7696. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7697. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7698. begin
  7699. TransferUsedRegs(TmpUsedRegs);
  7700. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7701. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7702. begin
  7703. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7704. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7705. RemoveInstruction(hp1);
  7706. result:=true;
  7707. end;
  7708. end;
  7709. end;
  7710. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7711. var
  7712. hp1 : tai;
  7713. begin
  7714. result:=false;
  7715. { replace
  7716. IMul %reg0,%reg1,%reg2
  7717. Mov %reg2,%reg3
  7718. dealloc %reg2
  7719. by
  7720. Imul %reg0,%reg1,%reg3
  7721. }
  7722. if GetNextInstruction(p,hp1) and
  7723. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7724. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7725. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7726. begin
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7729. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7730. begin
  7731. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7732. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7733. RemoveInstruction(hp1);
  7734. result:=true;
  7735. end;
  7736. end;
  7737. end;
  7738. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7739. var
  7740. hp1: tai;
  7741. begin
  7742. Result:=false;
  7743. { get rid of
  7744. (v)cvtss2sd reg0,<reg1,>reg2
  7745. (v)cvtss2sd reg2,<reg2,>reg0
  7746. }
  7747. if GetNextInstruction(p,hp1) and
  7748. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7749. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7750. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7751. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7752. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7753. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7754. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7755. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7756. )
  7757. ) then
  7758. begin
  7759. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7760. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7761. begin
  7762. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7763. RemoveCurrentP(p);
  7764. RemoveInstruction(hp1);
  7765. end
  7766. else
  7767. begin
  7768. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7769. if taicpu(hp1).opcode=A_CVTSD2SS then
  7770. begin
  7771. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7772. taicpu(p).opcode:=A_MOVAPS;
  7773. end
  7774. else
  7775. begin
  7776. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7777. taicpu(p).opcode:=A_VMOVAPS;
  7778. end;
  7779. taicpu(p).ops:=2;
  7780. RemoveInstruction(hp1);
  7781. end;
  7782. Result:=true;
  7783. Exit;
  7784. end;
  7785. end;
  7786. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7787. var
  7788. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7789. ThisReg: TRegister;
  7790. begin
  7791. Result := False;
  7792. if not GetNextInstruction(p,hp1) then
  7793. Exit;
  7794. {
  7795. convert
  7796. j<c> .L1
  7797. mov 1,reg
  7798. jmp .L2
  7799. .L1
  7800. mov 0,reg
  7801. .L2
  7802. into
  7803. mov 0,reg
  7804. set<not(c)> reg
  7805. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7806. would destroy the flag contents
  7807. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7808. executed at the same time as a previous comparison.
  7809. set<not(c)> reg
  7810. movzx reg, reg
  7811. }
  7812. if MatchInstruction(hp1,A_MOV,[]) and
  7813. (taicpu(hp1).oper[0]^.typ = top_const) and
  7814. (
  7815. (
  7816. (taicpu(hp1).oper[1]^.typ = top_reg)
  7817. {$ifdef i386}
  7818. { Under i386, ESI, EDI, EBP and ESP
  7819. don't have an 8-bit representation }
  7820. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7821. {$endif i386}
  7822. ) or (
  7823. {$ifdef i386}
  7824. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7825. {$endif i386}
  7826. (taicpu(hp1).opsize = S_B)
  7827. )
  7828. ) and
  7829. GetNextInstruction(hp1,hp2) and
  7830. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7831. GetNextInstruction(hp2,hp3) and
  7832. (hp3.typ=ait_label) and
  7833. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7834. GetNextInstruction(hp3,hp4) and
  7835. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7836. (taicpu(hp4).oper[0]^.typ = top_const) and
  7837. (
  7838. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7839. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7840. ) and
  7841. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7842. GetNextInstruction(hp4,hp5) and
  7843. (hp5.typ=ait_label) and
  7844. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7845. begin
  7846. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7847. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7848. tai_label(hp3).labsym.DecRefs;
  7849. { If this isn't the only reference to the middle label, we can
  7850. still make a saving - only that the first jump and everything
  7851. that follows will remain. }
  7852. if (tai_label(hp3).labsym.getrefs = 0) then
  7853. begin
  7854. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7855. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7856. else
  7857. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7858. { remove jump, first label and second MOV (also catching any aligns) }
  7859. repeat
  7860. if not GetNextInstruction(hp2, hp3) then
  7861. InternalError(2021040810);
  7862. RemoveInstruction(hp2);
  7863. hp2 := hp3;
  7864. until hp2 = hp5;
  7865. { Don't decrement reference count before the removal loop
  7866. above, otherwise GetNextInstruction won't stop on the
  7867. the label }
  7868. tai_label(hp5).labsym.DecRefs;
  7869. end
  7870. else
  7871. begin
  7872. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7873. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7874. else
  7875. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7876. end;
  7877. taicpu(p).opcode:=A_SETcc;
  7878. taicpu(p).opsize:=S_B;
  7879. taicpu(p).is_jmp:=False;
  7880. if taicpu(hp1).opsize=S_B then
  7881. begin
  7882. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7883. if taicpu(hp1).oper[1]^.typ = top_reg then
  7884. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7885. RemoveInstruction(hp1);
  7886. end
  7887. else
  7888. begin
  7889. { Will be a register because the size can't be S_B otherwise }
  7890. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7891. taicpu(p).loadreg(0, ThisReg);
  7892. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7893. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7894. begin
  7895. case taicpu(hp1).opsize of
  7896. S_W:
  7897. taicpu(hp1).opsize := S_BW;
  7898. S_L:
  7899. taicpu(hp1).opsize := S_BL;
  7900. {$ifdef x86_64}
  7901. S_Q:
  7902. begin
  7903. taicpu(hp1).opsize := S_BL;
  7904. { Change the destination register to 32-bit }
  7905. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7906. end;
  7907. {$endif x86_64}
  7908. else
  7909. InternalError(2021040820);
  7910. end;
  7911. taicpu(hp1).opcode := A_MOVZX;
  7912. taicpu(hp1).loadreg(0, ThisReg);
  7913. end
  7914. else
  7915. begin
  7916. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7917. { hp1 is already a MOV instruction with the correct register }
  7918. taicpu(hp1).loadconst(0, 0);
  7919. { Inserting it right before p will guarantee that the flags are also tracked }
  7920. asml.Remove(hp1);
  7921. asml.InsertBefore(hp1, p);
  7922. end;
  7923. end;
  7924. Result:=true;
  7925. exit;
  7926. end
  7927. else if (hp1.typ = ait_label) then
  7928. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7929. end;
  7930. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7931. var
  7932. hp1, hp2, hp3: tai;
  7933. SourceRef, TargetRef: TReference;
  7934. CurrentReg: TRegister;
  7935. begin
  7936. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7937. if not UseAVX then
  7938. InternalError(2021100501);
  7939. Result := False;
  7940. { Look for the following to simplify:
  7941. vmovdqa/u x(mem1), %xmmreg
  7942. vmovdqa/u %xmmreg, y(mem2)
  7943. vmovdqa/u x+16(mem1), %xmmreg
  7944. vmovdqa/u %xmmreg, y+16(mem2)
  7945. Change to:
  7946. vmovdqa/u x(mem1), %ymmreg
  7947. vmovdqa/u %ymmreg, y(mem2)
  7948. vpxor %ymmreg, %ymmreg, %ymmreg
  7949. ( The VPXOR instruction is to zero the upper half, thus removing the
  7950. need to call the potentially expensive VZEROUPPER instruction. Other
  7951. peephole optimisations can remove VPXOR if it's unnecessary )
  7952. }
  7953. TransferUsedRegs(TmpUsedRegs);
  7954. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7955. { NOTE: In the optimisations below, if the references dictate that an
  7956. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7957. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7958. if (taicpu(p).opsize = S_XMM) and
  7959. MatchOpType(taicpu(p), top_ref, top_reg) and
  7960. GetNextInstruction(p, hp1) and
  7961. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7962. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7963. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7964. begin
  7965. SourceRef := taicpu(p).oper[0]^.ref^;
  7966. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7967. if GetNextInstruction(hp1, hp2) and
  7968. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7969. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7970. begin
  7971. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7972. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7973. Inc(SourceRef.offset, 16);
  7974. { Reuse the register in the first block move }
  7975. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7976. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7977. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7978. begin
  7979. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7980. Inc(TargetRef.offset, 16);
  7981. if GetNextInstruction(hp2, hp3) and
  7982. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7983. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7984. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7985. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7986. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7987. begin
  7988. { Update the register tracking to the new size }
  7989. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7990. { Remember that the offsets are 16 ahead }
  7991. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7992. if not (
  7993. ((SourceRef.offset mod 32) = 16) and
  7994. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7995. ) then
  7996. taicpu(p).opcode := A_VMOVDQU;
  7997. taicpu(p).opsize := S_YMM;
  7998. taicpu(p).oper[1]^.reg := CurrentReg;
  7999. if not (
  8000. ((TargetRef.offset mod 32) = 16) and
  8001. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8002. ) then
  8003. taicpu(hp1).opcode := A_VMOVDQU;
  8004. taicpu(hp1).opsize := S_YMM;
  8005. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8006. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8007. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8008. if (pi_uses_ymm in current_procinfo.flags) then
  8009. RemoveInstruction(hp2)
  8010. else
  8011. begin
  8012. taicpu(hp2).opcode := A_VPXOR;
  8013. taicpu(hp2).opsize := S_YMM;
  8014. taicpu(hp2).loadreg(0, CurrentReg);
  8015. taicpu(hp2).loadreg(1, CurrentReg);
  8016. taicpu(hp2).loadreg(2, CurrentReg);
  8017. taicpu(hp2).ops := 3;
  8018. end;
  8019. RemoveInstruction(hp3);
  8020. Result := True;
  8021. Exit;
  8022. end;
  8023. end
  8024. else
  8025. begin
  8026. { See if the next references are 16 less rather than 16 greater }
  8027. Dec(SourceRef.offset, 32); { -16 the other way }
  8028. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8029. begin
  8030. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8031. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8032. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8033. GetNextInstruction(hp2, hp3) and
  8034. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8035. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8036. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8037. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8038. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8039. begin
  8040. { Update the register tracking to the new size }
  8041. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8042. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8043. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8044. if not(
  8045. ((SourceRef.offset mod 32) = 0) and
  8046. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8047. ) then
  8048. taicpu(hp2).opcode := A_VMOVDQU;
  8049. taicpu(hp2).opsize := S_YMM;
  8050. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8051. if not (
  8052. ((TargetRef.offset mod 32) = 0) and
  8053. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8054. ) then
  8055. taicpu(hp3).opcode := A_VMOVDQU;
  8056. taicpu(hp3).opsize := S_YMM;
  8057. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8058. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8059. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8060. if (pi_uses_ymm in current_procinfo.flags) then
  8061. RemoveInstruction(hp1)
  8062. else
  8063. begin
  8064. taicpu(hp1).opcode := A_VPXOR;
  8065. taicpu(hp1).opsize := S_YMM;
  8066. taicpu(hp1).loadreg(0, CurrentReg);
  8067. taicpu(hp1).loadreg(1, CurrentReg);
  8068. taicpu(hp1).loadreg(2, CurrentReg);
  8069. taicpu(hp1).ops := 3;
  8070. Asml.Remove(hp1);
  8071. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8072. end;
  8073. RemoveCurrentP(p, hp2);
  8074. Result := True;
  8075. Exit;
  8076. end;
  8077. end;
  8078. end;
  8079. end;
  8080. end;
  8081. end;
  8082. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8083. var
  8084. hp2, hp3, first_assignment: tai;
  8085. IncCount, OperIdx: Integer;
  8086. OrigLabel: TAsmLabel;
  8087. begin
  8088. Count := 0;
  8089. Result := False;
  8090. first_assignment := nil;
  8091. if (LoopCount >= 20) then
  8092. begin
  8093. { Guard against infinite loops }
  8094. Exit;
  8095. end;
  8096. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8097. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8098. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8099. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8100. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8101. Exit;
  8102. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8103. {
  8104. change
  8105. jmp .L1
  8106. ...
  8107. .L1:
  8108. mov ##, ## ( multiple movs possible )
  8109. jmp/ret
  8110. into
  8111. mov ##, ##
  8112. jmp/ret
  8113. }
  8114. if not Assigned(hp1) then
  8115. begin
  8116. hp1 := GetLabelWithSym(OrigLabel);
  8117. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8118. Exit;
  8119. end;
  8120. hp2 := hp1;
  8121. while Assigned(hp2) do
  8122. begin
  8123. if Assigned(hp2) and (hp2.typ = ait_label) then
  8124. SkipLabels(hp2,hp2);
  8125. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8126. Break;
  8127. case taicpu(hp2).opcode of
  8128. A_MOVSD:
  8129. begin
  8130. if taicpu(hp2).ops = 0 then
  8131. { Wrong MOVSD }
  8132. Break;
  8133. Inc(Count);
  8134. if Count >= 5 then
  8135. { Too many to be worthwhile }
  8136. Break;
  8137. GetNextInstruction(hp2, hp2);
  8138. Continue;
  8139. end;
  8140. A_MOV,
  8141. A_MOVD,
  8142. A_MOVQ,
  8143. A_MOVSX,
  8144. {$ifdef x86_64}
  8145. A_MOVSXD,
  8146. {$endif x86_64}
  8147. A_MOVZX,
  8148. A_MOVAPS,
  8149. A_MOVUPS,
  8150. A_MOVSS,
  8151. A_MOVAPD,
  8152. A_MOVUPD,
  8153. A_MOVDQA,
  8154. A_MOVDQU,
  8155. A_VMOVSS,
  8156. A_VMOVAPS,
  8157. A_VMOVUPS,
  8158. A_VMOVSD,
  8159. A_VMOVAPD,
  8160. A_VMOVUPD,
  8161. A_VMOVDQA,
  8162. A_VMOVDQU:
  8163. begin
  8164. Inc(Count);
  8165. if Count >= 5 then
  8166. { Too many to be worthwhile }
  8167. Break;
  8168. GetNextInstruction(hp2, hp2);
  8169. Continue;
  8170. end;
  8171. A_JMP:
  8172. begin
  8173. { Guard against infinite loops }
  8174. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8175. Exit;
  8176. { Analyse this jump first in case it also duplicates assignments }
  8177. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8178. begin
  8179. { Something did change! }
  8180. Result := True;
  8181. Inc(Count, IncCount);
  8182. if Count >= 5 then
  8183. begin
  8184. { Too many to be worthwhile }
  8185. Exit;
  8186. end;
  8187. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8188. Break;
  8189. end;
  8190. Result := True;
  8191. Break;
  8192. end;
  8193. A_RET:
  8194. begin
  8195. Result := True;
  8196. Break;
  8197. end;
  8198. else
  8199. Break;
  8200. end;
  8201. end;
  8202. if Result then
  8203. begin
  8204. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8205. if Count = 0 then
  8206. begin
  8207. Result := False;
  8208. Exit;
  8209. end;
  8210. hp3 := p;
  8211. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8212. while True do
  8213. begin
  8214. if Assigned(hp1) and (hp1.typ = ait_label) then
  8215. SkipLabels(hp1,hp1);
  8216. if (hp1.typ <> ait_instruction) then
  8217. InternalError(2021040720);
  8218. case taicpu(hp1).opcode of
  8219. A_JMP:
  8220. begin
  8221. { Change the original jump to the new destination }
  8222. OrigLabel.decrefs;
  8223. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8224. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8225. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8226. if not Assigned(first_assignment) then
  8227. InternalError(2021040810)
  8228. else
  8229. p := first_assignment;
  8230. Exit;
  8231. end;
  8232. A_RET:
  8233. begin
  8234. { Now change the jump into a RET instruction }
  8235. ConvertJumpToRET(p, hp1);
  8236. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8237. if not Assigned(first_assignment) then
  8238. InternalError(2021040811)
  8239. else
  8240. p := first_assignment;
  8241. Exit;
  8242. end;
  8243. else
  8244. begin
  8245. { Duplicate the MOV instruction }
  8246. hp3:=tai(hp1.getcopy);
  8247. if first_assignment = nil then
  8248. first_assignment := hp3;
  8249. asml.InsertBefore(hp3, p);
  8250. { Make sure the compiler knows about any final registers written here }
  8251. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8252. with taicpu(hp3).oper[OperIdx]^ do
  8253. begin
  8254. case typ of
  8255. top_ref:
  8256. begin
  8257. if (ref^.base <> NR_NO) and
  8258. (getsupreg(ref^.base) <> RS_ESP) and
  8259. (getsupreg(ref^.base) <> RS_EBP)
  8260. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8261. then
  8262. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8263. if (ref^.index <> NR_NO) and
  8264. (getsupreg(ref^.index) <> RS_ESP) and
  8265. (getsupreg(ref^.index) <> RS_EBP)
  8266. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8267. (ref^.index <> ref^.base) then
  8268. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8269. end;
  8270. top_reg:
  8271. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8272. else
  8273. ;
  8274. end;
  8275. end;
  8276. end;
  8277. end;
  8278. if not GetNextInstruction(hp1, hp1) then
  8279. { Should have dropped out earlier }
  8280. InternalError(2021040710);
  8281. end;
  8282. end;
  8283. end;
  8284. const
  8285. WriteOp: array[0..3] of set of TInsChange = (
  8286. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8287. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8288. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8289. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8290. RegWriteFlags: array[0..7] of set of TInsChange = (
  8291. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8292. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8293. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8294. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8295. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8296. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8297. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8298. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8299. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8300. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8301. var
  8302. hp2: tai;
  8303. X: Integer;
  8304. begin
  8305. { If we have something like:
  8306. op ###,###
  8307. mov ###,###
  8308. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8309. interfere in regards to what they write to.
  8310. NOTE: p must be a 2-operand instruction
  8311. }
  8312. Result := False;
  8313. if (hp1.typ <> ait_instruction) or
  8314. taicpu(hp1).is_jmp or
  8315. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8316. Exit;
  8317. { NOP is a pipeline fence, likely marking the beginning of the function
  8318. epilogue, so drop out. Similarly, drop out if POP or RET are
  8319. encountered }
  8320. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8321. Exit;
  8322. if (taicpu(hp1).opcode = A_MOVSD) and
  8323. (taicpu(hp1).ops = 0) then
  8324. { Wrong MOVSD }
  8325. Exit;
  8326. { Check for writes to specific registers first }
  8327. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8328. for X := 0 to 7 do
  8329. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8330. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8331. Exit;
  8332. for X := 0 to taicpu(hp1).ops - 1 do
  8333. begin
  8334. { Check to see if this operand writes to something }
  8335. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8336. { And matches something in the CMP/TEST instruction }
  8337. (
  8338. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8339. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8340. (
  8341. { If it's a register, make sure the register written to doesn't
  8342. appear in the cmp instruction as part of a reference }
  8343. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8344. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8345. )
  8346. ) then
  8347. Exit;
  8348. end;
  8349. { Check p to make sure it doesn't write to something that affects hp1 }
  8350. { Check for writes to specific registers first }
  8351. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8352. for X := 0 to 7 do
  8353. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8354. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8355. Exit;
  8356. for X := 0 to taicpu(p).ops - 1 do
  8357. begin
  8358. { Check to see if this operand writes to something }
  8359. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8360. { And matches something in hp1 }
  8361. (taicpu(p).oper[X]^.typ = top_reg) and
  8362. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8363. Exit;
  8364. end;
  8365. { The instruction can be safely moved }
  8366. asml.Remove(hp1);
  8367. { Try to insert after the last instructions where the FLAGS register is not
  8368. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8369. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8370. asml.InsertBefore(hp1, hp2)
  8371. { Failing that, try to insert after the last instructions where the
  8372. FLAGS register is not yet in use }
  8373. else if GetLastInstruction(p, hp2) and
  8374. (
  8375. (hp2.typ <> ait_instruction) or
  8376. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8377. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8378. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8379. ) then
  8380. asml.InsertAfter(hp1, hp2)
  8381. else
  8382. { Note, if p.Previous is nil (even if it should logically never be the
  8383. case), FindRegAllocBackward immediately exits with False and so we
  8384. safely land here (we can't just pass p because FindRegAllocBackward
  8385. immediately exits on an instruction). [Kit] }
  8386. asml.InsertBefore(hp1, p);
  8387. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8388. { We can't trust UsedRegs because we're looking backwards, although we
  8389. know the registers are allocated after p at the very least, so manually
  8390. create tai_regalloc objects if needed }
  8391. for X := 0 to taicpu(hp1).ops - 1 do
  8392. case taicpu(hp1).oper[X]^.typ of
  8393. top_reg:
  8394. begin
  8395. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8396. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8397. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8398. end;
  8399. top_ref:
  8400. begin
  8401. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8402. begin
  8403. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8404. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8405. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8406. end;
  8407. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8408. begin
  8409. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8410. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8411. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8412. end;
  8413. end;
  8414. else
  8415. ;
  8416. end;
  8417. Result := True;
  8418. end;
  8419. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8420. var
  8421. hp2: tai;
  8422. X: Integer;
  8423. begin
  8424. { If we have something like:
  8425. cmp ###,%reg1
  8426. mov 0,%reg2
  8427. And no modified registers are shared, move the instruction to before
  8428. the comparison as this means it can be optimised without worrying
  8429. about the FLAGS register. (CMP/MOV is generated by
  8430. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8431. As long as the second instruction doesn't use the flags or one of the
  8432. registers used by CMP or TEST (also check any references that use the
  8433. registers), then it can be moved prior to the comparison.
  8434. }
  8435. Result := False;
  8436. if not TrySwapMovOp(p, hp1) then
  8437. Exit;
  8438. if taicpu(hp1).opcode = A_LEA then
  8439. { The flags will be overwritten by the CMP/TEST instruction }
  8440. ConvertLEA(taicpu(hp1));
  8441. Result := True;
  8442. { Can we move it one further back? }
  8443. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8444. { Check to see if CMP/TEST is a comparison against zero }
  8445. (
  8446. (
  8447. (taicpu(p).opcode = A_CMP) and
  8448. MatchOperand(taicpu(p).oper[0]^, 0)
  8449. ) or
  8450. (
  8451. (taicpu(p).opcode = A_TEST) and
  8452. (
  8453. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8454. MatchOperand(taicpu(p).oper[0]^, -1)
  8455. )
  8456. )
  8457. ) and
  8458. { These instructions set the zero flag if the result is zero }
  8459. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8460. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8461. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8462. TrySwapMovOp(hp2, hp1);
  8463. end;
  8464. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8465. function IsXCHGAcceptable: Boolean; inline;
  8466. begin
  8467. { Always accept if optimising for size }
  8468. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8469. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8470. than 3, so it becomes a saving compared to three MOVs with two of
  8471. them able to execute simultaneously. [Kit] }
  8472. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8473. end;
  8474. var
  8475. NewRef: TReference;
  8476. hp1, hp2, hp3, hp4: Tai;
  8477. {$ifndef x86_64}
  8478. OperIdx: Integer;
  8479. {$endif x86_64}
  8480. NewInstr : Taicpu;
  8481. NewAligh : Tai_align;
  8482. DestLabel: TAsmLabel;
  8483. TempTracking: TAllUsedRegs;
  8484. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8485. var
  8486. NextInstr: tai;
  8487. begin
  8488. Result := False;
  8489. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8490. if not GetNextInstruction(InputInstr, NextInstr) or
  8491. (
  8492. { The FLAGS register isn't always tracked properly, so do not
  8493. perform this optimisation if a conditional statement follows }
  8494. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8495. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8496. ) then
  8497. begin
  8498. reference_reset(NewRef, 1, []);
  8499. NewRef.base := taicpu(p).oper[0]^.reg;
  8500. NewRef.scalefactor := 1;
  8501. if taicpu(InputInstr).opcode = A_ADD then
  8502. begin
  8503. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8504. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8505. end
  8506. else
  8507. begin
  8508. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8509. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8510. end;
  8511. taicpu(p).opcode := A_LEA;
  8512. taicpu(p).loadref(0, NewRef);
  8513. RemoveInstruction(InputInstr);
  8514. Result := True;
  8515. end;
  8516. end;
  8517. begin
  8518. Result:=false;
  8519. { This optimisation adds an instruction, so only do it for speed }
  8520. if not (cs_opt_size in current_settings.optimizerswitches) and
  8521. MatchOpType(taicpu(p), top_const, top_reg) and
  8522. (taicpu(p).oper[0]^.val = 0) then
  8523. begin
  8524. { To avoid compiler warning }
  8525. DestLabel := nil;
  8526. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8527. InternalError(2021040750);
  8528. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8529. Exit;
  8530. case hp1.typ of
  8531. ait_label:
  8532. begin
  8533. { Change:
  8534. mov $0,%reg mov $0,%reg
  8535. @Lbl1: @Lbl1:
  8536. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8537. je @Lbl2 jne @Lbl2
  8538. To: To:
  8539. mov $0,%reg mov $0,%reg
  8540. jmp @Lbl2 jmp @Lbl3
  8541. (align) (align)
  8542. @Lbl1: @Lbl1:
  8543. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8544. je @Lbl2 je @Lbl2
  8545. @Lbl3: <-- Only if label exists
  8546. (Not if it's optimised for size)
  8547. }
  8548. if not GetNextInstruction(hp1, hp2) then
  8549. Exit;
  8550. if (hp2.typ = ait_instruction) and
  8551. (
  8552. { Register sizes must exactly match }
  8553. (
  8554. (taicpu(hp2).opcode = A_CMP) and
  8555. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8556. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8557. ) or (
  8558. (taicpu(hp2).opcode = A_TEST) and
  8559. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8560. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8561. )
  8562. ) and GetNextInstruction(hp2, hp3) and
  8563. (hp3.typ = ait_instruction) and
  8564. (taicpu(hp3).opcode = A_JCC) and
  8565. (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
  8566. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8567. begin
  8568. { Check condition of jump }
  8569. { Always true? }
  8570. if condition_in(C_E, taicpu(hp3).condition) then
  8571. begin
  8572. { Copy label symbol and obtain matching label entry for the
  8573. conditional jump, as this will be our destination}
  8574. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8575. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8576. Result := True;
  8577. end
  8578. { Always false? }
  8579. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8580. begin
  8581. { This is only worth it if there's a jump to take }
  8582. case hp2.typ of
  8583. ait_instruction:
  8584. begin
  8585. if taicpu(hp2).opcode = A_JMP then
  8586. begin
  8587. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8588. { An unconditional jump follows the conditional jump which will always be false,
  8589. so use this jump's destination for the new jump }
  8590. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8591. Result := True;
  8592. end
  8593. else if taicpu(hp2).opcode = A_JCC then
  8594. begin
  8595. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8596. if condition_in(C_E, taicpu(hp2).condition) then
  8597. begin
  8598. { A second conditional jump follows the conditional jump which will always be false,
  8599. while the second jump is always True, so use this jump's destination for the new jump }
  8600. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8601. Result := True;
  8602. end;
  8603. { Don't risk it if the jump isn't always true (Result remains False) }
  8604. end;
  8605. end;
  8606. else
  8607. { If anything else don't optimise };
  8608. end;
  8609. end;
  8610. if Result then
  8611. begin
  8612. { Just so we have something to insert as a paremeter}
  8613. reference_reset(NewRef, 1, []);
  8614. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8615. { Now actually load the correct parameter (this also
  8616. increases the reference count) }
  8617. NewInstr.loadsymbol(0, DestLabel, 0);
  8618. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8619. begin
  8620. { Get instruction before original label (may not be p under -O3) }
  8621. if not GetLastInstruction(hp1, hp2) then
  8622. { Shouldn't fail here }
  8623. InternalError(2021040701);
  8624. end
  8625. else
  8626. hp2 := p;
  8627. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8628. AsmL.InsertAfter(NewInstr, hp2);
  8629. { Add new alignment field }
  8630. (* AsmL.InsertAfter(
  8631. cai_align.create_max(
  8632. current_settings.alignment.jumpalign,
  8633. current_settings.alignment.jumpalignskipmax
  8634. ),
  8635. NewInstr
  8636. ); *)
  8637. end;
  8638. Exit;
  8639. end;
  8640. end;
  8641. else
  8642. ;
  8643. end;
  8644. end;
  8645. if not GetNextInstruction(p, hp1) then
  8646. Exit;
  8647. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8648. and DoMovCmpMemOpt(p, hp1) then
  8649. begin
  8650. Result := True;
  8651. Exit;
  8652. end
  8653. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8654. begin
  8655. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8656. further, but we can't just put this jump optimisation in pass 1
  8657. because it tends to perform worse when conditional jumps are
  8658. nearby (e.g. when converting CMOV instructions). [Kit] }
  8659. CopyUsedRegs(TempTracking);
  8660. UpdateUsedRegs(tai(p.Next));
  8661. if OptPass2JMP(hp1) then
  8662. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8663. Result := OptPass1MOV(p);
  8664. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8665. returned True and the instruction is still a MOV, thus checking
  8666. the optimisations below }
  8667. { If OptPass2JMP returned False, no optimisations were done to
  8668. the jump and there are no further optimisations that can be done
  8669. to the MOV instruction on this pass }
  8670. { Restore register state }
  8671. RestoreUsedRegs(TempTracking);
  8672. ReleaseUsedRegs(TempTracking);
  8673. end
  8674. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8675. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8676. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8677. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8678. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8679. begin
  8680. { Change:
  8681. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8682. addl/q $x,%reg2 subl/q $x,%reg2
  8683. To:
  8684. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8685. }
  8686. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8687. { be lazy, checking separately for sub would be slightly better }
  8688. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8689. begin
  8690. TransferUsedRegs(TmpUsedRegs);
  8691. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8692. if TryMovArith2Lea(hp1) then
  8693. begin
  8694. Result := True;
  8695. Exit;
  8696. end
  8697. end
  8698. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8699. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8700. { Same as above, but also adds or subtracts to %reg2 in between.
  8701. It's still valid as long as the flags aren't in use }
  8702. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8703. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8704. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8705. { be lazy, checking separately for sub would be slightly better }
  8706. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8707. begin
  8708. TransferUsedRegs(TmpUsedRegs);
  8709. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8710. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8711. if TryMovArith2Lea(hp2) then
  8712. begin
  8713. Result := True;
  8714. Exit;
  8715. end;
  8716. end;
  8717. end
  8718. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8719. {$ifdef x86_64}
  8720. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8721. {$else x86_64}
  8722. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8723. {$endif x86_64}
  8724. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8725. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8726. { mov reg1, reg2 mov reg1, reg2
  8727. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8728. begin
  8729. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8730. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8731. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8732. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8733. TransferUsedRegs(TmpUsedRegs);
  8734. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8735. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8736. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8737. then
  8738. begin
  8739. RemoveCurrentP(p, hp1);
  8740. Result:=true;
  8741. end;
  8742. exit;
  8743. end
  8744. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8745. IsXCHGAcceptable and
  8746. { XCHG doesn't support 8-byte registers }
  8747. (taicpu(p).opsize <> S_B) and
  8748. MatchInstruction(hp1, A_MOV, []) and
  8749. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8750. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8751. GetNextInstruction(hp1, hp2) and
  8752. MatchInstruction(hp2, A_MOV, []) and
  8753. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8754. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8755. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8756. begin
  8757. { mov %reg1,%reg2
  8758. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8759. mov %reg2,%reg3
  8760. (%reg2 not used afterwards)
  8761. Note that xchg takes 3 cycles to execute, and generally mov's take
  8762. only one cycle apiece, but the first two mov's can be executed in
  8763. parallel, only taking 2 cycles overall. Older processors should
  8764. therefore only optimise for size. [Kit]
  8765. }
  8766. TransferUsedRegs(TmpUsedRegs);
  8767. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8768. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8769. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8770. begin
  8771. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8772. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8773. taicpu(hp1).opcode := A_XCHG;
  8774. RemoveCurrentP(p, hp1);
  8775. RemoveInstruction(hp2);
  8776. Result := True;
  8777. Exit;
  8778. end;
  8779. end
  8780. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8781. MatchInstruction(hp1, A_SAR, []) then
  8782. begin
  8783. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8784. begin
  8785. { the use of %edx also covers the opsize being S_L }
  8786. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8787. begin
  8788. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8789. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8790. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8791. begin
  8792. { Change:
  8793. movl %eax,%edx
  8794. sarl $31,%edx
  8795. To:
  8796. cltd
  8797. }
  8798. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8799. RemoveInstruction(hp1);
  8800. taicpu(p).opcode := A_CDQ;
  8801. taicpu(p).opsize := S_NO;
  8802. taicpu(p).clearop(1);
  8803. taicpu(p).clearop(0);
  8804. taicpu(p).ops:=0;
  8805. Result := True;
  8806. end
  8807. else if (cs_opt_size in current_settings.optimizerswitches) and
  8808. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8809. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8810. begin
  8811. { Change:
  8812. movl %edx,%eax
  8813. sarl $31,%edx
  8814. To:
  8815. movl %edx,%eax
  8816. cltd
  8817. Note that this creates a dependency between the two instructions,
  8818. so only perform if optimising for size.
  8819. }
  8820. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8821. taicpu(hp1).opcode := A_CDQ;
  8822. taicpu(hp1).opsize := S_NO;
  8823. taicpu(hp1).clearop(1);
  8824. taicpu(hp1).clearop(0);
  8825. taicpu(hp1).ops:=0;
  8826. end;
  8827. {$ifndef x86_64}
  8828. end
  8829. { Don't bother if CMOV is supported, because a more optimal
  8830. sequence would have been generated for the Abs() intrinsic }
  8831. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8832. { the use of %eax also covers the opsize being S_L }
  8833. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8834. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8835. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8836. GetNextInstruction(hp1, hp2) and
  8837. MatchInstruction(hp2, A_XOR, [S_L]) and
  8838. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8839. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8840. GetNextInstruction(hp2, hp3) and
  8841. MatchInstruction(hp3, A_SUB, [S_L]) and
  8842. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8843. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8844. begin
  8845. { Change:
  8846. movl %eax,%edx
  8847. sarl $31,%eax
  8848. xorl %eax,%edx
  8849. subl %eax,%edx
  8850. (Instruction that uses %edx)
  8851. (%eax deallocated)
  8852. (%edx deallocated)
  8853. To:
  8854. cltd
  8855. xorl %edx,%eax <-- Note the registers have swapped
  8856. subl %edx,%eax
  8857. (Instruction that uses %eax) <-- %eax rather than %edx
  8858. }
  8859. TransferUsedRegs(TmpUsedRegs);
  8860. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8861. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8862. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8863. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8864. begin
  8865. if GetNextInstruction(hp3, hp4) and
  8866. not RegModifiedByInstruction(NR_EDX, hp4) and
  8867. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8868. begin
  8869. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8870. taicpu(p).opcode := A_CDQ;
  8871. taicpu(p).clearop(1);
  8872. taicpu(p).clearop(0);
  8873. taicpu(p).ops:=0;
  8874. RemoveInstruction(hp1);
  8875. taicpu(hp2).loadreg(0, NR_EDX);
  8876. taicpu(hp2).loadreg(1, NR_EAX);
  8877. taicpu(hp3).loadreg(0, NR_EDX);
  8878. taicpu(hp3).loadreg(1, NR_EAX);
  8879. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8880. { Convert references in the following instruction (hp4) from %edx to %eax }
  8881. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8882. with taicpu(hp4).oper[OperIdx]^ do
  8883. case typ of
  8884. top_reg:
  8885. if getsupreg(reg) = RS_EDX then
  8886. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8887. top_ref:
  8888. begin
  8889. if getsupreg(reg) = RS_EDX then
  8890. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8891. if getsupreg(reg) = RS_EDX then
  8892. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8893. end;
  8894. else
  8895. ;
  8896. end;
  8897. end;
  8898. end;
  8899. {$else x86_64}
  8900. end;
  8901. end
  8902. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8903. { the use of %rdx also covers the opsize being S_Q }
  8904. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8905. begin
  8906. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8907. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8908. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8909. begin
  8910. { Change:
  8911. movq %rax,%rdx
  8912. sarq $63,%rdx
  8913. To:
  8914. cqto
  8915. }
  8916. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8917. RemoveInstruction(hp1);
  8918. taicpu(p).opcode := A_CQO;
  8919. taicpu(p).opsize := S_NO;
  8920. taicpu(p).clearop(1);
  8921. taicpu(p).clearop(0);
  8922. taicpu(p).ops:=0;
  8923. Result := True;
  8924. end
  8925. else if (cs_opt_size in current_settings.optimizerswitches) and
  8926. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8927. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8928. begin
  8929. { Change:
  8930. movq %rdx,%rax
  8931. sarq $63,%rdx
  8932. To:
  8933. movq %rdx,%rax
  8934. cqto
  8935. Note that this creates a dependency between the two instructions,
  8936. so only perform if optimising for size.
  8937. }
  8938. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8939. taicpu(hp1).opcode := A_CQO;
  8940. taicpu(hp1).opsize := S_NO;
  8941. taicpu(hp1).clearop(1);
  8942. taicpu(hp1).clearop(0);
  8943. taicpu(hp1).ops:=0;
  8944. {$endif x86_64}
  8945. end;
  8946. end;
  8947. end
  8948. else if MatchInstruction(hp1, A_MOV, []) and
  8949. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8950. { Though "GetNextInstruction" could be factored out, along with
  8951. the instructions that depend on hp2, it is an expensive call that
  8952. should be delayed for as long as possible, hence we do cheaper
  8953. checks first that are likely to be False. [Kit] }
  8954. begin
  8955. if (
  8956. (
  8957. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8958. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8959. (
  8960. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8961. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8962. )
  8963. ) or
  8964. (
  8965. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8966. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8967. (
  8968. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8969. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8970. )
  8971. )
  8972. ) and
  8973. GetNextInstruction(hp1, hp2) and
  8974. MatchInstruction(hp2, A_SAR, []) and
  8975. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8976. begin
  8977. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8978. begin
  8979. { Change:
  8980. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8981. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8982. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8983. To:
  8984. movl r/m,%eax <- Note the change in register
  8985. cltd
  8986. }
  8987. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8988. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8989. taicpu(p).loadreg(1, NR_EAX);
  8990. taicpu(hp1).opcode := A_CDQ;
  8991. taicpu(hp1).clearop(1);
  8992. taicpu(hp1).clearop(0);
  8993. taicpu(hp1).ops:=0;
  8994. RemoveInstruction(hp2);
  8995. (*
  8996. {$ifdef x86_64}
  8997. end
  8998. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8999. { This code sequence does not get generated - however it might become useful
  9000. if and when 128-bit signed integer types make an appearance, so the code
  9001. is kept here for when it is eventually needed. [Kit] }
  9002. (
  9003. (
  9004. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9005. (
  9006. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9007. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9008. )
  9009. ) or
  9010. (
  9011. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9012. (
  9013. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9014. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9015. )
  9016. )
  9017. ) and
  9018. GetNextInstruction(hp1, hp2) and
  9019. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9020. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9021. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9022. begin
  9023. { Change:
  9024. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9025. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9026. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9027. To:
  9028. movq r/m,%rax <- Note the change in register
  9029. cqto
  9030. }
  9031. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9032. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9033. taicpu(p).loadreg(1, NR_RAX);
  9034. taicpu(hp1).opcode := A_CQO;
  9035. taicpu(hp1).clearop(1);
  9036. taicpu(hp1).clearop(0);
  9037. taicpu(hp1).ops:=0;
  9038. RemoveInstruction(hp2);
  9039. {$endif x86_64}
  9040. *)
  9041. end;
  9042. end;
  9043. {$ifdef x86_64}
  9044. end
  9045. else if (taicpu(p).opsize = S_L) and
  9046. (taicpu(p).oper[1]^.typ = top_reg) and
  9047. (
  9048. MatchInstruction(hp1, A_MOV,[]) and
  9049. (taicpu(hp1).opsize = S_L) and
  9050. (taicpu(hp1).oper[1]^.typ = top_reg)
  9051. ) and (
  9052. GetNextInstruction(hp1, hp2) and
  9053. (tai(hp2).typ=ait_instruction) and
  9054. (taicpu(hp2).opsize = S_Q) and
  9055. (
  9056. (
  9057. MatchInstruction(hp2, A_ADD,[]) and
  9058. (taicpu(hp2).opsize = S_Q) and
  9059. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9060. (
  9061. (
  9062. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9063. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9064. ) or (
  9065. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9066. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9067. )
  9068. )
  9069. ) or (
  9070. MatchInstruction(hp2, A_LEA,[]) and
  9071. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9072. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9073. (
  9074. (
  9075. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9076. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9077. ) or (
  9078. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9079. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9080. )
  9081. ) and (
  9082. (
  9083. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9084. ) or (
  9085. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9086. )
  9087. )
  9088. )
  9089. )
  9090. ) and (
  9091. GetNextInstruction(hp2, hp3) and
  9092. MatchInstruction(hp3, A_SHR,[]) and
  9093. (taicpu(hp3).opsize = S_Q) and
  9094. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9095. (taicpu(hp3).oper[0]^.val = 1) and
  9096. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9097. ) then
  9098. begin
  9099. { Change movl x, reg1d movl x, reg1d
  9100. movl y, reg2d movl y, reg2d
  9101. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9102. shrq $1, reg1q shrq $1, reg1q
  9103. ( reg1d and reg2d can be switched around in the first two instructions )
  9104. To movl x, reg1d
  9105. addl y, reg1d
  9106. rcrl $1, reg1d
  9107. This corresponds to the common expression (x + y) shr 1, where
  9108. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9109. smaller code, but won't account for x + y causing an overflow). [Kit]
  9110. }
  9111. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9112. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9113. { Change first MOV command to have the same register as the final output }
  9114. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9115. else
  9116. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9117. { Change second MOV command to an ADD command. This is easier than
  9118. converting the existing command because it means we don't have to
  9119. touch 'y', which might be a complicated reference, and also the
  9120. fact that the third command might either be ADD or LEA. [Kit] }
  9121. taicpu(hp1).opcode := A_ADD;
  9122. { Delete old ADD/LEA instruction }
  9123. RemoveInstruction(hp2);
  9124. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9125. taicpu(hp3).opcode := A_RCR;
  9126. taicpu(hp3).changeopsize(S_L);
  9127. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9128. {$endif x86_64}
  9129. end;
  9130. if FuncMov2Func(p, hp1) then
  9131. begin
  9132. Result := True;
  9133. Exit;
  9134. end;
  9135. end;
  9136. {$push}
  9137. {$q-}{$r-}
  9138. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9139. var
  9140. ThisReg: TRegister;
  9141. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9142. TargetSubReg: TSubRegister;
  9143. hp1, hp2: tai;
  9144. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9145. { Store list of found instructions so we don't have to call
  9146. GetNextInstructionUsingReg multiple times }
  9147. InstrList: array of taicpu;
  9148. InstrMax, Index: Integer;
  9149. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9150. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9151. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9152. WorkingValue: TCgInt;
  9153. PreMessage: string;
  9154. { Data flow analysis }
  9155. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9156. BitwiseOnly, OrXorUsed,
  9157. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9158. function CheckOverflowConditions: Boolean;
  9159. begin
  9160. Result := True;
  9161. if (TestValSignedMax > SignedUpperLimit) then
  9162. UpperSignedOverflow := True;
  9163. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9164. LowerSignedOverflow := True;
  9165. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9166. LowerUnsignedOverflow := True;
  9167. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9168. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9169. begin
  9170. { Absolute overflow }
  9171. Result := False;
  9172. Exit;
  9173. end;
  9174. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9175. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9176. ShiftDownOverflow := True;
  9177. if (TestValMin < 0) or (TestValMax < 0) then
  9178. begin
  9179. LowerUnsignedOverflow := True;
  9180. UpperUnsignedOverflow := True;
  9181. end;
  9182. end;
  9183. function AdjustInitialLoadAndSize: Boolean;
  9184. begin
  9185. Result := False;
  9186. if not p_removed then
  9187. begin
  9188. if TargetSize = MinSize then
  9189. begin
  9190. { Convert the input MOVZX to a MOV }
  9191. if (taicpu(p).oper[0]^.typ = top_reg) and
  9192. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9193. begin
  9194. { Or remove it completely! }
  9195. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9196. RemoveCurrentP(p);
  9197. p_removed := True;
  9198. end
  9199. else
  9200. begin
  9201. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9202. taicpu(p).opcode := A_MOV;
  9203. taicpu(p).oper[1]^.reg := ThisReg;
  9204. taicpu(p).opsize := TargetSize;
  9205. end;
  9206. Result := True;
  9207. end
  9208. else if TargetSize <> MaxSize then
  9209. begin
  9210. case MaxSize of
  9211. S_L:
  9212. if TargetSize = S_W then
  9213. begin
  9214. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9215. taicpu(p).opsize := S_BW;
  9216. taicpu(p).oper[1]^.reg := ThisReg;
  9217. Result := True;
  9218. end
  9219. else
  9220. InternalError(2020112341);
  9221. S_W:
  9222. if TargetSize = S_L then
  9223. begin
  9224. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9225. taicpu(p).opsize := S_BL;
  9226. taicpu(p).oper[1]^.reg := ThisReg;
  9227. Result := True;
  9228. end
  9229. else
  9230. InternalError(2020112342);
  9231. else
  9232. ;
  9233. end;
  9234. end
  9235. else if not hp1_removed and not RegInUse then
  9236. begin
  9237. { If we have something like:
  9238. movzbl (oper),%regd
  9239. add x, %regd
  9240. movzbl %regb, %regd
  9241. We can reduce the register size to the input of the final
  9242. movzbl instruction. Overflows won't have any effect.
  9243. }
  9244. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9245. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9246. begin
  9247. TargetSize := S_B;
  9248. setsubreg(ThisReg, R_SUBL);
  9249. Result := True;
  9250. end
  9251. else if (taicpu(p).opsize = S_WL) and
  9252. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9253. begin
  9254. TargetSize := S_W;
  9255. setsubreg(ThisReg, R_SUBW);
  9256. Result := True;
  9257. end;
  9258. if Result then
  9259. begin
  9260. { Convert the input MOVZX to a MOV }
  9261. if (taicpu(p).oper[0]^.typ = top_reg) and
  9262. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9263. begin
  9264. { Or remove it completely! }
  9265. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9266. RemoveCurrentP(p);
  9267. p_removed := True;
  9268. end
  9269. else
  9270. begin
  9271. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9272. taicpu(p).opcode := A_MOV;
  9273. taicpu(p).oper[1]^.reg := ThisReg;
  9274. taicpu(p).opsize := TargetSize;
  9275. end;
  9276. end;
  9277. end;
  9278. end;
  9279. end;
  9280. procedure AdjustFinalLoad;
  9281. begin
  9282. if not LowerUnsignedOverflow then
  9283. begin
  9284. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9285. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9286. begin
  9287. { Convert the output MOVZX to a MOV }
  9288. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9289. begin
  9290. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9291. if (MinSize = S_B) or
  9292. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9293. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9294. begin
  9295. { Remove it completely! }
  9296. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9297. { Be careful; if p = hp1 and p was also removed, p
  9298. will become a dangling pointer }
  9299. if p = hp1 then
  9300. begin
  9301. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9302. p_removed := True;
  9303. end
  9304. else
  9305. RemoveInstruction(hp1);
  9306. hp1_removed := True;
  9307. end;
  9308. end
  9309. else
  9310. begin
  9311. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9312. taicpu(hp1).opcode := A_MOV;
  9313. taicpu(hp1).oper[0]^.reg := ThisReg;
  9314. taicpu(hp1).opsize := TargetSize;
  9315. end;
  9316. end
  9317. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9318. begin
  9319. { Need to change the size of the output }
  9320. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9321. taicpu(hp1).oper[0]^.reg := ThisReg;
  9322. taicpu(hp1).opsize := S_BL;
  9323. end;
  9324. end;
  9325. end;
  9326. function CompressInstructions: Boolean;
  9327. var
  9328. LocalIndex: Integer;
  9329. begin
  9330. Result := False;
  9331. { The objective here is to try to find a combination that
  9332. removes one of the MOV/Z instructions. }
  9333. if (
  9334. (taicpu(p).oper[0]^.typ <> top_reg) or
  9335. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9336. ) and
  9337. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9338. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9339. begin
  9340. { Make a preference to remove the second MOVZX instruction }
  9341. case taicpu(hp1).opsize of
  9342. S_BL, S_WL:
  9343. begin
  9344. TargetSize := S_L;
  9345. TargetSubReg := R_SUBD;
  9346. end;
  9347. S_BW:
  9348. begin
  9349. TargetSize := S_W;
  9350. TargetSubReg := R_SUBW;
  9351. end;
  9352. else
  9353. InternalError(2020112302);
  9354. end;
  9355. end
  9356. else
  9357. begin
  9358. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9359. begin
  9360. { Exceeded lower bound but not upper bound }
  9361. TargetSize := MaxSize;
  9362. end
  9363. else if not LowerUnsignedOverflow then
  9364. begin
  9365. { Size didn't exceed lower bound }
  9366. TargetSize := MinSize;
  9367. end
  9368. else
  9369. Exit;
  9370. end;
  9371. case TargetSize of
  9372. S_B:
  9373. TargetSubReg := R_SUBL;
  9374. S_W:
  9375. TargetSubReg := R_SUBW;
  9376. S_L:
  9377. TargetSubReg := R_SUBD;
  9378. else
  9379. InternalError(2020112350);
  9380. end;
  9381. { Update the register to its new size }
  9382. setsubreg(ThisReg, TargetSubReg);
  9383. RegInUse := False;
  9384. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9385. begin
  9386. { Check to see if the active register is used afterwards;
  9387. if not, we can change it and make a saving. }
  9388. TransferUsedRegs(TmpUsedRegs);
  9389. { The target register may be marked as in use to cross
  9390. a jump to a distant label, so exclude it }
  9391. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9392. hp2 := p;
  9393. repeat
  9394. { Explicitly check for the excluded register (don't include the first
  9395. instruction as it may be reading from here }
  9396. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9397. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9398. begin
  9399. RegInUse := True;
  9400. Break;
  9401. end;
  9402. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9403. if not GetNextInstruction(hp2, hp2) then
  9404. InternalError(2020112340);
  9405. until (hp2 = hp1);
  9406. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9407. { We might still be able to get away with this }
  9408. RegInUse := not
  9409. (
  9410. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9411. (hp2.typ = ait_instruction) and
  9412. (
  9413. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9414. instruction that doesn't actually contain ThisReg }
  9415. (cs_opt_level3 in current_settings.optimizerswitches) or
  9416. RegInInstruction(ThisReg, hp2)
  9417. ) and
  9418. RegLoadedWithNewValue(ThisReg, hp2)
  9419. );
  9420. if not RegInUse then
  9421. begin
  9422. { Force the register size to the same as this instruction so it can be removed}
  9423. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9424. begin
  9425. TargetSize := S_L;
  9426. TargetSubReg := R_SUBD;
  9427. end
  9428. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9429. begin
  9430. TargetSize := S_W;
  9431. TargetSubReg := R_SUBW;
  9432. end;
  9433. ThisReg := taicpu(hp1).oper[1]^.reg;
  9434. setsubreg(ThisReg, TargetSubReg);
  9435. RegChanged := True;
  9436. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9437. TransferUsedRegs(TmpUsedRegs);
  9438. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9439. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9440. if p = hp1 then
  9441. begin
  9442. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9443. p_removed := True;
  9444. end
  9445. else
  9446. RemoveInstruction(hp1);
  9447. hp1_removed := True;
  9448. { Instruction will become "mov %reg,%reg" }
  9449. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9450. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9451. begin
  9452. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9453. RemoveCurrentP(p);
  9454. p_removed := True;
  9455. end
  9456. else
  9457. taicpu(p).oper[1]^.reg := ThisReg;
  9458. Result := True;
  9459. end
  9460. else
  9461. begin
  9462. if TargetSize <> MaxSize then
  9463. begin
  9464. { Since the register is in use, we have to force it to
  9465. MaxSize otherwise part of it may become undefined later on }
  9466. TargetSize := MaxSize;
  9467. case TargetSize of
  9468. S_B:
  9469. TargetSubReg := R_SUBL;
  9470. S_W:
  9471. TargetSubReg := R_SUBW;
  9472. S_L:
  9473. TargetSubReg := R_SUBD;
  9474. else
  9475. InternalError(2020112351);
  9476. end;
  9477. setsubreg(ThisReg, TargetSubReg);
  9478. end;
  9479. AdjustFinalLoad;
  9480. end;
  9481. end
  9482. else
  9483. AdjustFinalLoad;
  9484. Result := AdjustInitialLoadAndSize or Result;
  9485. { Now go through every instruction we found and change the
  9486. size. If TargetSize = MaxSize, then almost no changes are
  9487. needed and Result can remain False if it hasn't been set
  9488. yet.
  9489. If RegChanged is True, then the register requires changing
  9490. and so the point about TargetSize = MaxSize doesn't apply. }
  9491. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9492. begin
  9493. for LocalIndex := 0 to InstrMax do
  9494. begin
  9495. { If p_removed is true, then the original MOV/Z was removed
  9496. and removing the AND instruction may not be safe if it
  9497. appears first }
  9498. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9499. InternalError(2020112310);
  9500. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9501. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9502. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9503. InstrList[LocalIndex].opsize := TargetSize;
  9504. end;
  9505. Result := True;
  9506. end;
  9507. end;
  9508. begin
  9509. Result := False;
  9510. p_removed := False;
  9511. hp1_removed := False;
  9512. ThisReg := taicpu(p).oper[1]^.reg;
  9513. { Check for:
  9514. movs/z ###,%ecx (or %cx or %rcx)
  9515. ...
  9516. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9517. (dealloc %ecx)
  9518. Change to:
  9519. mov ###,%cl (if ### = %cl, then remove completely)
  9520. ...
  9521. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9522. }
  9523. if (getsupreg(ThisReg) = RS_ECX) and
  9524. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9525. (hp1.typ = ait_instruction) and
  9526. (
  9527. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9528. instruction that doesn't actually contain ECX }
  9529. (cs_opt_level3 in current_settings.optimizerswitches) or
  9530. RegInInstruction(NR_ECX, hp1) or
  9531. (
  9532. { It's common for the shift/rotate's read/write register to be
  9533. initialised in between, so under -O2 and under, search ahead
  9534. one more instruction
  9535. }
  9536. GetNextInstruction(hp1, hp1) and
  9537. (hp1.typ = ait_instruction) and
  9538. RegInInstruction(NR_ECX, hp1)
  9539. )
  9540. ) and
  9541. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9542. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9543. begin
  9544. TransferUsedRegs(TmpUsedRegs);
  9545. hp2 := p;
  9546. repeat
  9547. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9548. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9549. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9550. begin
  9551. case taicpu(p).opsize of
  9552. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9553. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9554. begin
  9555. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9556. RemoveCurrentP(p);
  9557. end
  9558. else
  9559. begin
  9560. taicpu(p).opcode := A_MOV;
  9561. taicpu(p).opsize := S_B;
  9562. taicpu(p).oper[1]^.reg := NR_CL;
  9563. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9564. end;
  9565. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9566. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9567. begin
  9568. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9569. RemoveCurrentP(p);
  9570. end
  9571. else
  9572. begin
  9573. taicpu(p).opcode := A_MOV;
  9574. taicpu(p).opsize := S_W;
  9575. taicpu(p).oper[1]^.reg := NR_CX;
  9576. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9577. end;
  9578. {$ifdef x86_64}
  9579. S_LQ:
  9580. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9581. begin
  9582. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9583. RemoveCurrentP(p);
  9584. end
  9585. else
  9586. begin
  9587. taicpu(p).opcode := A_MOV;
  9588. taicpu(p).opsize := S_L;
  9589. taicpu(p).oper[1]^.reg := NR_ECX;
  9590. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9591. end;
  9592. {$endif x86_64}
  9593. else
  9594. InternalError(2021120401);
  9595. end;
  9596. Result := True;
  9597. Exit;
  9598. end;
  9599. end;
  9600. { This is anything but quick! }
  9601. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9602. Exit;
  9603. SetLength(InstrList, 0);
  9604. InstrMax := -1;
  9605. case taicpu(p).opsize of
  9606. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9607. begin
  9608. {$if defined(i386) or defined(i8086)}
  9609. { If the target size is 8-bit, make sure we can actually encode it }
  9610. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9611. Exit;
  9612. {$endif i386 or i8086}
  9613. LowerLimit := $FF;
  9614. SignedLowerLimit := $7F;
  9615. SignedLowerLimitBottom := -128;
  9616. MinSize := S_B;
  9617. if taicpu(p).opsize = S_BW then
  9618. begin
  9619. MaxSize := S_W;
  9620. UpperLimit := $FFFF;
  9621. SignedUpperLimit := $7FFF;
  9622. SignedUpperLimitBottom := -32768;
  9623. end
  9624. else
  9625. begin
  9626. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9627. MaxSize := S_L;
  9628. UpperLimit := $FFFFFFFF;
  9629. SignedUpperLimit := $7FFFFFFF;
  9630. SignedUpperLimitBottom := -2147483648;
  9631. end;
  9632. end;
  9633. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9634. begin
  9635. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9636. LowerLimit := $FFFF;
  9637. SignedLowerLimit := $7FFF;
  9638. SignedLowerLimitBottom := -32768;
  9639. UpperLimit := $FFFFFFFF;
  9640. SignedUpperLimit := $7FFFFFFF;
  9641. SignedUpperLimitBottom := -2147483648;
  9642. MinSize := S_W;
  9643. MaxSize := S_L;
  9644. end;
  9645. {$ifdef x86_64}
  9646. S_LQ:
  9647. begin
  9648. { Both the lower and upper limits are set to 32-bit. If a limit
  9649. is breached, then optimisation is impossible }
  9650. LowerLimit := $FFFFFFFF;
  9651. SignedLowerLimit := $7FFFFFFF;
  9652. SignedLowerLimitBottom := -2147483648;
  9653. UpperLimit := $FFFFFFFF;
  9654. SignedUpperLimit := $7FFFFFFF;
  9655. SignedUpperLimitBottom := -2147483648;
  9656. MinSize := S_L;
  9657. MaxSize := S_L;
  9658. end;
  9659. {$endif x86_64}
  9660. else
  9661. InternalError(2020112301);
  9662. end;
  9663. TestValMin := 0;
  9664. TestValMax := LowerLimit;
  9665. TestValSignedMax := SignedLowerLimit;
  9666. TryShiftDownLimit := LowerLimit;
  9667. TryShiftDown := S_NO;
  9668. ShiftDownOverflow := False;
  9669. RegChanged := False;
  9670. BitwiseOnly := True;
  9671. OrXorUsed := False;
  9672. UpperSignedOverflow := False;
  9673. LowerSignedOverflow := False;
  9674. UpperUnsignedOverflow := False;
  9675. LowerUnsignedOverflow := False;
  9676. hp1 := p;
  9677. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9678. (hp1.typ = ait_instruction) and
  9679. (
  9680. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9681. instruction that doesn't actually contain ThisReg }
  9682. (cs_opt_level3 in current_settings.optimizerswitches) or
  9683. { This allows this Movx optimisation to work through the SETcc instructions
  9684. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9685. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9686. skip over these SETcc instructions). }
  9687. (taicpu(hp1).opcode = A_SETcc) or
  9688. RegInInstruction(ThisReg, hp1)
  9689. ) do
  9690. begin
  9691. case taicpu(hp1).opcode of
  9692. A_INC,A_DEC:
  9693. begin
  9694. { Has to be an exact match on the register }
  9695. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9696. Break;
  9697. if taicpu(hp1).opcode = A_INC then
  9698. begin
  9699. Inc(TestValMin);
  9700. Inc(TestValMax);
  9701. Inc(TestValSignedMax);
  9702. end
  9703. else
  9704. begin
  9705. Dec(TestValMin);
  9706. Dec(TestValMax);
  9707. Dec(TestValSignedMax);
  9708. end;
  9709. end;
  9710. A_TEST, A_CMP:
  9711. begin
  9712. if (
  9713. { Too high a risk of non-linear behaviour that breaks DFA
  9714. here, unless it's cmp $0,%reg, which is equivalent to
  9715. test %reg,%reg }
  9716. OrXorUsed and
  9717. (taicpu(hp1).opcode = A_CMP) and
  9718. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9719. ) or
  9720. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9721. { Has to be an exact match on the register }
  9722. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9723. (
  9724. { Permit "test %reg,%reg" }
  9725. (taicpu(hp1).opcode = A_TEST) and
  9726. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9727. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9728. ) or
  9729. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9730. { Make sure the comparison value is not smaller than the
  9731. smallest allowed signed value for the minimum size (e.g.
  9732. -128 for 8-bit) }
  9733. not (
  9734. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9735. { Is it in the negative range? }
  9736. (
  9737. (taicpu(hp1).oper[0]^.val < 0) and
  9738. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9739. )
  9740. ) then
  9741. Break;
  9742. { Check to see if the active register is used afterwards }
  9743. TransferUsedRegs(TmpUsedRegs);
  9744. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9745. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9746. begin
  9747. { Make sure the comparison or any previous instructions
  9748. hasn't pushed the test values outside of the range of
  9749. MinSize }
  9750. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9751. begin
  9752. { Exceeded lower bound but not upper bound }
  9753. Exit;
  9754. end
  9755. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9756. begin
  9757. { Size didn't exceed lower bound }
  9758. TargetSize := MinSize;
  9759. end
  9760. else
  9761. Break;
  9762. case TargetSize of
  9763. S_B:
  9764. TargetSubReg := R_SUBL;
  9765. S_W:
  9766. TargetSubReg := R_SUBW;
  9767. S_L:
  9768. TargetSubReg := R_SUBD;
  9769. else
  9770. InternalError(2021051002);
  9771. end;
  9772. if TargetSize <> MaxSize then
  9773. begin
  9774. { Update the register to its new size }
  9775. setsubreg(ThisReg, TargetSubReg);
  9776. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9777. taicpu(hp1).oper[1]^.reg := ThisReg;
  9778. taicpu(hp1).opsize := TargetSize;
  9779. { Convert the input MOVZX to a MOV if necessary }
  9780. AdjustInitialLoadAndSize;
  9781. if (InstrMax >= 0) then
  9782. begin
  9783. for Index := 0 to InstrMax do
  9784. begin
  9785. { If p_removed is true, then the original MOV/Z was removed
  9786. and removing the AND instruction may not be safe if it
  9787. appears first }
  9788. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9789. InternalError(2020112311);
  9790. if InstrList[Index].oper[0]^.typ = top_reg then
  9791. InstrList[Index].oper[0]^.reg := ThisReg;
  9792. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9793. InstrList[Index].opsize := MinSize;
  9794. end;
  9795. end;
  9796. Result := True;
  9797. end;
  9798. Exit;
  9799. end;
  9800. end;
  9801. A_SETcc:
  9802. begin
  9803. { This allows this Movx optimisation to work through the SETcc instructions
  9804. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9805. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9806. skip over these SETcc instructions). }
  9807. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9808. { Of course, break out if the current register is used }
  9809. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9810. Break
  9811. else
  9812. { We must use Continue so the instruction doesn't get added
  9813. to InstrList }
  9814. Continue;
  9815. end;
  9816. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9817. begin
  9818. if
  9819. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9820. { Has to be an exact match on the register }
  9821. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9822. (
  9823. (
  9824. (taicpu(hp1).oper[0]^.typ = top_const) and
  9825. (
  9826. (
  9827. (taicpu(hp1).opcode = A_SHL) and
  9828. (
  9829. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9830. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9831. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9832. )
  9833. ) or (
  9834. (taicpu(hp1).opcode <> A_SHL) and
  9835. (
  9836. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9837. { Is it in the negative range? }
  9838. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9839. )
  9840. )
  9841. )
  9842. ) or (
  9843. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9844. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9845. )
  9846. ) then
  9847. Break;
  9848. { Only process OR and XOR if there are only bitwise operations,
  9849. since otherwise they can too easily fool the data flow
  9850. analysis (they can cause non-linear behaviour) }
  9851. case taicpu(hp1).opcode of
  9852. A_ADD:
  9853. begin
  9854. if OrXorUsed then
  9855. { Too high a risk of non-linear behaviour that breaks DFA here }
  9856. Break
  9857. else
  9858. BitwiseOnly := False;
  9859. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9860. begin
  9861. TestValMin := TestValMin * 2;
  9862. TestValMax := TestValMax * 2;
  9863. TestValSignedMax := TestValSignedMax * 2;
  9864. end
  9865. else
  9866. begin
  9867. WorkingValue := taicpu(hp1).oper[0]^.val;
  9868. TestValMin := TestValMin + WorkingValue;
  9869. TestValMax := TestValMax + WorkingValue;
  9870. TestValSignedMax := TestValSignedMax + WorkingValue;
  9871. end;
  9872. end;
  9873. A_SUB:
  9874. begin
  9875. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9876. begin
  9877. TestValMin := 0;
  9878. TestValMax := 0;
  9879. TestValSignedMax := 0;
  9880. end
  9881. else
  9882. begin
  9883. if OrXorUsed then
  9884. { Too high a risk of non-linear behaviour that breaks DFA here }
  9885. Break
  9886. else
  9887. BitwiseOnly := False;
  9888. WorkingValue := taicpu(hp1).oper[0]^.val;
  9889. TestValMin := TestValMin - WorkingValue;
  9890. TestValMax := TestValMax - WorkingValue;
  9891. TestValSignedMax := TestValSignedMax - WorkingValue;
  9892. end;
  9893. end;
  9894. A_AND:
  9895. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9896. begin
  9897. { we might be able to go smaller if AND appears first }
  9898. if InstrMax = -1 then
  9899. case MinSize of
  9900. S_B:
  9901. ;
  9902. S_W:
  9903. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9904. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9905. begin
  9906. TryShiftDown := S_B;
  9907. TryShiftDownLimit := $FF;
  9908. end;
  9909. S_L:
  9910. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9911. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9912. begin
  9913. TryShiftDown := S_B;
  9914. TryShiftDownLimit := $FF;
  9915. end
  9916. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9917. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9918. begin
  9919. TryShiftDown := S_W;
  9920. TryShiftDownLimit := $FFFF;
  9921. end;
  9922. else
  9923. InternalError(2020112320);
  9924. end;
  9925. WorkingValue := taicpu(hp1).oper[0]^.val;
  9926. TestValMin := TestValMin and WorkingValue;
  9927. TestValMax := TestValMax and WorkingValue;
  9928. TestValSignedMax := TestValSignedMax and WorkingValue;
  9929. end;
  9930. A_OR:
  9931. begin
  9932. if not BitwiseOnly then
  9933. Break;
  9934. OrXorUsed := True;
  9935. WorkingValue := taicpu(hp1).oper[0]^.val;
  9936. TestValMin := TestValMin or WorkingValue;
  9937. TestValMax := TestValMax or WorkingValue;
  9938. TestValSignedMax := TestValSignedMax or WorkingValue;
  9939. end;
  9940. A_XOR:
  9941. begin
  9942. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9943. begin
  9944. TestValMin := 0;
  9945. TestValMax := 0;
  9946. TestValSignedMax := 0;
  9947. end
  9948. else
  9949. begin
  9950. if not BitwiseOnly then
  9951. Break;
  9952. OrXorUsed := True;
  9953. WorkingValue := taicpu(hp1).oper[0]^.val;
  9954. TestValMin := TestValMin xor WorkingValue;
  9955. TestValMax := TestValMax xor WorkingValue;
  9956. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9957. end;
  9958. end;
  9959. A_SHL:
  9960. begin
  9961. BitwiseOnly := False;
  9962. WorkingValue := taicpu(hp1).oper[0]^.val;
  9963. TestValMin := TestValMin shl WorkingValue;
  9964. TestValMax := TestValMax shl WorkingValue;
  9965. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9966. end;
  9967. A_SHR,
  9968. { The first instruction was MOVZX, so the value won't be negative }
  9969. A_SAR:
  9970. begin
  9971. if InstrMax <> -1 then
  9972. BitwiseOnly := False
  9973. else
  9974. { we might be able to go smaller if SHR appears first }
  9975. case MinSize of
  9976. S_B:
  9977. ;
  9978. S_W:
  9979. if (taicpu(hp1).oper[0]^.val >= 8) then
  9980. begin
  9981. TryShiftDown := S_B;
  9982. TryShiftDownLimit := $FF;
  9983. TryShiftDownSignedLimit := $7F;
  9984. TryShiftDownSignedLimitLower := -128;
  9985. end;
  9986. S_L:
  9987. if (taicpu(hp1).oper[0]^.val >= 24) then
  9988. begin
  9989. TryShiftDown := S_B;
  9990. TryShiftDownLimit := $FF;
  9991. TryShiftDownSignedLimit := $7F;
  9992. TryShiftDownSignedLimitLower := -128;
  9993. end
  9994. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9995. begin
  9996. TryShiftDown := S_W;
  9997. TryShiftDownLimit := $FFFF;
  9998. TryShiftDownSignedLimit := $7FFF;
  9999. TryShiftDownSignedLimitLower := -32768;
  10000. end;
  10001. else
  10002. InternalError(2020112321);
  10003. end;
  10004. WorkingValue := taicpu(hp1).oper[0]^.val;
  10005. if taicpu(hp1).opcode = A_SAR then
  10006. begin
  10007. TestValMin := SarInt64(TestValMin, WorkingValue);
  10008. TestValMax := SarInt64(TestValMax, WorkingValue);
  10009. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10010. end
  10011. else
  10012. begin
  10013. TestValMin := TestValMin shr WorkingValue;
  10014. TestValMax := TestValMax shr WorkingValue;
  10015. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10016. end;
  10017. end;
  10018. else
  10019. InternalError(2020112303);
  10020. end;
  10021. end;
  10022. (*
  10023. A_IMUL:
  10024. case taicpu(hp1).ops of
  10025. 2:
  10026. begin
  10027. if not MatchOpType(hp1, top_reg, top_reg) or
  10028. { Has to be an exact match on the register }
  10029. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10030. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10031. Break;
  10032. TestValMin := TestValMin * TestValMin;
  10033. TestValMax := TestValMax * TestValMax;
  10034. TestValSignedMax := TestValSignedMax * TestValMax;
  10035. end;
  10036. 3:
  10037. begin
  10038. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10039. { Has to be an exact match on the register }
  10040. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10041. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10042. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10043. { Is it in the negative range? }
  10044. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10045. Break;
  10046. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10047. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10048. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10049. end;
  10050. else
  10051. Break;
  10052. end;
  10053. A_IDIV:
  10054. case taicpu(hp1).ops of
  10055. 3:
  10056. begin
  10057. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10058. { Has to be an exact match on the register }
  10059. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10060. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10061. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10062. { Is it in the negative range? }
  10063. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10064. Break;
  10065. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10066. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10067. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10068. end;
  10069. else
  10070. Break;
  10071. end;
  10072. *)
  10073. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10074. begin
  10075. { If there are no instructions in between, then we might be able to make a saving }
  10076. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10077. Break;
  10078. { We have something like:
  10079. movzbw %dl,%dx
  10080. ...
  10081. movswl %dx,%edx
  10082. Change the latter to a zero-extension then enter the
  10083. A_MOVZX case branch.
  10084. }
  10085. {$ifdef x86_64}
  10086. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10087. begin
  10088. { this becomes a zero extension from 32-bit to 64-bit, but
  10089. the upper 32 bits are already zero, so just delete the
  10090. instruction }
  10091. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10092. RemoveInstruction(hp1);
  10093. Result := True;
  10094. Exit;
  10095. end
  10096. else
  10097. {$endif x86_64}
  10098. begin
  10099. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10100. taicpu(hp1).opcode := A_MOVZX;
  10101. {$ifdef x86_64}
  10102. case taicpu(hp1).opsize of
  10103. S_BQ:
  10104. begin
  10105. taicpu(hp1).opsize := S_BL;
  10106. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10107. end;
  10108. S_WQ:
  10109. begin
  10110. taicpu(hp1).opsize := S_WL;
  10111. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10112. end;
  10113. S_LQ:
  10114. begin
  10115. taicpu(hp1).opcode := A_MOV;
  10116. taicpu(hp1).opsize := S_L;
  10117. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10118. { In this instance, we need to break out because the
  10119. instruction is no longer MOVZX or MOVSXD }
  10120. Result := True;
  10121. Exit;
  10122. end;
  10123. else
  10124. ;
  10125. end;
  10126. {$endif x86_64}
  10127. Result := CompressInstructions;
  10128. Exit;
  10129. end;
  10130. end;
  10131. A_MOVZX:
  10132. begin
  10133. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10134. Break;
  10135. if (InstrMax = -1) then
  10136. begin
  10137. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10138. begin
  10139. { Optimise around i40003 }
  10140. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10141. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10142. {$ifndef x86_64}
  10143. and (
  10144. (taicpu(p).oper[0]^.typ <> top_reg) or
  10145. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10146. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10147. )
  10148. {$endif not x86_64}
  10149. then
  10150. begin
  10151. if (taicpu(p).oper[0]^.typ = top_reg) then
  10152. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10153. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10154. taicpu(p).opsize := S_BL;
  10155. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10156. RemoveInstruction(hp1);
  10157. Result := True;
  10158. Exit;
  10159. end;
  10160. end
  10161. else
  10162. begin
  10163. { Will return false if the second parameter isn't ThisReg
  10164. (can happen on -O2 and under) }
  10165. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10166. begin
  10167. { The two MOVZX instructions are adjacent, so remove the first one }
  10168. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10169. RemoveCurrentP(p);
  10170. Result := True;
  10171. Exit;
  10172. end;
  10173. Break;
  10174. end;
  10175. end;
  10176. Result := CompressInstructions;
  10177. Exit;
  10178. end;
  10179. else
  10180. { This includes ADC, SBB and IDIV }
  10181. Break;
  10182. end;
  10183. if not CheckOverflowConditions then
  10184. Break;
  10185. { Contains highest index (so instruction count - 1) }
  10186. Inc(InstrMax);
  10187. if InstrMax > High(InstrList) then
  10188. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10189. InstrList[InstrMax] := taicpu(hp1);
  10190. end;
  10191. end;
  10192. {$pop}
  10193. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10194. var
  10195. hp1 : tai;
  10196. begin
  10197. Result:=false;
  10198. if (taicpu(p).ops >= 2) and
  10199. ((taicpu(p).oper[0]^.typ = top_const) or
  10200. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10201. (taicpu(p).oper[1]^.typ = top_reg) and
  10202. ((taicpu(p).ops = 2) or
  10203. ((taicpu(p).oper[2]^.typ = top_reg) and
  10204. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10205. GetLastInstruction(p,hp1) and
  10206. MatchInstruction(hp1,A_MOV,[]) and
  10207. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10208. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10209. begin
  10210. TransferUsedRegs(TmpUsedRegs);
  10211. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10212. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10213. { change
  10214. mov reg1,reg2
  10215. imul y,reg2 to imul y,reg1,reg2 }
  10216. begin
  10217. taicpu(p).ops := 3;
  10218. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10219. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10220. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10221. RemoveInstruction(hp1);
  10222. result:=true;
  10223. end;
  10224. end;
  10225. end;
  10226. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10227. var
  10228. ThisLabel: TAsmLabel;
  10229. begin
  10230. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10231. ThisLabel.decrefs;
  10232. taicpu(p).condition := C_None;
  10233. taicpu(p).opcode := A_RET;
  10234. taicpu(p).is_jmp := false;
  10235. taicpu(p).ops := taicpu(ret_p).ops;
  10236. case taicpu(ret_p).ops of
  10237. 0:
  10238. taicpu(p).clearop(0);
  10239. 1:
  10240. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10241. else
  10242. internalerror(2016041301);
  10243. end;
  10244. { If the original label is now dead, it might turn out that the label
  10245. immediately follows p. As a result, everything beyond it, which will
  10246. be just some final register configuration and a RET instruction, is
  10247. now dead code. [Kit] }
  10248. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10249. running RemoveDeadCodeAfterJump for each RET instruction, because
  10250. this optimisation rarely happens and most RETs appear at the end of
  10251. routines where there is nothing that can be stripped. [Kit] }
  10252. if not ThisLabel.is_used then
  10253. RemoveDeadCodeAfterJump(p);
  10254. end;
  10255. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10256. var
  10257. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10258. Unconditional, PotentialModified: Boolean;
  10259. OperPtr: POper;
  10260. NewRef: TReference;
  10261. InstrList: array of taicpu;
  10262. InstrMax, Index: Integer;
  10263. const
  10264. {$ifdef DEBUG_AOPTCPU}
  10265. SNoFlags: shortstring = ' so the flags aren''t modified';
  10266. {$else DEBUG_AOPTCPU}
  10267. SNoFlags = '';
  10268. {$endif DEBUG_AOPTCPU}
  10269. begin
  10270. Result:=false;
  10271. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10272. begin
  10273. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10274. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10275. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10276. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10277. GetNextInstruction(hp1, hp2) and
  10278. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10279. { Change from: To:
  10280. set(C) %reg j(~C) label
  10281. test %reg,%reg/cmp $0,%reg
  10282. je label
  10283. set(C) %reg j(C) label
  10284. test %reg,%reg/cmp $0,%reg
  10285. jne label
  10286. (Also do something similar with sete/setne instead of je/jne)
  10287. }
  10288. begin
  10289. { Before we do anything else, we need to check the instructions
  10290. in between SETcc and TEST to make sure they don't modify the
  10291. FLAGS register - if -O2 or under, there won't be any
  10292. instructions between SET and TEST }
  10293. TransferUsedRegs(TmpUsedRegs);
  10294. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10295. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10296. begin
  10297. next := p;
  10298. SetLength(InstrList, 0);
  10299. InstrMax := -1;
  10300. PotentialModified := False;
  10301. { Make a note of every instruction that modifies the FLAGS
  10302. register }
  10303. while GetNextInstruction(next, next) and (next <> hp1) do
  10304. begin
  10305. if next.typ <> ait_instruction then
  10306. { GetNextInstructionUsingReg should have returned False }
  10307. InternalError(2021051701);
  10308. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10309. begin
  10310. case taicpu(next).opcode of
  10311. A_SETcc,
  10312. A_CMOVcc,
  10313. A_Jcc:
  10314. begin
  10315. if PotentialModified then
  10316. { Not safe because the flags were modified earlier }
  10317. Exit
  10318. else
  10319. { Condition is the same as the initial SETcc, so this is safe
  10320. (don't add to instruction list though) }
  10321. Continue;
  10322. end;
  10323. A_ADD:
  10324. begin
  10325. if (taicpu(next).opsize = S_B) or
  10326. { LEA doesn't support 8-bit operands }
  10327. (taicpu(next).oper[1]^.typ <> top_reg) or
  10328. { Must write to a register }
  10329. (taicpu(next).oper[0]^.typ = top_ref) then
  10330. { Require a constant or a register }
  10331. Exit;
  10332. PotentialModified := True;
  10333. end;
  10334. A_SUB:
  10335. begin
  10336. if (taicpu(next).opsize = S_B) or
  10337. { LEA doesn't support 8-bit operands }
  10338. (taicpu(next).oper[1]^.typ <> top_reg) or
  10339. { Must write to a register }
  10340. (taicpu(next).oper[0]^.typ <> top_const) or
  10341. (taicpu(next).oper[0]^.val = $80000000) then
  10342. { Can't subtract a register with LEA - also
  10343. check that the value isn't -2^31, as this
  10344. can't be negated }
  10345. Exit;
  10346. PotentialModified := True;
  10347. end;
  10348. A_SAL,
  10349. A_SHL:
  10350. begin
  10351. if (taicpu(next).opsize = S_B) or
  10352. { LEA doesn't support 8-bit operands }
  10353. (taicpu(next).oper[1]^.typ <> top_reg) or
  10354. { Must write to a register }
  10355. (taicpu(next).oper[0]^.typ <> top_const) or
  10356. (taicpu(next).oper[0]^.val < 0) or
  10357. (taicpu(next).oper[0]^.val > 3) then
  10358. Exit;
  10359. PotentialModified := True;
  10360. end;
  10361. A_IMUL:
  10362. begin
  10363. if (taicpu(next).ops <> 3) or
  10364. (taicpu(next).oper[1]^.typ <> top_reg) or
  10365. { Must write to a register }
  10366. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10367. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10368. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10369. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10370. Exit
  10371. else
  10372. PotentialModified := True;
  10373. end;
  10374. else
  10375. { Don't know how to change this, so abort }
  10376. Exit;
  10377. end;
  10378. { Contains highest index (so instruction count - 1) }
  10379. Inc(InstrMax);
  10380. if InstrMax > High(InstrList) then
  10381. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10382. InstrList[InstrMax] := taicpu(next);
  10383. end;
  10384. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10385. end;
  10386. if not Assigned(next) or (next <> hp1) then
  10387. { It should be equal to hp1 }
  10388. InternalError(2021051702);
  10389. { Cycle through each instruction and check to see if we can
  10390. change them to versions that don't modify the flags }
  10391. if (InstrMax >= 0) then
  10392. begin
  10393. for Index := 0 to InstrMax do
  10394. case InstrList[Index].opcode of
  10395. A_ADD:
  10396. begin
  10397. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10398. InstrList[Index].opcode := A_LEA;
  10399. reference_reset(NewRef, 1, []);
  10400. NewRef.base := InstrList[Index].oper[1]^.reg;
  10401. if InstrList[Index].oper[0]^.typ = top_reg then
  10402. begin
  10403. NewRef.index := InstrList[Index].oper[0]^.reg;
  10404. NewRef.scalefactor := 1;
  10405. end
  10406. else
  10407. NewRef.offset := InstrList[Index].oper[0]^.val;
  10408. InstrList[Index].loadref(0, NewRef);
  10409. end;
  10410. A_SUB:
  10411. begin
  10412. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10413. InstrList[Index].opcode := A_LEA;
  10414. reference_reset(NewRef, 1, []);
  10415. NewRef.base := InstrList[Index].oper[1]^.reg;
  10416. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10417. InstrList[Index].loadref(0, NewRef);
  10418. end;
  10419. A_SHL,
  10420. A_SAL:
  10421. begin
  10422. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10423. InstrList[Index].opcode := A_LEA;
  10424. reference_reset(NewRef, 1, []);
  10425. NewRef.index := InstrList[Index].oper[1]^.reg;
  10426. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10427. InstrList[Index].loadref(0, NewRef);
  10428. end;
  10429. A_IMUL:
  10430. begin
  10431. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10432. InstrList[Index].opcode := A_LEA;
  10433. reference_reset(NewRef, 1, []);
  10434. NewRef.index := InstrList[Index].oper[1]^.reg;
  10435. case InstrList[Index].oper[0]^.val of
  10436. 2, 4, 8:
  10437. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10438. else {3, 5 and 9}
  10439. begin
  10440. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10441. NewRef.base := InstrList[Index].oper[1]^.reg;
  10442. end;
  10443. end;
  10444. InstrList[Index].loadref(0, NewRef);
  10445. end;
  10446. else
  10447. InternalError(2021051710);
  10448. end;
  10449. end;
  10450. { Mark the FLAGS register as used across this whole block }
  10451. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10452. end;
  10453. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10454. JumpC := taicpu(hp2).condition;
  10455. Unconditional := False;
  10456. if conditions_equal(JumpC, C_E) then
  10457. SetC := inverse_cond(taicpu(p).condition)
  10458. else if conditions_equal(JumpC, C_NE) then
  10459. SetC := taicpu(p).condition
  10460. else
  10461. { We've got something weird here (and inefficent) }
  10462. begin
  10463. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10464. SetC := C_NONE;
  10465. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10466. if condition_in(C_AE, JumpC) then
  10467. Unconditional := True
  10468. else
  10469. { Not sure what to do with this jump - drop out }
  10470. Exit;
  10471. end;
  10472. RemoveInstruction(hp1);
  10473. if Unconditional then
  10474. MakeUnconditional(taicpu(hp2))
  10475. else
  10476. begin
  10477. if SetC = C_NONE then
  10478. InternalError(2018061402);
  10479. taicpu(hp2).SetCondition(SetC);
  10480. end;
  10481. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10482. TmpUsedRegs }
  10483. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10484. begin
  10485. RemoveCurrentp(p, hp2);
  10486. if taicpu(hp2).opcode = A_SETcc then
  10487. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10488. else
  10489. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10490. end
  10491. else
  10492. if taicpu(hp2).opcode = A_SETcc then
  10493. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10494. else
  10495. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10496. Result := True;
  10497. end
  10498. else if
  10499. { Make sure the instructions are adjacent }
  10500. (
  10501. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10502. GetNextInstruction(p, hp1)
  10503. ) and
  10504. MatchInstruction(hp1, A_MOV, [S_B]) and
  10505. { Writing to memory is allowed }
  10506. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10507. begin
  10508. {
  10509. Watch out for sequences such as:
  10510. set(c)b %regb
  10511. movb %regb,(ref)
  10512. movb $0,1(ref)
  10513. movb $0,2(ref)
  10514. movb $0,3(ref)
  10515. Much more efficient to turn it into:
  10516. movl $0,%regl
  10517. set(c)b %regb
  10518. movl %regl,(ref)
  10519. Or:
  10520. set(c)b %regb
  10521. movzbl %regb,%regl
  10522. movl %regl,(ref)
  10523. }
  10524. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10525. GetNextInstruction(hp1, hp2) and
  10526. MatchInstruction(hp2, A_MOV, [S_B]) and
  10527. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10528. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10529. begin
  10530. { Don't do anything else except set Result to True }
  10531. end
  10532. else
  10533. begin
  10534. if taicpu(p).oper[0]^.typ = top_reg then
  10535. begin
  10536. TransferUsedRegs(TmpUsedRegs);
  10537. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10538. end;
  10539. { If it's not a register, it's a memory address }
  10540. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10541. begin
  10542. { Even if the register is still in use, we can minimise the
  10543. pipeline stall by changing the MOV into another SETcc. }
  10544. taicpu(hp1).opcode := A_SETcc;
  10545. taicpu(hp1).condition := taicpu(p).condition;
  10546. if taicpu(hp1).oper[1]^.typ = top_ref then
  10547. begin
  10548. { Swapping the operand pointers like this is probably a
  10549. bit naughty, but it is far faster than using loadoper
  10550. to transfer the reference from oper[1] to oper[0] if
  10551. you take into account the extra procedure calls and
  10552. the memory allocation and deallocation required }
  10553. OperPtr := taicpu(hp1).oper[1];
  10554. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10555. taicpu(hp1).oper[0] := OperPtr;
  10556. end
  10557. else
  10558. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10559. taicpu(hp1).clearop(1);
  10560. taicpu(hp1).ops := 1;
  10561. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10562. end
  10563. else
  10564. begin
  10565. if taicpu(hp1).oper[1]^.typ = top_reg then
  10566. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10567. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10568. RemoveInstruction(hp1);
  10569. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10570. end
  10571. end;
  10572. Result := True;
  10573. end;
  10574. end;
  10575. end;
  10576. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10577. var
  10578. hp1: tai;
  10579. Count: Integer;
  10580. OrigLabel: TAsmLabel;
  10581. begin
  10582. result := False;
  10583. { Sometimes, the optimisations below can permit this }
  10584. RemoveDeadCodeAfterJump(p);
  10585. 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
  10586. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10587. begin
  10588. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10589. { Also a side-effect of optimisations }
  10590. if CollapseZeroDistJump(p, OrigLabel) then
  10591. begin
  10592. Result := True;
  10593. Exit;
  10594. end;
  10595. hp1 := GetLabelWithSym(OrigLabel);
  10596. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10597. begin
  10598. if taicpu(hp1).opcode = A_RET then
  10599. begin
  10600. {
  10601. change
  10602. jmp .L1
  10603. ...
  10604. .L1:
  10605. ret
  10606. into
  10607. ret
  10608. }
  10609. begin
  10610. ConvertJumpToRET(p, hp1);
  10611. result:=true;
  10612. end;
  10613. end
  10614. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10615. not (cs_opt_size in current_settings.optimizerswitches) and
  10616. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10617. begin
  10618. Result := True;
  10619. Exit;
  10620. end;
  10621. end;
  10622. end;
  10623. end;
  10624. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10625. begin
  10626. Result := assigned(p) and
  10627. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10628. (taicpu(p).oper[1]^.typ = top_reg) and
  10629. (
  10630. (taicpu(p).oper[0]^.typ = top_reg) or
  10631. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10632. it is not expected that this can cause a seg. violation }
  10633. (
  10634. (taicpu(p).oper[0]^.typ = top_ref) and
  10635. { TODO: Can we detect which references become constants at this
  10636. stage so we don't have to do a blanket ban? }
  10637. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10638. (
  10639. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10640. (
  10641. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10642. not RefModified and
  10643. { If the reference also appears in the condition, then we know it's safe, otherwise
  10644. any kind of access violation would have occurred already }
  10645. Assigned(cond_p) and
  10646. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10647. (cond_p.typ = ait_instruction) and
  10648. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10649. { Just consider 2-operand comparison instructions for now to be safe }
  10650. (taicpu(cond_p).ops = 2) and
  10651. (
  10652. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10653. (
  10654. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10655. { Don't risk identical registers but different offsets, as we may have constructs
  10656. such as buffer streams with things like length fields that indicate whether
  10657. any more data follows. And there are probably some contrived examples where
  10658. writing to offsets behind the one being read also lead to access violations }
  10659. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10660. (
  10661. { Check that we're not modifying a register that appears in the reference }
  10662. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10663. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10664. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10665. )
  10666. )
  10667. )
  10668. )
  10669. )
  10670. )
  10671. );
  10672. end;
  10673. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10674. begin
  10675. { Update integer registers, ignoring deallocations }
  10676. repeat
  10677. while assigned(p) and
  10678. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10679. (p.typ = ait_label) or
  10680. ((p.typ = ait_marker) and
  10681. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10682. p := tai(p.next);
  10683. while assigned(p) and
  10684. (p.typ=ait_RegAlloc) Do
  10685. begin
  10686. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10687. begin
  10688. case tai_regalloc(p).ratype of
  10689. ra_alloc :
  10690. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10691. else
  10692. ;
  10693. end;
  10694. end;
  10695. p := tai(p.next);
  10696. end;
  10697. until not(assigned(p)) or
  10698. (not(p.typ in SkipInstr) and
  10699. not((p.typ = ait_label) and
  10700. labelCanBeSkipped(tai_label(p))));
  10701. end;
  10702. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10703. var
  10704. hp1,hp2: tai;
  10705. carryadd_opcode : TAsmOp;
  10706. symbol: TAsmSymbol;
  10707. increg, tmpreg: TRegister;
  10708. RefModified: Boolean;
  10709. {$ifndef i8086}
  10710. { Code and variables specific to CMOV optimisations }
  10711. hp3,hp4,hp5,
  10712. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10713. l, c, w, x : Longint;
  10714. condition, second_condition : TAsmCond;
  10715. FoundMatchingJump, RegMatch: Boolean;
  10716. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10717. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10718. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10719. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10720. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10721. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10722. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10723. new register to store the constant }
  10724. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10725. var
  10726. RegSize: TSubRegister;
  10727. CurrentVal: TCGInt;
  10728. ANewReg: TRegister;
  10729. X: ShortInt;
  10730. begin
  10731. Result := False;
  10732. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10733. Exit;
  10734. if StoredCount >= MAX_CMOV_REGISTERS then
  10735. { Arrays are full }
  10736. Exit;
  10737. { Remember that CMOV can't encode 8-bit registers }
  10738. case taicpu(p).opsize of
  10739. S_W:
  10740. RegSize := R_SUBW;
  10741. S_L:
  10742. RegSize := R_SUBD;
  10743. {$ifdef x86_64}
  10744. S_Q:
  10745. RegSize := R_SUBQ;
  10746. {$endif x86_64}
  10747. else
  10748. InternalError(2021100401);
  10749. end;
  10750. { See if the value has already been reserved for another CMOV instruction }
  10751. CurrentVal := taicpu(p).oper[0]^.val;
  10752. for X := 0 to StoredCount - 1 do
  10753. if ConstVals[X] = CurrentVal then
  10754. begin
  10755. ConstRegs[StoredCount] := ConstRegs[X];
  10756. ConstSizes[StoredCount] := RegSize;
  10757. ConstVals[StoredCount] := CurrentVal;
  10758. Result := True;
  10759. Inc(StoredCount);
  10760. { Don't increase CMOVCount this time, since we're re-using a register }
  10761. Exit;
  10762. end;
  10763. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10764. if ANewReg = NR_NO then
  10765. { No free registers }
  10766. Exit;
  10767. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10768. up vying for the same register }
  10769. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10770. ConstRegs[StoredCount] := ANewReg;
  10771. ConstSizes[StoredCount] := RegSize;
  10772. ConstVals[StoredCount] := CurrentVal;
  10773. Inc(StoredCount);
  10774. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10775. MOV required adds complexity and will cause diminishing returns
  10776. sooner than normal. This is more of an approximate weighting than
  10777. anything else. }
  10778. Inc(CMOVCount);
  10779. Result := True;
  10780. end;
  10781. {$endif i8086}
  10782. begin
  10783. result:=false;
  10784. if GetNextInstruction(p,hp1) then
  10785. begin
  10786. if (hp1.typ=ait_label) then
  10787. begin
  10788. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10789. Exit;
  10790. end
  10791. else if (hp1.typ<>ait_instruction) then
  10792. Exit;
  10793. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10794. if (
  10795. (
  10796. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10797. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10798. (Taicpu(hp1).oper[0]^.val=1)
  10799. ) or
  10800. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10801. ) and
  10802. GetNextInstruction(hp1,hp2) and
  10803. (hp2.typ = ait_label) and
  10804. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10805. { jb @@1 cmc
  10806. inc/dec operand --> adc/sbb operand,0
  10807. @@1:
  10808. ... and ...
  10809. jnb @@1
  10810. inc/dec operand --> adc/sbb operand,0
  10811. @@1: }
  10812. begin
  10813. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10814. begin
  10815. case taicpu(hp1).opcode of
  10816. A_INC,
  10817. A_ADD:
  10818. carryadd_opcode:=A_ADC;
  10819. A_DEC,
  10820. A_SUB:
  10821. carryadd_opcode:=A_SBB;
  10822. else
  10823. InternalError(2021011001);
  10824. end;
  10825. Taicpu(p).clearop(0);
  10826. Taicpu(p).ops:=0;
  10827. Taicpu(p).is_jmp:=false;
  10828. Taicpu(p).opcode:=A_CMC;
  10829. Taicpu(p).condition:=C_NONE;
  10830. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10831. Taicpu(hp1).ops:=2;
  10832. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10833. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10834. else
  10835. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10836. Taicpu(hp1).loadconst(0,0);
  10837. Taicpu(hp1).opcode:=carryadd_opcode;
  10838. result:=true;
  10839. exit;
  10840. end
  10841. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10842. begin
  10843. case taicpu(hp1).opcode of
  10844. A_INC,
  10845. A_ADD:
  10846. carryadd_opcode:=A_ADC;
  10847. A_DEC,
  10848. A_SUB:
  10849. carryadd_opcode:=A_SBB;
  10850. else
  10851. InternalError(2021011002);
  10852. end;
  10853. Taicpu(hp1).ops:=2;
  10854. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10855. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10856. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10857. else
  10858. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10859. Taicpu(hp1).loadconst(0,0);
  10860. Taicpu(hp1).opcode:=carryadd_opcode;
  10861. RemoveCurrentP(p, hp1);
  10862. result:=true;
  10863. exit;
  10864. end
  10865. {
  10866. jcc @@1 setcc tmpreg
  10867. inc/dec/add/sub operand -> (movzx tmpreg)
  10868. @@1: add/sub tmpreg,operand
  10869. While this increases code size slightly, it makes the code much faster if the
  10870. jump is unpredictable
  10871. }
  10872. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10873. begin
  10874. { search for an available register which is volatile }
  10875. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10876. if increg <> NR_NO then
  10877. begin
  10878. { We don't need to check if tmpreg is in hp1 or not, because
  10879. it will be marked as in use at p (if not, this is
  10880. indictive of a compiler bug). }
  10881. TAsmLabel(symbol).decrefs;
  10882. Taicpu(p).clearop(0);
  10883. Taicpu(p).ops:=1;
  10884. Taicpu(p).is_jmp:=false;
  10885. Taicpu(p).opcode:=A_SETcc;
  10886. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10887. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10888. Taicpu(p).loadreg(0,increg);
  10889. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10890. begin
  10891. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10892. R_SUBW:
  10893. begin
  10894. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10895. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10896. end;
  10897. R_SUBD:
  10898. begin
  10899. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10900. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10901. end;
  10902. {$ifdef x86_64}
  10903. R_SUBQ:
  10904. begin
  10905. { MOVZX doesn't have a 64-bit variant, because
  10906. the 32-bit version implicitly zeroes the
  10907. upper 32-bits of the destination register }
  10908. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10909. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10910. setsubreg(tmpreg, R_SUBQ);
  10911. end;
  10912. {$endif x86_64}
  10913. else
  10914. Internalerror(2020030601);
  10915. end;
  10916. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10917. asml.InsertAfter(hp2,p);
  10918. end
  10919. else
  10920. tmpreg := increg;
  10921. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10922. begin
  10923. Taicpu(hp1).ops:=2;
  10924. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10925. end;
  10926. Taicpu(hp1).loadreg(0,tmpreg);
  10927. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10928. Result := True;
  10929. { p is no longer a Jcc instruction, so exit }
  10930. Exit;
  10931. end;
  10932. end;
  10933. end;
  10934. { Detect the following:
  10935. jmp<cond> @Lbl1
  10936. jmp @Lbl2
  10937. ...
  10938. @Lbl1:
  10939. ret
  10940. Change to:
  10941. jmp<inv_cond> @Lbl2
  10942. ret
  10943. }
  10944. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10945. begin
  10946. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10947. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10948. MatchInstruction(hp2,A_RET,[S_NO]) then
  10949. begin
  10950. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10951. { Change label address to that of the unconditional jump }
  10952. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10953. TAsmLabel(symbol).DecRefs;
  10954. taicpu(hp1).opcode := A_RET;
  10955. taicpu(hp1).is_jmp := false;
  10956. taicpu(hp1).ops := taicpu(hp2).ops;
  10957. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10958. case taicpu(hp2).ops of
  10959. 0:
  10960. taicpu(hp1).clearop(0);
  10961. 1:
  10962. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10963. else
  10964. internalerror(2016041302);
  10965. end;
  10966. end;
  10967. {$ifndef i8086}
  10968. end
  10969. {
  10970. convert
  10971. j<c> .L1
  10972. mov 1,reg
  10973. jmp .L2
  10974. .L1
  10975. mov 0,reg
  10976. .L2
  10977. into
  10978. mov 0,reg
  10979. set<not(c)> reg
  10980. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10981. would destroy the flag contents
  10982. }
  10983. else if MatchInstruction(hp1,A_MOV,[]) and
  10984. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10985. {$ifdef i386}
  10986. (
  10987. { Under i386, ESI, EDI, EBP and ESP
  10988. don't have an 8-bit representation }
  10989. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10990. ) and
  10991. {$endif i386}
  10992. (taicpu(hp1).oper[0]^.val=1) and
  10993. GetNextInstruction(hp1,hp2) and
  10994. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10995. GetNextInstruction(hp2,hp3) and
  10996. (hp3.typ=ait_label) and
  10997. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10998. (tai_label(hp3).labsym.getrefs=1) and
  10999. GetNextInstruction(hp3,hp4) and
  11000. MatchInstruction(hp4,A_MOV,[]) and
  11001. MatchOpType(taicpu(hp4),top_const,top_reg) and
  11002. (taicpu(hp4).oper[0]^.val=0) and
  11003. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  11004. GetNextInstruction(hp4,hp5) and
  11005. (hp5.typ=ait_label) and
  11006. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  11007. (tai_label(hp5).labsym.getrefs=1) then
  11008. begin
  11009. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  11010. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  11011. { remove last label }
  11012. RemoveInstruction(hp5);
  11013. { remove second label }
  11014. RemoveInstruction(hp3);
  11015. { remove jmp }
  11016. RemoveInstruction(hp2);
  11017. if taicpu(hp1).opsize=S_B then
  11018. RemoveInstruction(hp1)
  11019. else
  11020. taicpu(hp1).loadconst(0,0);
  11021. taicpu(hp4).opcode:=A_SETcc;
  11022. taicpu(hp4).opsize:=S_B;
  11023. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  11024. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  11025. taicpu(hp4).opercnt:=1;
  11026. taicpu(hp4).ops:=1;
  11027. taicpu(hp4).freeop(1);
  11028. RemoveCurrentP(p);
  11029. Result:=true;
  11030. exit;
  11031. end
  11032. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  11033. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  11034. begin
  11035. { check for
  11036. jCC xxx
  11037. <several movs>
  11038. xxx:
  11039. Also spot:
  11040. Jcc xxx
  11041. <several movs>
  11042. jmp xxx
  11043. Change to:
  11044. <several cmovs with inverted condition>
  11045. jmp xxx (only for the 2nd case)
  11046. }
  11047. hp2 := p;
  11048. hp_lblxxx := hp1;
  11049. hp_flagalloc := nil;
  11050. hp_stop := nil;
  11051. FoundMatchingJump := False;
  11052. { Remember the first instruction in the first block of MOVs }
  11053. hpmov1 := hp1;
  11054. TransferUsedRegs(TmpUsedRegs);
  11055. while assigned(hp_lblxxx) and
  11056. { stop on labels }
  11057. (hp_lblxxx.typ <> ait_label) do
  11058. begin
  11059. { Keep track of all integer registers that are used }
  11060. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11061. if hp_lblxxx.typ = ait_instruction then
  11062. begin
  11063. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  11064. IsJumpToLabel(taicpu(hp_lblxxx)) then
  11065. begin
  11066. hp_stop := hp_lblxxx;
  11067. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  11068. begin
  11069. { We found Jcc xxx; <several movs>; Jmp xxx }
  11070. FoundMatchingJump := True;
  11071. Break;
  11072. end;
  11073. { If it's not the jump we're looking for, it's
  11074. possibly the "if..else" variant }
  11075. end
  11076. { Check to see if we have a valid MOV instruction instead }
  11077. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11078. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11079. Break
  11080. else
  11081. { This will be a valid MOV }
  11082. hp_stop := hp_lblxxx;
  11083. end;
  11084. hp2 := hp_lblxxx;
  11085. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11086. end;
  11087. { Just make sure the last MOV is included if there's no jump }
  11088. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11089. hp_stop := hp_lblxxx;
  11090. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11091. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11092. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11093. jmp yyy; xxx:; movs; yyy:" variation }
  11094. if assigned(hp_lblxxx) and
  11095. (
  11096. { If we found JMP xxx, we don't actually need a label
  11097. (hp_lblxxx is the JMP instruction instead) }
  11098. FoundMatchingJump or
  11099. { Make sure we actually have the right label }
  11100. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11101. ) then
  11102. begin
  11103. { Use TmpUsedRegs to track registers that we reserve }
  11104. { When allocating temporary registers, try to look one
  11105. instruction back, as defining them before a CMP or TEST
  11106. instruction will be faster, and also avoid picking a
  11107. register that was only just deallocated }
  11108. if GetLastInstruction(p, hp_prev) and
  11109. 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
  11110. begin
  11111. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11112. for l := 0 to 1 do
  11113. with taicpu(hp_prev).oper[l]^ do
  11114. case typ of
  11115. top_reg:
  11116. if getregtype(reg) = R_INTREGISTER then
  11117. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11118. top_ref:
  11119. begin
  11120. if
  11121. {$ifdef x86_64}
  11122. (ref^.base <> NR_RIP) and
  11123. {$endif x86_64}
  11124. (ref^.base <> NR_NO) then
  11125. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11126. if (ref^.index <> NR_NO) then
  11127. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11128. end
  11129. else
  11130. ;
  11131. end;
  11132. { When inserting instructions before hp_prev, try to insert
  11133. them before the allocation of the FLAGS register }
  11134. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11135. { If not found, set it equal to hp_prev so it's something sensible }
  11136. hp_flagalloc := hp_prev;
  11137. hp_prev2 := nil;
  11138. { When dealing with a comparison against zero, take
  11139. note of the instruction before it to see if we can
  11140. move instructions further back in order to benefit
  11141. PostPeepholeOptTestOr.
  11142. }
  11143. if (
  11144. (
  11145. (taicpu(hp_prev).opcode = A_CMP) and
  11146. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11147. ) or
  11148. (
  11149. (taicpu(hp_prev).opcode = A_TEST) and
  11150. (
  11151. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11152. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11153. )
  11154. )
  11155. ) and
  11156. GetLastInstruction(hp_prev, hp_prev2) then
  11157. begin
  11158. if (hp_prev2.typ = ait_instruction) and
  11159. { These instructions set the zero flag if the result is zero }
  11160. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11161. begin
  11162. { Also mark all the registers in this previous instruction
  11163. as 'in use', even if they've just been deallocated }
  11164. for l := 0 to 1 do
  11165. with taicpu(hp_prev2).oper[l]^ do
  11166. case typ of
  11167. top_reg:
  11168. if getregtype(reg) = R_INTREGISTER then
  11169. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11170. top_ref:
  11171. begin
  11172. if
  11173. {$ifdef x86_64}
  11174. (ref^.base <> NR_RIP) and
  11175. {$endif x86_64}
  11176. (ref^.base <> NR_NO) then
  11177. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11178. if (ref^.index <> NR_NO) then
  11179. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11180. end
  11181. else
  11182. ;
  11183. end;
  11184. end
  11185. else
  11186. { Unsuitable instruction }
  11187. hp_prev2 := nil;
  11188. end;
  11189. end
  11190. else
  11191. begin
  11192. hp_prev := p;
  11193. { When inserting instructions before hp_prev, try to insert
  11194. them before the allocation of the FLAGS register }
  11195. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11196. { If not found, set it equal to p so it's something sensible }
  11197. hp_flagalloc := p;
  11198. hp_prev2 := nil;
  11199. end;
  11200. l := 0;
  11201. c := 0;
  11202. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11203. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11204. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11205. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11206. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11207. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11208. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11209. RefModified := False;
  11210. while assigned(hp1) and
  11211. { Stop on the label we found }
  11212. (hp1 <> hp_lblxxx) do
  11213. begin
  11214. case hp1.typ of
  11215. ait_instruction:
  11216. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11217. begin
  11218. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11219. begin
  11220. Inc(l);
  11221. { MOV instruction will be writing to a register }
  11222. if Assigned(hp_prev) and
  11223. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11224. (hp_prev.typ = ait_instruction) and
  11225. (taicpu(hp_prev).ops = 2) and
  11226. (
  11227. (
  11228. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11229. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11230. ) or
  11231. (
  11232. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11233. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11234. )
  11235. ) then
  11236. { It is no longer safe to use the reference in the condition.
  11237. this prevents problems such as:
  11238. mov (%reg),%reg
  11239. mov (%reg),...
  11240. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11241. (fixes #40165)
  11242. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11243. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11244. }
  11245. RefModified := True;
  11246. end
  11247. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11248. { CMOV with constants grows the code size }
  11249. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11250. begin
  11251. { Register was reserved by TryCMOVConst and
  11252. stored on ConstRegs[c] }
  11253. end
  11254. else
  11255. Break;
  11256. end
  11257. else
  11258. Break;
  11259. else
  11260. ;
  11261. end;
  11262. GetNextInstruction(hp1,hp1);
  11263. end;
  11264. if (hp1 = hp_lblxxx) then
  11265. begin
  11266. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11267. begin
  11268. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11269. TmpUsedRegs[R_INTREGISTER].Clear;
  11270. x := 0;
  11271. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11272. condition := inverse_cond(taicpu(p).condition);
  11273. UpdateUsedRegs(tai(p.next));
  11274. hp1 := hpmov1;
  11275. repeat
  11276. if not Assigned(hp1) then
  11277. InternalError(2018062900);
  11278. if (hp1.typ = ait_instruction) then
  11279. begin
  11280. { Extra safeguard }
  11281. if (taicpu(hp1).opcode <> A_MOV) then
  11282. InternalError(2018062901);
  11283. if taicpu(hp1).oper[0]^.typ = top_const then
  11284. begin
  11285. if x >= MAX_CMOV_REGISTERS then
  11286. InternalError(2021100410);
  11287. { If it's in TmpUsedRegs, then this register
  11288. is being used more than once and hence has
  11289. already had its value defined (it gets
  11290. added to UsedRegs through AllocRegBetween
  11291. below) }
  11292. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11293. begin
  11294. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11295. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11296. asml.InsertBefore(hp_new, hp_flagalloc);
  11297. if Assigned(hp_prev2) then
  11298. TrySwapMovOp(hp_prev2, hp_new);
  11299. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11300. ConstMovs[X] := hp_new;
  11301. end
  11302. else
  11303. { We just need an instruction between hp_prev and hp1
  11304. where we know the register is marked as in use }
  11305. hp_new := hpmov1;
  11306. { Keep track of largest write for this register so it can be optimised later }
  11307. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11308. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11309. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11310. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11311. Inc(x);
  11312. end;
  11313. taicpu(hp1).opcode := A_CMOVcc;
  11314. taicpu(hp1).condition := condition;
  11315. end;
  11316. UpdateUsedRegs(tai(hp1.next));
  11317. GetNextInstruction(hp1, hp1);
  11318. until (hp1 = hp_lblxxx);
  11319. { Update initialisation MOVs to the smallest possible size }
  11320. for c := 0 to x - 1 do
  11321. if Assigned(ConstMovs[c]) then
  11322. begin
  11323. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11324. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11325. end;
  11326. hp2 := hp_lblxxx;
  11327. repeat
  11328. if not Assigned(hp2) then
  11329. InternalError(2018062910);
  11330. case hp2.typ of
  11331. ait_label:
  11332. { What we expected - break out of the loop (it won't be a dead label at the top of
  11333. a cluster because that was optimised at an earlier stage) }
  11334. Break;
  11335. ait_instruction:
  11336. begin
  11337. if taicpu(hp2).opcode<>A_JMP then
  11338. InternalError(2018062912);
  11339. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11340. Break;
  11341. end
  11342. else
  11343. begin
  11344. { Might be a comment or temporary allocation entry }
  11345. if not (hp2.typ in SkipInstr) then
  11346. InternalError(2018062911);
  11347. hp2 := tai(hp2.Next);
  11348. Continue;
  11349. end;
  11350. end;
  11351. until False;
  11352. { Now we can safely decrement the reference count }
  11353. tasmlabel(symbol).decrefs;
  11354. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11355. { Remove the original jump }
  11356. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11357. if hp2.typ=ait_instruction then
  11358. begin
  11359. p := hp2;
  11360. Result := True;
  11361. end
  11362. else
  11363. begin
  11364. UpdateUsedRegs(tai(hp2.next));
  11365. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11366. { Remove the label if this is its final reference }
  11367. if (tasmlabel(symbol).getrefs=0) then
  11368. begin
  11369. { Make sure the aligns get stripped too }
  11370. hp1 := tai(hp_lblxxx.Previous);
  11371. while Assigned(hp1) and (hp1.typ = ait_align) do
  11372. begin
  11373. hp_lblxxx := hp1;
  11374. hp1 := tai(hp_lblxxx.Previous);
  11375. end;
  11376. StripLabelFast(hp_lblxxx);
  11377. end;
  11378. end;
  11379. Exit;
  11380. end;
  11381. end
  11382. else if assigned(hp_lblxxx) and
  11383. { check further for
  11384. jCC xxx
  11385. <several movs 1>
  11386. jmp yyy
  11387. xxx:
  11388. <several movs 2>
  11389. yyy:
  11390. }
  11391. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11392. { hp1 should be pointing to jmp yyy }
  11393. MatchInstruction(hp1, A_JMP, []) and
  11394. { real label and jump, no further references to the
  11395. label are allowed }
  11396. (TAsmLabel(symbol).getrefs=1) and
  11397. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11398. begin
  11399. hp_jump := hp1;
  11400. { Don't set c to zero }
  11401. l := 0;
  11402. w := 0;
  11403. GetNextInstruction(hp_lblxxx, hpmov2);
  11404. hp2 := hp_lblxxx;
  11405. hp_lblyyy := hpmov2;
  11406. while assigned(hp_lblyyy) and
  11407. { stop on labels }
  11408. (hp_lblyyy.typ <> ait_label) do
  11409. begin
  11410. { Keep track of all integer registers that are used }
  11411. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11412. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11413. Break;
  11414. hp2 := hp_lblyyy;
  11415. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11416. end;
  11417. { Analyse the second batch of MOVs to see if the setup is valid }
  11418. RefModified := False;
  11419. hp1 := hpmov2;
  11420. while assigned(hp1) and
  11421. (hp1 <> hp_lblyyy) do
  11422. begin
  11423. case hp1.typ of
  11424. ait_instruction:
  11425. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11426. begin
  11427. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11428. begin
  11429. Inc(l);
  11430. { MOV instruction will be writing to a register }
  11431. if Assigned(hp_prev) and
  11432. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11433. (hp_prev.typ = ait_instruction) and
  11434. (taicpu(hp_prev).ops = 2) and
  11435. (
  11436. (
  11437. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11438. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11439. ) or
  11440. (
  11441. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11442. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11443. )
  11444. ) then
  11445. { It is no longer safe to use the reference in the condition.
  11446. this prevents problems such as:
  11447. mov (%reg),%reg
  11448. mov (%reg),...
  11449. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11450. (fixes #40165)
  11451. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11452. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11453. }
  11454. RefModified := True;
  11455. end
  11456. else if not (cs_opt_size in current_settings.optimizerswitches)
  11457. { CMOV with constants grows the code size }
  11458. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11459. begin
  11460. { Register was reserved by TryCMOVConst and
  11461. stored on ConstRegs[c] }
  11462. end
  11463. else
  11464. Break;
  11465. end
  11466. else
  11467. Break;
  11468. else
  11469. ;
  11470. end;
  11471. GetNextInstruction(hp1,hp1);
  11472. end;
  11473. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11474. TmpUsedRegs[R_INTREGISTER].Clear;
  11475. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11476. (hp1 = hp_lblyyy) and
  11477. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11478. begin
  11479. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11480. second_condition := taicpu(p).condition;
  11481. condition := inverse_cond(taicpu(p).condition);
  11482. UpdateUsedRegs(tai(p.next));
  11483. { Scan through the first set of MOVs to update UsedRegs,
  11484. but don't process them yet }
  11485. hp1 := hpmov1;
  11486. repeat
  11487. if not Assigned(hp1) then
  11488. InternalError(2018062901);
  11489. UpdateUsedRegs(tai(hp1.next));
  11490. GetNextInstruction(hp1, hp1);
  11491. until (hp1 = hp_lblxxx);
  11492. UpdateUsedRegs(tai(hp_lblxxx.next));
  11493. { Process the second set of MOVs first,
  11494. because if a destination register is
  11495. shared between the first and second MOV
  11496. sets, it is more efficient to turn the
  11497. first one into a MOV instruction and place
  11498. it before the CMP if possible, but we
  11499. won't know which registers are shared
  11500. until we've processed at least one list,
  11501. so we might as well make it the second
  11502. one since that won't be modified again. }
  11503. hp1 := hpmov2;
  11504. repeat
  11505. if not Assigned(hp1) then
  11506. InternalError(2018062902);
  11507. if (hp1.typ = ait_instruction) then
  11508. begin
  11509. { Extra safeguard }
  11510. if (taicpu(hp1).opcode <> A_MOV) then
  11511. InternalError(2018062903);
  11512. if taicpu(hp1).oper[0]^.typ = top_const then
  11513. begin
  11514. RegMatch := False;
  11515. for x := 0 to c - 1 do
  11516. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11517. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11518. begin
  11519. RegMatch := True;
  11520. { If it's in TmpUsedRegs, then this register
  11521. is being used more than once and hence has
  11522. already had its value defined (it gets
  11523. added to UsedRegs through AllocRegBetween
  11524. below) }
  11525. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11526. begin
  11527. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11528. asml.InsertBefore(hp_new, hp_flagalloc);
  11529. if Assigned(hp_prev2) then
  11530. TrySwapMovOp(hp_prev2, hp_new);
  11531. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11532. ConstMovs[X] := hp_new;
  11533. end
  11534. else
  11535. { We just need an instruction between hp_prev and hp1
  11536. where we know the register is marked as in use }
  11537. hp_new := hpmov2;
  11538. { Keep track of largest write for this register so it can be optimised later }
  11539. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11540. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11541. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11542. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11543. Break;
  11544. end;
  11545. if not RegMatch then
  11546. InternalError(2021100411);
  11547. end;
  11548. taicpu(hp1).opcode := A_CMOVcc;
  11549. taicpu(hp1).condition := second_condition;
  11550. { Store these writes to search for
  11551. duplicates later on }
  11552. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11553. Inc(w);
  11554. end;
  11555. UpdateUsedRegs(tai(hp1.next));
  11556. GetNextInstruction(hp1, hp1);
  11557. until (hp1 = hp_lblyyy);
  11558. { Now do the first set of MOVs }
  11559. hp1 := hpmov1;
  11560. repeat
  11561. if not Assigned(hp1) then
  11562. InternalError(2018062904);
  11563. if (hp1.typ = ait_instruction) then
  11564. begin
  11565. RegMatch := False;
  11566. { Extra safeguard }
  11567. if (taicpu(hp1).opcode <> A_MOV) then
  11568. InternalError(2018062905);
  11569. { Search through the RegWrites list to see
  11570. if there are any opposing CMOV pairs that
  11571. write to the same register }
  11572. for x := 0 to w - 1 do
  11573. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11574. begin
  11575. { We have a match. Keep this as a MOV }
  11576. { Move ahead in preparation }
  11577. GetNextInstruction(hp1, hp1);
  11578. RegMatch := True;
  11579. Break;
  11580. end;
  11581. if RegMatch then
  11582. Continue;
  11583. if taicpu(hp1).oper[0]^.typ = top_const then
  11584. begin
  11585. RegMatch := False;
  11586. for x := 0 to c - 1 do
  11587. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11588. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11589. begin
  11590. RegMatch := True;
  11591. { If it's in TmpUsedRegs, then this register
  11592. is being used more than once and hence has
  11593. already had its value defined (it gets
  11594. added to UsedRegs through AllocRegBetween
  11595. below) }
  11596. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11597. begin
  11598. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11599. asml.InsertBefore(hp_new, hp_flagalloc);
  11600. if Assigned(hp_prev2) then
  11601. TrySwapMovOp(hp_prev2, hp_new);
  11602. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11603. ConstMovs[X] := hp_new;
  11604. end
  11605. else
  11606. { We just need an instruction between hp_prev and hp1
  11607. where we know the register is marked as in use }
  11608. hp_new := hpmov1;
  11609. { Keep track of largest write for this register so it can be optimised later }
  11610. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11611. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11612. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11613. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11614. Break;
  11615. end;
  11616. if not RegMatch then
  11617. InternalError(2021100412);
  11618. end;
  11619. taicpu(hp1).opcode := A_CMOVcc;
  11620. taicpu(hp1).condition := condition;
  11621. end;
  11622. GetNextInstruction(hp1, hp1);
  11623. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11624. { Update initialisation MOVs to the smallest possible size }
  11625. for x := 0 to c - 1 do
  11626. if Assigned(ConstMovs[x]) then
  11627. begin
  11628. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11629. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11630. end;
  11631. UpdateUsedRegs(tai(hp_jump.next));
  11632. UpdateUsedRegs(tai(hp_lblyyy.next));
  11633. { Get first instruction after label }
  11634. hp1 := p;
  11635. GetNextInstruction(hp_lblyyy, p);
  11636. { Don't dereference yet, as doing so will cause
  11637. GetNextInstruction to skip the label and
  11638. optional align marker. [Kit] }
  11639. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11640. { remove Jcc }
  11641. RemoveInstruction(hp1);
  11642. { Now we can safely decrement it }
  11643. tasmlabel(symbol).decrefs;
  11644. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11645. { Make sure the aligns get stripped too }
  11646. hp1 := tai(hp_lblxxx.Previous);
  11647. while Assigned(hp1) and (hp1.typ = ait_align) do
  11648. begin
  11649. hp_lblxxx := hp1;
  11650. hp1 := tai(hp_lblxxx.Previous);
  11651. end;
  11652. StripLabelFast(hp_lblxxx);
  11653. { remove jmp }
  11654. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11655. RemoveInstruction(hp_jump);
  11656. { As before, now we can safely decrement it }
  11657. TAsmLabel(symbol).decrefs;
  11658. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11659. if TAsmLabel(symbol).getrefs = 0 then
  11660. begin
  11661. { Make sure the aligns get stripped too }
  11662. hp1 := tai(hp_lblyyy.Previous);
  11663. while Assigned(hp1) and (hp1.typ = ait_align) do
  11664. begin
  11665. hp_lblyyy := hp1;
  11666. hp1 := tai(hp_lblyyy.Previous);
  11667. end;
  11668. StripLabelFast(hp_lblyyy);
  11669. end;
  11670. if Assigned(p) then
  11671. result := True;
  11672. exit;
  11673. end;
  11674. end;
  11675. end;
  11676. {$endif i8086}
  11677. end;
  11678. end;
  11679. end;
  11680. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11681. var
  11682. hp1,hp2,hp3: tai;
  11683. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11684. NewSize: TOpSize;
  11685. NewRegSize: TSubRegister;
  11686. Limit: TCgInt;
  11687. SwapOper: POper;
  11688. begin
  11689. result:=false;
  11690. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11691. GetNextInstruction(p,hp1) and
  11692. (hp1.typ = ait_instruction);
  11693. if reg_and_hp1_is_instr and
  11694. (
  11695. (taicpu(hp1).opcode <> A_LEA) or
  11696. { If the LEA instruction can be converted into an arithmetic instruction,
  11697. it may be possible to then fold it. }
  11698. (
  11699. { If the flags register is in use, don't change the instruction
  11700. to an ADD otherwise this will scramble the flags. [Kit] }
  11701. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11702. ConvertLEA(taicpu(hp1))
  11703. )
  11704. ) and
  11705. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11706. GetNextInstruction(hp1,hp2) and
  11707. MatchInstruction(hp2,A_MOV,[]) and
  11708. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11709. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11710. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11711. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11712. {$ifdef i386}
  11713. { not all registers have byte size sub registers on i386 }
  11714. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11715. {$endif i386}
  11716. (((taicpu(hp1).ops=2) and
  11717. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11718. ((taicpu(hp1).ops=1) and
  11719. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11720. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11721. begin
  11722. { change movsX/movzX reg/ref, reg2
  11723. add/sub/or/... reg3/$const, reg2
  11724. mov reg2 reg/ref
  11725. to add/sub/or/... reg3/$const, reg/ref }
  11726. { by example:
  11727. movswl %si,%eax movswl %si,%eax p
  11728. decl %eax addl %edx,%eax hp1
  11729. movw %ax,%si movw %ax,%si hp2
  11730. ->
  11731. movswl %si,%eax movswl %si,%eax p
  11732. decw %eax addw %edx,%eax hp1
  11733. movw %ax,%si movw %ax,%si hp2
  11734. }
  11735. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11736. {
  11737. ->
  11738. movswl %si,%eax movswl %si,%eax p
  11739. decw %si addw %dx,%si hp1
  11740. movw %ax,%si movw %ax,%si hp2
  11741. }
  11742. case taicpu(hp1).ops of
  11743. 1:
  11744. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11745. 2:
  11746. begin
  11747. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11748. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11749. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11750. end;
  11751. else
  11752. internalerror(2008042702);
  11753. end;
  11754. {
  11755. ->
  11756. decw %si addw %dx,%si p
  11757. }
  11758. DebugMsg(SPeepholeOptimization + 'var3',p);
  11759. RemoveCurrentP(p, hp1);
  11760. RemoveInstruction(hp2);
  11761. Result := True;
  11762. Exit;
  11763. end;
  11764. if reg_and_hp1_is_instr and
  11765. (taicpu(hp1).opcode = A_MOV) and
  11766. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11767. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11768. {$ifdef x86_64}
  11769. { check for implicit extension to 64 bit }
  11770. or
  11771. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11772. (taicpu(hp1).opsize=S_Q) and
  11773. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11774. )
  11775. {$endif x86_64}
  11776. )
  11777. then
  11778. begin
  11779. { change
  11780. movx %reg1,%reg2
  11781. mov %reg2,%reg3
  11782. dealloc %reg2
  11783. into
  11784. movx %reg,%reg3
  11785. }
  11786. TransferUsedRegs(TmpUsedRegs);
  11787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11788. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11789. begin
  11790. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11791. {$ifdef x86_64}
  11792. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11793. (taicpu(hp1).opsize=S_Q) then
  11794. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11795. else
  11796. {$endif x86_64}
  11797. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11798. RemoveInstruction(hp1);
  11799. Result := True;
  11800. Exit;
  11801. end;
  11802. end;
  11803. if reg_and_hp1_is_instr and
  11804. ((taicpu(hp1).opcode=A_MOV) or
  11805. (taicpu(hp1).opcode=A_ADD) or
  11806. (taicpu(hp1).opcode=A_SUB) or
  11807. (taicpu(hp1).opcode=A_CMP) or
  11808. (taicpu(hp1).opcode=A_OR) or
  11809. (taicpu(hp1).opcode=A_XOR) or
  11810. (taicpu(hp1).opcode=A_AND)
  11811. ) and
  11812. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11813. begin
  11814. AndTest := (taicpu(hp1).opcode=A_AND) and
  11815. GetNextInstruction(hp1, hp2) and
  11816. (hp2.typ = ait_instruction) and
  11817. (
  11818. (
  11819. (taicpu(hp2).opcode=A_TEST) and
  11820. (
  11821. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11822. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11823. (
  11824. { If the AND and TEST instructions share a constant, this is also valid }
  11825. (taicpu(hp1).oper[0]^.typ = top_const) and
  11826. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11827. )
  11828. ) and
  11829. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11830. ) or
  11831. (
  11832. (taicpu(hp2).opcode=A_CMP) and
  11833. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11834. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11835. )
  11836. );
  11837. { change
  11838. movx (oper),%reg2
  11839. and $x,%reg2
  11840. test %reg2,%reg2
  11841. dealloc %reg2
  11842. into
  11843. op %reg1,%reg3
  11844. if the second op accesses only the bits stored in reg1
  11845. }
  11846. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11847. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11848. (taicpu(hp1).oper[0]^.typ = top_const) and
  11849. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11850. AndTest then
  11851. begin
  11852. { Check if the AND constant is in range }
  11853. case taicpu(p).opsize of
  11854. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11855. begin
  11856. NewSize := S_B;
  11857. Limit := $FF;
  11858. end;
  11859. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11860. begin
  11861. NewSize := S_W;
  11862. Limit := $FFFF;
  11863. end;
  11864. {$ifdef x86_64}
  11865. S_LQ:
  11866. begin
  11867. NewSize := S_L;
  11868. Limit := $FFFFFFFF;
  11869. end;
  11870. {$endif x86_64}
  11871. else
  11872. InternalError(2021120303);
  11873. end;
  11874. if (
  11875. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11876. { Check for negative operands }
  11877. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11878. ) and
  11879. GetNextInstruction(hp2,hp3) and
  11880. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11881. (taicpu(hp3).condition in [C_E,C_NE]) then
  11882. begin
  11883. TransferUsedRegs(TmpUsedRegs);
  11884. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11885. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11886. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11887. begin
  11888. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11889. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11890. taicpu(hp1).opcode := A_TEST;
  11891. taicpu(hp1).opsize := NewSize;
  11892. RemoveInstruction(hp2);
  11893. RemoveCurrentP(p, hp1);
  11894. Result:=true;
  11895. exit;
  11896. end;
  11897. end;
  11898. end;
  11899. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11900. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11901. (taicpu(hp1).opsize=S_B)) or
  11902. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11903. (taicpu(hp1).opsize=S_W))
  11904. {$ifdef x86_64}
  11905. or ((taicpu(p).opsize=S_LQ) and
  11906. (taicpu(hp1).opsize=S_L))
  11907. {$endif x86_64}
  11908. ) and
  11909. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11910. begin
  11911. { change
  11912. movx %reg1,%reg2
  11913. op %reg2,%reg3
  11914. dealloc %reg2
  11915. into
  11916. op %reg1,%reg3
  11917. if the second op accesses only the bits stored in reg1
  11918. }
  11919. TransferUsedRegs(TmpUsedRegs);
  11920. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11921. if AndTest then
  11922. begin
  11923. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11924. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11925. end
  11926. else
  11927. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11928. if not RegUsed then
  11929. begin
  11930. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11931. if taicpu(p).oper[0]^.typ=top_reg then
  11932. begin
  11933. case taicpu(hp1).opsize of
  11934. S_B:
  11935. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11936. S_W:
  11937. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11938. S_L:
  11939. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11940. else
  11941. Internalerror(2020102301);
  11942. end;
  11943. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11944. end
  11945. else
  11946. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11947. RemoveCurrentP(p);
  11948. if AndTest then
  11949. RemoveInstruction(hp2);
  11950. result:=true;
  11951. exit;
  11952. end;
  11953. end
  11954. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11955. (
  11956. { Bitwise operations only }
  11957. (taicpu(hp1).opcode=A_AND) or
  11958. (taicpu(hp1).opcode=A_TEST) or
  11959. (
  11960. (taicpu(hp1).oper[0]^.typ = top_const) and
  11961. (
  11962. (taicpu(hp1).opcode=A_OR) or
  11963. (taicpu(hp1).opcode=A_XOR)
  11964. )
  11965. )
  11966. ) and
  11967. (
  11968. (taicpu(hp1).oper[0]^.typ = top_const) or
  11969. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11970. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11971. ) then
  11972. begin
  11973. { change
  11974. movx %reg2,%reg2
  11975. op const,%reg2
  11976. into
  11977. op const,%reg2 (smaller version)
  11978. movx %reg2,%reg2
  11979. also change
  11980. movx %reg1,%reg2
  11981. and/test (oper),%reg2
  11982. dealloc %reg2
  11983. into
  11984. and/test (oper),%reg1
  11985. }
  11986. case taicpu(p).opsize of
  11987. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11988. begin
  11989. NewSize := S_B;
  11990. NewRegSize := R_SUBL;
  11991. Limit := $FF;
  11992. end;
  11993. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11994. begin
  11995. NewSize := S_W;
  11996. NewRegSize := R_SUBW;
  11997. Limit := $FFFF;
  11998. end;
  11999. {$ifdef x86_64}
  12000. S_LQ:
  12001. begin
  12002. NewSize := S_L;
  12003. NewRegSize := R_SUBD;
  12004. Limit := $FFFFFFFF;
  12005. end;
  12006. {$endif x86_64}
  12007. else
  12008. Internalerror(2021120302);
  12009. end;
  12010. TransferUsedRegs(TmpUsedRegs);
  12011. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12012. if AndTest then
  12013. begin
  12014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12015. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12016. end
  12017. else
  12018. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12019. if
  12020. (
  12021. (taicpu(p).opcode = A_MOVZX) and
  12022. (
  12023. (taicpu(hp1).opcode=A_AND) or
  12024. (taicpu(hp1).opcode=A_TEST)
  12025. ) and
  12026. not (
  12027. { If both are references, then the final instruction will have
  12028. both operands as references, which is not allowed }
  12029. (taicpu(p).oper[0]^.typ = top_ref) and
  12030. (taicpu(hp1).oper[0]^.typ = top_ref)
  12031. ) and
  12032. not RegUsed
  12033. ) or
  12034. (
  12035. (
  12036. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12037. not RegUsed
  12038. ) and
  12039. (taicpu(p).oper[0]^.typ = top_reg) and
  12040. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12041. (taicpu(hp1).oper[0]^.typ = top_const) and
  12042. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12043. ) then
  12044. begin
  12045. {$if defined(i386) or defined(i8086)}
  12046. { If the target size is 8-bit, make sure we can actually encode it }
  12047. 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
  12048. Exit;
  12049. {$endif i386 or i8086}
  12050. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12051. taicpu(hp1).opsize := NewSize;
  12052. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12053. if AndTest then
  12054. begin
  12055. RemoveInstruction(hp2);
  12056. if not RegUsed then
  12057. begin
  12058. taicpu(hp1).opcode := A_TEST;
  12059. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12060. begin
  12061. { Make sure the reference is the second operand }
  12062. SwapOper := taicpu(hp1).oper[0];
  12063. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12064. taicpu(hp1).oper[1] := SwapOper;
  12065. end;
  12066. end;
  12067. end;
  12068. case taicpu(hp1).oper[0]^.typ of
  12069. top_reg:
  12070. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12071. top_const:
  12072. { For the AND/TEST case }
  12073. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12074. else
  12075. ;
  12076. end;
  12077. if RegUsed then
  12078. begin
  12079. AsmL.Remove(p);
  12080. AsmL.InsertAfter(p, hp1);
  12081. p := hp1;
  12082. end
  12083. else
  12084. RemoveCurrentP(p, hp1);
  12085. result:=true;
  12086. exit;
  12087. end;
  12088. end;
  12089. end;
  12090. if reg_and_hp1_is_instr and
  12091. (taicpu(p).oper[0]^.typ = top_reg) and
  12092. (
  12093. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12094. ) and
  12095. (taicpu(hp1).oper[0]^.typ = top_const) and
  12096. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12097. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12098. { Minimum shift value allowed is the bit difference between the sizes }
  12099. (taicpu(hp1).oper[0]^.val >=
  12100. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12101. 8 * (
  12102. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12103. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12104. )
  12105. ) then
  12106. begin
  12107. { For:
  12108. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12109. shl/sal ##, %reg1
  12110. Remove the movsx/movzx instruction if the shift overwrites the
  12111. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12112. }
  12113. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12114. RemoveCurrentP(p, hp1);
  12115. Result := True;
  12116. Exit;
  12117. end
  12118. else if reg_and_hp1_is_instr and
  12119. (taicpu(p).oper[0]^.typ = top_reg) and
  12120. (
  12121. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12122. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12123. ) and
  12124. (taicpu(hp1).oper[0]^.typ = top_const) and
  12125. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12126. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12127. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12128. (taicpu(hp1).oper[0]^.val <
  12129. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12130. 8 * (
  12131. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12132. )
  12133. ) then
  12134. begin
  12135. { For:
  12136. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12137. sar ##, %reg1 shr ##, %reg1
  12138. Move the shift to before the movx instruction if the shift value
  12139. is not too large.
  12140. }
  12141. asml.Remove(hp1);
  12142. asml.InsertBefore(hp1, p);
  12143. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12144. case taicpu(p).opsize of
  12145. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12146. taicpu(hp1).opsize := S_B;
  12147. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12148. taicpu(hp1).opsize := S_W;
  12149. {$ifdef x86_64}
  12150. S_LQ:
  12151. taicpu(hp1).opsize := S_L;
  12152. {$endif}
  12153. else
  12154. InternalError(2020112401);
  12155. end;
  12156. if (taicpu(hp1).opcode = A_SHR) then
  12157. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12158. else
  12159. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12160. Result := True;
  12161. end;
  12162. if reg_and_hp1_is_instr and
  12163. (taicpu(p).oper[0]^.typ = top_reg) and
  12164. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12165. (
  12166. (taicpu(hp1).opcode = taicpu(p).opcode)
  12167. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12168. {$ifdef x86_64}
  12169. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12170. {$endif x86_64}
  12171. ) then
  12172. begin
  12173. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12174. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12175. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12176. begin
  12177. {
  12178. For example:
  12179. movzbw %al,%ax
  12180. movzwl %ax,%eax
  12181. Compress into:
  12182. movzbl %al,%eax
  12183. }
  12184. RegUsed := False;
  12185. case taicpu(p).opsize of
  12186. S_BW:
  12187. case taicpu(hp1).opsize of
  12188. S_WL:
  12189. begin
  12190. taicpu(p).opsize := S_BL;
  12191. RegUsed := True;
  12192. end;
  12193. {$ifdef x86_64}
  12194. S_WQ:
  12195. begin
  12196. if taicpu(p).opcode = A_MOVZX then
  12197. begin
  12198. taicpu(p).opsize := S_BL;
  12199. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12200. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12201. end
  12202. else
  12203. taicpu(p).opsize := S_BQ;
  12204. RegUsed := True;
  12205. end;
  12206. {$endif x86_64}
  12207. else
  12208. ;
  12209. end;
  12210. {$ifdef x86_64}
  12211. S_BL:
  12212. case taicpu(hp1).opsize of
  12213. S_LQ:
  12214. begin
  12215. if taicpu(p).opcode = A_MOVZX then
  12216. begin
  12217. taicpu(p).opsize := S_BL;
  12218. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12219. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12220. end
  12221. else
  12222. taicpu(p).opsize := S_BQ;
  12223. RegUsed := True;
  12224. end;
  12225. else
  12226. ;
  12227. end;
  12228. S_WL:
  12229. case taicpu(hp1).opsize of
  12230. S_LQ:
  12231. begin
  12232. if taicpu(p).opcode = A_MOVZX then
  12233. begin
  12234. taicpu(p).opsize := S_WL;
  12235. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12236. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12237. end
  12238. else
  12239. taicpu(p).opsize := S_WQ;
  12240. RegUsed := True;
  12241. end;
  12242. else
  12243. ;
  12244. end;
  12245. {$endif x86_64}
  12246. else
  12247. ;
  12248. end;
  12249. if RegUsed then
  12250. begin
  12251. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12252. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12253. RemoveInstruction(hp1);
  12254. Result := True;
  12255. Exit;
  12256. end;
  12257. end;
  12258. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12259. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12260. GetNextInstruction(hp1, hp2) and
  12261. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12262. (
  12263. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12264. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12265. {$ifdef x86_64}
  12266. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12267. {$endif x86_64}
  12268. ) and
  12269. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12270. (
  12271. (
  12272. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12273. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12274. ) or
  12275. (
  12276. { Only allow the operands in reverse order for TEST instructions }
  12277. (taicpu(hp2).opcode = A_TEST) and
  12278. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12279. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12280. )
  12281. ) then
  12282. begin
  12283. {
  12284. For example:
  12285. movzbl %al,%eax
  12286. movzbl (ref),%edx
  12287. andl %edx,%eax
  12288. (%edx deallocated)
  12289. Change to:
  12290. andb (ref),%al
  12291. movzbl %al,%eax
  12292. Rules are:
  12293. - First two instructions have the same opcode and opsize
  12294. - First instruction's operands are the same super-register
  12295. - Second instruction operates on a different register
  12296. - Third instruction is AND, OR, XOR or TEST
  12297. - Third instruction's operands are the destination registers of the first two instructions
  12298. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12299. - Second instruction's destination register is deallocated afterwards
  12300. }
  12301. TransferUsedRegs(TmpUsedRegs);
  12302. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12303. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12304. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12305. begin
  12306. case taicpu(p).opsize of
  12307. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12308. NewSize := S_B;
  12309. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12310. NewSize := S_W;
  12311. {$ifdef x86_64}
  12312. S_LQ:
  12313. NewSize := S_L;
  12314. {$endif x86_64}
  12315. else
  12316. InternalError(2021120301);
  12317. end;
  12318. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12319. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12320. taicpu(hp2).opsize := NewSize;
  12321. RemoveInstruction(hp1);
  12322. { With TEST, it's best to keep the MOVX instruction at the top }
  12323. if (taicpu(hp2).opcode <> A_TEST) then
  12324. begin
  12325. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12326. asml.Remove(p);
  12327. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12328. asml.InsertAfter(p, hp2);
  12329. p := hp2;
  12330. end
  12331. else
  12332. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12333. Result := True;
  12334. Exit;
  12335. end;
  12336. end;
  12337. end;
  12338. if taicpu(p).opcode=A_MOVZX then
  12339. begin
  12340. { removes superfluous And's after movzx's }
  12341. if reg_and_hp1_is_instr and
  12342. (taicpu(hp1).opcode = A_AND) and
  12343. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12344. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12345. {$ifdef x86_64}
  12346. { check for implicit extension to 64 bit }
  12347. or
  12348. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12349. (taicpu(hp1).opsize=S_Q) and
  12350. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12351. )
  12352. {$endif x86_64}
  12353. )
  12354. then
  12355. begin
  12356. case taicpu(p).opsize Of
  12357. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12358. if (taicpu(hp1).oper[0]^.val = $ff) then
  12359. begin
  12360. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12361. RemoveInstruction(hp1);
  12362. Result:=true;
  12363. exit;
  12364. end;
  12365. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12366. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12367. begin
  12368. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12369. RemoveInstruction(hp1);
  12370. Result:=true;
  12371. exit;
  12372. end;
  12373. {$ifdef x86_64}
  12374. S_LQ:
  12375. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12376. begin
  12377. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12378. RemoveInstruction(hp1);
  12379. Result:=true;
  12380. exit;
  12381. end;
  12382. {$endif x86_64}
  12383. else
  12384. ;
  12385. end;
  12386. { we cannot get rid of the and, but can we get rid of the movz ?}
  12387. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12388. begin
  12389. case taicpu(p).opsize Of
  12390. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12391. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12392. begin
  12393. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12394. RemoveCurrentP(p,hp1);
  12395. Result:=true;
  12396. exit;
  12397. end;
  12398. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12399. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12400. begin
  12401. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12402. RemoveCurrentP(p,hp1);
  12403. Result:=true;
  12404. exit;
  12405. end;
  12406. {$ifdef x86_64}
  12407. S_LQ:
  12408. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12409. begin
  12410. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12411. RemoveCurrentP(p,hp1);
  12412. Result:=true;
  12413. exit;
  12414. end;
  12415. {$endif x86_64}
  12416. else
  12417. ;
  12418. end;
  12419. end;
  12420. end;
  12421. { changes some movzx constructs to faster synonyms (all examples
  12422. are given with eax/ax, but are also valid for other registers)}
  12423. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12424. begin
  12425. case taicpu(p).opsize of
  12426. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12427. (the machine code is equivalent to movzbl %al,%eax), but the
  12428. code generator still generates that assembler instruction and
  12429. it is silently converted. This should probably be checked.
  12430. [Kit] }
  12431. S_BW:
  12432. begin
  12433. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12434. (
  12435. not IsMOVZXAcceptable
  12436. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12437. or (
  12438. (cs_opt_size in current_settings.optimizerswitches) and
  12439. (taicpu(p).oper[1]^.reg = NR_AX)
  12440. )
  12441. ) then
  12442. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12443. begin
  12444. DebugMsg(SPeepholeOptimization + 'var7',p);
  12445. taicpu(p).opcode := A_AND;
  12446. taicpu(p).changeopsize(S_W);
  12447. taicpu(p).loadConst(0,$ff);
  12448. Result := True;
  12449. end
  12450. else if not IsMOVZXAcceptable and
  12451. GetNextInstruction(p, hp1) and
  12452. (tai(hp1).typ = ait_instruction) and
  12453. (taicpu(hp1).opcode = A_AND) and
  12454. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12455. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12456. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12457. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12458. begin
  12459. DebugMsg(SPeepholeOptimization + 'var8',p);
  12460. taicpu(p).opcode := A_MOV;
  12461. taicpu(p).changeopsize(S_W);
  12462. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12463. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12464. Result := True;
  12465. end;
  12466. end;
  12467. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12468. S_BL:
  12469. if not IsMOVZXAcceptable then
  12470. begin
  12471. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12472. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12473. begin
  12474. DebugMsg(SPeepholeOptimization + 'var9',p);
  12475. taicpu(p).opcode := A_AND;
  12476. taicpu(p).changeopsize(S_L);
  12477. taicpu(p).loadConst(0,$ff);
  12478. Result := True;
  12479. end
  12480. else if GetNextInstruction(p, hp1) and
  12481. (tai(hp1).typ = ait_instruction) and
  12482. (taicpu(hp1).opcode = A_AND) and
  12483. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12484. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12485. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12486. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12487. begin
  12488. DebugMsg(SPeepholeOptimization + 'var10',p);
  12489. taicpu(p).opcode := A_MOV;
  12490. taicpu(p).changeopsize(S_L);
  12491. { do not use R_SUBWHOLE
  12492. as movl %rdx,%eax
  12493. is invalid in assembler PM }
  12494. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12495. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12496. Result := True;
  12497. end;
  12498. end;
  12499. {$endif i8086}
  12500. S_WL:
  12501. if not IsMOVZXAcceptable then
  12502. begin
  12503. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12504. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12505. begin
  12506. DebugMsg(SPeepholeOptimization + 'var11',p);
  12507. taicpu(p).opcode := A_AND;
  12508. taicpu(p).changeopsize(S_L);
  12509. taicpu(p).loadConst(0,$ffff);
  12510. Result := True;
  12511. end
  12512. else if GetNextInstruction(p, hp1) and
  12513. (tai(hp1).typ = ait_instruction) and
  12514. (taicpu(hp1).opcode = A_AND) and
  12515. (taicpu(hp1).oper[0]^.typ = top_const) and
  12516. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12517. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12518. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12519. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12520. begin
  12521. DebugMsg(SPeepholeOptimization + 'var12',p);
  12522. taicpu(p).opcode := A_MOV;
  12523. taicpu(p).changeopsize(S_L);
  12524. { do not use R_SUBWHOLE
  12525. as movl %rdx,%eax
  12526. is invalid in assembler PM }
  12527. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12528. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12529. Result := True;
  12530. end;
  12531. end;
  12532. else
  12533. InternalError(2017050705);
  12534. end;
  12535. end
  12536. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12537. begin
  12538. if GetNextInstruction(p, hp1) and
  12539. (tai(hp1).typ = ait_instruction) and
  12540. (taicpu(hp1).opcode = A_AND) and
  12541. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12542. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12543. begin
  12544. //taicpu(p).opcode := A_MOV;
  12545. case taicpu(p).opsize Of
  12546. S_BL:
  12547. begin
  12548. DebugMsg(SPeepholeOptimization + 'var13',p);
  12549. taicpu(hp1).changeopsize(S_L);
  12550. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12551. end;
  12552. S_WL:
  12553. begin
  12554. DebugMsg(SPeepholeOptimization + 'var14',p);
  12555. taicpu(hp1).changeopsize(S_L);
  12556. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12557. end;
  12558. S_BW:
  12559. begin
  12560. DebugMsg(SPeepholeOptimization + 'var15',p);
  12561. taicpu(hp1).changeopsize(S_W);
  12562. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12563. end;
  12564. else
  12565. Internalerror(2017050704)
  12566. end;
  12567. Result := True;
  12568. end;
  12569. end;
  12570. end;
  12571. end;
  12572. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12573. var
  12574. hp1, hp2 : tai;
  12575. MaskLength : Cardinal;
  12576. MaskedBits : TCgInt;
  12577. ActiveReg : TRegister;
  12578. begin
  12579. Result:=false;
  12580. { There are no optimisations for reference targets }
  12581. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12582. Exit;
  12583. while GetNextInstruction(p, hp1) and
  12584. (hp1.typ = ait_instruction) do
  12585. begin
  12586. if (taicpu(p).oper[0]^.typ = top_const) then
  12587. begin
  12588. case taicpu(hp1).opcode of
  12589. A_AND:
  12590. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12591. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12592. { the second register must contain the first one, so compare their subreg types }
  12593. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12594. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12595. { change
  12596. and const1, reg
  12597. and const2, reg
  12598. to
  12599. and (const1 and const2), reg
  12600. }
  12601. begin
  12602. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12603. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12604. RemoveCurrentP(p, hp1);
  12605. Result:=true;
  12606. exit;
  12607. end;
  12608. A_CMP:
  12609. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12610. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12611. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12612. { Just check that the condition on the next instruction is compatible }
  12613. GetNextInstruction(hp1, hp2) and
  12614. (hp2.typ = ait_instruction) and
  12615. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12616. then
  12617. { change
  12618. and 2^n, reg
  12619. cmp 2^n, reg
  12620. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12621. to
  12622. and 2^n, reg
  12623. test reg, reg
  12624. j(~c) / set(~c) / cmov(~c)
  12625. }
  12626. begin
  12627. { Keep TEST instruction in, rather than remove it, because
  12628. it may trigger other optimisations such as MovAndTest2Test }
  12629. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12630. taicpu(hp1).opcode := A_TEST;
  12631. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12632. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12633. Result := True;
  12634. Exit;
  12635. end
  12636. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12637. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12638. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12639. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12640. { change
  12641. and $ff/$ff/$ffff, reg
  12642. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12643. dealloc reg
  12644. to
  12645. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12646. }
  12647. begin
  12648. TransferUsedRegs(TmpUsedRegs);
  12649. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12650. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12651. begin
  12652. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12653. case taicpu(p).oper[0]^.val of
  12654. $ff:
  12655. begin
  12656. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12657. taicpu(hp1).opsize:=S_B;
  12658. end;
  12659. $ffff:
  12660. begin
  12661. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12662. taicpu(hp1).opsize:=S_W;
  12663. end;
  12664. $ffffffff:
  12665. begin
  12666. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12667. taicpu(hp1).opsize:=S_L;
  12668. end;
  12669. else
  12670. Internalerror(2023030401);
  12671. end;
  12672. RemoveCurrentP(p);
  12673. Result := True;
  12674. Exit;
  12675. end;
  12676. end;
  12677. A_MOVZX:
  12678. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12679. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12680. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12681. (
  12682. (
  12683. (taicpu(p).opsize=S_W) and
  12684. (taicpu(hp1).opsize=S_BW)
  12685. ) or
  12686. (
  12687. (taicpu(p).opsize=S_L) and
  12688. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12689. )
  12690. {$ifdef x86_64}
  12691. or
  12692. (
  12693. (taicpu(p).opsize=S_Q) and
  12694. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12695. )
  12696. {$endif x86_64}
  12697. ) then
  12698. begin
  12699. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12700. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12701. ) or
  12702. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12703. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12704. then
  12705. begin
  12706. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12707. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12708. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12709. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12710. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12711. }
  12712. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12713. RemoveInstruction(hp1);
  12714. { See if there are other optimisations possible }
  12715. Continue;
  12716. end;
  12717. end;
  12718. A_SHL:
  12719. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12720. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12721. begin
  12722. {$ifopt R+}
  12723. {$define RANGE_WAS_ON}
  12724. {$R-}
  12725. {$endif}
  12726. { get length of potential and mask }
  12727. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12728. { really a mask? }
  12729. {$ifdef RANGE_WAS_ON}
  12730. {$R+}
  12731. {$endif}
  12732. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12733. { unmasked part shifted out? }
  12734. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12735. begin
  12736. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12737. RemoveCurrentP(p, hp1);
  12738. Result:=true;
  12739. exit;
  12740. end;
  12741. end;
  12742. A_SHR:
  12743. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12744. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12745. (taicpu(hp1).oper[0]^.val <= 63) then
  12746. begin
  12747. { Does SHR combined with the AND cover all the bits?
  12748. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12749. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12750. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12751. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12752. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12753. begin
  12754. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12755. RemoveCurrentP(p, hp1);
  12756. Result := True;
  12757. Exit;
  12758. end;
  12759. end;
  12760. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12761. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12762. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12763. begin
  12764. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12765. (
  12766. (
  12767. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12768. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12769. ) or (
  12770. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12771. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12772. {$ifdef x86_64}
  12773. ) or (
  12774. (taicpu(hp1).opsize = S_LQ) and
  12775. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12776. {$endif x86_64}
  12777. )
  12778. ) then
  12779. begin
  12780. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12781. begin
  12782. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12783. RemoveInstruction(hp1);
  12784. { See if there are other optimisations possible }
  12785. Continue;
  12786. end;
  12787. { The super-registers are the same though.
  12788. Note that this change by itself doesn't improve
  12789. code speed, but it opens up other optimisations. }
  12790. {$ifdef x86_64}
  12791. { Convert 64-bit register to 32-bit }
  12792. case taicpu(hp1).opsize of
  12793. S_BQ:
  12794. begin
  12795. taicpu(hp1).opsize := S_BL;
  12796. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12797. end;
  12798. S_WQ:
  12799. begin
  12800. taicpu(hp1).opsize := S_WL;
  12801. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12802. end
  12803. else
  12804. ;
  12805. end;
  12806. {$endif x86_64}
  12807. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12808. taicpu(hp1).opcode := A_MOVZX;
  12809. { See if there are other optimisations possible }
  12810. Continue;
  12811. end;
  12812. end;
  12813. else
  12814. ;
  12815. end;
  12816. end
  12817. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12818. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12819. begin
  12820. {$ifdef x86_64}
  12821. if (taicpu(p).opsize = S_Q) then
  12822. begin
  12823. { Never necessary }
  12824. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12825. RemoveCurrentP(p, hp1);
  12826. Result := True;
  12827. Exit;
  12828. end;
  12829. {$endif x86_64}
  12830. { Forward check to determine necessity of and %reg,%reg }
  12831. TransferUsedRegs(TmpUsedRegs);
  12832. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12833. { Saves on a bunch of dereferences }
  12834. ActiveReg := taicpu(p).oper[1]^.reg;
  12835. case taicpu(hp1).opcode of
  12836. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12837. if (
  12838. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12839. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12840. ) and
  12841. (
  12842. (taicpu(hp1).opcode <> A_MOV) or
  12843. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12844. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12845. ) and
  12846. not (
  12847. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12848. (taicpu(hp1).opcode = A_MOV) and
  12849. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12850. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12851. ) and
  12852. (
  12853. (
  12854. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12855. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12856. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12857. ) or
  12858. (
  12859. {$ifdef x86_64}
  12860. (
  12861. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12862. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12863. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12864. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12865. ) and
  12866. {$endif x86_64}
  12867. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12868. )
  12869. ) then
  12870. begin
  12871. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12872. RemoveCurrentP(p, hp1);
  12873. Result := True;
  12874. Exit;
  12875. end;
  12876. A_ADD,
  12877. A_AND,
  12878. A_BSF,
  12879. A_BSR,
  12880. A_BTC,
  12881. A_BTR,
  12882. A_BTS,
  12883. A_OR,
  12884. A_SUB,
  12885. A_XOR:
  12886. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12887. if (
  12888. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12889. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12890. ) and
  12891. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12892. begin
  12893. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12894. RemoveCurrentP(p, hp1);
  12895. Result := True;
  12896. Exit;
  12897. end;
  12898. A_CMP,
  12899. A_TEST:
  12900. if (
  12901. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12902. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12903. ) and
  12904. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12905. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12906. begin
  12907. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12908. RemoveCurrentP(p, hp1);
  12909. Result := True;
  12910. Exit;
  12911. end;
  12912. A_BSWAP,
  12913. A_NEG,
  12914. A_NOT:
  12915. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12916. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12917. begin
  12918. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12919. RemoveCurrentP(p, hp1);
  12920. Result := True;
  12921. Exit;
  12922. end;
  12923. else
  12924. ;
  12925. end;
  12926. end;
  12927. if (taicpu(hp1).is_jmp) and
  12928. (taicpu(hp1).opcode<>A_JMP) and
  12929. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12930. begin
  12931. { change
  12932. and x, reg
  12933. jxx
  12934. to
  12935. test x, reg
  12936. jxx
  12937. if reg is deallocated before the
  12938. jump, but only if it's a conditional jump (PFV)
  12939. }
  12940. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12941. taicpu(p).opcode := A_TEST;
  12942. Exit;
  12943. end;
  12944. Break;
  12945. end;
  12946. { Lone AND tests }
  12947. if (taicpu(p).oper[0]^.typ = top_const) then
  12948. begin
  12949. {
  12950. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12951. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12952. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12953. }
  12954. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12955. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12956. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12957. begin
  12958. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12959. if taicpu(p).opsize = S_L then
  12960. begin
  12961. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12962. Result := True;
  12963. end;
  12964. end;
  12965. end;
  12966. { Backward check to determine necessity of and %reg,%reg }
  12967. if (taicpu(p).oper[0]^.typ = top_reg) and
  12968. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12969. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12970. GetLastInstruction(p, hp2) and
  12971. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12972. { Check size of adjacent instruction to determine if the AND is
  12973. effectively a null operation }
  12974. (
  12975. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12976. { Note: Don't include S_Q }
  12977. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12978. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12979. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12980. ) then
  12981. begin
  12982. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12983. { If GetNextInstruction returned False, hp1 will be nil }
  12984. RemoveCurrentP(p, hp1);
  12985. Result := True;
  12986. Exit;
  12987. end;
  12988. end;
  12989. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12990. var
  12991. hp1, hp2: tai;
  12992. NewRef: TReference;
  12993. Distance: Cardinal;
  12994. TempTracking: TAllUsedRegs;
  12995. { This entire nested function is used in an if-statement below, but we
  12996. want to avoid all the used reg transfers and GetNextInstruction calls
  12997. until we really have to check }
  12998. function MemRegisterNotUsedLater: Boolean; inline;
  12999. var
  13000. hp2: tai;
  13001. begin
  13002. TransferUsedRegs(TmpUsedRegs);
  13003. hp2 := p;
  13004. repeat
  13005. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13006. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13007. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13008. end;
  13009. begin
  13010. Result := False;
  13011. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13012. (taicpu(p).oper[1]^.typ = top_reg) then
  13013. begin
  13014. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13015. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13016. (hp1.typ <> ait_instruction) or
  13017. not
  13018. (
  13019. (cs_opt_level3 in current_settings.optimizerswitches) or
  13020. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13021. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13022. ) then
  13023. Exit;
  13024. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13025. addq $x, %rax
  13026. movq %rax, %rdx
  13027. sarq $63, %rdx
  13028. (%rax still in use)
  13029. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13030. leaq $x(%rax),%rdx
  13031. addq $x, %rax
  13032. sarq $63, %rdx
  13033. ...which is okay since it breaks the dependency chain between
  13034. addq and movq, but if OptPass2MOV is called first:
  13035. addq $x, %rax
  13036. cqto
  13037. ...which is better in all ways, taking only 2 cycles to execute
  13038. and much smaller in code size.
  13039. }
  13040. { The extra register tracking is quite strenuous }
  13041. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13042. MatchInstruction(hp1, A_MOV, []) then
  13043. begin
  13044. { Update the register tracking to the MOV instruction }
  13045. CopyUsedRegs(TempTracking);
  13046. hp2 := p;
  13047. repeat
  13048. UpdateUsedRegs(tai(hp2.Next));
  13049. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13050. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13051. OptPass2ADD get called again }
  13052. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13053. begin
  13054. { Reset the tracking to the current instruction }
  13055. RestoreUsedRegs(TempTracking);
  13056. ReleaseUsedRegs(TempTracking);
  13057. Result := True;
  13058. Exit;
  13059. end;
  13060. { Reset the tracking to the current instruction }
  13061. RestoreUsedRegs(TempTracking);
  13062. ReleaseUsedRegs(TempTracking);
  13063. { If OptPass2MOV returned True, we don't need to set Result to
  13064. True if hp1 didn't change because the ADD instruction didn't
  13065. get modified and we'll be evaluating hp1 again when the
  13066. peephole optimizer reaches it }
  13067. end;
  13068. { Change:
  13069. add %reg2,%reg1
  13070. (%reg2 not modified in between)
  13071. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13072. To:
  13073. mov/s/z #(%reg1,%reg2),%reg1
  13074. }
  13075. if (taicpu(p).oper[0]^.typ = top_reg) and
  13076. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13077. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13078. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13079. (
  13080. (
  13081. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13082. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13083. { r/esp cannot be an index }
  13084. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13085. ) or (
  13086. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13087. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13088. )
  13089. ) and (
  13090. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13091. (
  13092. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13093. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13094. MemRegisterNotUsedLater
  13095. )
  13096. ) then
  13097. begin
  13098. if (
  13099. { Instructions are guaranteed to be adjacent on -O2 and under }
  13100. (cs_opt_level3 in current_settings.optimizerswitches) and
  13101. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13102. ) then
  13103. begin
  13104. { If the other register is used in between, move the MOV
  13105. instruction to right after the ADD instruction so a
  13106. saving can still be made }
  13107. Asml.Remove(hp1);
  13108. Asml.InsertAfter(hp1, p);
  13109. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13110. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13111. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13112. RemoveCurrentp(p, hp1);
  13113. end
  13114. else
  13115. begin
  13116. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13117. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13118. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13119. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13120. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13121. { hp1 may not be the immediate next instruction under -O3 }
  13122. RemoveCurrentp(p)
  13123. else
  13124. RemoveCurrentp(p, hp1);
  13125. end;
  13126. Result := True;
  13127. Exit;
  13128. end;
  13129. { Change:
  13130. addl/q $x,%reg1
  13131. movl/q %reg1,%reg2
  13132. To:
  13133. leal/q $x(%reg1),%reg2
  13134. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13135. Breaks the dependency chain.
  13136. }
  13137. if (taicpu(p).oper[0]^.typ = top_const) and
  13138. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13139. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13140. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13141. (
  13142. { Instructions are guaranteed to be adjacent on -O2 and under }
  13143. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13144. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13145. ) then
  13146. begin
  13147. TransferUsedRegs(TmpUsedRegs);
  13148. hp2 := p;
  13149. repeat
  13150. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13151. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13152. if (
  13153. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13154. not (cs_opt_size in current_settings.optimizerswitches) or
  13155. (
  13156. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13157. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13158. )
  13159. ) then
  13160. begin
  13161. { Change the MOV instruction to a LEA instruction, and update the
  13162. first operand }
  13163. reference_reset(NewRef, 1, []);
  13164. NewRef.base := taicpu(p).oper[1]^.reg;
  13165. NewRef.scalefactor := 1;
  13166. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13167. taicpu(hp1).opcode := A_LEA;
  13168. taicpu(hp1).loadref(0, NewRef);
  13169. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13170. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13171. begin
  13172. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13173. { Move what is now the LEA instruction to before the ADD instruction }
  13174. Asml.Remove(hp1);
  13175. Asml.InsertBefore(hp1, p);
  13176. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13177. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13178. p := hp1;
  13179. end
  13180. else
  13181. begin
  13182. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13183. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13184. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13185. { hp1 may not be the immediate next instruction under -O3 }
  13186. RemoveCurrentp(p)
  13187. else
  13188. RemoveCurrentp(p, hp1);
  13189. end;
  13190. Result := True;
  13191. end;
  13192. end;
  13193. end;
  13194. end;
  13195. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13196. var
  13197. SubReg: TSubRegister;
  13198. begin
  13199. Result:=false;
  13200. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13201. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13202. with taicpu(p).oper[0]^.ref^ do
  13203. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13204. begin
  13205. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13206. begin
  13207. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13208. taicpu(p).opcode := A_ADD;
  13209. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13210. Result := True;
  13211. end
  13212. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13213. begin
  13214. if (base <> NR_NO) then
  13215. begin
  13216. if (scalefactor <= 1) then
  13217. begin
  13218. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13219. taicpu(p).opcode := A_ADD;
  13220. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13221. Result := True;
  13222. end;
  13223. end
  13224. else
  13225. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13226. if (scalefactor in [2, 4, 8]) then
  13227. begin
  13228. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13229. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13230. taicpu(p).opcode := A_SHL;
  13231. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13232. Result := True;
  13233. end;
  13234. end;
  13235. end;
  13236. end;
  13237. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13238. var
  13239. hp1, hp2: tai;
  13240. NewRef: TReference;
  13241. Distance: Cardinal;
  13242. TempTracking: TAllUsedRegs;
  13243. begin
  13244. Result := False;
  13245. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13246. MatchOpType(taicpu(p),top_const,top_reg) then
  13247. begin
  13248. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13249. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13250. (hp1.typ <> ait_instruction) or
  13251. not
  13252. (
  13253. (cs_opt_level3 in current_settings.optimizerswitches) or
  13254. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13255. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13256. ) then
  13257. Exit;
  13258. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13259. subq $x, %rax
  13260. movq %rax, %rdx
  13261. sarq $63, %rdx
  13262. (%rax still in use)
  13263. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13264. leaq $-x(%rax),%rdx
  13265. movq $x, %rax
  13266. sarq $63, %rdx
  13267. ...which is okay since it breaks the dependency chain between
  13268. subq and movq, but if OptPass2MOV is called first:
  13269. subq $x, %rax
  13270. cqto
  13271. ...which is better in all ways, taking only 2 cycles to execute
  13272. and much smaller in code size.
  13273. }
  13274. { The extra register tracking is quite strenuous }
  13275. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13276. MatchInstruction(hp1, A_MOV, []) then
  13277. begin
  13278. { Update the register tracking to the MOV instruction }
  13279. CopyUsedRegs(TempTracking);
  13280. hp2 := p;
  13281. repeat
  13282. UpdateUsedRegs(tai(hp2.Next));
  13283. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13284. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13285. OptPass2SUB get called again }
  13286. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13287. begin
  13288. { Reset the tracking to the current instruction }
  13289. RestoreUsedRegs(TempTracking);
  13290. ReleaseUsedRegs(TempTracking);
  13291. Result := True;
  13292. Exit;
  13293. end;
  13294. { Reset the tracking to the current instruction }
  13295. RestoreUsedRegs(TempTracking);
  13296. ReleaseUsedRegs(TempTracking);
  13297. { If OptPass2MOV returned True, we don't need to set Result to
  13298. True if hp1 didn't change because the SUB instruction didn't
  13299. get modified and we'll be evaluating hp1 again when the
  13300. peephole optimizer reaches it }
  13301. end;
  13302. { Change:
  13303. subl/q $x,%reg1
  13304. movl/q %reg1,%reg2
  13305. To:
  13306. leal/q $-x(%reg1),%reg2
  13307. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13308. Breaks the dependency chain and potentially permits the removal of
  13309. a CMP instruction if one follows.
  13310. }
  13311. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13312. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13313. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13314. (
  13315. { Instructions are guaranteed to be adjacent on -O2 and under }
  13316. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13317. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13318. ) then
  13319. begin
  13320. TransferUsedRegs(TmpUsedRegs);
  13321. hp2 := p;
  13322. repeat
  13323. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13324. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13325. if (
  13326. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13327. not (cs_opt_size in current_settings.optimizerswitches) or
  13328. (
  13329. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13330. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13331. )
  13332. ) then
  13333. begin
  13334. { Change the MOV instruction to a LEA instruction, and update the
  13335. first operand }
  13336. reference_reset(NewRef, 1, []);
  13337. NewRef.base := taicpu(p).oper[1]^.reg;
  13338. NewRef.scalefactor := 1;
  13339. NewRef.offset := -taicpu(p).oper[0]^.val;
  13340. taicpu(hp1).opcode := A_LEA;
  13341. taicpu(hp1).loadref(0, NewRef);
  13342. TransferUsedRegs(TmpUsedRegs);
  13343. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13344. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13345. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13346. begin
  13347. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13348. { Move what is now the LEA instruction to before the SUB instruction }
  13349. Asml.Remove(hp1);
  13350. Asml.InsertBefore(hp1, p);
  13351. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13352. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13353. p := hp1;
  13354. end
  13355. else
  13356. begin
  13357. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13358. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13359. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13360. { hp1 may not be the immediate next instruction under -O3 }
  13361. RemoveCurrentp(p)
  13362. else
  13363. RemoveCurrentp(p, hp1);
  13364. end;
  13365. Result := True;
  13366. end;
  13367. end;
  13368. end;
  13369. end;
  13370. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13371. begin
  13372. { we can skip all instructions not messing with the stack pointer }
  13373. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13374. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13375. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13376. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13377. ({(taicpu(hp1).ops=0) or }
  13378. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13379. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13380. ) and }
  13381. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13382. )
  13383. ) do
  13384. GetNextInstruction(hp1,hp1);
  13385. Result:=assigned(hp1);
  13386. end;
  13387. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13388. var
  13389. hp1, hp2, hp3, hp4, hp5: tai;
  13390. begin
  13391. Result:=false;
  13392. hp5:=nil;
  13393. { replace
  13394. leal(q) x(<stackpointer>),<stackpointer>
  13395. call procname
  13396. leal(q) -x(<stackpointer>),<stackpointer>
  13397. ret
  13398. by
  13399. jmp procname
  13400. but do it only on level 4 because it destroys stack back traces
  13401. }
  13402. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13403. MatchOpType(taicpu(p),top_ref,top_reg) and
  13404. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13405. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13406. { the -8 or -24 are not required, but bail out early if possible,
  13407. higher values are unlikely }
  13408. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13409. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13410. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13411. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13412. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13413. GetNextInstruction(p, hp1) and
  13414. { Take a copy of hp1 }
  13415. SetAndTest(hp1, hp4) and
  13416. { trick to skip label }
  13417. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13418. SkipSimpleInstructions(hp1) and
  13419. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13420. GetNextInstruction(hp1, hp2) and
  13421. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13422. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13423. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13424. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13425. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13426. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13427. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13428. { Segment register will be NR_NO }
  13429. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13430. GetNextInstruction(hp2, hp3) and
  13431. { trick to skip label }
  13432. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13433. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13434. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13435. SetAndTest(hp3,hp5) and
  13436. GetNextInstruction(hp3,hp3) and
  13437. MatchInstruction(hp3,A_RET,[S_NO])
  13438. )
  13439. ) and
  13440. (taicpu(hp3).ops=0) then
  13441. begin
  13442. taicpu(hp1).opcode := A_JMP;
  13443. taicpu(hp1).is_jmp := true;
  13444. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13445. RemoveCurrentP(p, hp4);
  13446. RemoveInstruction(hp2);
  13447. RemoveInstruction(hp3);
  13448. if Assigned(hp5) then
  13449. begin
  13450. AsmL.Remove(hp5);
  13451. ASmL.InsertBefore(hp5,hp1)
  13452. end;
  13453. Result:=true;
  13454. end;
  13455. end;
  13456. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13457. {$ifdef x86_64}
  13458. var
  13459. hp1, hp2, hp3, hp4, hp5: tai;
  13460. {$endif x86_64}
  13461. begin
  13462. Result:=false;
  13463. {$ifdef x86_64}
  13464. hp5:=nil;
  13465. { replace
  13466. push %rax
  13467. call procname
  13468. pop %rcx
  13469. ret
  13470. by
  13471. jmp procname
  13472. but do it only on level 4 because it destroys stack back traces
  13473. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13474. for all supported calling conventions
  13475. }
  13476. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13477. MatchOpType(taicpu(p),top_reg) and
  13478. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13479. GetNextInstruction(p, hp1) and
  13480. { Take a copy of hp1 }
  13481. SetAndTest(hp1, hp4) and
  13482. { trick to skip label }
  13483. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13484. SkipSimpleInstructions(hp1) and
  13485. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13486. GetNextInstruction(hp1, hp2) and
  13487. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13488. MatchOpType(taicpu(hp2),top_reg) and
  13489. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13490. GetNextInstruction(hp2, hp3) and
  13491. { trick to skip label }
  13492. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13493. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13494. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13495. SetAndTest(hp3,hp5) and
  13496. GetNextInstruction(hp3,hp3) and
  13497. MatchInstruction(hp3,A_RET,[S_NO])
  13498. )
  13499. ) and
  13500. (taicpu(hp3).ops=0) then
  13501. begin
  13502. taicpu(hp1).opcode := A_JMP;
  13503. taicpu(hp1).is_jmp := true;
  13504. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13505. RemoveCurrentP(p, hp4);
  13506. RemoveInstruction(hp2);
  13507. RemoveInstruction(hp3);
  13508. if Assigned(hp5) then
  13509. begin
  13510. AsmL.Remove(hp5);
  13511. ASmL.InsertBefore(hp5,hp1)
  13512. end;
  13513. Result:=true;
  13514. end;
  13515. {$endif x86_64}
  13516. end;
  13517. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13518. var
  13519. Value, RegName: string;
  13520. begin
  13521. Result:=false;
  13522. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13523. begin
  13524. case taicpu(p).oper[0]^.val of
  13525. 0:
  13526. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13527. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13528. begin
  13529. { change "mov $0,%reg" into "xor %reg,%reg" }
  13530. taicpu(p).opcode := A_XOR;
  13531. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13532. Result := True;
  13533. {$ifdef x86_64}
  13534. end
  13535. else if (taicpu(p).opsize = S_Q) then
  13536. begin
  13537. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13538. { The actual optimization }
  13539. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13540. taicpu(p).changeopsize(S_L);
  13541. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13542. Result := True;
  13543. end;
  13544. $1..$FFFFFFFF:
  13545. begin
  13546. { Code size reduction by J. Gareth "Kit" Moreton }
  13547. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13548. case taicpu(p).opsize of
  13549. S_Q:
  13550. begin
  13551. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13552. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13553. { The actual optimization }
  13554. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13555. taicpu(p).changeopsize(S_L);
  13556. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13557. Result := True;
  13558. end;
  13559. else
  13560. { Do nothing };
  13561. end;
  13562. {$endif x86_64}
  13563. end;
  13564. -1:
  13565. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13566. if (cs_opt_size in current_settings.optimizerswitches) and
  13567. (taicpu(p).opsize <> S_B) and
  13568. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13569. begin
  13570. { change "mov $-1,%reg" into "or $-1,%reg" }
  13571. { NOTES:
  13572. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13573. - This operation creates a false dependency on the register, so only do it when optimising for size
  13574. - 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
  13575. }
  13576. taicpu(p).opcode := A_OR;
  13577. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13578. Result := True;
  13579. end;
  13580. else
  13581. { Do nothing };
  13582. end;
  13583. end;
  13584. end;
  13585. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13586. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13587. begin
  13588. Result := False;
  13589. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13590. Exit;
  13591. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13592. so don't bother optimising }
  13593. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13594. Exit;
  13595. if (taicpu(p).oper[0]^.typ <> top_const) or
  13596. { If the value can fit into an 8-bit signed integer, a smaller
  13597. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13598. falls within this range }
  13599. (
  13600. (taicpu(p).oper[0]^.val > -128) and
  13601. (taicpu(p).oper[0]^.val <= 127)
  13602. ) then
  13603. Exit;
  13604. { If we're optimising for size, this is acceptable }
  13605. if (cs_opt_size in current_settings.optimizerswitches) then
  13606. Exit(True);
  13607. if (taicpu(p).oper[1]^.typ = top_reg) and
  13608. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13609. Exit(True);
  13610. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13611. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13612. Exit(True);
  13613. end;
  13614. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13615. var
  13616. hp1: tai;
  13617. Value: TCGInt;
  13618. begin
  13619. Result := False;
  13620. if MatchOpType(taicpu(p), top_const, top_reg) then
  13621. begin
  13622. { Detect:
  13623. andw x, %ax (0 <= x < $8000)
  13624. ...
  13625. movzwl %ax,%eax
  13626. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13627. }
  13628. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13629. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13630. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13631. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13632. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13633. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13634. begin
  13635. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13636. taicpu(hp1).opcode := A_CWDE;
  13637. taicpu(hp1).clearop(0);
  13638. taicpu(hp1).clearop(1);
  13639. taicpu(hp1).ops := 0;
  13640. { A change was made, but not with p, so don't set Result, but
  13641. notify the compiler that a change was made }
  13642. Include(OptsToCheck, aoc_ForceNewIteration);
  13643. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13644. end;
  13645. end;
  13646. { If "not x" is a power of 2 (popcnt = 1), change:
  13647. and $x, %reg/ref
  13648. To:
  13649. btr lb(x), %reg/ref
  13650. }
  13651. if IsBTXAcceptable(p) and
  13652. (
  13653. { Make sure a TEST doesn't follow that plays with the register }
  13654. not GetNextInstruction(p, hp1) or
  13655. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13656. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13657. ) then
  13658. begin
  13659. {$push}{$R-}{$Q-}
  13660. { Value is a sign-extended 32-bit integer - just correct it
  13661. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13662. checks to see if this operand is an immediate. }
  13663. Value := not taicpu(p).oper[0]^.val;
  13664. {$pop}
  13665. {$ifdef x86_64}
  13666. if taicpu(p).opsize = S_L then
  13667. {$endif x86_64}
  13668. Value := Value and $FFFFFFFF;
  13669. if (PopCnt(QWord(Value)) = 1) then
  13670. begin
  13671. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13672. taicpu(p).opcode := A_BTR;
  13673. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13674. Result := True;
  13675. Exit;
  13676. end;
  13677. end;
  13678. end;
  13679. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13680. begin
  13681. Result := False;
  13682. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13683. Exit;
  13684. { Convert:
  13685. movswl %ax,%eax -> cwtl
  13686. movslq %eax,%rax -> cdqe
  13687. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13688. refer to the same opcode and depends only on the assembler's
  13689. current operand-size attribute. [Kit]
  13690. }
  13691. with taicpu(p) do
  13692. case opsize of
  13693. S_WL:
  13694. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13695. begin
  13696. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13697. opcode := A_CWDE;
  13698. clearop(0);
  13699. clearop(1);
  13700. ops := 0;
  13701. Result := True;
  13702. end;
  13703. {$ifdef x86_64}
  13704. S_LQ:
  13705. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13706. begin
  13707. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13708. opcode := A_CDQE;
  13709. clearop(0);
  13710. clearop(1);
  13711. ops := 0;
  13712. Result := True;
  13713. end;
  13714. {$endif x86_64}
  13715. else
  13716. ;
  13717. end;
  13718. end;
  13719. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13720. var
  13721. hp1, hp2: tai;
  13722. IdentityMask, Shift: TCGInt;
  13723. LimitSize: Topsize;
  13724. DoNotMerge: Boolean;
  13725. begin
  13726. Result := False;
  13727. { All these optimisations work on "shr const,%reg" }
  13728. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13729. Exit;
  13730. DoNotMerge := False;
  13731. Shift := taicpu(p).oper[0]^.val;
  13732. LimitSize := taicpu(p).opsize;
  13733. hp1 := p;
  13734. repeat
  13735. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13736. Break;
  13737. { Detect:
  13738. shr x, %reg
  13739. and y, %reg
  13740. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13741. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13742. }
  13743. case taicpu(hp1).opcode of
  13744. A_AND:
  13745. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13746. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13747. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13748. begin
  13749. { Make sure the FLAGS register isn't in use }
  13750. TransferUsedRegs(TmpUsedRegs);
  13751. hp2 := p;
  13752. repeat
  13753. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13754. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13755. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13756. begin
  13757. { Generate the identity mask }
  13758. case taicpu(p).opsize of
  13759. S_B:
  13760. IdentityMask := $FF shr Shift;
  13761. S_W:
  13762. IdentityMask := $FFFF shr Shift;
  13763. S_L:
  13764. IdentityMask := $FFFFFFFF shr Shift;
  13765. {$ifdef x86_64}
  13766. S_Q:
  13767. { We need to force the operands to be unsigned 64-bit
  13768. integers otherwise the wrong value is generated }
  13769. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13770. {$endif x86_64}
  13771. else
  13772. InternalError(2022081501);
  13773. end;
  13774. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13775. begin
  13776. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13777. { All the possible 1 bits are covered, so we can remove the AND }
  13778. hp2 := tai(hp1.Previous);
  13779. RemoveInstruction(hp1);
  13780. { p wasn't actually changed, so don't set Result to True,
  13781. but a change was nonetheless made elsewhere }
  13782. Include(OptsToCheck, aoc_ForceNewIteration);
  13783. { Do another pass in case other AND or MOVZX instructions
  13784. follow }
  13785. hp1 := hp2;
  13786. Continue;
  13787. end;
  13788. end;
  13789. end;
  13790. A_TEST, A_CMP, A_Jcc:
  13791. { Skip over conditional jumps and relevant comparisons }
  13792. Continue;
  13793. A_MOVZX:
  13794. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13795. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13796. begin
  13797. { Since the original register is being read as is, subsequent
  13798. SHRs must not be merged at this point }
  13799. DoNotMerge := True;
  13800. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13801. begin
  13802. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13803. begin
  13804. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13805. { All the possible 1 bits are covered, so we can remove the AND }
  13806. hp2 := tai(hp1.Previous);
  13807. RemoveInstruction(hp1);
  13808. hp1 := hp2;
  13809. end
  13810. else { Different register target }
  13811. begin
  13812. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13813. taicpu(hp1).opcode := A_MOV;
  13814. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13815. case taicpu(hp1).opsize of
  13816. S_BW:
  13817. taicpu(hp1).opsize := S_W;
  13818. S_BL, S_WL:
  13819. taicpu(hp1).opsize := S_L;
  13820. else
  13821. InternalError(2022081503);
  13822. end;
  13823. end;
  13824. end
  13825. else if (Shift > 0) and
  13826. (taicpu(p).opsize = S_W) and
  13827. (taicpu(hp1).opsize = S_WL) and
  13828. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13829. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13830. begin
  13831. { Detect:
  13832. shr x, %ax (x > 0)
  13833. ...
  13834. movzwl %ax,%eax
  13835. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13836. }
  13837. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13838. taicpu(hp1).opcode := A_CWDE;
  13839. taicpu(hp1).clearop(0);
  13840. taicpu(hp1).clearop(1);
  13841. taicpu(hp1).ops := 0;
  13842. end;
  13843. { Move onto the next instruction }
  13844. Continue;
  13845. end;
  13846. A_SHL, A_SAL, A_SHR:
  13847. if (taicpu(hp1).opsize <= LimitSize) and
  13848. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13849. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13850. begin
  13851. { Make sure the sizes don't exceed the register size limit
  13852. (measured by the shift value falling below the limit) }
  13853. if taicpu(hp1).opsize < LimitSize then
  13854. LimitSize := taicpu(hp1).opsize;
  13855. if taicpu(hp1).opcode = A_SHR then
  13856. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13857. else
  13858. begin
  13859. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13860. DoNotMerge := True;
  13861. end;
  13862. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13863. Break;
  13864. { Since we've established that the combined shift is within
  13865. limits, we can actually combine the adjacent SHR
  13866. instructions even if they're different sizes }
  13867. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13868. begin
  13869. hp2 := tai(hp1.Previous);
  13870. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13871. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13872. RemoveInstruction(hp1);
  13873. hp1 := hp2;
  13874. end;
  13875. { Move onto the next instruction }
  13876. Continue;
  13877. end;
  13878. else
  13879. ;
  13880. end;
  13881. Break;
  13882. until False;
  13883. { Detect the following (looking backwards):
  13884. shr %cl,%reg
  13885. shr x, %reg
  13886. Swap the two SHR instructions to minimise a pipeline stall.
  13887. }
  13888. if GetLastInstruction(p, hp1) and
  13889. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13890. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13891. { First operand will be %cl }
  13892. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13893. { Just to be sure }
  13894. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13895. begin
  13896. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13897. { Moving the entries this way ensures the register tracking remains correct }
  13898. Asml.Remove(p);
  13899. Asml.InsertBefore(p, hp1);
  13900. p := hp1;
  13901. { Don't set Result to True because the current instruction is now
  13902. "shr %cl,%reg" and there's nothing more we can do with it }
  13903. end;
  13904. end;
  13905. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13906. var
  13907. hp1, hp2: tai;
  13908. Opposite, SecondOpposite: TAsmOp;
  13909. NewCond: TAsmCond;
  13910. begin
  13911. Result := False;
  13912. { Change:
  13913. add/sub 128,(dest)
  13914. To:
  13915. sub/add -128,(dest)
  13916. This generaally takes fewer bytes to encode because -128 can be stored
  13917. in a signed byte, whereas +128 cannot.
  13918. }
  13919. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13920. begin
  13921. if taicpu(p).opcode = A_ADD then
  13922. Opposite := A_SUB
  13923. else
  13924. Opposite := A_ADD;
  13925. { Be careful if the flags are in use, because the CF flag inverts
  13926. when changing from ADD to SUB and vice versa }
  13927. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13928. GetNextInstruction(p, hp1) then
  13929. begin
  13930. TransferUsedRegs(TmpUsedRegs);
  13931. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13932. hp2 := hp1;
  13933. { Scan ahead to check if everything's safe }
  13934. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13935. begin
  13936. if (hp1.typ <> ait_instruction) then
  13937. { Probably unsafe since the flags are still in use }
  13938. Exit;
  13939. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13940. { Stop searching at an unconditional jump }
  13941. Break;
  13942. if not
  13943. (
  13944. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13945. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13946. ) and
  13947. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13948. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13949. Exit;
  13950. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13951. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13952. { Move to the next instruction }
  13953. GetNextInstruction(hp1, hp1);
  13954. end;
  13955. while Assigned(hp2) and (hp2 <> hp1) do
  13956. begin
  13957. NewCond := C_None;
  13958. case taicpu(hp2).condition of
  13959. C_A, C_NBE:
  13960. NewCond := C_BE;
  13961. C_B, C_C, C_NAE:
  13962. NewCond := C_AE;
  13963. C_AE, C_NB, C_NC:
  13964. NewCond := C_B;
  13965. C_BE, C_NA:
  13966. NewCond := C_A;
  13967. else
  13968. { No change needed };
  13969. end;
  13970. if NewCond <> C_None then
  13971. begin
  13972. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13973. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13974. taicpu(hp2).condition := NewCond;
  13975. end
  13976. else
  13977. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13978. begin
  13979. { Because of the flipping of the carry bit, to ensure
  13980. the operation remains equivalent, ADC becomes SBB
  13981. and vice versa, and the constant is not-inverted.
  13982. If multiple ADCs or SBBs appear in a row, each one
  13983. changed causes the carry bit to invert, so they all
  13984. need to be flipped }
  13985. if taicpu(hp2).opcode = A_ADC then
  13986. SecondOpposite := A_SBB
  13987. else
  13988. SecondOpposite := A_ADC;
  13989. if taicpu(hp2).oper[0]^.typ <> top_const then
  13990. { Should have broken out of this optimisation already }
  13991. InternalError(2021112901);
  13992. 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]^) + ' -> ' +
  13993. 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);
  13994. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13995. taicpu(hp2).opcode := SecondOpposite;
  13996. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13997. end;
  13998. { Move to the next instruction }
  13999. GetNextInstruction(hp2, hp2);
  14000. end;
  14001. if (hp2 <> hp1) then
  14002. InternalError(2021111501);
  14003. end;
  14004. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14005. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14006. taicpu(p).opcode := Opposite;
  14007. taicpu(p).oper[0]^.val := -128;
  14008. { No further optimisations can be made on this instruction, so move
  14009. onto the next one to save time }
  14010. p := tai(p.Next);
  14011. UpdateUsedRegs(p);
  14012. Result := True;
  14013. Exit;
  14014. end;
  14015. { Detect:
  14016. add/sub %reg2,(dest)
  14017. add/sub x, (dest)
  14018. (dest can be a register or a reference)
  14019. Swap the instructions to minimise a pipeline stall. This reverses the
  14020. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14021. optimisations could be made.
  14022. }
  14023. if (taicpu(p).oper[0]^.typ = top_reg) and
  14024. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14025. (
  14026. (
  14027. (taicpu(p).oper[1]^.typ = top_reg) and
  14028. { We can try searching further ahead if we're writing to a register }
  14029. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14030. ) or
  14031. (
  14032. (taicpu(p).oper[1]^.typ = top_ref) and
  14033. GetNextInstruction(p, hp1)
  14034. )
  14035. ) and
  14036. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14037. (taicpu(hp1).oper[0]^.typ = top_const) and
  14038. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14039. begin
  14040. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14041. TransferUsedRegs(TmpUsedRegs);
  14042. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14043. hp2 := p;
  14044. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14045. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14046. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14047. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14048. begin
  14049. asml.remove(hp1);
  14050. asml.InsertBefore(hp1, p);
  14051. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14052. Result := True;
  14053. end;
  14054. end;
  14055. end;
  14056. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14057. var
  14058. hp1: tai;
  14059. begin
  14060. Result:=false;
  14061. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14062. while GetNextInstruction(p, hp1) and
  14063. TrySwapMovCmp(p, hp1) do
  14064. begin
  14065. if MatchInstruction(hp1, A_MOV, []) then
  14066. begin
  14067. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14068. begin
  14069. { A little hacky, but since CMP doesn't read the flags, only
  14070. modify them, it's safe if they get scrambled by MOV -> XOR }
  14071. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14072. Result := PostPeepholeOptMov(hp1);
  14073. {$ifdef x86_64}
  14074. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14075. { Used to shrink instruction size }
  14076. PostPeepholeOptXor(hp1);
  14077. {$endif x86_64}
  14078. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14079. end
  14080. else
  14081. begin
  14082. Result := PostPeepholeOptMov(hp1);
  14083. {$ifdef x86_64}
  14084. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14085. { Used to shrink instruction size }
  14086. PostPeepholeOptXor(hp1);
  14087. {$endif x86_64}
  14088. end;
  14089. end;
  14090. { Enabling this flag is actually a null operation, but it marks
  14091. the code as 'modified' during this pass }
  14092. Include(OptsToCheck, aoc_ForceNewIteration);
  14093. end;
  14094. { change "cmp $0, %reg" to "test %reg, %reg" }
  14095. if MatchOpType(taicpu(p),top_const,top_reg) and
  14096. (taicpu(p).oper[0]^.val = 0) then
  14097. begin
  14098. taicpu(p).opcode := A_TEST;
  14099. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14100. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14101. Result:=true;
  14102. end;
  14103. end;
  14104. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14105. var
  14106. IsTestConstX, IsValid : Boolean;
  14107. hp1,hp2 : tai;
  14108. begin
  14109. Result:=false;
  14110. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14111. if (taicpu(p).opcode = A_TEST) then
  14112. while GetNextInstruction(p, hp1) and
  14113. TrySwapMovCmp(p, hp1) do
  14114. begin
  14115. if MatchInstruction(hp1, A_MOV, []) then
  14116. begin
  14117. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14118. begin
  14119. { A little hacky, but since TEST doesn't read the flags, only
  14120. modify them, it's safe if they get scrambled by MOV -> XOR }
  14121. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14122. Result := PostPeepholeOptMov(hp1);
  14123. {$ifdef x86_64}
  14124. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14125. { Used to shrink instruction size }
  14126. PostPeepholeOptXor(hp1);
  14127. {$endif x86_64}
  14128. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14129. end
  14130. else
  14131. begin
  14132. Result := PostPeepholeOptMov(hp1);
  14133. {$ifdef x86_64}
  14134. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14135. { Used to shrink instruction size }
  14136. PostPeepholeOptXor(hp1);
  14137. {$endif x86_64}
  14138. end;
  14139. end;
  14140. { Enabling this flag is actually a null operation, but it marks
  14141. the code as 'modified' during this pass }
  14142. Include(OptsToCheck, aoc_ForceNewIteration);
  14143. end;
  14144. { If x is a power of 2 (popcnt = 1), change:
  14145. or $x, %reg/ref
  14146. To:
  14147. bts lb(x), %reg/ref
  14148. }
  14149. if (taicpu(p).opcode = A_OR) and
  14150. IsBTXAcceptable(p) and
  14151. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14152. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14153. (
  14154. { Don't optimise if a test instruction follows }
  14155. not GetNextInstruction(p, hp1) or
  14156. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14157. ) then
  14158. begin
  14159. 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);
  14160. taicpu(p).opcode := A_BTS;
  14161. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14162. Result := True;
  14163. Exit;
  14164. end;
  14165. { If x is a power of 2 (popcnt = 1), change:
  14166. test $x, %reg/ref
  14167. je / sete / cmove (or jne / setne)
  14168. To:
  14169. bt lb(x), %reg/ref
  14170. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14171. }
  14172. if (taicpu(p).opcode = A_TEST) and
  14173. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14174. (taicpu(p).oper[0]^.typ = top_const) and
  14175. (
  14176. (cs_opt_size in current_settings.optimizerswitches) or
  14177. (
  14178. (taicpu(p).oper[1]^.typ = top_reg) and
  14179. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14180. ) or
  14181. (
  14182. (taicpu(p).oper[1]^.typ <> top_reg) and
  14183. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14184. )
  14185. ) and
  14186. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14187. { For sizes less than S_L, the byte size is equal or larger with BT,
  14188. so don't bother optimising }
  14189. (taicpu(p).opsize >= S_L) then
  14190. begin
  14191. IsValid := True;
  14192. { Check the next set of instructions, watching the FLAGS register
  14193. and the conditions used }
  14194. TransferUsedRegs(TmpUsedRegs);
  14195. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14196. hp1 := p;
  14197. hp2 := nil;
  14198. while GetNextInstruction(hp1, hp1) do
  14199. begin
  14200. if not Assigned(hp2) then
  14201. { The first instruction after TEST }
  14202. hp2 := hp1;
  14203. if (hp1.typ <> ait_instruction) then
  14204. begin
  14205. { If the flags are no longer in use, everything is fine }
  14206. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14207. IsValid := False;
  14208. Break;
  14209. end;
  14210. case taicpu(hp1).condition of
  14211. C_None:
  14212. begin
  14213. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14214. { Something is not quite normal, so play safe and don't change }
  14215. IsValid := False;
  14216. Break;
  14217. end;
  14218. C_E, C_Z, C_NE, C_NZ:
  14219. { This is fine };
  14220. else
  14221. begin
  14222. { Unsupported condition }
  14223. IsValid := False;
  14224. Break;
  14225. end;
  14226. end;
  14227. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14228. end;
  14229. if IsValid then
  14230. begin
  14231. while hp2 <> hp1 do
  14232. begin
  14233. case taicpu(hp2).condition of
  14234. C_Z, C_E:
  14235. taicpu(hp2).condition := C_NC;
  14236. C_NZ, C_NE:
  14237. taicpu(hp2).condition := C_C;
  14238. else
  14239. { Should not get this by this point }
  14240. InternalError(2022110701);
  14241. end;
  14242. GetNextInstruction(hp2, hp2);
  14243. end;
  14244. 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);
  14245. taicpu(p).opcode := A_BT;
  14246. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14247. Result := True;
  14248. Exit;
  14249. end;
  14250. end;
  14251. { removes the line marked with (x) from the sequence
  14252. and/or/xor/add/sub/... $x, %y
  14253. test/or %y, %y | test $-1, %y (x)
  14254. j(n)z _Label
  14255. as the first instruction already adjusts the ZF
  14256. %y operand may also be a reference }
  14257. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14258. MatchOperand(taicpu(p).oper[0]^,-1);
  14259. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14260. GetLastInstruction(p, hp1) and
  14261. (tai(hp1).typ = ait_instruction) and
  14262. GetNextInstruction(p,hp2) and
  14263. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14264. case taicpu(hp1).opcode Of
  14265. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14266. { These two instructions set the zero flag if the result is zero }
  14267. A_POPCNT, A_LZCNT:
  14268. begin
  14269. if (
  14270. { With POPCNT, an input of zero will set the zero flag
  14271. because the population count of zero is zero }
  14272. (taicpu(hp1).opcode = A_POPCNT) and
  14273. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14274. (
  14275. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14276. { Faster than going through the second half of the 'or'
  14277. condition below }
  14278. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14279. )
  14280. ) or (
  14281. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14282. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14283. { and in case of carry for A(E)/B(E)/C/NC }
  14284. (
  14285. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14286. (
  14287. (taicpu(hp1).opcode <> A_ADD) and
  14288. (taicpu(hp1).opcode <> A_SUB) and
  14289. (taicpu(hp1).opcode <> A_LZCNT)
  14290. )
  14291. )
  14292. ) then
  14293. begin
  14294. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14295. RemoveCurrentP(p, hp2);
  14296. Result:=true;
  14297. Exit;
  14298. end;
  14299. end;
  14300. A_SHL, A_SAL, A_SHR, A_SAR:
  14301. begin
  14302. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14303. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14304. { therefore, it's only safe to do this optimization for }
  14305. { shifts by a (nonzero) constant }
  14306. (taicpu(hp1).oper[0]^.typ = top_const) and
  14307. (taicpu(hp1).oper[0]^.val <> 0) and
  14308. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14309. { and in case of carry for A(E)/B(E)/C/NC }
  14310. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14311. begin
  14312. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14313. RemoveCurrentP(p, hp2);
  14314. Result:=true;
  14315. Exit;
  14316. end;
  14317. end;
  14318. A_DEC, A_INC, A_NEG:
  14319. begin
  14320. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14321. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14322. { and in case of carry for A(E)/B(E)/C/NC }
  14323. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14324. begin
  14325. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14326. RemoveCurrentP(p, hp2);
  14327. Result:=true;
  14328. Exit;
  14329. end;
  14330. end;
  14331. A_ANDN, A_BZHI:
  14332. begin
  14333. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14334. { Only the zero and sign flags are consistent with what the result is }
  14335. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14336. begin
  14337. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14338. RemoveCurrentP(p, hp2);
  14339. Result:=true;
  14340. Exit;
  14341. end;
  14342. end;
  14343. A_BEXTR:
  14344. begin
  14345. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14346. { Only the zero flag is set }
  14347. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14348. begin
  14349. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14350. RemoveCurrentP(p, hp2);
  14351. Result:=true;
  14352. Exit;
  14353. end;
  14354. end;
  14355. else
  14356. ;
  14357. end; { case }
  14358. { change "test $-1,%reg" into "test %reg,%reg" }
  14359. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14360. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14361. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14362. if MatchInstruction(p, A_OR, []) and
  14363. { Can only match if they're both registers }
  14364. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14365. begin
  14366. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14367. taicpu(p).opcode := A_TEST;
  14368. { No need to set Result to True, as we've done all the optimisations we can }
  14369. end;
  14370. end;
  14371. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14372. var
  14373. hp1,hp3 : tai;
  14374. {$ifndef x86_64}
  14375. hp2 : taicpu;
  14376. {$endif x86_64}
  14377. begin
  14378. Result:=false;
  14379. hp3:=nil;
  14380. {$ifndef x86_64}
  14381. { don't do this on modern CPUs, this really hurts them due to
  14382. broken call/ret pairing }
  14383. if (current_settings.optimizecputype < cpu_Pentium2) and
  14384. not(cs_create_pic in current_settings.moduleswitches) and
  14385. GetNextInstruction(p, hp1) and
  14386. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14387. MatchOpType(taicpu(hp1),top_ref) and
  14388. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14389. begin
  14390. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14391. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14392. InsertLLItem(p.previous, p, hp2);
  14393. taicpu(p).opcode := A_JMP;
  14394. taicpu(p).is_jmp := true;
  14395. RemoveInstruction(hp1);
  14396. Result:=true;
  14397. end
  14398. else
  14399. {$endif x86_64}
  14400. { replace
  14401. call procname
  14402. ret
  14403. by
  14404. jmp procname
  14405. but do it only on level 4 because it destroys stack back traces
  14406. else if the subroutine is marked as no return, remove the ret
  14407. }
  14408. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14409. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14410. GetNextInstruction(p, hp1) and
  14411. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14412. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14413. SetAndTest(hp1,hp3) and
  14414. GetNextInstruction(hp1,hp1) and
  14415. MatchInstruction(hp1,A_RET,[S_NO])
  14416. )
  14417. ) and
  14418. (taicpu(hp1).ops=0) then
  14419. begin
  14420. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14421. { we might destroy stack alignment here if we do not do a call }
  14422. (target_info.stackalign<=sizeof(SizeUInt)) then
  14423. begin
  14424. taicpu(p).opcode := A_JMP;
  14425. taicpu(p).is_jmp := true;
  14426. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14427. end
  14428. else
  14429. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14430. RemoveInstruction(hp1);
  14431. if Assigned(hp3) then
  14432. begin
  14433. AsmL.Remove(hp3);
  14434. AsmL.InsertBefore(hp3,p)
  14435. end;
  14436. Result:=true;
  14437. end;
  14438. end;
  14439. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14440. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14441. begin
  14442. case OpSize of
  14443. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14444. Result := (Val <= $FF) and (Val >= -128);
  14445. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14446. Result := (Val <= $FFFF) and (Val >= -32768);
  14447. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14448. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14449. else
  14450. Result := True;
  14451. end;
  14452. end;
  14453. var
  14454. hp1, hp2 : tai;
  14455. SizeChange: Boolean;
  14456. PreMessage: string;
  14457. begin
  14458. Result := False;
  14459. if (taicpu(p).oper[0]^.typ = top_reg) and
  14460. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14461. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14462. begin
  14463. { Change (using movzbl %al,%eax as an example):
  14464. movzbl %al, %eax movzbl %al, %eax
  14465. cmpl x, %eax testl %eax,%eax
  14466. To:
  14467. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14468. movzbl %al, %eax movzbl %al, %eax
  14469. Smaller instruction and minimises pipeline stall as the CPU
  14470. doesn't have to wait for the register to get zero-extended. [Kit]
  14471. Also allow if the smaller of the two registers is being checked,
  14472. as this still removes the false dependency.
  14473. }
  14474. if
  14475. (
  14476. (
  14477. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14478. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14479. ) or (
  14480. { If MatchOperand returns True, they must both be registers }
  14481. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14482. )
  14483. ) and
  14484. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14485. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14486. begin
  14487. 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);
  14488. asml.Remove(hp1);
  14489. asml.InsertBefore(hp1, p);
  14490. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14491. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14492. begin
  14493. taicpu(hp1).opcode := A_TEST;
  14494. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14495. end;
  14496. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14497. case taicpu(p).opsize of
  14498. S_BW, S_BL:
  14499. begin
  14500. SizeChange := taicpu(hp1).opsize <> S_B;
  14501. taicpu(hp1).changeopsize(S_B);
  14502. end;
  14503. S_WL:
  14504. begin
  14505. SizeChange := taicpu(hp1).opsize <> S_W;
  14506. taicpu(hp1).changeopsize(S_W);
  14507. end
  14508. else
  14509. InternalError(2020112701);
  14510. end;
  14511. UpdateUsedRegs(tai(p.Next));
  14512. { Check if the register is used aferwards - if not, we can
  14513. remove the movzx instruction completely }
  14514. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14515. begin
  14516. { Hp1 is a better position than p for debugging purposes }
  14517. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14518. RemoveCurrentp(p, hp1);
  14519. Result := True;
  14520. end;
  14521. if SizeChange then
  14522. DebugMsg(SPeepholeOptimization + PreMessage +
  14523. 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)
  14524. else
  14525. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14526. Exit;
  14527. end;
  14528. { Change (using movzwl %ax,%eax as an example):
  14529. movzwl %ax, %eax
  14530. movb %al, (dest) (Register is smaller than read register in movz)
  14531. To:
  14532. movb %al, (dest) (Move one back to avoid a false dependency)
  14533. movzwl %ax, %eax
  14534. }
  14535. if (taicpu(hp1).opcode = A_MOV) and
  14536. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14537. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14538. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14539. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14540. begin
  14541. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14542. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14543. asml.Remove(hp1);
  14544. asml.InsertBefore(hp1, p);
  14545. if taicpu(hp1).oper[1]^.typ = top_reg then
  14546. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14547. { Check if the register is used aferwards - if not, we can
  14548. remove the movzx instruction completely }
  14549. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14550. begin
  14551. { Hp1 is a better position than p for debugging purposes }
  14552. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14553. RemoveCurrentp(p, hp1);
  14554. Result := True;
  14555. end;
  14556. Exit;
  14557. end;
  14558. end;
  14559. end;
  14560. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14561. var
  14562. hp1: tai;
  14563. {$ifdef x86_64}
  14564. PreMessage, RegName: string;
  14565. {$endif x86_64}
  14566. begin
  14567. Result := False;
  14568. { If x is a power of 2 (popcnt = 1), change:
  14569. xor $x, %reg/ref
  14570. To:
  14571. btc lb(x), %reg/ref
  14572. }
  14573. if IsBTXAcceptable(p) and
  14574. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14575. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14576. (
  14577. { Don't optimise if a test instruction follows }
  14578. not GetNextInstruction(p, hp1) or
  14579. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14580. ) then
  14581. begin
  14582. 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);
  14583. taicpu(p).opcode := A_BTC;
  14584. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14585. Result := True;
  14586. Exit;
  14587. end;
  14588. {$ifdef x86_64}
  14589. { Code size reduction by J. Gareth "Kit" Moreton }
  14590. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14591. as this removes the REX prefix }
  14592. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14593. Exit;
  14594. if taicpu(p).oper[0]^.typ <> top_reg then
  14595. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14596. InternalError(2018011500);
  14597. case taicpu(p).opsize of
  14598. S_Q:
  14599. begin
  14600. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14601. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14602. { The actual optimization }
  14603. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14604. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14605. taicpu(p).changeopsize(S_L);
  14606. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14607. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14608. end;
  14609. else
  14610. ;
  14611. end;
  14612. {$endif x86_64}
  14613. end;
  14614. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14615. var
  14616. XReg: TRegister;
  14617. begin
  14618. Result := False;
  14619. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14620. Smaller encoding and slightly faster on some platforms (also works for
  14621. ZMM-sized registers) }
  14622. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14623. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14624. begin
  14625. XReg := taicpu(p).oper[0]^.reg;
  14626. if (taicpu(p).oper[1]^.reg = XReg) then
  14627. begin
  14628. taicpu(p).changeopsize(S_XMM);
  14629. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14630. if (cs_opt_size in current_settings.optimizerswitches) then
  14631. begin
  14632. { Change input registers to %xmm0 to reduce size. Note that
  14633. there's a risk of a false dependency doing this, so only
  14634. optimise for size here }
  14635. XReg := NR_XMM0;
  14636. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14637. end
  14638. else
  14639. begin
  14640. setsubreg(XReg, R_SUBMMX);
  14641. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14642. end;
  14643. taicpu(p).oper[0]^.reg := XReg;
  14644. taicpu(p).oper[1]^.reg := XReg;
  14645. Result := True;
  14646. end;
  14647. end;
  14648. end;
  14649. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14650. var
  14651. OperIdx: Integer;
  14652. begin
  14653. for OperIdx := 0 to p.ops - 1 do
  14654. if p.oper[OperIdx]^.typ = top_ref then
  14655. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14656. end;
  14657. end.