aoptx86.pas 781 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212
  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. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. {$ifdef x86_64}
  118. { If a "mov %reg1d,%reg2d; and %reg1d,%reg1d" is found, we can possibly
  119. replace %reg2q with %reg1q in later instructions }
  120. function DoZeroUpper32Opt(var mov_p: tai; var and_p: tai): Boolean;
  121. {$endif x86_64}
  122. procedure DebugMsg(const s : string; p : tai);inline;
  123. class function IsExitCode(p : tai) : boolean; static;
  124. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  125. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  126. procedure RemoveLastDeallocForFuncRes(p : tai);
  127. function DoArithCombineOpt(var p : tai) : Boolean;
  128. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  129. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  130. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  131. function PrePeepholeOptSxx(var p : tai) : boolean;
  132. function PrePeepholeOptIMUL(var p : tai) : boolean;
  133. function PrePeepholeOptAND(var p : tai) : boolean;
  134. function OptPass1Test(var p: tai): boolean;
  135. function OptPass1Add(var p: tai): boolean;
  136. function OptPass1AND(var p : tai) : boolean;
  137. function OptPass1CMOVcc(var p: tai): Boolean;
  138. function OptPass1_V_MOVAP(var p : tai) : boolean;
  139. function OptPass1VOP(var p : tai) : boolean;
  140. function OptPass1MOV(var p : tai) : boolean;
  141. function OptPass1MOVD(var p : tai) : boolean;
  142. function OptPass1Movx(var p : tai) : boolean;
  143. function OptPass1MOVXX(var p : tai) : boolean;
  144. {$ifndef i8086}
  145. function OptPass1NOT(var p : tai) : boolean;
  146. {$endif not i8086}
  147. function OptPass1OP(var p : tai) : boolean;
  148. function OptPass1LEA(var p : tai) : boolean;
  149. function OptPass1Sub(var p : tai) : boolean;
  150. function OptPass1SHLSAL(var p : tai) : boolean;
  151. function OptPass1SHR(var p : tai) : boolean;
  152. function OptPass1FSTP(var p : tai) : boolean;
  153. function OptPass1FLD(var p : tai) : boolean;
  154. function OptPass1Cmp(var p : tai) : boolean;
  155. function OptPass1PXor(var p : tai) : boolean;
  156. function OptPass1VPXor(var p: tai): boolean;
  157. function OptPass1Imul(var p : tai) : boolean;
  158. function OptPass1Jcc(var p : tai) : boolean;
  159. function OptPass1SHXX(var p: tai): boolean;
  160. function OptPass1VMOVDQ(var p: tai): Boolean;
  161. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  162. function OptPass1STCCLC(var p: tai): Boolean;
  163. function OptPass2STCCLC(var p: tai): Boolean;
  164. function OptPass2CMOVcc(var p: tai): Boolean;
  165. function OptPass2Movx(var p : tai): Boolean;
  166. function OptPass2MOV(var p : tai) : boolean;
  167. function OptPass2Imul(var p : tai) : boolean;
  168. function OptPass2Jmp(var p : tai) : boolean;
  169. function OptPass2Jcc(var p : tai) : boolean;
  170. function OptPass2Lea(var p: tai): Boolean;
  171. function OptPass2SUB(var p: tai): Boolean;
  172. function OptPass2ADD(var p : tai): Boolean;
  173. function OptPass2SETcc(var p : tai) : boolean;
  174. function OptPass2Cmp(var p: tai): Boolean;
  175. function OptPass2Test(var p: tai): Boolean;
  176. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  177. function PostPeepholeOptMov(var p : tai) : Boolean;
  178. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  179. function PostPeepholeOptXor(var p : tai) : Boolean;
  180. function PostPeepholeOptAnd(var p : tai) : boolean;
  181. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  182. function PostPeepholeOptCmp(var p : tai) : Boolean;
  183. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  184. function PostPeepholeOptCall(var p : tai) : Boolean;
  185. function PostPeepholeOptLea(var p : tai) : Boolean;
  186. function PostPeepholeOptPush(var p: tai): Boolean;
  187. function PostPeepholeOptShr(var p : tai) : boolean;
  188. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  189. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  190. function PostPeepholeOptRET(var p: tai): Boolean;
  191. function PostPeepholeOptRORX(var p: tai): Boolean;
  192. function PostPeepholeOptSARXSHLXSHRX(var p: tai): Boolean;
  193. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  194. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  195. function TrySwapMovOp(var p, hp1: tai): Boolean;
  196. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  197. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  198. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  199. { Processor-dependent reference optimisation }
  200. class procedure OptimizeRefs(var p: taicpu); static;
  201. end;
  202. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  203. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  204. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  205. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  206. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  207. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  208. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  209. {$if max_operands>2}
  210. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  211. {$endif max_operands>2}
  212. function RefsEqual(const r1, r2: treference): boolean;
  213. { Like RefsEqual, but doesn't compare the offsets }
  214. function RefsAlmostEqual(const r1, r2: treference): boolean;
  215. { Note that Result is set to True if the references COULD overlap but the
  216. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  217. might still overlap because %reg2 could be equal to %reg1-4 }
  218. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  219. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  220. { returns true, if ref is a reference using only the registers passed as base and index
  221. and having an offset }
  222. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  223. implementation
  224. uses
  225. cutils,verbose,
  226. systems,
  227. globals,
  228. cpuinfo,
  229. procinfo,
  230. paramgr,
  231. aasmbase,
  232. aoptbase,aoptutils,
  233. symconst,symsym,
  234. cgx86,
  235. itcpugas;
  236. {$ifndef 8086}
  237. const
  238. MAX_CMOV_INSTRUCTIONS = 4;
  239. MAX_CMOV_REGISTERS = 8;
  240. type
  241. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  242. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  243. tsProcessed);
  244. { For OptPass2Jcc }
  245. TCMOVTracking = object
  246. private
  247. CMOVScore, ConstCount: LongInt;
  248. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  249. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  250. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  251. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  252. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  253. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  254. fOptimizer: TX86AsmOptimizer;
  255. fLabel: TAsmSymbol;
  256. fInsertionPoint,
  257. fCondition,
  258. fInitialJump,
  259. fFirstMovBlock,
  260. fFirstMovBlockStop,
  261. fSecondJump,
  262. fThirdJump,
  263. fSecondMovBlock,
  264. fSecondMovBlockStop,
  265. fMidLabel,
  266. fEndLabel,
  267. fAllocationRange: tai;
  268. fState: TCMovTrackingState;
  269. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  270. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  271. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  272. public
  273. RegisterTracking: TAllUsedRegs;
  274. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  275. destructor Done;
  276. procedure Process(out new_p: tai);
  277. property State: TCMovTrackingState read fState;
  278. end;
  279. PCMOVTracking = ^TCMOVTracking;
  280. {$endif 8086}
  281. {$ifdef DEBUG_AOPTCPU}
  282. const
  283. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  284. {$else DEBUG_AOPTCPU}
  285. { Empty strings help the optimizer to remove string concatenations that won't
  286. ever appear to the user on release builds. [Kit] }
  287. const
  288. SPeepholeOptimization = '';
  289. {$endif DEBUG_AOPTCPU}
  290. LIST_STEP_SIZE = 4;
  291. type
  292. TJumpTrackingItem = class(TLinkedListItem)
  293. private
  294. FSymbol: TAsmSymbol;
  295. FRefs: LongInt;
  296. public
  297. constructor Create(ASymbol: TAsmSymbol);
  298. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  299. property Symbol: TAsmSymbol read FSymbol;
  300. property Refs: LongInt read FRefs;
  301. end;
  302. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  303. begin
  304. inherited Create;
  305. FSymbol := ASymbol;
  306. FRefs := 0;
  307. end;
  308. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  309. begin
  310. Inc(FRefs);
  311. end;
  312. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  313. begin
  314. result :=
  315. (instr.typ = ait_instruction) and
  316. (taicpu(instr).opcode = op) and
  317. ((opsize = []) or (taicpu(instr).opsize in opsize));
  318. end;
  319. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  320. begin
  321. result :=
  322. (instr.typ = ait_instruction) and
  323. ((taicpu(instr).opcode = op1) or
  324. (taicpu(instr).opcode = op2)
  325. ) and
  326. ((opsize = []) or (taicpu(instr).opsize in opsize));
  327. end;
  328. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  329. begin
  330. result :=
  331. (instr.typ = ait_instruction) and
  332. ((taicpu(instr).opcode = op1) or
  333. (taicpu(instr).opcode = op2) or
  334. (taicpu(instr).opcode = op3)
  335. ) and
  336. ((opsize = []) or (taicpu(instr).opsize in opsize));
  337. end;
  338. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  339. const opsize : topsizes) : boolean;
  340. var
  341. op : TAsmOp;
  342. begin
  343. result:=false;
  344. if (instr.typ <> ait_instruction) or
  345. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  346. exit;
  347. for op in ops do
  348. begin
  349. if taicpu(instr).opcode = op then
  350. begin
  351. result:=true;
  352. exit;
  353. end;
  354. end;
  355. end;
  356. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  357. begin
  358. result := (oper.typ = top_reg) and (oper.reg = reg);
  359. end;
  360. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  361. begin
  362. result := (oper.typ = top_const) and (oper.val = a);
  363. end;
  364. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  365. begin
  366. result := oper1.typ = oper2.typ;
  367. if result then
  368. case oper1.typ of
  369. top_const:
  370. Result:=oper1.val = oper2.val;
  371. top_reg:
  372. Result:=oper1.reg = oper2.reg;
  373. top_ref:
  374. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  375. else
  376. internalerror(2013102801);
  377. end
  378. end;
  379. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  380. begin
  381. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  382. if result then
  383. case oper1.typ of
  384. top_const:
  385. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  386. top_reg:
  387. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  388. top_ref:
  389. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  390. else
  391. internalerror(2020052401);
  392. end
  393. end;
  394. function RefsEqual(const r1, r2: treference): boolean;
  395. begin
  396. RefsEqual :=
  397. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  398. (r1.relsymbol = r2.relsymbol) and
  399. (r1.segment = r2.segment) and (r1.base = r2.base) and
  400. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  401. (r1.offset = r2.offset) and
  402. (r1.volatility + r2.volatility = []);
  403. end;
  404. function RefsAlmostEqual(const r1, r2: treference): boolean;
  405. begin
  406. RefsAlmostEqual :=
  407. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. { Don't compare the offsets }
  412. (r1.volatility + r2.volatility = []);
  413. end;
  414. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  415. begin
  416. if (r1.symbol<>r2.symbol) then
  417. { If the index registers are different, there's a chance one could
  418. be set so it equals the other symbol }
  419. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  420. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  421. (r1.relsymbol = r2.relsymbol) and
  422. (r1.segment = r2.segment) and (r1.base = r2.base) and
  423. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  424. (r1.volatility + r2.volatility = []) then
  425. { In this case, it all depends on the offsets }
  426. Exit(abs(r1.offset - r2.offset) < Range);
  427. { There's a chance things MIGHT overlap, so take no chances }
  428. Result := True;
  429. end;
  430. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.offset=0) and
  433. (ref.scalefactor in [0,1]) and
  434. (ref.segment=NR_NO) and
  435. (ref.symbol=nil) and
  436. (ref.relsymbol=nil) and
  437. ((base=NR_INVALID) or
  438. (ref.base=base)) and
  439. ((index=NR_INVALID) or
  440. (ref.index=index)) and
  441. (ref.volatility=[]);
  442. end;
  443. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  444. begin
  445. Result:=(ref.scalefactor in [0,1]) and
  446. (ref.segment=NR_NO) and
  447. (ref.symbol=nil) and
  448. (ref.relsymbol=nil) and
  449. ((base=NR_INVALID) or
  450. (ref.base=base)) and
  451. ((index=NR_INVALID) or
  452. (ref.index=index)) and
  453. (ref.volatility=[]);
  454. end;
  455. function InstrReadsFlags(p: tai): boolean;
  456. begin
  457. InstrReadsFlags := true;
  458. case p.typ of
  459. ait_instruction:
  460. if InsProp[taicpu(p).opcode].Ch*
  461. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  462. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  463. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  464. exit;
  465. ait_label:
  466. exit;
  467. else
  468. ;
  469. end;
  470. InstrReadsFlags := false;
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  473. begin
  474. Next:=Current;
  475. repeat
  476. Result:=GetNextInstruction(Next,Next);
  477. until not (Result) or
  478. not(cs_opt_level3 in current_settings.optimizerswitches) or
  479. (Next.typ<>ait_instruction) or
  480. RegInInstruction(reg,Next) or
  481. is_calljmp(taicpu(Next).opcode);
  482. end;
  483. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  484. var
  485. GetNextResult: Boolean;
  486. begin
  487. Result:=0;
  488. Next:=Current;
  489. repeat
  490. GetNextResult := GetNextInstruction(Next,Next);
  491. if GetNextResult then
  492. Inc(Result)
  493. else
  494. { Must return zero upon hitting the end of the linked list without a match }
  495. Result := 0;
  496. until not (GetNextResult) or
  497. not(cs_opt_level3 in current_settings.optimizerswitches) or
  498. (Next.typ<>ait_instruction) or
  499. RegInInstruction(reg,Next) or
  500. is_calljmp(taicpu(Next).opcode);
  501. end;
  502. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  503. procedure TrackJump(Symbol: TAsmSymbol);
  504. var
  505. Search: TJumpTrackingItem;
  506. begin
  507. { See if an entry already exists in our jump tracking list
  508. (faster to search backwards due to the higher chance of
  509. matching destinations) }
  510. Search := TJumpTrackingItem(JumpTracking.Last);
  511. while Assigned(Search) do
  512. begin
  513. if Search.Symbol = Symbol then
  514. begin
  515. { Found it - remove it so it can be pushed to the front }
  516. JumpTracking.Remove(Search);
  517. Break;
  518. end;
  519. Search := TJumpTrackingItem(Search.Previous);
  520. end;
  521. if not Assigned(Search) then
  522. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  523. JumpTracking.Concat(Search);
  524. Search.IncRefs;
  525. end;
  526. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  527. var
  528. Search: TJumpTrackingItem;
  529. begin
  530. Result := False;
  531. { See if this label appears in the tracking list }
  532. Search := TJumpTrackingItem(JumpTracking.Last);
  533. while Assigned(Search) do
  534. begin
  535. if Search.Symbol = Symbol then
  536. begin
  537. { Found it - let's see what we can discover }
  538. if Search.Symbol.getrefs = Search.Refs then
  539. begin
  540. { Success - all the references are accounted for }
  541. JumpTracking.Remove(Search);
  542. Search.Free;
  543. { It is logically impossible for CrossJump to be false here
  544. because we must have run into a conditional jump for
  545. this label at some point }
  546. if not CrossJump then
  547. InternalError(2022041710);
  548. if JumpTracking.First = nil then
  549. { Tracking list is now empty - no more cross jumps }
  550. CrossJump := False;
  551. Result := True;
  552. Exit;
  553. end;
  554. { If the references don't match, it's possible to enter
  555. this label through other means, so drop out }
  556. Exit;
  557. end;
  558. Search := TJumpTrackingItem(Search.Previous);
  559. end;
  560. end;
  561. var
  562. Next_Label: tai;
  563. begin
  564. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  565. Next := Current;
  566. repeat
  567. Result := GetNextInstruction(Next,Next);
  568. if not Result then
  569. Break;
  570. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  571. if is_calljmpuncondret(taicpu(Next).opcode) then
  572. begin
  573. if (taicpu(Next).opcode = A_JMP) and
  574. { Remove dead code now to save time }
  575. RemoveDeadCodeAfterJump(taicpu(Next)) then
  576. { A jump was removed, but not the current instruction, and
  577. Result doesn't necessarily translate into an optimisation
  578. routine's Result, so use the "Force New Iteration" flag so
  579. mark a new pass }
  580. Include(OptsToCheck, aoc_ForceNewIteration);
  581. if not Assigned(JumpTracking) then
  582. begin
  583. { Cross-label optimisations often causes other optimisations
  584. to perform worse because they're not given the chance to
  585. optimise locally. In this case, don't do the cross-label
  586. optimisations yet, but flag them as a potential possibility
  587. for the next iteration of Pass 1 }
  588. if not NotFirstIteration then
  589. Include(OptsToCheck, aoc_ForceNewIteration);
  590. end
  591. else if IsJumpToLabel(taicpu(Next)) and
  592. GetNextInstruction(Next, Next_Label) then
  593. begin
  594. { If we have JMP .lbl, and the label after it has all of its
  595. references tracked, then this is probably an if-else style of
  596. block and we can keep tracking. If the label for this jump
  597. then appears later and is fully tracked, then it's the end
  598. of the if-else blocks and the code paths converge (thus
  599. marking the end of the cross-jump) }
  600. if (Next_Label.typ = ait_label) then
  601. begin
  602. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  603. begin
  604. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  605. Next := Next_Label;
  606. { CrossJump gets set to false by LabelAccountedFor if the
  607. list is completely emptied (as it indicates that all
  608. code paths have converged). We could avoid this nuance
  609. by moving the TrackJump call to before the
  610. LabelAccountedFor call, but this is slower in situations
  611. where LabelAccountedFor would return False due to the
  612. creation of a new object that is not used and destroyed
  613. soon after. }
  614. CrossJump := True;
  615. Continue;
  616. end;
  617. end
  618. else if (Next_Label.typ <> ait_marker) then
  619. { We just did a RemoveDeadCodeAfterJump, so either we find
  620. a label, the end of the procedure or some kind of marker}
  621. InternalError(2022041720);
  622. end;
  623. Result := False;
  624. Exit;
  625. end
  626. else
  627. begin
  628. if not Assigned(JumpTracking) then
  629. begin
  630. { Cross-label optimisations often causes other optimisations
  631. to perform worse because they're not given the chance to
  632. optimise locally. In this case, don't do the cross-label
  633. optimisations yet, but flag them as a potential possibility
  634. for the next iteration of Pass 1 }
  635. if not NotFirstIteration then
  636. Include(OptsToCheck, aoc_ForceNewIteration);
  637. end
  638. else if IsJumpToLabel(taicpu(Next)) then
  639. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  640. else
  641. { Conditional jumps should always be a jump to label }
  642. InternalError(2022041701);
  643. CrossJump := True;
  644. Continue;
  645. end;
  646. if Next.typ = ait_label then
  647. begin
  648. if not Assigned(JumpTracking) then
  649. begin
  650. { Cross-label optimisations often causes other optimisations
  651. to perform worse because they're not given the chance to
  652. optimise locally. In this case, don't do the cross-label
  653. optimisations yet, but flag them as a potential possibility
  654. for the next iteration of Pass 1 }
  655. if not NotFirstIteration then
  656. Include(OptsToCheck, aoc_ForceNewIteration);
  657. end
  658. else if LabelAccountedFor(tai_label(Next).labsym) then
  659. Continue;
  660. { If we reach here, we're at a label that hasn't been seen before
  661. (or JumpTracking was nil) }
  662. Break;
  663. end;
  664. until not Result or
  665. not (cs_opt_level3 in current_settings.optimizerswitches) or
  666. not (Next.typ in [ait_label, ait_instruction]) or
  667. RegInInstruction(reg,Next);
  668. end;
  669. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  670. begin
  671. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  672. begin
  673. Result:=GetNextInstruction(Current,Next);
  674. exit;
  675. end;
  676. Next:=tai(Current.Next);
  677. Result:=false;
  678. while assigned(Next) do
  679. begin
  680. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  681. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  682. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  683. exit
  684. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  685. begin
  686. Result:=true;
  687. exit;
  688. end;
  689. Next:=tai(Next.Next);
  690. end;
  691. end;
  692. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  693. begin
  694. Result:=RegReadByInstruction(reg,hp);
  695. end;
  696. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  697. var
  698. p: taicpu;
  699. opcount: longint;
  700. begin
  701. RegReadByInstruction := false;
  702. if hp.typ <> ait_instruction then
  703. exit;
  704. p := taicpu(hp);
  705. case p.opcode of
  706. A_CALL:
  707. regreadbyinstruction := true;
  708. A_IMUL:
  709. case p.ops of
  710. 1:
  711. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  712. (
  713. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  714. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  715. );
  716. 2,3:
  717. regReadByInstruction :=
  718. reginop(reg,p.oper[0]^) or
  719. reginop(reg,p.oper[1]^);
  720. else
  721. InternalError(2019112801);
  722. end;
  723. A_MUL:
  724. begin
  725. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  726. (
  727. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  728. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  729. );
  730. end;
  731. A_IDIV,A_DIV:
  732. begin
  733. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  734. (
  735. (getregtype(reg)=R_INTREGISTER) and
  736. (
  737. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  738. )
  739. );
  740. end;
  741. else
  742. begin
  743. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  744. begin
  745. RegReadByInstruction := false;
  746. exit;
  747. end;
  748. for opcount := 0 to p.ops-1 do
  749. if (p.oper[opCount]^.typ = top_ref) and
  750. RegInRef(reg,p.oper[opcount]^.ref^) then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. { special handling for SSE MOVSD }
  756. if (p.opcode=A_MOVSD) and (p.ops>0) then
  757. begin
  758. if p.ops<>2 then
  759. internalerror(2017042702);
  760. regReadByInstruction := reginop(reg,p.oper[0]^) or
  761. (
  762. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  763. );
  764. exit;
  765. end;
  766. with insprop[p.opcode] do
  767. begin
  768. case getregtype(reg) of
  769. R_INTREGISTER:
  770. begin
  771. case getsupreg(reg) of
  772. RS_EAX:
  773. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_ECX:
  779. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_EDX:
  785. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. RS_EBX:
  791. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. RS_ESP:
  797. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. RS_EBP:
  803. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  804. begin
  805. RegReadByInstruction := true;
  806. exit
  807. end;
  808. RS_ESI:
  809. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  810. begin
  811. RegReadByInstruction := true;
  812. exit
  813. end;
  814. RS_EDI:
  815. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  816. begin
  817. RegReadByInstruction := true;
  818. exit
  819. end;
  820. end;
  821. end;
  822. R_MMREGISTER:
  823. begin
  824. case getsupreg(reg) of
  825. RS_XMM0:
  826. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  827. begin
  828. RegReadByInstruction := true;
  829. exit
  830. end;
  831. end;
  832. end;
  833. else
  834. ;
  835. end;
  836. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  837. begin
  838. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  839. begin
  840. case p.condition of
  841. C_A,C_NBE, { CF=0 and ZF=0 }
  842. C_BE,C_NA: { CF=1 or ZF=1 }
  843. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  844. C_AE,C_NB,C_NC, { CF=0 }
  845. C_B,C_NAE,C_C: { CF=1 }
  846. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  847. C_NE,C_NZ, { ZF=0 }
  848. C_E,C_Z: { ZF=1 }
  849. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  850. C_G,C_NLE, { ZF=0 and SF=OF }
  851. C_LE,C_NG: { ZF=1 or SF<>OF }
  852. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  853. C_GE,C_NL, { SF=OF }
  854. C_L,C_NGE: { SF<>OF }
  855. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  856. C_NO, { OF=0 }
  857. C_O: { OF=1 }
  858. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  859. C_NP,C_PO, { PF=0 }
  860. C_P,C_PE: { PF=1 }
  861. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  862. C_NS, { SF=0 }
  863. C_S: { SF=1 }
  864. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  865. else
  866. internalerror(2017042701);
  867. end;
  868. if RegReadByInstruction then
  869. exit;
  870. end;
  871. case getsubreg(reg) of
  872. R_SUBW,R_SUBD,R_SUBQ:
  873. RegReadByInstruction :=
  874. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  875. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  876. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  877. R_SUBFLAGCARRY:
  878. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGPARITY:
  880. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. R_SUBFLAGAUXILIARY:
  882. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  883. R_SUBFLAGZERO:
  884. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  885. R_SUBFLAGSIGN:
  886. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  887. R_SUBFLAGOVERFLOW:
  888. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  889. R_SUBFLAGINTERRUPT:
  890. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  891. R_SUBFLAGDIRECTION:
  892. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  893. else
  894. internalerror(2017042601);
  895. end;
  896. exit;
  897. end;
  898. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  899. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  900. (p.oper[0]^.reg=p.oper[1]^.reg) then
  901. exit;
  902. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  903. begin
  904. RegReadByInstruction := true;
  905. exit
  906. end;
  907. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  908. begin
  909. RegReadByInstruction := true;
  910. exit
  911. end;
  912. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  913. begin
  914. RegReadByInstruction := true;
  915. exit
  916. end;
  917. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  918. begin
  919. RegReadByInstruction := true;
  920. exit
  921. end;
  922. end;
  923. end;
  924. end;
  925. end;
  926. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  927. begin
  928. result:=false;
  929. if p1.typ<>ait_instruction then
  930. exit;
  931. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  932. exit(true);
  933. if (getregtype(reg)=R_INTREGISTER) and
  934. { change information for xmm movsd are not correct }
  935. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  936. begin
  937. { Handle instructions that behave differently depending on the size and operand count }
  938. case taicpu(p1).opcode of
  939. A_MUL, A_DIV, A_IDIV:
  940. if taicpu(p1).opsize = S_B then
  941. Result := (getsupreg(Reg) = RS_EAX)
  942. else
  943. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  944. A_IMUL:
  945. if taicpu(p1).ops = 1 then
  946. begin
  947. if taicpu(p1).opsize = S_B then
  948. Result := (getsupreg(Reg) = RS_EAX)
  949. else
  950. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  951. end;
  952. { If ops are greater than 1, call inherited method }
  953. else
  954. case getsupreg(reg) of
  955. { RS_EAX = RS_RAX on x86-64 }
  956. RS_EAX:
  957. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_ECX:
  959. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. RS_EDX:
  961. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  962. RS_EBX:
  963. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  964. RS_ESP:
  965. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. RS_EBP:
  967. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. RS_ESI:
  969. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. RS_EDI:
  971. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. else
  973. ;
  974. end;
  975. end;
  976. if result then
  977. exit;
  978. end
  979. else if getregtype(reg)=R_MMREGISTER then
  980. begin
  981. case getsupreg(reg) of
  982. RS_XMM0:
  983. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. else
  985. ;
  986. end;
  987. if result then
  988. exit;
  989. end
  990. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  991. begin
  992. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  993. exit(true);
  994. case getsubreg(reg) of
  995. R_SUBFLAGCARRY:
  996. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGPARITY:
  998. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBFLAGAUXILIARY:
  1000. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1001. R_SUBFLAGZERO:
  1002. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1003. R_SUBFLAGSIGN:
  1004. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1005. R_SUBFLAGOVERFLOW:
  1006. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1007. R_SUBFLAGINTERRUPT:
  1008. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1009. R_SUBFLAGDIRECTION:
  1010. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1011. R_SUBW,R_SUBD,R_SUBQ:
  1012. { Everything except the direction bits }
  1013. Result:=
  1014. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1015. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1016. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1017. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1018. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1019. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1020. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1021. else
  1022. ;
  1023. end;
  1024. if result then
  1025. exit;
  1026. end
  1027. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1028. exit(true);
  1029. Result:=inherited RegInInstruction(Reg, p1);
  1030. end;
  1031. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1032. const
  1033. WriteOps: array[0..3] of set of TInsChange =
  1034. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1035. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1036. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1037. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1038. var
  1039. OperIdx: Integer;
  1040. begin
  1041. Result := False;
  1042. if p1.typ <> ait_instruction then
  1043. exit;
  1044. with insprop[taicpu(p1).opcode] do
  1045. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1046. begin
  1047. case getsubreg(reg) of
  1048. R_SUBW,R_SUBD,R_SUBQ:
  1049. Result :=
  1050. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1051. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1052. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1053. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1054. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1055. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGCARRY:
  1057. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGPARITY:
  1059. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. R_SUBFLAGAUXILIARY:
  1061. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1062. R_SUBFLAGZERO:
  1063. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1064. R_SUBFLAGSIGN:
  1065. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1066. R_SUBFLAGOVERFLOW:
  1067. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1068. R_SUBFLAGINTERRUPT:
  1069. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1070. R_SUBFLAGDIRECTION:
  1071. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1072. else
  1073. internalerror(2017042602);
  1074. end;
  1075. exit;
  1076. end;
  1077. case taicpu(p1).opcode of
  1078. A_CALL:
  1079. { We could potentially set Result to False if the register in
  1080. question is non-volatile for the subroutine's calling convention,
  1081. but this would require detecting the calling convention in use and
  1082. also assuming that the routine doesn't contain malformed assembly
  1083. language, for example... so it could only be done under -O4 as it
  1084. would be considered a side-effect. [Kit] }
  1085. Result := True;
  1086. A_MOVSD:
  1087. { special handling for SSE MOVSD }
  1088. if (taicpu(p1).ops>0) then
  1089. begin
  1090. if taicpu(p1).ops<>2 then
  1091. internalerror(2017042703);
  1092. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1093. end;
  1094. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1095. so fix it here (FK)
  1096. }
  1097. A_VMOVSS,
  1098. A_VMOVSD:
  1099. begin
  1100. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1101. exit;
  1102. end;
  1103. A_MUL, A_DIV, A_IDIV:
  1104. begin
  1105. if taicpu(p1).opsize = S_B then
  1106. Result := (getsupreg(Reg) = RS_EAX)
  1107. else
  1108. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1109. end;
  1110. A_IMUL:
  1111. begin
  1112. if taicpu(p1).ops = 1 then
  1113. begin
  1114. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1115. end
  1116. else
  1117. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1118. Exit;
  1119. end;
  1120. else
  1121. ;
  1122. end;
  1123. if Result then
  1124. exit;
  1125. with insprop[taicpu(p1).opcode] do
  1126. begin
  1127. if getregtype(reg)=R_INTREGISTER then
  1128. begin
  1129. case getsupreg(reg) of
  1130. RS_EAX:
  1131. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1132. begin
  1133. Result := True;
  1134. exit
  1135. end;
  1136. RS_ECX:
  1137. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1138. begin
  1139. Result := True;
  1140. exit
  1141. end;
  1142. RS_EDX:
  1143. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1144. begin
  1145. Result := True;
  1146. exit
  1147. end;
  1148. RS_EBX:
  1149. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1150. begin
  1151. Result := True;
  1152. exit
  1153. end;
  1154. RS_ESP:
  1155. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1156. begin
  1157. Result := True;
  1158. exit
  1159. end;
  1160. RS_EBP:
  1161. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1162. begin
  1163. Result := True;
  1164. exit
  1165. end;
  1166. RS_ESI:
  1167. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1168. begin
  1169. Result := True;
  1170. exit
  1171. end;
  1172. RS_EDI:
  1173. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1174. begin
  1175. Result := True;
  1176. exit
  1177. end;
  1178. end;
  1179. end;
  1180. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1181. if (WriteOps[OperIdx]*Ch<>[]) and
  1182. { The register doesn't get modified inside a reference }
  1183. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1184. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1185. begin
  1186. Result := true;
  1187. exit
  1188. end;
  1189. end;
  1190. end;
  1191. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1192. const
  1193. WriteOps: array[0..3] of set of TInsChange =
  1194. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1195. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1196. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1197. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1198. var
  1199. X: Integer;
  1200. CurrentP1Size: asizeint;
  1201. begin
  1202. Result := (
  1203. (Ref.base <> NR_NO) and
  1204. {$ifdef x86_64}
  1205. (Ref.base <> NR_RIP) and
  1206. {$endif x86_64}
  1207. RegModifiedBetween(Ref.base, p1, p2)
  1208. ) or
  1209. (
  1210. (Ref.index <> NR_NO) and
  1211. (Ref.index <> Ref.base) and
  1212. RegModifiedBetween(Ref.index, p1, p2)
  1213. );
  1214. { Now check to see if the memory itself is written to }
  1215. if not Result then
  1216. begin
  1217. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1218. if p1.typ = ait_instruction then
  1219. begin
  1220. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1221. with insprop[taicpu(p1).opcode] do
  1222. for X := 0 to taicpu(p1).ops - 1 do
  1223. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1224. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1225. { Catch any potential overlaps }
  1226. (
  1227. (RefSize = 0) or
  1228. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1229. ) and
  1230. (
  1231. (CurrentP1Size = 0) or
  1232. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1233. ) and
  1234. { Reference is used, but does the instruction write to it? }
  1235. (
  1236. (Ch_All in Ch) or
  1237. ((WriteOps[X] * Ch) <> [])
  1238. ) then
  1239. begin
  1240. Result := True;
  1241. Break;
  1242. end;
  1243. end;
  1244. end;
  1245. end;
  1246. {$ifdef DEBUG_AOPTCPU}
  1247. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1248. begin
  1249. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1250. end;
  1251. function debug_tostr(i: tcgint): string; inline;
  1252. begin
  1253. Result := tostr(i);
  1254. end;
  1255. function debug_hexstr(i: tcgint): string;
  1256. begin
  1257. Result := '0x';
  1258. case i of
  1259. 0..$FF:
  1260. Result := Result + hexstr(i, 2);
  1261. $100..$FFFF:
  1262. Result := Result + hexstr(i, 4);
  1263. $10000..$FFFFFF:
  1264. Result := Result + hexstr(i, 6);
  1265. $1000000..$FFFFFFFF:
  1266. Result := Result + hexstr(i, 8);
  1267. else
  1268. Result := Result + hexstr(i, 16);
  1269. end;
  1270. end;
  1271. function debug_regname(r: TRegister): string; inline;
  1272. begin
  1273. Result := '%' + std_regname(r);
  1274. end;
  1275. { Debug output function - creates a string representation of an operator }
  1276. function debug_operstr(oper: TOper): string;
  1277. begin
  1278. case oper.typ of
  1279. top_const:
  1280. Result := '$' + debug_tostr(oper.val);
  1281. top_reg:
  1282. Result := debug_regname(oper.reg);
  1283. top_ref:
  1284. begin
  1285. if oper.ref^.offset <> 0 then
  1286. Result := debug_tostr(oper.ref^.offset) + '('
  1287. else
  1288. Result := '(';
  1289. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1290. begin
  1291. Result := Result + debug_regname(oper.ref^.base);
  1292. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1293. Result := Result + ',' + debug_regname(oper.ref^.index);
  1294. end
  1295. else
  1296. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1297. Result := Result + debug_regname(oper.ref^.index);
  1298. if (oper.ref^.scalefactor > 1) then
  1299. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1300. else
  1301. Result := Result + ')';
  1302. end;
  1303. else
  1304. Result := '[UNKNOWN]';
  1305. end;
  1306. end;
  1307. function debug_op2str(opcode: tasmop): string; inline;
  1308. begin
  1309. Result := std_op2str[opcode];
  1310. end;
  1311. function debug_opsize2str(opsize: topsize): string; inline;
  1312. begin
  1313. Result := gas_opsize2str[opsize];
  1314. end;
  1315. {$else DEBUG_AOPTCPU}
  1316. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1317. begin
  1318. end;
  1319. function debug_tostr(i: tcgint): string; inline;
  1320. begin
  1321. Result := '';
  1322. end;
  1323. function debug_hexstr(i: tcgint): string; inline;
  1324. begin
  1325. Result := '';
  1326. end;
  1327. function debug_regname(r: TRegister): string; inline;
  1328. begin
  1329. Result := '';
  1330. end;
  1331. function debug_operstr(oper: TOper): string; inline;
  1332. begin
  1333. Result := '';
  1334. end;
  1335. function debug_op2str(opcode: tasmop): string; inline;
  1336. begin
  1337. Result := '';
  1338. end;
  1339. function debug_opsize2str(opsize: topsize): string; inline;
  1340. begin
  1341. Result := '';
  1342. end;
  1343. {$endif DEBUG_AOPTCPU}
  1344. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1345. begin
  1346. {$ifdef x86_64}
  1347. { Always fine on x86-64 }
  1348. Result := True;
  1349. {$else x86_64}
  1350. Result :=
  1351. {$ifdef i8086}
  1352. (current_settings.cputype >= cpu_386) and
  1353. {$endif i8086}
  1354. (
  1355. { Always accept if optimising for size }
  1356. (cs_opt_size in current_settings.optimizerswitches) or
  1357. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1358. (current_settings.optimizecputype >= cpu_Pentium2)
  1359. );
  1360. {$endif x86_64}
  1361. end;
  1362. { Attempts to allocate a volatile integer register for use between p and hp,
  1363. using AUsedRegs for the current register usage information. Returns NR_NO
  1364. if no free register could be found }
  1365. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1366. var
  1367. RegSet: TCPURegisterSet;
  1368. CurrentSuperReg: Integer;
  1369. CurrentReg: TRegister;
  1370. Currentp: tai;
  1371. Breakout: Boolean;
  1372. begin
  1373. Result := NR_NO;
  1374. RegSet :=
  1375. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1376. current_procinfo.saved_regs_int;
  1377. (*
  1378. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1379. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1380. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1381. *)
  1382. for CurrentSuperReg in RegSet do
  1383. begin
  1384. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1385. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1386. {$if defined(i386) or defined(i8086)}
  1387. { If the target size is 8-bit, make sure we can actually encode it }
  1388. and (
  1389. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1390. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1391. )
  1392. {$endif i386 or i8086}
  1393. then
  1394. begin
  1395. Currentp := p;
  1396. Breakout := False;
  1397. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1398. begin
  1399. case Currentp.typ of
  1400. ait_instruction:
  1401. begin
  1402. if RegInInstruction(CurrentReg, Currentp) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. { Cannot allocate across an unconditional jump }
  1408. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1409. Exit;
  1410. end;
  1411. ait_marker:
  1412. { Don't try anything more if a marker is hit }
  1413. Exit;
  1414. ait_regalloc:
  1415. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1416. begin
  1417. Breakout := True;
  1418. Break;
  1419. end;
  1420. else
  1421. ;
  1422. end;
  1423. end;
  1424. if Breakout then
  1425. { Try the next register }
  1426. Continue;
  1427. { We have a free register available }
  1428. Result := CurrentReg;
  1429. if not DontAlloc then
  1430. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1431. Exit;
  1432. end;
  1433. end;
  1434. end;
  1435. { Attempts to allocate a volatile MM register for use between p and hp,
  1436. using AUsedRegs for the current register usage information. Returns NR_NO
  1437. if no free register could be found }
  1438. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1439. var
  1440. RegSet: TCPURegisterSet;
  1441. CurrentSuperReg: Integer;
  1442. CurrentReg: TRegister;
  1443. Currentp: tai;
  1444. Breakout: Boolean;
  1445. begin
  1446. Result := NR_NO;
  1447. RegSet :=
  1448. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1449. current_procinfo.saved_regs_mm;
  1450. for CurrentSuperReg in RegSet do
  1451. begin
  1452. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1453. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1454. begin
  1455. Currentp := p;
  1456. Breakout := False;
  1457. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1458. begin
  1459. case Currentp.typ of
  1460. ait_instruction:
  1461. begin
  1462. if RegInInstruction(CurrentReg, Currentp) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. { Cannot allocate across an unconditional jump }
  1468. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1469. Exit;
  1470. end;
  1471. ait_marker:
  1472. { Don't try anything more if a marker is hit }
  1473. Exit;
  1474. ait_regalloc:
  1475. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1476. begin
  1477. Breakout := True;
  1478. Break;
  1479. end;
  1480. else
  1481. ;
  1482. end;
  1483. end;
  1484. if Breakout then
  1485. { Try the next register }
  1486. Continue;
  1487. { We have a free register available }
  1488. Result := CurrentReg;
  1489. if not DontAlloc then
  1490. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1491. Exit;
  1492. end;
  1493. end;
  1494. end;
  1495. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1496. begin
  1497. if not SuperRegistersEqual(reg1,reg2) then
  1498. exit(false);
  1499. if getregtype(reg1)<>R_INTREGISTER then
  1500. exit(true); {because SuperRegisterEqual is true}
  1501. case getsubreg(reg1) of
  1502. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1503. higher, it preserves the high bits, so the new value depends on
  1504. reg2's previous value. In other words, it is equivalent to doing:
  1505. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1506. R_SUBL:
  1507. exit(getsubreg(reg2)=R_SUBL);
  1508. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1509. higher, it actually does a:
  1510. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1511. R_SUBH:
  1512. exit(getsubreg(reg2)=R_SUBH);
  1513. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1514. bits of reg2:
  1515. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1516. R_SUBW:
  1517. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1518. { a write to R_SUBD always overwrites every other subregister,
  1519. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1520. R_SUBD,
  1521. R_SUBQ:
  1522. exit(true);
  1523. else
  1524. internalerror(2017042801);
  1525. end;
  1526. end;
  1527. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1528. begin
  1529. if not SuperRegistersEqual(reg1,reg2) then
  1530. exit(false);
  1531. if getregtype(reg1)<>R_INTREGISTER then
  1532. exit(true); {because SuperRegisterEqual is true}
  1533. case getsubreg(reg1) of
  1534. R_SUBL:
  1535. exit(getsubreg(reg2)<>R_SUBH);
  1536. R_SUBH:
  1537. exit(getsubreg(reg2)<>R_SUBL);
  1538. R_SUBW,
  1539. R_SUBD,
  1540. R_SUBQ:
  1541. exit(true);
  1542. else
  1543. internalerror(2017042802);
  1544. end;
  1545. end;
  1546. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1547. var
  1548. hp1 : tai;
  1549. l : TCGInt;
  1550. begin
  1551. result:=false;
  1552. if not(GetNextInstruction(p, hp1)) then
  1553. exit;
  1554. { changes the code sequence
  1555. shr/sar const1, x
  1556. shl const2, x
  1557. to
  1558. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1559. if (taicpu(p).oper[0]^.typ = top_const) and
  1560. MatchInstruction(hp1,A_SHL,[]) and
  1561. (taicpu(hp1).oper[0]^.typ = top_const) and
  1562. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1563. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1564. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1565. begin
  1566. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1567. not(cs_opt_size in current_settings.optimizerswitches)
  1568. {$ifdef x86_64}
  1569. and (
  1570. (taicpu(p).opsize <> S_Q) or
  1571. { 64-bit AND can only store signed 32-bit immediates }
  1572. (taicpu(p).oper[0]^.val < 32)
  1573. )
  1574. {$endif x86_64}
  1575. then
  1576. begin
  1577. { shr/sar const1, %reg
  1578. shl const2, %reg
  1579. with const1 > const2 }
  1580. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1581. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1582. taicpu(hp1).opcode := A_AND;
  1583. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1584. case taicpu(p).opsize Of
  1585. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1586. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1587. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1588. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1589. else
  1590. Internalerror(2017050703)
  1591. end;
  1592. end
  1593. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1594. not(cs_opt_size in current_settings.optimizerswitches)
  1595. {$ifdef x86_64}
  1596. and (
  1597. (taicpu(p).opsize <> S_Q) or
  1598. { 64-bit AND can only store signed 32-bit immediates }
  1599. (taicpu(p).oper[0]^.val < 32)
  1600. )
  1601. {$endif x86_64}
  1602. then
  1603. begin
  1604. { shr/sar const1, %reg
  1605. shl const2, %reg
  1606. with const1 < const2 }
  1607. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1608. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1609. taicpu(p).opcode := A_AND;
  1610. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1611. case taicpu(p).opsize Of
  1612. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1613. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1614. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1615. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1616. else
  1617. Internalerror(2017050702)
  1618. end;
  1619. end
  1620. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1621. {$ifdef x86_64}
  1622. and (
  1623. (taicpu(p).opsize <> S_Q) or
  1624. { 64-bit AND can only store signed 32-bit immediates }
  1625. (taicpu(p).oper[0]^.val < 32)
  1626. )
  1627. {$endif x86_64}
  1628. then
  1629. begin
  1630. { shr/sar const1, %reg
  1631. shl const2, %reg
  1632. with const1 = const2 }
  1633. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1634. taicpu(p).opcode := A_AND;
  1635. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1636. case taicpu(p).opsize Of
  1637. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1638. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1639. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1640. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1641. else
  1642. Internalerror(2017050701)
  1643. end;
  1644. RemoveInstruction(hp1);
  1645. end;
  1646. end;
  1647. end;
  1648. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1649. var
  1650. opsize : topsize;
  1651. hp1, hp2 : tai;
  1652. tmpref : treference;
  1653. ShiftValue : Cardinal;
  1654. BaseValue : TCGInt;
  1655. begin
  1656. result:=false;
  1657. opsize:=taicpu(p).opsize;
  1658. { changes certain "imul const, %reg"'s to lea sequences }
  1659. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1660. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1661. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1662. if (taicpu(p).oper[0]^.val = 1) then
  1663. if (taicpu(p).ops = 2) then
  1664. { remove "imul $1, reg" }
  1665. begin
  1666. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1667. Result := RemoveCurrentP(p);
  1668. end
  1669. else
  1670. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1671. begin
  1672. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1673. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1674. asml.InsertAfter(hp1, p);
  1675. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1676. RemoveCurrentP(p, hp1);
  1677. Result := True;
  1678. end
  1679. else if ((taicpu(p).ops <= 2) or
  1680. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1681. not(cs_opt_size in current_settings.optimizerswitches) and
  1682. (not(GetNextInstruction(p, hp1)) or
  1683. not((tai(hp1).typ = ait_instruction) and
  1684. ((taicpu(hp1).opcode=A_Jcc) and
  1685. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1686. begin
  1687. {
  1688. imul X, reg1, reg2 to
  1689. lea (reg1,reg1,Y), reg2
  1690. shl ZZ,reg2
  1691. imul XX, reg1 to
  1692. lea (reg1,reg1,YY), reg1
  1693. shl ZZ,reg2
  1694. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1695. it does not exist as a separate optimization target in FPC though.
  1696. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1697. at most two zeros
  1698. }
  1699. reference_reset(tmpref,1,[]);
  1700. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1701. begin
  1702. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1703. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1704. TmpRef.base := taicpu(p).oper[1]^.reg;
  1705. TmpRef.index := taicpu(p).oper[1]^.reg;
  1706. if not(BaseValue in [3,5,9]) then
  1707. Internalerror(2018110101);
  1708. TmpRef.ScaleFactor := BaseValue-1;
  1709. if (taicpu(p).ops = 2) then
  1710. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1711. else
  1712. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1713. AsmL.InsertAfter(hp1,p);
  1714. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1715. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1716. RemoveCurrentP(p, hp1);
  1717. if ShiftValue>0 then
  1718. begin
  1719. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1720. AsmL.InsertAfter(hp2,hp1);
  1721. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1722. end;
  1723. Result := True;
  1724. end;
  1725. end;
  1726. end;
  1727. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1728. begin
  1729. Result := False;
  1730. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1731. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1732. begin
  1733. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1734. taicpu(p).opcode := A_MOV;
  1735. Result := True;
  1736. end;
  1737. end;
  1738. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1739. var
  1740. p: taicpu absolute hp; { Implicit typecast }
  1741. i: Integer;
  1742. begin
  1743. Result := False;
  1744. if not assigned(hp) or
  1745. (hp.typ <> ait_instruction) then
  1746. Exit;
  1747. Prefetch(insprop[p.opcode]);
  1748. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1749. with insprop[p.opcode] do
  1750. begin
  1751. case getsubreg(reg) of
  1752. R_SUBW,R_SUBD,R_SUBQ:
  1753. Result:=
  1754. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1755. uncommon flags are checked first }
  1756. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1757. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1758. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1759. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1760. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1761. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1762. R_SUBFLAGCARRY:
  1763. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1764. R_SUBFLAGPARITY:
  1765. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1766. R_SUBFLAGAUXILIARY:
  1767. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1768. R_SUBFLAGZERO:
  1769. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1770. R_SUBFLAGSIGN:
  1771. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1772. R_SUBFLAGOVERFLOW:
  1773. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1774. R_SUBFLAGINTERRUPT:
  1775. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1776. R_SUBFLAGDIRECTION:
  1777. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1778. else
  1779. internalerror(2017050501);
  1780. end;
  1781. exit;
  1782. end;
  1783. { Handle special cases first }
  1784. case p.opcode of
  1785. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1786. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1787. begin
  1788. Result :=
  1789. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1790. (p.oper[1]^.typ = top_reg) and
  1791. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1792. (
  1793. (p.oper[0]^.typ = top_const) or
  1794. (
  1795. (p.oper[0]^.typ = top_reg) and
  1796. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1797. ) or (
  1798. (p.oper[0]^.typ = top_ref) and
  1799. not RegInRef(reg,p.oper[0]^.ref^)
  1800. )
  1801. );
  1802. end;
  1803. A_MUL, A_IMUL:
  1804. Result :=
  1805. (
  1806. (p.ops=3) and { IMUL only }
  1807. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1808. (
  1809. (
  1810. (p.oper[1]^.typ=top_reg) and
  1811. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1812. ) or (
  1813. (p.oper[1]^.typ=top_ref) and
  1814. not RegInRef(reg,p.oper[1]^.ref^)
  1815. )
  1816. )
  1817. ) or (
  1818. (
  1819. (p.ops=1) and
  1820. (
  1821. (
  1822. (
  1823. (p.oper[0]^.typ=top_reg) and
  1824. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1825. )
  1826. ) or (
  1827. (p.oper[0]^.typ=top_ref) and
  1828. not RegInRef(reg,p.oper[0]^.ref^)
  1829. )
  1830. ) and (
  1831. (
  1832. (p.opsize=S_B) and
  1833. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1834. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1835. ) or (
  1836. (p.opsize=S_W) and
  1837. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1838. ) or (
  1839. (p.opsize=S_L) and
  1840. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1841. {$ifdef x86_64}
  1842. ) or (
  1843. (p.opsize=S_Q) and
  1844. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1845. {$endif x86_64}
  1846. )
  1847. )
  1848. )
  1849. );
  1850. A_CBW:
  1851. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1852. {$ifndef x86_64}
  1853. A_LDS:
  1854. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1855. A_LES:
  1856. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1857. {$endif not x86_64}
  1858. A_LFS:
  1859. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1860. A_LGS:
  1861. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1862. A_LSS:
  1863. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1864. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1865. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1866. A_LODSB:
  1867. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1868. A_LODSW:
  1869. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1870. {$ifdef x86_64}
  1871. A_LODSQ:
  1872. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1873. {$endif x86_64}
  1874. A_LODSD:
  1875. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1876. A_FSTSW, A_FNSTSW:
  1877. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1878. else
  1879. begin
  1880. with insprop[p.opcode] do
  1881. begin
  1882. if (
  1883. { xor %reg,%reg etc. is classed as a new value }
  1884. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1885. MatchOpType(p, top_reg, top_reg) and
  1886. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1887. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1888. ) then
  1889. begin
  1890. Result := True;
  1891. Exit;
  1892. end;
  1893. { Make sure the entire register is overwritten }
  1894. if (getregtype(reg) = R_INTREGISTER) then
  1895. begin
  1896. if (p.ops > 0) then
  1897. begin
  1898. if RegInOp(reg, p.oper[0]^) then
  1899. begin
  1900. if (p.oper[0]^.typ = top_ref) then
  1901. begin
  1902. if RegInRef(reg, p.oper[0]^.ref^) then
  1903. begin
  1904. Result := False;
  1905. Exit;
  1906. end;
  1907. end
  1908. else if (p.oper[0]^.typ = top_reg) then
  1909. begin
  1910. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1911. begin
  1912. Result := False;
  1913. Exit;
  1914. end
  1915. else if ([Ch_WOp1]*Ch<>[]) then
  1916. begin
  1917. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1918. Result := True
  1919. else
  1920. begin
  1921. Result := False;
  1922. Exit;
  1923. end;
  1924. end;
  1925. end;
  1926. end;
  1927. if (p.ops > 1) then
  1928. begin
  1929. if RegInOp(reg, p.oper[1]^) then
  1930. begin
  1931. if (p.oper[1]^.typ = top_ref) then
  1932. begin
  1933. if RegInRef(reg, p.oper[1]^.ref^) then
  1934. begin
  1935. Result := False;
  1936. Exit;
  1937. end;
  1938. end
  1939. else if (p.oper[1]^.typ = top_reg) then
  1940. begin
  1941. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1942. begin
  1943. Result := False;
  1944. Exit;
  1945. end
  1946. else if ([Ch_WOp2]*Ch<>[]) then
  1947. begin
  1948. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1949. Result := True
  1950. else
  1951. begin
  1952. Result := False;
  1953. Exit;
  1954. end;
  1955. end;
  1956. end;
  1957. end;
  1958. if (p.ops > 2) then
  1959. begin
  1960. if RegInOp(reg, p.oper[2]^) then
  1961. begin
  1962. if (p.oper[2]^.typ = top_ref) then
  1963. begin
  1964. if RegInRef(reg, p.oper[2]^.ref^) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end;
  1969. end
  1970. else if (p.oper[2]^.typ = top_reg) then
  1971. begin
  1972. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1973. begin
  1974. Result := False;
  1975. Exit;
  1976. end
  1977. else if ([Ch_WOp3]*Ch<>[]) then
  1978. begin
  1979. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1980. Result := True
  1981. else
  1982. begin
  1983. Result := False;
  1984. Exit;
  1985. end;
  1986. end;
  1987. end;
  1988. end;
  1989. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1990. begin
  1991. if (p.oper[3]^.typ = top_ref) then
  1992. begin
  1993. if RegInRef(reg, p.oper[3]^.ref^) then
  1994. begin
  1995. Result := False;
  1996. Exit;
  1997. end;
  1998. end
  1999. else if (p.oper[3]^.typ = top_reg) then
  2000. begin
  2001. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  2002. begin
  2003. Result := False;
  2004. Exit;
  2005. end
  2006. else if ([Ch_WOp4]*Ch<>[]) then
  2007. begin
  2008. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  2009. Result := True
  2010. else
  2011. begin
  2012. Result := False;
  2013. Exit;
  2014. end;
  2015. end;
  2016. end;
  2017. end;
  2018. end;
  2019. end;
  2020. end;
  2021. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2022. case getsupreg(reg) of
  2023. RS_EAX:
  2024. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2025. begin
  2026. Result := True;
  2027. Exit;
  2028. end;
  2029. RS_ECX:
  2030. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2031. begin
  2032. Result := True;
  2033. Exit;
  2034. end;
  2035. RS_EDX:
  2036. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2037. begin
  2038. Result := True;
  2039. Exit;
  2040. end;
  2041. RS_EBX:
  2042. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2043. begin
  2044. Result := True;
  2045. Exit;
  2046. end;
  2047. RS_ESP:
  2048. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2049. begin
  2050. Result := True;
  2051. Exit;
  2052. end;
  2053. RS_EBP:
  2054. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2055. begin
  2056. Result := True;
  2057. Exit;
  2058. end;
  2059. RS_ESI:
  2060. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2061. begin
  2062. Result := True;
  2063. Exit;
  2064. end;
  2065. RS_EDI:
  2066. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2067. begin
  2068. Result := True;
  2069. Exit;
  2070. end;
  2071. else
  2072. ;
  2073. end;
  2074. end;
  2075. end;
  2076. end;
  2077. end;
  2078. end;
  2079. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2080. var
  2081. hp2,hp3 : tai;
  2082. begin
  2083. { some x86-64 issue a NOP before the real exit code }
  2084. if MatchInstruction(p,A_NOP,[]) then
  2085. GetNextInstruction(p,p);
  2086. result:=assigned(p) and (p.typ=ait_instruction) and
  2087. ((taicpu(p).opcode = A_RET) or
  2088. ((taicpu(p).opcode=A_LEAVE) and
  2089. GetNextInstruction(p,hp2) and
  2090. MatchInstruction(hp2,A_RET,[S_NO])
  2091. ) or
  2092. (((taicpu(p).opcode=A_LEA) and
  2093. MatchOpType(taicpu(p),top_ref,top_reg) and
  2094. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2095. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2096. ) and
  2097. GetNextInstruction(p,hp2) and
  2098. MatchInstruction(hp2,A_RET,[S_NO])
  2099. ) or
  2100. ((((taicpu(p).opcode=A_MOV) and
  2101. MatchOpType(taicpu(p),top_reg,top_reg) and
  2102. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2103. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2104. ((taicpu(p).opcode=A_LEA) and
  2105. MatchOpType(taicpu(p),top_ref,top_reg) and
  2106. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2107. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2108. )
  2109. ) and
  2110. GetNextInstruction(p,hp2) and
  2111. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2112. MatchOpType(taicpu(hp2),top_reg) and
  2113. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2114. GetNextInstruction(hp2,hp3) and
  2115. MatchInstruction(hp3,A_RET,[S_NO])
  2116. )
  2117. );
  2118. end;
  2119. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2120. begin
  2121. isFoldableArithOp := False;
  2122. case hp1.opcode of
  2123. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2124. isFoldableArithOp :=
  2125. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2126. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2127. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2128. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2129. (taicpu(hp1).oper[1]^.reg = reg);
  2130. A_INC,A_DEC,A_NEG,A_NOT:
  2131. isFoldableArithOp :=
  2132. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2133. (taicpu(hp1).oper[0]^.reg = reg);
  2134. else
  2135. ;
  2136. end;
  2137. end;
  2138. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2139. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2140. var
  2141. hp2: tai;
  2142. begin
  2143. hp2 := p;
  2144. repeat
  2145. hp2 := tai(hp2.previous);
  2146. if assigned(hp2) and
  2147. (hp2.typ = ait_regalloc) and
  2148. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2149. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2150. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2151. begin
  2152. RemoveInstruction(hp2);
  2153. break;
  2154. end;
  2155. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2156. end;
  2157. begin
  2158. case current_procinfo.procdef.returndef.typ of
  2159. arraydef,recorddef,pointerdef,
  2160. stringdef,enumdef,procdef,objectdef,errordef,
  2161. filedef,setdef,procvardef,
  2162. classrefdef,forwarddef:
  2163. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2164. orddef:
  2165. if current_procinfo.procdef.returndef.size <> 0 then
  2166. begin
  2167. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2168. { for int64/qword }
  2169. if current_procinfo.procdef.returndef.size = 8 then
  2170. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2171. end;
  2172. else
  2173. ;
  2174. end;
  2175. end;
  2176. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2177. var
  2178. hp1: tai;
  2179. operswap: poper;
  2180. begin
  2181. Result := False;
  2182. { Optimise:
  2183. cmov(c) %reg1,%reg2
  2184. mov %reg2,%reg1
  2185. (%reg2 dealloc.)
  2186. To:
  2187. cmov(~c) %reg2,%reg1
  2188. }
  2189. if (taicpu(p).oper[0]^.typ = top_reg) then
  2190. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2191. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2192. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2193. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2194. begin
  2195. TransferUsedRegs(TmpUsedRegs);
  2196. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2197. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2198. begin
  2199. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2200. { Save time by swapping the pointers (they're both registers, so
  2201. we don't need to worry about reference counts) }
  2202. operswap := taicpu(p).oper[0];
  2203. taicpu(p).oper[0] := taicpu(p).oper[1];
  2204. taicpu(p).oper[1] := operswap;
  2205. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2206. RemoveInstruction(hp1);
  2207. { It's still a CMOV, so we can look further ahead }
  2208. Include(OptsToCheck, aoc_ForceNewIteration);
  2209. { But first, let's see if this will get optimised again
  2210. (probably won't happen, but best to be sure) }
  2211. Continue;
  2212. end;
  2213. Break;
  2214. end;
  2215. end;
  2216. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2217. var
  2218. hp1,hp2 : tai;
  2219. begin
  2220. result:=false;
  2221. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2222. begin
  2223. { vmova* reg1,reg1
  2224. =>
  2225. <nop> }
  2226. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2227. begin
  2228. RemoveCurrentP(p);
  2229. result:=true;
  2230. exit;
  2231. end;
  2232. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2233. (hp1.typ = ait_instruction) and
  2234. (
  2235. { Under -O2 and below, the instructions are always adjacent }
  2236. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2237. (taicpu(hp1).ops <= 1) or
  2238. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2239. { If reg1 = reg3, reg1 must not be modified in between }
  2240. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2241. ) then
  2242. begin
  2243. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2244. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2245. begin
  2246. { vmova* reg1,reg2
  2247. ...
  2248. vmova* reg2,reg3
  2249. dealloc reg2
  2250. =>
  2251. vmova* reg1,reg3 }
  2252. TransferUsedRegs(TmpUsedRegs);
  2253. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2254. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2255. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2256. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2257. begin
  2258. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2259. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2260. TransferUsedRegs(TmpUsedRegs);
  2261. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2262. RemoveInstruction(hp1);
  2263. result:=true;
  2264. exit;
  2265. end;
  2266. { special case:
  2267. vmova* reg1,<op>
  2268. ...
  2269. vmova* <op>,reg1
  2270. =>
  2271. vmova* reg1,<op> }
  2272. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2273. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2274. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2275. ) then
  2276. begin
  2277. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2278. RemoveInstruction(hp1);
  2279. result:=true;
  2280. exit;
  2281. end
  2282. end
  2283. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2284. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2285. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2286. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2287. ) and
  2288. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2289. begin
  2290. { vmova* reg1,reg2
  2291. ...
  2292. vmovs* reg2,<op>
  2293. dealloc reg2
  2294. =>
  2295. vmovs* reg1,<op> }
  2296. TransferUsedRegs(TmpUsedRegs);
  2297. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2298. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2299. begin
  2300. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2301. taicpu(p).opcode:=taicpu(hp1).opcode;
  2302. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2303. TransferUsedRegs(TmpUsedRegs);
  2304. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2305. RemoveInstruction(hp1);
  2306. result:=true;
  2307. exit;
  2308. end
  2309. end;
  2310. if MatchInstruction(hp1,[A_VFMADDPD,
  2311. A_VFMADD132PD,
  2312. A_VFMADD132PS,
  2313. A_VFMADD132SD,
  2314. A_VFMADD132SS,
  2315. A_VFMADD213PD,
  2316. A_VFMADD213PS,
  2317. A_VFMADD213SD,
  2318. A_VFMADD213SS,
  2319. A_VFMADD231PD,
  2320. A_VFMADD231PS,
  2321. A_VFMADD231SD,
  2322. A_VFMADD231SS,
  2323. A_VFMADDSUB132PD,
  2324. A_VFMADDSUB132PS,
  2325. A_VFMADDSUB213PD,
  2326. A_VFMADDSUB213PS,
  2327. A_VFMADDSUB231PD,
  2328. A_VFMADDSUB231PS,
  2329. A_VFMSUB132PD,
  2330. A_VFMSUB132PS,
  2331. A_VFMSUB132SD,
  2332. A_VFMSUB132SS,
  2333. A_VFMSUB213PD,
  2334. A_VFMSUB213PS,
  2335. A_VFMSUB213SD,
  2336. A_VFMSUB213SS,
  2337. A_VFMSUB231PD,
  2338. A_VFMSUB231PS,
  2339. A_VFMSUB231SD,
  2340. A_VFMSUB231SS,
  2341. A_VFMSUBADD132PD,
  2342. A_VFMSUBADD132PS,
  2343. A_VFMSUBADD213PD,
  2344. A_VFMSUBADD213PS,
  2345. A_VFMSUBADD231PD,
  2346. A_VFMSUBADD231PS,
  2347. A_VFNMADD132PD,
  2348. A_VFNMADD132PS,
  2349. A_VFNMADD132SD,
  2350. A_VFNMADD132SS,
  2351. A_VFNMADD213PD,
  2352. A_VFNMADD213PS,
  2353. A_VFNMADD213SD,
  2354. A_VFNMADD213SS,
  2355. A_VFNMADD231PD,
  2356. A_VFNMADD231PS,
  2357. A_VFNMADD231SD,
  2358. A_VFNMADD231SS,
  2359. A_VFNMSUB132PD,
  2360. A_VFNMSUB132PS,
  2361. A_VFNMSUB132SD,
  2362. A_VFNMSUB132SS,
  2363. A_VFNMSUB213PD,
  2364. A_VFNMSUB213PS,
  2365. A_VFNMSUB213SD,
  2366. A_VFNMSUB213SS,
  2367. A_VFNMSUB231PD,
  2368. A_VFNMSUB231PS,
  2369. A_VFNMSUB231SD,
  2370. A_VFNMSUB231SS],[S_NO]) and
  2371. { we mix single and double opperations here because we assume that the compiler
  2372. generates vmovapd only after double operations and vmovaps only after single operations }
  2373. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2374. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2375. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2376. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2377. begin
  2378. TransferUsedRegs(TmpUsedRegs);
  2379. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2380. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2381. begin
  2382. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2383. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2384. RemoveCurrentP(p)
  2385. else
  2386. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2387. RemoveInstruction(hp2);
  2388. end;
  2389. end
  2390. else if (hp1.typ = ait_instruction) and
  2391. (((taicpu(p).opcode=A_MOVAPS) and
  2392. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2393. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2394. ((taicpu(p).opcode=A_MOVAPD) and
  2395. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2396. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2397. ) and
  2398. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2399. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2400. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2401. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2402. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2403. { change
  2404. movapX reg,reg2
  2405. addsX/subsX/... reg3, reg2
  2406. movapX reg2,reg
  2407. to
  2408. addsX/subsX/... reg3,reg
  2409. }
  2410. begin
  2411. TransferUsedRegs(TmpUsedRegs);
  2412. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2413. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2414. begin
  2415. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2416. debug_op2str(taicpu(p).opcode)+' '+
  2417. debug_op2str(taicpu(hp1).opcode)+' '+
  2418. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2419. { we cannot eliminate the first move if
  2420. the operations uses the same register for source and dest }
  2421. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2422. { Remember that hp1 is not necessarily the immediate
  2423. next instruction }
  2424. RemoveCurrentP(p);
  2425. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2426. RemoveInstruction(hp2);
  2427. result:=true;
  2428. end;
  2429. end
  2430. else if (hp1.typ = ait_instruction) and
  2431. (((taicpu(p).opcode=A_VMOVAPD) and
  2432. (taicpu(hp1).opcode=A_VCOMISD)) or
  2433. ((taicpu(p).opcode=A_VMOVAPS) and
  2434. ((taicpu(hp1).opcode=A_VCOMISS))
  2435. )
  2436. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2437. { change
  2438. movapX reg,reg1
  2439. vcomisX reg1,reg1
  2440. to
  2441. vcomisX reg,reg
  2442. }
  2443. begin
  2444. TransferUsedRegs(TmpUsedRegs);
  2445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2446. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2447. begin
  2448. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2449. debug_op2str(taicpu(p).opcode)+' '+
  2450. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2451. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2452. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2453. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2454. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2455. RemoveCurrentP(p);
  2456. result:=true;
  2457. exit;
  2458. end;
  2459. end
  2460. end;
  2461. end;
  2462. end;
  2463. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2464. var
  2465. hp1 : tai;
  2466. begin
  2467. result:=false;
  2468. { replace
  2469. V<Op>X %mreg1,%mreg2,%mreg3
  2470. VMovX %mreg3,%mreg4
  2471. dealloc %mreg3
  2472. by
  2473. V<Op>X %mreg1,%mreg2,%mreg4
  2474. ?
  2475. }
  2476. if GetNextInstruction(p,hp1) and
  2477. { we mix single and double operations here because we assume that the compiler
  2478. generates vmovapd only after double operations and vmovaps only after single operations }
  2479. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2480. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2481. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2482. begin
  2483. TransferUsedRegs(TmpUsedRegs);
  2484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2485. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2486. begin
  2487. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2488. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2489. RemoveInstruction(hp1);
  2490. result:=true;
  2491. end;
  2492. end;
  2493. end;
  2494. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2495. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2496. begin
  2497. Result := False;
  2498. { For safety reasons, only check for exact register matches }
  2499. { Check base register }
  2500. if (ref.base = AOldReg) then
  2501. begin
  2502. ref.base := ANewReg;
  2503. Result := True;
  2504. end;
  2505. { Check index register }
  2506. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2507. begin
  2508. ref.index := ANewReg;
  2509. Result := True;
  2510. end;
  2511. end;
  2512. { Replaces all references to AOldReg in an operand to ANewReg }
  2513. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2514. var
  2515. OldSupReg, NewSupReg: TSuperRegister;
  2516. OldSubReg, NewSubReg: TSubRegister;
  2517. OldRegType: TRegisterType;
  2518. ThisOper: POper;
  2519. begin
  2520. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2521. Result := False;
  2522. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2523. InternalError(2020011801);
  2524. OldSupReg := getsupreg(AOldReg);
  2525. OldSubReg := getsubreg(AOldReg);
  2526. OldRegType := getregtype(AOldReg);
  2527. NewSupReg := getsupreg(ANewReg);
  2528. NewSubReg := getsubreg(ANewReg);
  2529. if OldRegType <> getregtype(ANewReg) then
  2530. InternalError(2020011802);
  2531. if OldSubReg <> NewSubReg then
  2532. InternalError(2020011803);
  2533. case ThisOper^.typ of
  2534. top_reg:
  2535. if (
  2536. (ThisOper^.reg = AOldReg) or
  2537. (
  2538. (OldRegType = R_INTREGISTER) and
  2539. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2540. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2541. (
  2542. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2543. {$ifndef x86_64}
  2544. and (
  2545. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2546. don't have an 8-bit representation }
  2547. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2548. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2549. )
  2550. {$endif x86_64}
  2551. )
  2552. )
  2553. ) then
  2554. begin
  2555. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2556. Result := True;
  2557. end;
  2558. top_ref:
  2559. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2560. Result := True;
  2561. else
  2562. ;
  2563. end;
  2564. end;
  2565. { Replaces all references to AOldReg in an instruction to ANewReg }
  2566. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2567. const
  2568. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2569. var
  2570. OperIdx: Integer;
  2571. begin
  2572. Result := False;
  2573. for OperIdx := 0 to p.ops - 1 do
  2574. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2575. begin
  2576. { The shift and rotate instructions can only use CL }
  2577. if not (
  2578. (OperIdx = 0) and
  2579. { This second condition just helps to avoid unnecessarily
  2580. calling MatchInstruction for 10 different opcodes }
  2581. (p.oper[0]^.reg = NR_CL) and
  2582. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2583. ) then
  2584. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2585. end
  2586. else if p.oper[OperIdx]^.typ = top_ref then
  2587. { It's okay to replace registers in references that get written to }
  2588. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2589. end;
  2590. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2591. begin
  2592. Result :=
  2593. (ref^.index = NR_NO) and
  2594. (
  2595. {$ifdef x86_64}
  2596. (
  2597. (ref^.base = NR_RIP) and
  2598. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2599. ) or
  2600. {$endif x86_64}
  2601. (ref^.refaddr = addr_full) or
  2602. (ref^.base = NR_STACK_POINTER_REG) or
  2603. (ref^.base = current_procinfo.framepointer)
  2604. );
  2605. end;
  2606. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2607. var
  2608. l: asizeint;
  2609. begin
  2610. Result := False;
  2611. { Should have been checked previously }
  2612. if p.opcode <> A_LEA then
  2613. InternalError(2020072501);
  2614. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2615. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2616. not(cs_opt_size in current_settings.optimizerswitches) then
  2617. exit;
  2618. with p.oper[0]^.ref^ do
  2619. begin
  2620. if (base <> p.oper[1]^.reg) or
  2621. (index <> NR_NO) or
  2622. assigned(symbol) then
  2623. exit;
  2624. l:=offset;
  2625. if (l=1) and UseIncDec then
  2626. begin
  2627. p.opcode:=A_INC;
  2628. p.loadreg(0,p.oper[1]^.reg);
  2629. p.ops:=1;
  2630. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2631. end
  2632. else if (l=-1) and UseIncDec then
  2633. begin
  2634. p.opcode:=A_DEC;
  2635. p.loadreg(0,p.oper[1]^.reg);
  2636. p.ops:=1;
  2637. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2638. end
  2639. else
  2640. begin
  2641. if (l<0) and (l<>-2147483648) then
  2642. begin
  2643. p.opcode:=A_SUB;
  2644. p.loadConst(0,-l);
  2645. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2646. end
  2647. else
  2648. begin
  2649. p.opcode:=A_ADD;
  2650. p.loadConst(0,l);
  2651. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2652. end;
  2653. end;
  2654. end;
  2655. Result := True;
  2656. end;
  2657. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2658. var
  2659. CurrentReg, ReplaceReg: TRegister;
  2660. begin
  2661. Result := False;
  2662. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2663. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2664. case hp.opcode of
  2665. A_FSTSW, A_FNSTSW,
  2666. A_IN, A_INS, A_OUT, A_OUTS,
  2667. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2668. { These routines have explicit operands, but they are restricted in
  2669. what they can be (e.g. IN and OUT can only read from AL, AX or
  2670. EAX. }
  2671. Exit;
  2672. A_IMUL:
  2673. begin
  2674. { The 1-operand version writes to implicit registers
  2675. The 2-operand version reads from the first operator, and reads
  2676. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2677. the 3-operand version reads from a register that it doesn't write to
  2678. }
  2679. case hp.ops of
  2680. 1:
  2681. if (
  2682. (
  2683. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2684. ) or
  2685. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2686. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2687. begin
  2688. Result := True;
  2689. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2690. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2691. end;
  2692. 2:
  2693. { Only modify the first parameter }
  2694. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2695. begin
  2696. Result := True;
  2697. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2698. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2699. end;
  2700. 3:
  2701. { Only modify the second parameter }
  2702. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2703. begin
  2704. Result := True;
  2705. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2706. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2707. end;
  2708. else
  2709. InternalError(2020012901);
  2710. end;
  2711. end;
  2712. else
  2713. if (hp.ops > 0) and
  2714. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2715. begin
  2716. Result := True;
  2717. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2718. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2719. end;
  2720. end;
  2721. end;
  2722. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2723. var
  2724. hp2, hp_regalloc: tai;
  2725. p_SourceReg, p_TargetReg: TRegister;
  2726. begin
  2727. Result := False;
  2728. { Backward optimisation. If we have:
  2729. func. %reg1,%reg2
  2730. mov %reg2,%reg3
  2731. (dealloc %reg2)
  2732. Change to:
  2733. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2734. Perform similar optimisations with 1, 3 and 4-operand instructions
  2735. that only have one output.
  2736. }
  2737. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2738. begin
  2739. p_SourceReg := taicpu(p).oper[0]^.reg;
  2740. p_TargetReg := taicpu(p).oper[1]^.reg;
  2741. TransferUsedRegs(TmpUsedRegs);
  2742. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2743. GetLastInstruction(p, hp2) and
  2744. (hp2.typ = ait_instruction) and
  2745. { Have to make sure it's an instruction that only reads from
  2746. the first operands and only writes (not reads or modifies) to
  2747. the last one; in essence, a pure function such as BSR, POPCNT
  2748. or ANDN }
  2749. (
  2750. (
  2751. (taicpu(hp2).ops = 1) and
  2752. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2753. ) or
  2754. (
  2755. (taicpu(hp2).ops = 2) and
  2756. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2757. ) or
  2758. (
  2759. (taicpu(hp2).ops = 3) and
  2760. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2761. ) or
  2762. (
  2763. (taicpu(hp2).ops = 4) and
  2764. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2765. )
  2766. ) and
  2767. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2768. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2769. begin
  2770. case taicpu(hp2).opcode of
  2771. A_FSTSW, A_FNSTSW,
  2772. A_IN, A_INS, A_OUT, A_OUTS,
  2773. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2774. { These routines have explicit operands, but they are restricted in
  2775. what they can be (e.g. IN and OUT can only read from AL, AX or
  2776. EAX. }
  2777. ;
  2778. else
  2779. begin
  2780. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2781. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2782. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2783. if Assigned(hp_regalloc) then
  2784. begin
  2785. Asml.Remove(hp_regalloc);
  2786. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2787. begin
  2788. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2789. hp_regalloc.Free;
  2790. end
  2791. else
  2792. { If the register is not explicitly deallocated, it's
  2793. being reused, so move the allocation to after func. }
  2794. AsmL.InsertAfter(hp_regalloc, hp2);
  2795. end;
  2796. if not RegInInstruction(p_TargetReg, hp2) then
  2797. begin
  2798. TransferUsedRegs(TmpUsedRegs);
  2799. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2800. end;
  2801. { Actually make the changes }
  2802. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2803. RemoveCurrentp(p, hp1);
  2804. { If the Func was another MOV instruction, we might get
  2805. "mov %reg,%reg" that doesn't get removed in Pass 2
  2806. otherwise, so deal with it here (also do something
  2807. similar with lea (%reg),%reg}
  2808. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2809. begin
  2810. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2811. if p = hp2 then
  2812. RemoveCurrentp(p)
  2813. else
  2814. RemoveInstruction(hp2);
  2815. end;
  2816. Result := True;
  2817. Exit;
  2818. end;
  2819. end;
  2820. end;
  2821. end;
  2822. end;
  2823. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2824. begin
  2825. Result := False;
  2826. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2827. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2828. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2829. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2830. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2831. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2832. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2833. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2834. begin
  2835. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2836. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2837. Result := True;
  2838. Include(OptsToCheck, aoc_ForceNewIteration);
  2839. end;
  2840. end;
  2841. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2842. var
  2843. hp1, hp2, hp3, hp4, last_hp1: tai;
  2844. GetNextInstruction_p, DoOptimisation, TempBool: Boolean;
  2845. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2846. {$ifdef x86_64}
  2847. NewConst: TCGInt;
  2848. {$endif x86_64}
  2849. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2850. begin
  2851. if taicpu(hp1).opcode = signed_movop then
  2852. begin
  2853. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2854. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2855. end
  2856. else
  2857. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2858. end;
  2859. function GetNextHp1(const in_p: tai): Boolean;
  2860. begin
  2861. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2862. GetNextInstruction_p := GetNextInstructionUsingReg(in_p, hp1, p_TargetReg)
  2863. else
  2864. GetNextInstruction_p := GetNextInstruction(in_p, hp1);
  2865. Result := GetNextInstruction_p and (hp1.typ = ait_instruction);
  2866. end;
  2867. function TryConstMerge(var p1, p2: tai): Boolean;
  2868. var
  2869. ThisRef: TReference;
  2870. begin
  2871. Result := False;
  2872. ThisRef := taicpu(p2).oper[1]^.ref^;
  2873. { Only permit writes to the stack, since we can guarantee alignment with that }
  2874. if (ThisRef.index = NR_NO) and
  2875. (
  2876. (ThisRef.base = NR_STACK_POINTER_REG) or
  2877. (ThisRef.base = current_procinfo.framepointer)
  2878. ) then
  2879. begin
  2880. case taicpu(p).opsize of
  2881. S_B:
  2882. begin
  2883. { Word writes must be on a 2-byte boundary }
  2884. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2885. begin
  2886. { Reduce offset of second reference to see if it is sequential with the first }
  2887. Dec(ThisRef.offset, 1);
  2888. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2889. begin
  2890. { Make sure the constants aren't represented as a
  2891. negative number, as these won't merge properly }
  2892. taicpu(p1).opsize := S_W;
  2893. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2894. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2895. RemoveInstruction(p2);
  2896. Result := True;
  2897. end;
  2898. end;
  2899. end;
  2900. S_W:
  2901. begin
  2902. { Longword writes must be on a 4-byte boundary }
  2903. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2904. begin
  2905. { Reduce offset of second reference to see if it is sequential with the first }
  2906. Dec(ThisRef.offset, 2);
  2907. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2908. begin
  2909. { Make sure the constants aren't represented as a
  2910. negative number, as these won't merge properly }
  2911. taicpu(p1).opsize := S_L;
  2912. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2913. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2914. RemoveInstruction(p2);
  2915. Result := True;
  2916. end;
  2917. end;
  2918. end;
  2919. {$ifdef x86_64}
  2920. S_L:
  2921. begin
  2922. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2923. see if the constants can be encoded this way. }
  2924. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2925. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2926. { Quadword writes must be on an 8-byte boundary }
  2927. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2928. begin
  2929. { Reduce offset of second reference to see if it is sequential with the first }
  2930. Dec(ThisRef.offset, 4);
  2931. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2932. begin
  2933. { Make sure the constants aren't represented as a
  2934. negative number, as these won't merge properly }
  2935. taicpu(p1).opsize := S_Q;
  2936. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2937. taicpu(p1).oper[0]^.val := NewConst;
  2938. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2939. RemoveInstruction(p2);
  2940. Result := True;
  2941. end;
  2942. end;
  2943. end;
  2944. {$endif x86_64}
  2945. else
  2946. ;
  2947. end;
  2948. end;
  2949. end;
  2950. var
  2951. TempRegUsed, CrossJump: Boolean;
  2952. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2953. NewSize: topsize; NewOffset: asizeint;
  2954. SourceRef, TargetRef: TReference;
  2955. MovAligned, MovUnaligned: TAsmOp;
  2956. JumpTracking: TLinkedList;
  2957. begin
  2958. Result:=false;
  2959. { remove mov reg1,reg1? }
  2960. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2961. then
  2962. begin
  2963. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2964. { take care of the register (de)allocs following p }
  2965. RemoveCurrentP(p);
  2966. Result := True;
  2967. exit;
  2968. end;
  2969. { Prevent compiler warnings }
  2970. p_SourceReg := NR_NO;
  2971. p_TargetReg := NR_NO;
  2972. hp1 := nil;
  2973. if taicpu(p).oper[1]^.typ = top_reg then
  2974. begin
  2975. { Saves on a large number of dereferences }
  2976. p_TargetReg := taicpu(p).oper[1]^.reg;
  2977. TransferUsedRegs(TmpUsedRegs);
  2978. last_hp1 := p;
  2979. if GetNextHp1(p) then
  2980. while True do
  2981. begin
  2982. if (taicpu(hp1).opcode = A_AND) and
  2983. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2984. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[1]^.reg) then
  2985. begin
  2986. UpdateUsedRegsBetween(TmpUsedRegs, last_hp1, hp1);
  2987. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2988. (taicpu(hp1).oper[0]^.typ = top_const) and
  2989. (taicpu(p).opsize = taicpu(hp1).opsize) then
  2990. begin
  2991. case taicpu(p).opsize of
  2992. S_L:
  2993. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2994. begin
  2995. { Optimize out:
  2996. mov x, %reg
  2997. and ffffffffh, %reg
  2998. }
  2999. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3000. hp2 := tai(hp1.Previous);
  3001. RemoveInstruction(hp1);
  3002. //Include(OptsToCheck, aoc_ForceNewIteration);
  3003. if GetNextHp1(hp2) then
  3004. Continue
  3005. else
  3006. Exit;
  3007. end;
  3008. S_Q: { TODO: Confirm if this is even possible }
  3009. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3010. begin
  3011. { Optimize out:
  3012. mov x, %reg
  3013. and ffffffffffffffffh, %reg
  3014. }
  3015. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3016. hp2 := tai(hp1.Previous);
  3017. RemoveInstruction(hp1);
  3018. //Include(OptsToCheck, aoc_ForceNewIteration);
  3019. if GetNextHp1(hp2) then
  3020. Continue
  3021. else
  3022. Exit;
  3023. end;
  3024. else
  3025. ;
  3026. end;
  3027. if (
  3028. { Make sure that if a reference is used, its registers
  3029. are not modified in between }
  3030. (
  3031. (taicpu(p).oper[0]^.typ = top_reg) and
  3032. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3033. ) or
  3034. (
  3035. (taicpu(p).oper[0]^.typ = top_ref) and
  3036. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3037. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3038. )
  3039. ) and
  3040. GetNextInstruction(hp1,hp2) and
  3041. MatchInstruction(hp2,A_TEST,[]) and
  3042. (
  3043. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3044. (
  3045. { If the register being tested is smaller than the one
  3046. that received a bitwise AND, permit it if the constant
  3047. fits into the smaller size }
  3048. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3049. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3050. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3051. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3052. (
  3053. (
  3054. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3055. (taicpu(hp1).oper[0]^.val <= $FF)
  3056. ) or
  3057. (
  3058. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3059. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3060. {$ifdef x86_64}
  3061. ) or
  3062. (
  3063. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3064. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3065. {$endif x86_64}
  3066. )
  3067. )
  3068. )
  3069. ) and
  3070. (
  3071. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3072. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3073. ) and
  3074. GetNextInstruction(hp2,hp3) and
  3075. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3076. (taicpu(hp3).condition in [C_E,C_NE]) then
  3077. begin
  3078. TransferUsedRegs(TmpUsedRegs);
  3079. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3081. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3082. begin
  3083. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3084. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3085. taicpu(hp1).opcode:=A_TEST;
  3086. { Shrink the TEST instruction down to the smallest possible size }
  3087. case taicpu(hp1).oper[0]^.val of
  3088. 0..255:
  3089. if (taicpu(hp1).opsize <> S_B)
  3090. {$ifndef x86_64}
  3091. and (
  3092. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3093. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3094. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3095. )
  3096. {$endif x86_64}
  3097. then
  3098. begin
  3099. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3100. { Only print debug message if the TEST instruction
  3101. is a different size before and after }
  3102. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3103. taicpu(hp1).opsize := S_B;
  3104. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3105. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3106. end;
  3107. 256..65535:
  3108. if (taicpu(hp1).opsize <> S_W) then
  3109. begin
  3110. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3111. { Only print debug message if the TEST instruction
  3112. is a different size before and after }
  3113. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3114. taicpu(hp1).opsize := S_W;
  3115. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3116. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3117. end;
  3118. {$ifdef x86_64}
  3119. 65536..$7FFFFFFF:
  3120. if (taicpu(hp1).opsize <> S_L) then
  3121. begin
  3122. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3123. { Only print debug message if the TEST instruction
  3124. is a different size before and after }
  3125. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3126. taicpu(hp1).opsize := S_L;
  3127. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3128. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3129. end;
  3130. {$endif x86_64}
  3131. else
  3132. ;
  3133. end;
  3134. RemoveInstruction(hp2);
  3135. RemoveCurrentP(p);
  3136. Result:=true;
  3137. exit;
  3138. end;
  3139. end;
  3140. end;
  3141. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3142. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3143. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3144. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^) and
  3145. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) and
  3146. (
  3147. not (cs_opt_level3 in current_settings.optimizerswitches) or
  3148. (taicpu(hp1).oper[0]^.typ = top_const) or
  3149. not RegModifiedBetween(taicpu(hp1).oper[0]^.reg, p, hp1)
  3150. ) then
  3151. begin
  3152. { With:
  3153. mov %reg1,%reg2
  3154. ...
  3155. and %reg1,%reg2
  3156. Or:
  3157. mov $x,%reg2
  3158. ...
  3159. and $x,%reg2
  3160. Remove the 'and' instruction
  3161. }
  3162. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 4 done',hp1);
  3163. hp2 := tai(hp1.Previous);
  3164. RemoveInstruction(hp1);
  3165. //Include(OptsToCheck, aoc_ForceNewIteration);
  3166. if GetNextHp1(hp2) then
  3167. Continue
  3168. else
  3169. Exit;
  3170. end;
  3171. if IsMOVZXAcceptable and
  3172. (taicpu(p).oper[0]^.typ <> top_const) then { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3173. begin
  3174. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3175. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3176. case taicpu(p).opsize of
  3177. S_B:
  3178. if (taicpu(hp1).oper[0]^.val = $ff) then
  3179. begin
  3180. { Convert:
  3181. movb x, %regl movb x, %regl
  3182. andw ffh, %regw andl ffh, %regd
  3183. To:
  3184. movzbw x, %regd movzbl x, %regd
  3185. (Identical registers, just different sizes)
  3186. }
  3187. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3188. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3189. case taicpu(hp1).opsize of
  3190. S_W: NewSize := S_BW;
  3191. S_L: NewSize := S_BL;
  3192. {$ifdef x86_64}
  3193. S_Q: NewSize := S_BQ;
  3194. {$endif x86_64}
  3195. else
  3196. InternalError(2018011510);
  3197. end;
  3198. end
  3199. else
  3200. NewSize := S_NO;
  3201. S_W:
  3202. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3203. begin
  3204. { Convert:
  3205. movw x, %regw
  3206. andl ffffh, %regd
  3207. To:
  3208. movzwl x, %regd
  3209. (Identical registers, just different sizes)
  3210. }
  3211. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3212. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3213. case taicpu(hp1).opsize of
  3214. S_L: NewSize := S_WL;
  3215. {$ifdef x86_64}
  3216. S_Q: NewSize := S_WQ;
  3217. {$endif x86_64}
  3218. else
  3219. InternalError(2018011511);
  3220. end;
  3221. end
  3222. else
  3223. NewSize := S_NO;
  3224. else
  3225. NewSize := S_NO;
  3226. end;
  3227. if NewSize <> S_NO then
  3228. begin
  3229. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3230. { The actual optimization }
  3231. taicpu(p).opcode := A_MOVZX;
  3232. taicpu(p).changeopsize(NewSize);
  3233. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3234. { Make sure we deal with any reference counts that were increased }
  3235. if taicpu(hp1).oper[1]^.typ = top_ref then
  3236. begin
  3237. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3238. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3239. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3240. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3241. end;
  3242. { Safeguard if "and" is followed by a conditional command }
  3243. TransferUsedRegs(TmpUsedRegs);
  3244. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3245. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3246. begin
  3247. { At this point, the "and" command is effectively equivalent to
  3248. "test %reg,%reg". This will be handled separately by the
  3249. Peephole Optimizer. [Kit] }
  3250. DebugMsg(SPeepholeOptimization + PreMessage +
  3251. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3252. end
  3253. else
  3254. begin
  3255. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3256. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3257. RemoveInstruction(hp1);
  3258. end;
  3259. Result := True;
  3260. Exit;
  3261. { Go through DeepMOVOpt again (jump to "while True do") }
  3262. Continue;
  3263. end;
  3264. end;
  3265. end;
  3266. if taicpu(p).oper[0]^.typ = top_reg then
  3267. begin
  3268. p_SourceReg := taicpu(p).oper[0]^.reg;
  3269. { Look for:
  3270. mov %reg1,%reg2
  3271. ??? %reg2,r/m
  3272. Change to:
  3273. mov %reg1,%reg2
  3274. ??? %reg1,r/m
  3275. }
  3276. if RegReadByInstruction(p_TargetReg, hp1) and
  3277. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3278. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3279. begin
  3280. { A change has occurred, just not in p }
  3281. Include(OptsToCheck, aoc_ForceNewIteration);
  3282. TransferUsedRegs(TmpUsedRegs);
  3283. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3284. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3285. { Just in case something didn't get modified (e.g. an
  3286. implicit register) }
  3287. not RegReadByInstruction(p_TargetReg, hp1) then
  3288. begin
  3289. { We can remove the original MOV }
  3290. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3291. RemoveCurrentP(p);
  3292. { UsedRegs got updated by RemoveCurrentp }
  3293. Result := True;
  3294. Exit;
  3295. end;
  3296. { If we know a MOV instruction has become a null operation, we might as well
  3297. get rid of it now to save time. }
  3298. if (taicpu(hp1).opcode = A_MOV) and
  3299. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3300. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3301. { Just being a register is enough to confirm it's a null operation }
  3302. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3303. begin
  3304. Result := True;
  3305. { Speed-up to reduce a pipeline stall... if we had something like...
  3306. movl %eax,%edx
  3307. movw %dx,%ax
  3308. ... the second instruction would change to movw %ax,%ax, but
  3309. given that it is now %ax that's active rather than %eax,
  3310. penalties might occur due to a partial register write, so instead,
  3311. change it to a MOVZX instruction when optimising for speed.
  3312. }
  3313. if not (cs_opt_size in current_settings.optimizerswitches) and
  3314. IsMOVZXAcceptable and
  3315. (taicpu(hp1).opsize < taicpu(p).opsize)
  3316. {$ifdef x86_64}
  3317. { operations already implicitly set the upper 64 bits to zero }
  3318. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3319. {$endif x86_64}
  3320. then
  3321. begin
  3322. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3323. case taicpu(p).opsize of
  3324. S_W:
  3325. if taicpu(hp1).opsize = S_B then
  3326. taicpu(hp1).opsize := S_BL
  3327. else
  3328. InternalError(2020012911);
  3329. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3330. case taicpu(hp1).opsize of
  3331. S_B:
  3332. taicpu(hp1).opsize := S_BL;
  3333. S_W:
  3334. taicpu(hp1).opsize := S_WL;
  3335. else
  3336. InternalError(2020012912);
  3337. end;
  3338. else
  3339. InternalError(2020012910);
  3340. end;
  3341. taicpu(hp1).opcode := A_MOVZX;
  3342. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3343. end
  3344. else
  3345. begin
  3346. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3347. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3348. RemoveInstruction(hp1);
  3349. { The instruction after what was hp1 is now the immediate next instruction,
  3350. so we can continue to make optimisations if it's present }
  3351. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3352. Exit;
  3353. hp1 := hp2;
  3354. end;
  3355. end;
  3356. end;
  3357. {$ifdef x86_64}
  3358. { Change:
  3359. movl %reg1l,%reg2l
  3360. movq %reg2q,%reg1q
  3361. To:
  3362. movl %reg1l,%reg2l
  3363. andl %reg1l,%reg1l
  3364. }
  3365. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3366. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3367. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3368. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) and
  3369. SuperRegistersEqual(p_SourceReg, taicpu(hp1).oper[1]^.reg) then
  3370. begin
  3371. TransferUsedRegs(TmpUsedRegs);
  3372. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3373. taicpu(hp1).opsize := S_L;
  3374. taicpu(hp1).loadreg(0, p_SourceReg);
  3375. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3376. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3377. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3378. taicpu(hp1).opcode := A_AND;
  3379. { We may be able to do more and replace references
  3380. to %reg2q with %reg1q etc. }
  3381. if (cs_opt_level3 in current_settings.optimizerswitches) and
  3382. { p_TargetReg is not used between, otherwise the earlier
  3383. GetNextInstructionUsingReg would have stopped sooner }
  3384. DoZeroUpper32Opt(p,hp1) then
  3385. begin
  3386. Result := True;
  3387. Exit;
  3388. end;
  3389. end;
  3390. {
  3391. If we have the following already in the code...
  3392. movl %reg1l,%reg2l
  3393. andl %reg1l,%reg1l
  3394. ...we may be able to do more and replace references to
  3395. %reg2q with %reg1q etc. (program flow won't reach this
  3396. point if the second instruction was originally a MOV
  3397. and just got changed to AND)
  3398. }
  3399. if (cs_opt_level3 in current_settings.optimizerswitches) and
  3400. (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_AND,[S_L]) and
  3401. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3402. { p_TargetReg is not used between, otherwise the earlier
  3403. GetNextInstructionUsingReg would have stopped sooner }
  3404. MatchOperand(taicpu(hp1).oper[1]^, p_SourceReg) and
  3405. (
  3406. MatchOperand(taicpu(hp1).oper[0]^, p_SourceReg) or
  3407. MatchOperand(taicpu(hp1).oper[0]^, $ffffffff)
  3408. ) and
  3409. DoZeroUpper32Opt(p,hp1) then
  3410. begin
  3411. Result := True;
  3412. Exit;
  3413. end;
  3414. {$endif x86_64}
  3415. end
  3416. else if taicpu(p).oper[0]^.typ = top_const then
  3417. begin
  3418. if (taicpu(hp1).opcode = A_OR) and
  3419. (taicpu(p).oper[1]^.typ = top_reg) and
  3420. MatchOperand(taicpu(p).oper[0]^, 0) and
  3421. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3422. begin
  3423. { mov 0, %reg
  3424. or ###,%reg
  3425. Change to (only if the flags are not used):
  3426. mov ###,%reg
  3427. }
  3428. TransferUsedRegs(TmpUsedRegs);
  3429. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3430. DoOptimisation := True;
  3431. { Even if the flags are used, we might be able to do the optimisation
  3432. if the conditions are predictable }
  3433. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3434. begin
  3435. { Only perform if ### = %reg (the same register) or equal to 0,
  3436. so %reg is guaranteed to still have a value of zero }
  3437. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3438. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3439. begin
  3440. hp2 := hp1;
  3441. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3442. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3443. GetNextInstruction(hp2, hp3) do
  3444. begin
  3445. { Don't continue modifying if the flags state is getting changed }
  3446. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3447. Break;
  3448. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3449. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3450. begin
  3451. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3452. begin
  3453. { Condition is always true }
  3454. case taicpu(hp3).opcode of
  3455. A_Jcc:
  3456. begin
  3457. { Check for jump shortcuts before we destroy the condition }
  3458. hp4 := hp3;
  3459. DoJumpOptimizations(hp3, TempBool);
  3460. { Make sure hp3 hasn't changed }
  3461. if (hp4 = hp3) then
  3462. begin
  3463. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3464. MakeUnconditional(taicpu(hp3));
  3465. end;
  3466. Result := True;
  3467. end;
  3468. A_CMOVcc:
  3469. begin
  3470. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3471. taicpu(hp3).opcode := A_MOV;
  3472. taicpu(hp3).condition := C_None;
  3473. Result := True;
  3474. end;
  3475. A_SETcc:
  3476. begin
  3477. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3478. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3479. taicpu(hp3).opcode := A_MOV;
  3480. taicpu(hp3).ops := 2;
  3481. taicpu(hp3).condition := C_None;
  3482. taicpu(hp3).opsize := S_B;
  3483. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3484. taicpu(hp3).loadconst(0, 1);
  3485. Result := True;
  3486. end;
  3487. else
  3488. InternalError(2021090701);
  3489. end;
  3490. end
  3491. 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
  3492. begin
  3493. { Condition is always false }
  3494. case taicpu(hp3).opcode of
  3495. A_Jcc:
  3496. begin
  3497. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3498. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3499. RemoveInstruction(hp3);
  3500. Result := True;
  3501. { Since hp3 was deleted, hp2 must not be updated }
  3502. Continue;
  3503. end;
  3504. A_CMOVcc:
  3505. begin
  3506. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3507. RemoveInstruction(hp3);
  3508. Result := True;
  3509. { Since hp3 was deleted, hp2 must not be updated }
  3510. Continue;
  3511. end;
  3512. A_SETcc:
  3513. begin
  3514. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3515. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3516. taicpu(hp3).opcode := A_MOV;
  3517. taicpu(hp3).ops := 2;
  3518. taicpu(hp3).condition := C_None;
  3519. taicpu(hp3).opsize := S_B;
  3520. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3521. taicpu(hp3).loadconst(0, 0);
  3522. Result := True;
  3523. end;
  3524. else
  3525. InternalError(2021090702);
  3526. end;
  3527. end
  3528. else
  3529. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3530. DoOptimisation := False;
  3531. end;
  3532. hp2 := hp3;
  3533. end;
  3534. if DoOptimisation then
  3535. begin
  3536. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3537. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3538. { Flags are still in use - don't optimise }
  3539. DoOptimisation := False;
  3540. end;
  3541. end
  3542. else
  3543. DoOptimisation := False;
  3544. end;
  3545. if DoOptimisation then
  3546. begin
  3547. {$ifdef x86_64}
  3548. { OR only supports 32-bit sign-extended constants for 64-bit
  3549. instructions, so compensate for this if the constant is
  3550. encoded as a value greater than or equal to 2^31 }
  3551. if (taicpu(hp1).opsize = S_Q) and
  3552. (taicpu(hp1).oper[0]^.typ = top_const) and
  3553. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3554. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3555. {$endif x86_64}
  3556. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3557. taicpu(hp1).opcode := A_MOV;
  3558. RemoveCurrentP(p);
  3559. Result := True;
  3560. Exit;
  3561. end;
  3562. end;
  3563. end
  3564. else if
  3565. { oper[0] is a reference }
  3566. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3567. begin
  3568. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3569. begin
  3570. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3571. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3572. ) or
  3573. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3574. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3575. )
  3576. ) and
  3577. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3578. { mov ref,reg1
  3579. lea (reg1,reg2),reg2
  3580. to
  3581. add ref,reg2 }
  3582. begin
  3583. TransferUsedRegs(TmpUsedRegs);
  3584. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3585. { If the flags register is in use, don't change the instruction to an
  3586. ADD otherwise this will scramble the flags. [Kit] }
  3587. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3588. { reg1 may not be used afterwards }
  3589. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3590. begin
  3591. Taicpu(hp1).opcode:=A_ADD;
  3592. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3593. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3594. RemoveCurrentp(p);
  3595. result:=true;
  3596. exit;
  3597. end;
  3598. end;
  3599. { If the LEA instruction can be converted into an arithmetic instruction,
  3600. it may be possible to then fold it in the next optimisation. }
  3601. if ConvertLEA(taicpu(hp1)) then
  3602. Include(OptsToCheck, aoc_ForceNewIteration);
  3603. end;
  3604. {
  3605. mov ref,reg0
  3606. <op> reg0,reg1
  3607. dealloc reg0
  3608. to
  3609. <op> ref,reg1
  3610. }
  3611. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3612. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3613. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3614. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3615. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3616. begin
  3617. TransferUsedRegs(TmpUsedRegs);
  3618. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3619. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3620. begin
  3621. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3622. { loadref increases the reference count, so decrement it again }
  3623. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3624. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3625. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3626. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3627. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3628. { See if we can remove the allocation of reg0 }
  3629. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3630. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3631. RemoveCurrentp(p);
  3632. Result:=true;
  3633. exit;
  3634. end;
  3635. end;
  3636. end;
  3637. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3638. overwrites the original destination register. e.g.
  3639. movl ###,%reg2d
  3640. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3641. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3642. }
  3643. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3644. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3645. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3646. begin
  3647. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3648. begin
  3649. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3650. case taicpu(p).oper[0]^.typ of
  3651. top_const:
  3652. { We have something like:
  3653. movb $x, %regb
  3654. movzbl %regb,%regd
  3655. Change to:
  3656. movl $x, %regd
  3657. }
  3658. begin
  3659. case taicpu(hp1).opsize of
  3660. S_BW:
  3661. begin
  3662. convert_mov_value(A_MOVSX, $FF);
  3663. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3664. taicpu(p).opsize := S_W;
  3665. end;
  3666. S_BL:
  3667. begin
  3668. convert_mov_value(A_MOVSX, $FF);
  3669. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3670. taicpu(p).opsize := S_L;
  3671. end;
  3672. S_WL:
  3673. begin
  3674. convert_mov_value(A_MOVSX, $FFFF);
  3675. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3676. taicpu(p).opsize := S_L;
  3677. end;
  3678. {$ifdef x86_64}
  3679. S_BQ:
  3680. begin
  3681. convert_mov_value(A_MOVSX, $FF);
  3682. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3683. taicpu(p).opsize := S_Q;
  3684. end;
  3685. S_WQ:
  3686. begin
  3687. convert_mov_value(A_MOVSX, $FFFF);
  3688. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3689. taicpu(p).opsize := S_Q;
  3690. end;
  3691. S_LQ:
  3692. begin
  3693. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3694. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3695. taicpu(p).opsize := S_Q;
  3696. end;
  3697. {$endif x86_64}
  3698. else
  3699. { If hp1 was a MOV instruction, it should have been
  3700. optimised already }
  3701. InternalError(2020021001);
  3702. end;
  3703. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3704. RemoveInstruction(hp1);
  3705. Result := True;
  3706. Exit;
  3707. end;
  3708. top_ref:
  3709. begin
  3710. { We have something like:
  3711. movb mem, %regb
  3712. movzbl %regb,%regd
  3713. Change to:
  3714. movzbl mem, %regd
  3715. }
  3716. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3717. begin
  3718. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3719. taicpu(p).opcode := taicpu(hp1).opcode;
  3720. taicpu(p).opsize := taicpu(hp1).opsize;
  3721. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3722. RemoveInstruction(hp1);
  3723. Result := True;
  3724. Exit;
  3725. end;
  3726. end;
  3727. else
  3728. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3729. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3730. Exit;
  3731. end;
  3732. end
  3733. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3734. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3735. optimised }
  3736. else
  3737. begin
  3738. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3739. RemoveCurrentP(p);
  3740. Result := True;
  3741. Exit;
  3742. end;
  3743. end;
  3744. if (taicpu(hp1).opcode = A_MOV) and
  3745. (
  3746. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3747. {$ifdef x86_64}
  3748. or (
  3749. { Permit zero extension from 32- to 64-bit when writing
  3750. a constant (it will be checked to see if it fits into
  3751. a signed 32-bit integer) }
  3752. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3753. (
  3754. { Valid situations... writing an unsigned 32-bit
  3755. immediate, or the destination is a 64-bit register }
  3756. (taicpu(p).oper[0]^.typ = top_const) or
  3757. (taicpu(hp1).oper[1]^.typ = top_reg)
  3758. ) and
  3759. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3760. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3761. )
  3762. {$endif x86_64}
  3763. ) then
  3764. begin
  3765. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3766. TransferUsedRegs(TmpUsedRegs);
  3767. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3768. { we have
  3769. mov x, %treg
  3770. mov %treg, y
  3771. }
  3772. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3773. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3774. begin
  3775. { we've got
  3776. mov x, %treg
  3777. mov %treg, y
  3778. with %treg is not used after }
  3779. case taicpu(p).oper[0]^.typ Of
  3780. { top_reg is covered by DeepMOVOpt }
  3781. top_const:
  3782. begin
  3783. { change
  3784. mov const, %treg
  3785. mov %treg, y
  3786. to
  3787. mov const, y
  3788. }
  3789. {$ifdef x86_64}
  3790. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3791. (
  3792. { For 32-to-64-bit zero-extension, the immediate
  3793. must be between 0 and 2^31 - 1}
  3794. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3795. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3796. ) or
  3797. (
  3798. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3799. (
  3800. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3801. )
  3802. ) then
  3803. {$endif x86_64}
  3804. begin
  3805. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3806. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3807. RemoveCurrentP(p);
  3808. Result := True;
  3809. Exit;
  3810. end;
  3811. end;
  3812. top_ref:
  3813. case taicpu(hp1).oper[1]^.typ of
  3814. top_reg:
  3815. { change
  3816. mov mem, %treg
  3817. mov %treg, %reg
  3818. to
  3819. mov mem, %reg"
  3820. }
  3821. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3822. begin
  3823. {$ifdef x86_64}
  3824. { If zero extending from 32-bit to 64-bit,
  3825. we have to make sure the replaced
  3826. register is the right size }
  3827. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3828. {$else}
  3829. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3830. {$endif x86_64}
  3831. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3832. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3833. RemoveInstruction(hp1);
  3834. Result := True;
  3835. Exit;
  3836. end
  3837. else if
  3838. { Make sure that if a reference is used, its
  3839. registers are not modified in between }
  3840. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3841. begin
  3842. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3843. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3844. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3845. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3846. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3847. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3848. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3849. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3850. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3851. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3852. RemoveCurrentP(p);
  3853. Result := True;
  3854. Exit;
  3855. end;
  3856. top_ref:
  3857. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3858. begin
  3859. {$ifdef x86_64}
  3860. { Look for the following to simplify:
  3861. mov x(mem1), %reg
  3862. mov %reg, y(mem2)
  3863. mov x+8(mem1), %reg
  3864. mov %reg, y+8(mem2)
  3865. Change to:
  3866. movdqu x(mem1), %xmmreg
  3867. movdqu %xmmreg, y(mem2)
  3868. ...but only as long as the memory blocks don't overlap
  3869. }
  3870. SourceRef := taicpu(p).oper[0]^.ref^;
  3871. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3872. if (taicpu(p).opsize = S_Q) and
  3873. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3874. GetNextInstruction(hp1, hp2) and
  3875. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3876. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3877. begin
  3878. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3879. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3880. Inc(SourceRef.offset, 8);
  3881. if UseAVX then
  3882. begin
  3883. MovAligned := A_VMOVDQA;
  3884. MovUnaligned := A_VMOVDQU;
  3885. end
  3886. else
  3887. begin
  3888. MovAligned := A_MOVDQA;
  3889. MovUnaligned := A_MOVDQU;
  3890. end;
  3891. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3892. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3893. begin
  3894. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3895. Inc(TargetRef.offset, 8);
  3896. if GetNextInstruction(hp2, hp3) and
  3897. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3898. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3899. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3900. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3901. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3902. begin
  3903. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3904. if NewMMReg <> NR_NO then
  3905. begin
  3906. { Remember that the offsets are 8 ahead }
  3907. if ((SourceRef.offset mod 16) = 8) and
  3908. (
  3909. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3910. (SourceRef.base = current_procinfo.framepointer) or
  3911. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3912. ) then
  3913. taicpu(p).opcode := MovAligned
  3914. else
  3915. taicpu(p).opcode := MovUnaligned;
  3916. taicpu(p).opsize := S_XMM;
  3917. taicpu(p).oper[1]^.reg := NewMMReg;
  3918. if ((TargetRef.offset mod 16) = 8) and
  3919. (
  3920. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3921. (TargetRef.base = current_procinfo.framepointer) or
  3922. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3923. ) then
  3924. taicpu(hp1).opcode := MovAligned
  3925. else
  3926. taicpu(hp1).opcode := MovUnaligned;
  3927. taicpu(hp1).opsize := S_XMM;
  3928. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3929. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3930. RemoveInstruction(hp2);
  3931. RemoveInstruction(hp3);
  3932. Result := True;
  3933. Exit;
  3934. end;
  3935. end;
  3936. end
  3937. else
  3938. begin
  3939. { See if the next references are 8 less rather than 8 greater }
  3940. Dec(SourceRef.offset, 16); { -8 the other way }
  3941. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3942. begin
  3943. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3944. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3945. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3946. GetNextInstruction(hp2, hp3) and
  3947. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3948. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3949. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3950. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3951. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3952. begin
  3953. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3954. if NewMMReg <> NR_NO then
  3955. begin
  3956. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3957. if ((SourceRef.offset mod 16) = 0) and
  3958. (
  3959. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3960. (SourceRef.base = current_procinfo.framepointer) or
  3961. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3962. ) then
  3963. taicpu(hp2).opcode := MovAligned
  3964. else
  3965. taicpu(hp2).opcode := MovUnaligned;
  3966. taicpu(hp2).opsize := S_XMM;
  3967. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3968. if ((TargetRef.offset mod 16) = 0) and
  3969. (
  3970. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3971. (TargetRef.base = current_procinfo.framepointer) or
  3972. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3973. ) then
  3974. taicpu(hp3).opcode := MovAligned
  3975. else
  3976. taicpu(hp3).opcode := MovUnaligned;
  3977. taicpu(hp3).opsize := S_XMM;
  3978. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3979. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3980. RemoveInstruction(hp1);
  3981. RemoveCurrentP(p);
  3982. Result := True;
  3983. Exit;
  3984. end;
  3985. end;
  3986. end;
  3987. end;
  3988. end;
  3989. {$endif x86_64}
  3990. end;
  3991. else
  3992. { The write target should be a reg or a ref }
  3993. InternalError(2021091601);
  3994. end;
  3995. else
  3996. ;
  3997. end;
  3998. end
  3999. else if (taicpu(p).oper[0]^.typ = top_const) and
  4000. { %treg is used afterwards, but all eventualities other
  4001. than the first MOV instruction being a constant are
  4002. covered by DeepMOVOpt, so only check for that }
  4003. (
  4004. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  4005. not (cs_opt_size in current_settings.optimizerswitches) or
  4006. (taicpu(hp1).opsize = S_B)
  4007. ) and
  4008. (
  4009. (taicpu(hp1).oper[1]^.typ=top_reg) or
  4010. (
  4011. { For 32-to-64-bit zero-extension, the immediate
  4012. must be between 0 and 2^31 - 1}
  4013. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  4014. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  4015. ) or
  4016. (
  4017. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  4018. (
  4019. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  4020. )
  4021. )
  4022. ) then
  4023. begin
  4024. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  4025. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  4026. Include(OptsToCheck, aoc_ForceNewIteration);
  4027. end;
  4028. end;
  4029. Break;
  4030. end;
  4031. end;
  4032. if taicpu(p).oper[0]^.typ = top_reg then
  4033. begin
  4034. { oper[1] is a reference }
  4035. { Saves on a large number of dereferences }
  4036. p_SourceReg := taicpu(p).oper[0]^.reg;
  4037. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  4038. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  4039. else
  4040. GetNextInstruction_p := GetNextInstruction(p, hp1);
  4041. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  4042. begin
  4043. if taicpu(p).oper[1]^.typ = top_reg then
  4044. begin
  4045. p_TargetReg := taicpu(p).oper[1]^.reg;
  4046. { Change:
  4047. movl %reg1,%reg2
  4048. ...
  4049. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  4050. ...
  4051. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  4052. To:
  4053. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  4054. ...
  4055. movl x(%reg1),%reg1
  4056. ...
  4057. movl %reg1,%regX
  4058. }
  4059. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4060. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4061. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4062. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4063. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4064. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4065. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4066. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4067. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4068. begin
  4069. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4070. if RegInRef(p_TargetReg, SourceRef) and
  4071. { If %reg1 also appears in the second reference, then it will
  4072. not refer to the same memory block as the first reference }
  4073. not RegInRef(p_SourceReg, SourceRef) then
  4074. begin
  4075. { Check to see if the references match if %reg2 is changed to %reg1 }
  4076. if SourceRef.base = p_TargetReg then
  4077. SourceRef.base := p_SourceReg;
  4078. if SourceRef.index = p_TargetReg then
  4079. SourceRef.index := p_SourceReg;
  4080. { RefsEqual also checks to ensure both references are non-volatile }
  4081. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4082. begin
  4083. taicpu(hp2).loadreg(0, p_SourceReg);
  4084. TransferUsedRegs(TmpUsedRegs);
  4085. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4086. { Make sure the register is allocated between these instructions
  4087. even though it doesn't change value, since it may cause
  4088. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4089. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4090. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4091. Result := True;
  4092. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4093. begin
  4094. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4095. RemoveCurrentP(p);
  4096. Exit;
  4097. end
  4098. else
  4099. begin
  4100. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4101. begin
  4102. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4103. RemoveCurrentP(p);
  4104. Exit;
  4105. end;
  4106. end;
  4107. { If we reach this point, p and hp1 weren't actually modified,
  4108. so we can do a bit more work on this pass }
  4109. end;
  4110. end;
  4111. end;
  4112. end;
  4113. end;
  4114. end;
  4115. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4116. { All the next optimisations require a next instruction }
  4117. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4118. Exit;
  4119. { Change:
  4120. movl/q (ref), %reg
  4121. movd/q %reg, %xmm0
  4122. (dealloc %reg)
  4123. To:
  4124. movd/q (ref), %xmm0
  4125. }
  4126. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4127. MatchInstruction(hp1,[A_MOVD,A_VMOVD{$ifdef x86_64},A_MOVQ,A_VMOVQ{$endif x86_64}],[]) and
  4128. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  4129. (taicpu(hp1).oper[1]^.typ=top_reg) and
  4130. (GetRegType(taicpu(hp1).oper[1]^.reg)=R_MMREGISTER) then
  4131. begin
  4132. TransferUsedRegs(TmpUsedRegs);
  4133. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4134. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  4135. begin
  4136. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  4137. { loadref increases the reference count, so decrement it again }
  4138. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  4139. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  4140. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  4141. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  4142. DebugMsg(SPeepholeOptimization+'Merged MOV and (V)MOVD/(V)MOVQ to eliminate intermediate register (MovMovD/Q2MovD/Q)',p);
  4143. RemoveCurrentP(p,hp1);
  4144. Result:=True;
  4145. Exit;
  4146. end;
  4147. end;
  4148. { Next instruction is also a MOV ? }
  4149. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4150. begin
  4151. if MatchOpType(taicpu(p), top_const, top_ref) and
  4152. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4153. TryConstMerge(p, hp1) then
  4154. begin
  4155. Result := True;
  4156. { In case we have four byte writes in a row, check for 2 more
  4157. right now so we don't have to wait for another iteration of
  4158. pass 1
  4159. }
  4160. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4161. case taicpu(p).opsize of
  4162. S_W:
  4163. begin
  4164. if GetNextInstruction(p, hp1) and
  4165. MatchInstruction(hp1, A_MOV, [S_B]) and
  4166. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4167. GetNextInstruction(hp1, hp2) and
  4168. MatchInstruction(hp2, A_MOV, [S_B]) and
  4169. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4170. { Try to merge the two bytes }
  4171. TryConstMerge(hp1, hp2) then
  4172. { Now try to merge the two words (hp2 will get deleted) }
  4173. TryConstMerge(p, hp1);
  4174. end;
  4175. S_L:
  4176. begin
  4177. { Though this only really benefits x86_64 and not i386, it
  4178. gets a potential optimisation done faster and hence
  4179. reduces the number of times OptPass1MOV is entered }
  4180. if GetNextInstruction(p, hp1) and
  4181. MatchInstruction(hp1, A_MOV, [S_W]) and
  4182. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4183. GetNextInstruction(hp1, hp2) and
  4184. MatchInstruction(hp2, A_MOV, [S_W]) and
  4185. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4186. { Try to merge the two words }
  4187. TryConstMerge(hp1, hp2) then
  4188. { This will always fail on i386, so don't bother
  4189. calling it unless we're doing x86_64 }
  4190. {$ifdef x86_64}
  4191. { Now try to merge the two longwords (hp2 will get deleted) }
  4192. TryConstMerge(p, hp1)
  4193. {$endif x86_64}
  4194. ;
  4195. end;
  4196. else
  4197. ;
  4198. end;
  4199. Exit;
  4200. end;
  4201. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4202. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4203. { mov reg1, mem1 or mov mem1, reg1
  4204. mov mem2, reg2 mov reg2, mem2}
  4205. begin
  4206. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4207. { mov reg1, mem1 or mov mem1, reg1
  4208. mov mem2, reg1 mov reg2, mem1}
  4209. begin
  4210. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4211. { Removes the second statement from
  4212. mov reg1, mem1/reg2
  4213. mov mem1/reg2, reg1 }
  4214. begin
  4215. if taicpu(p).oper[0]^.typ=top_reg then
  4216. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4217. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4218. RemoveInstruction(hp1);
  4219. Result:=true;
  4220. if (taicpu(p).oper[1]^.typ = top_reg) then
  4221. begin
  4222. TransferUsedRegs(TmpUsedRegs);
  4223. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, p, TmpUsedRegs) then
  4224. begin
  4225. { reg2 is no longer in use }
  4226. DebugMsg(SPeepholeOptimization + 'Mov2Nop 6 done',p);
  4227. RemoveCurrentP(p);
  4228. end;
  4229. end;
  4230. exit;
  4231. end
  4232. else
  4233. begin
  4234. TransferUsedRegs(TmpUsedRegs);
  4235. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4236. if (taicpu(p).oper[1]^.typ = top_ref) and
  4237. { mov reg1, mem1
  4238. mov mem2, reg1 }
  4239. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4240. GetNextInstruction(hp1, hp2) and
  4241. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4242. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4243. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4244. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4245. { change to
  4246. mov reg1, mem1 mov reg1, mem1
  4247. mov mem2, reg1 cmp reg1, mem2
  4248. cmp mem1, reg1
  4249. }
  4250. begin
  4251. RemoveInstruction(hp2);
  4252. taicpu(hp1).opcode := A_CMP;
  4253. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4254. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4255. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4256. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4257. end;
  4258. end;
  4259. end
  4260. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4261. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4262. begin
  4263. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4264. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4265. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4266. end
  4267. else
  4268. begin
  4269. TransferUsedRegs(TmpUsedRegs);
  4270. if GetNextInstruction(hp1, hp2) and
  4271. MatchOpType(taicpu(p),top_ref,top_reg) and
  4272. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4273. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4274. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4275. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4276. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4277. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4278. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4279. { mov mem1, %reg1
  4280. mov %reg1, mem2
  4281. mov mem2, reg2
  4282. to:
  4283. mov mem1, reg2
  4284. mov reg2, mem2}
  4285. begin
  4286. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4287. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4288. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4289. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4290. RemoveInstruction(hp2);
  4291. Result := True;
  4292. end
  4293. {$ifdef i386}
  4294. { this is enabled for i386 only, as the rules to create the reg sets below
  4295. are too complicated for x86-64, so this makes this code too error prone
  4296. on x86-64
  4297. }
  4298. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4299. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4300. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4301. { mov mem1, reg1 mov mem1, reg1
  4302. mov reg1, mem2 mov reg1, mem2
  4303. mov mem2, reg2 mov mem2, reg1
  4304. to: to:
  4305. mov mem1, reg1 mov mem1, reg1
  4306. mov mem1, reg2 mov reg1, mem2
  4307. mov reg1, mem2
  4308. or (if mem1 depends on reg1
  4309. and/or if mem2 depends on reg2)
  4310. to:
  4311. mov mem1, reg1
  4312. mov reg1, mem2
  4313. mov reg1, reg2
  4314. }
  4315. begin
  4316. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4317. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4318. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4319. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4320. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4321. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4322. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4323. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4324. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4325. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4326. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4327. end
  4328. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4329. begin
  4330. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4331. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4332. end
  4333. else
  4334. begin
  4335. RemoveInstruction(hp2);
  4336. end
  4337. {$endif i386}
  4338. ;
  4339. end;
  4340. end
  4341. { movl [mem1],reg1
  4342. movl [mem1],reg2
  4343. to
  4344. movl [mem1],reg1
  4345. movl reg1,reg2
  4346. }
  4347. else if not CheckMovMov2MovMov2(p, hp1) and
  4348. { movl const1,[mem1]
  4349. movl [mem1],reg1
  4350. to
  4351. movl const1,reg1
  4352. movl reg1,[mem1]
  4353. }
  4354. MatchOpType(Taicpu(p),top_const,top_ref) and
  4355. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4356. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4357. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4358. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4359. begin
  4360. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4361. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4362. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4363. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4364. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4365. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4366. Result:=true;
  4367. exit;
  4368. end;
  4369. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4370. end;
  4371. { search further than the next instruction for a mov (as long as it's not a jump) }
  4372. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4373. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4374. (taicpu(p).oper[1]^.typ = top_reg) and
  4375. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4376. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4377. begin
  4378. { we work with hp2 here, so hp1 can be still used later on when
  4379. checking for GetNextInstruction_p }
  4380. hp3 := hp1;
  4381. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4382. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4383. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4384. TransferUsedRegs(TmpUsedRegs);
  4385. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4386. if NotFirstIteration then
  4387. JumpTracking := TLinkedList.Create
  4388. else
  4389. JumpTracking := nil;
  4390. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4391. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4392. (hp2.typ=ait_instruction) do
  4393. begin
  4394. case taicpu(hp2).opcode of
  4395. A_POP:
  4396. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4397. begin
  4398. if not CrossJump and
  4399. not RegUsedBetween(p_TargetReg, p, hp2) then
  4400. begin
  4401. { We can remove the original MOV since the register
  4402. wasn't used between it and its popping from the stack }
  4403. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4404. RemoveCurrentp(p, hp1);
  4405. Result := True;
  4406. JumpTracking.Free;
  4407. Exit;
  4408. end;
  4409. { Can't go any further }
  4410. Break;
  4411. end;
  4412. A_MOV:
  4413. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4414. ((taicpu(p).oper[0]^.typ=top_const) or
  4415. ((taicpu(p).oper[0]^.typ=top_reg) and
  4416. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4417. )
  4418. ) then
  4419. begin
  4420. { we have
  4421. mov x, %treg
  4422. mov %treg, y
  4423. }
  4424. { We don't need to call UpdateUsedRegs for every instruction between
  4425. p and hp2 because the register we're concerned about will not
  4426. become deallocated (otherwise GetNextInstructionUsingReg would
  4427. have stopped at an earlier instruction). [Kit] }
  4428. TempRegUsed :=
  4429. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4430. RegReadByInstruction(p_TargetReg, hp3) or
  4431. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4432. case taicpu(p).oper[0]^.typ Of
  4433. top_reg:
  4434. begin
  4435. { change
  4436. mov %reg, %treg
  4437. mov %treg, y
  4438. to
  4439. mov %reg, y
  4440. }
  4441. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4442. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4443. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4444. begin
  4445. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4446. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4447. if TempRegUsed then
  4448. begin
  4449. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4450. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4451. { Set the start of the next GetNextInstructionUsingRegCond search
  4452. to start at the entry right before hp2 (which is about to be removed) }
  4453. hp3 := tai(hp2.Previous);
  4454. RemoveInstruction(hp2);
  4455. Include(OptsToCheck, aoc_ForceNewIteration);
  4456. { See if there's more we can optimise }
  4457. Continue;
  4458. end
  4459. else
  4460. begin
  4461. RemoveInstruction(hp2);
  4462. { We can remove the original MOV too }
  4463. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4464. RemoveCurrentP(p, hp1);
  4465. Result:=true;
  4466. JumpTracking.Free;
  4467. Exit;
  4468. end;
  4469. end
  4470. else
  4471. begin
  4472. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4473. taicpu(hp2).loadReg(0, p_SourceReg);
  4474. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4475. { Check to see if the register also appears in the reference }
  4476. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4477. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4478. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4479. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4480. begin
  4481. { Don't remove the first instruction if the temporary register is in use }
  4482. if not TempRegUsed then
  4483. begin
  4484. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4485. RemoveCurrentP(p, hp1);
  4486. Result:=true;
  4487. JumpTracking.Free;
  4488. Exit;
  4489. end;
  4490. { No need to set Result to True here. If there's another instruction later
  4491. on that can be optimised, it will be detected when the main Pass 1 loop
  4492. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4493. hp3 := hp2;
  4494. Continue;
  4495. end;
  4496. end;
  4497. end;
  4498. top_const:
  4499. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4500. begin
  4501. { change
  4502. mov const, %treg
  4503. mov %treg, y
  4504. to
  4505. mov const, y
  4506. }
  4507. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4508. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4509. begin
  4510. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4511. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4512. if TempRegUsed then
  4513. begin
  4514. { Don't remove the first instruction if the temporary register is in use }
  4515. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4516. { No need to set Result to True. If there's another instruction later on
  4517. that can be optimised, it will be detected when the main Pass 1 loop
  4518. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4519. end
  4520. else
  4521. begin
  4522. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4523. RemoveCurrentP(p, hp1);
  4524. Result:=true;
  4525. Exit;
  4526. end;
  4527. end;
  4528. end;
  4529. else
  4530. Internalerror(2019103001);
  4531. end;
  4532. end
  4533. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4534. begin
  4535. if not CrossJump and
  4536. not RegUsedBetween(p_TargetReg, p, hp2) and
  4537. not RegReadByInstruction(p_TargetReg, hp2) then
  4538. begin
  4539. { Register is not used before it is overwritten }
  4540. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4541. RemoveCurrentp(p, hp1);
  4542. Result := True;
  4543. Exit;
  4544. end;
  4545. if (taicpu(p).oper[0]^.typ = top_const) and
  4546. (taicpu(hp2).oper[0]^.typ = top_const) then
  4547. begin
  4548. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4549. begin
  4550. { Same value - register hasn't changed }
  4551. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4552. RemoveInstruction(hp2);
  4553. Include(OptsToCheck, aoc_ForceNewIteration);
  4554. { See if there's more we can optimise }
  4555. Continue;
  4556. end;
  4557. end;
  4558. {$ifdef x86_64}
  4559. end
  4560. { Change:
  4561. movl %reg1l,%reg2l
  4562. ...
  4563. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4564. To:
  4565. movl %reg1l,%reg2l
  4566. ...
  4567. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4568. If %reg1 = %reg3, convert to:
  4569. movl %reg1l,%reg2l
  4570. ...
  4571. andl %reg1l,%reg1l
  4572. }
  4573. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4574. (taicpu(p).oper[0]^.typ = top_reg) and
  4575. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4576. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4577. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4578. begin
  4579. TempRegUsed :=
  4580. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4581. RegReadByInstruction(p_TargetReg, hp3) or
  4582. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4583. taicpu(hp2).opsize := S_L;
  4584. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4585. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4586. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4587. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4588. begin
  4589. { %reg1 = %reg3 }
  4590. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4591. taicpu(hp2).opcode := A_AND;
  4592. end
  4593. else
  4594. begin
  4595. { %reg1 <> %reg3 }
  4596. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4597. end;
  4598. if not TempRegUsed then
  4599. begin
  4600. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4601. RemoveCurrentP(p, hp1);
  4602. Result := True;
  4603. Exit;
  4604. end
  4605. else
  4606. begin
  4607. { Initial instruction wasn't actually changed }
  4608. Include(OptsToCheck, aoc_ForceNewIteration);
  4609. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4610. appears below since %reg1 has technically changed }
  4611. if taicpu(hp2).opcode = A_AND then
  4612. Break;
  4613. end;
  4614. {$endif x86_64}
  4615. end
  4616. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4617. GetNextInstruction(hp2, hp4) and
  4618. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4619. { Optimise the following first:
  4620. movl [mem1],reg1
  4621. movl [mem1],reg2
  4622. to
  4623. movl [mem1],reg1
  4624. movl reg1,reg2
  4625. If [mem1] contains the target register and reg1 is the
  4626. the source register, this optimisation will get missed
  4627. and produce less efficient code later on.
  4628. }
  4629. if CheckMovMov2MovMov2(hp2, hp4) then
  4630. { Initial instruction wasn't actually changed }
  4631. Include(OptsToCheck, aoc_ForceNewIteration);
  4632. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4633. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4634. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4635. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4636. begin
  4637. {
  4638. Change from:
  4639. mov ###, %reg
  4640. ...
  4641. movs/z %reg,%reg (Same register, just different sizes)
  4642. To:
  4643. movs/z ###, %reg (Longer version)
  4644. ...
  4645. (remove)
  4646. }
  4647. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4648. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4649. { Keep the first instruction as mov if ### is a constant }
  4650. if taicpu(p).oper[0]^.typ = top_const then
  4651. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4652. else
  4653. begin
  4654. taicpu(p).opcode := taicpu(hp2).opcode;
  4655. taicpu(p).opsize := taicpu(hp2).opsize;
  4656. end;
  4657. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4658. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4659. RemoveInstruction(hp2);
  4660. Result := True;
  4661. JumpTracking.Free;
  4662. Exit;
  4663. end;
  4664. else
  4665. { Move down to the if-block below };
  4666. end;
  4667. { Also catches MOV/S/Z instructions that aren't modified }
  4668. if taicpu(p).oper[0]^.typ = top_reg then
  4669. begin
  4670. p_SourceReg := taicpu(p).oper[0]^.reg;
  4671. if
  4672. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4673. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4674. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4675. begin
  4676. Result := True;
  4677. { Just in case something didn't get modified (e.g. an
  4678. implicit register). Also, if it does read from this
  4679. register, then there's no longer an advantage to
  4680. changing the register on subsequent instructions.}
  4681. if not RegReadByInstruction(p_TargetReg, hp2) then
  4682. begin
  4683. { If a conditional jump was crossed, do not delete
  4684. the original MOV no matter what }
  4685. if not CrossJump and
  4686. { RegEndOfLife returns True if the register is
  4687. deallocated before the next instruction or has
  4688. been loaded with a new value }
  4689. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4690. begin
  4691. { We can remove the original MOV }
  4692. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4693. RemoveCurrentp(p, hp1);
  4694. JumpTracking.Free;
  4695. Result := True;
  4696. Exit;
  4697. end;
  4698. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4699. begin
  4700. { See if there's more we can optimise }
  4701. hp3 := hp2;
  4702. Continue;
  4703. end;
  4704. end;
  4705. end;
  4706. end;
  4707. { Break out of the while loop under normal circumstances }
  4708. Break;
  4709. end;
  4710. JumpTracking.Free;
  4711. end;
  4712. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4713. (taicpu(p).oper[1]^.typ = top_reg) and
  4714. (taicpu(p).opsize = S_L) and
  4715. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4716. (hp2.typ = ait_instruction) and
  4717. (taicpu(hp2).opcode = A_AND) and
  4718. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4719. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4720. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4721. ) then
  4722. begin
  4723. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4724. begin
  4725. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4726. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4727. begin
  4728. { Optimize out:
  4729. mov x, %reg
  4730. and ffffffffh, %reg
  4731. }
  4732. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4733. RemoveInstruction(hp2);
  4734. Result:=true;
  4735. exit;
  4736. end;
  4737. end;
  4738. end;
  4739. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4740. x >= RetOffset) as it doesn't do anything (it writes either to a
  4741. parameter or to the temporary storage room for the function
  4742. result)
  4743. }
  4744. if IsExitCode(hp1) and
  4745. (taicpu(p).oper[1]^.typ = top_ref) and
  4746. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4747. (
  4748. (
  4749. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4750. not (
  4751. assigned(current_procinfo.procdef.funcretsym) and
  4752. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4753. )
  4754. ) or
  4755. { Also discard writes to the stack that are below the base pointer,
  4756. as this is temporary storage rather than a function result on the
  4757. stack, say. }
  4758. (
  4759. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4760. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4761. )
  4762. ) then
  4763. begin
  4764. RemoveCurrentp(p, hp1);
  4765. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4766. RemoveLastDeallocForFuncRes(p);
  4767. Result:=true;
  4768. exit;
  4769. end;
  4770. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4771. begin
  4772. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4773. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4774. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4775. begin
  4776. { change
  4777. mov reg1, mem1
  4778. test/cmp x, mem1
  4779. to
  4780. mov reg1, mem1
  4781. test/cmp x, reg1
  4782. }
  4783. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4784. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4785. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4786. Result := True;
  4787. Exit;
  4788. end;
  4789. if DoMovCmpMemOpt(p, hp1) then
  4790. begin
  4791. Result := True;
  4792. Exit;
  4793. end;
  4794. end;
  4795. if (taicpu(p).oper[1]^.typ = top_reg) and
  4796. (hp1.typ = ait_instruction) and
  4797. GetNextInstruction(hp1, hp2) and
  4798. MatchInstruction(hp2,A_MOV,[]) and
  4799. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4800. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4801. (
  4802. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4803. {$ifdef x86_64}
  4804. or
  4805. (
  4806. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4807. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4808. )
  4809. {$endif x86_64}
  4810. ) then
  4811. begin
  4812. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4813. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4814. { change movsX/movzX reg/ref, reg2
  4815. add/sub/or/... reg3/$const, reg2
  4816. mov reg2 reg/ref
  4817. dealloc reg2
  4818. to
  4819. add/sub/or/... reg3/$const, reg/ref }
  4820. begin
  4821. TransferUsedRegs(TmpUsedRegs);
  4822. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4823. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4824. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4825. begin
  4826. { by example:
  4827. movswl %si,%eax movswl %si,%eax p
  4828. decl %eax addl %edx,%eax hp1
  4829. movw %ax,%si movw %ax,%si hp2
  4830. ->
  4831. movswl %si,%eax movswl %si,%eax p
  4832. decw %eax addw %edx,%eax hp1
  4833. movw %ax,%si movw %ax,%si hp2
  4834. }
  4835. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4836. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4837. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4838. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4839. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4840. {
  4841. ->
  4842. movswl %si,%eax movswl %si,%eax p
  4843. decw %si addw %dx,%si hp1
  4844. movw %ax,%si movw %ax,%si hp2
  4845. }
  4846. case taicpu(hp1).ops of
  4847. 1:
  4848. begin
  4849. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4850. if taicpu(hp1).oper[0]^.typ=top_reg then
  4851. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4852. end;
  4853. 2:
  4854. begin
  4855. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4856. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4857. (taicpu(hp1).opcode<>A_SHL) and
  4858. (taicpu(hp1).opcode<>A_SHR) and
  4859. (taicpu(hp1).opcode<>A_SAR) then
  4860. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4861. end;
  4862. else
  4863. internalerror(2008042701);
  4864. end;
  4865. {
  4866. ->
  4867. decw %si addw %dx,%si p
  4868. }
  4869. RemoveInstruction(hp2);
  4870. RemoveCurrentP(p, hp1);
  4871. Result:=True;
  4872. Exit;
  4873. end;
  4874. end;
  4875. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4876. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4877. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4878. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4879. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4880. ) and
  4881. { if ref contains a symbol, we cannot change its size to a smaller size }
  4882. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4883. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4884. )
  4885. {$ifdef i386}
  4886. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4887. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4888. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4889. {$endif i386}
  4890. then
  4891. { change movsX/movzX reg/ref, reg2
  4892. add/sub/or/... regX/$const, reg2
  4893. mov reg2, reg3
  4894. dealloc reg2
  4895. to
  4896. movsX/movzX reg/ref, reg3
  4897. add/sub/or/... reg3/$const, reg3
  4898. }
  4899. begin
  4900. TransferUsedRegs(TmpUsedRegs);
  4901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4904. begin
  4905. { by example:
  4906. movswl %si,%eax movswl %si,%eax p
  4907. decl %eax addl %edx,%eax hp1
  4908. movw %ax,%si movw %ax,%si hp2
  4909. ->
  4910. movswl %si,%eax movswl %si,%eax p
  4911. decw %eax addw %edx,%eax hp1
  4912. movw %ax,%si movw %ax,%si hp2
  4913. }
  4914. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4915. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4916. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4917. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4918. { limit size of constants as well to avoid assembler errors, but
  4919. check opsize to avoid overflow when left shifting the 1 }
  4920. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4921. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4922. {$ifdef x86_64}
  4923. { Be careful of, for example:
  4924. movl %reg1,%reg2
  4925. addl %reg3,%reg2
  4926. movq %reg2,%reg4
  4927. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4928. }
  4929. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4930. begin
  4931. taicpu(hp2).changeopsize(S_L);
  4932. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4933. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4934. end;
  4935. {$endif x86_64}
  4936. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4937. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4938. if taicpu(p).oper[0]^.typ=top_reg then
  4939. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4940. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4941. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4942. {
  4943. ->
  4944. movswl %si,%eax movswl %si,%eax p
  4945. decw %si addw %dx,%si hp1
  4946. movw %ax,%si movw %ax,%si hp2
  4947. }
  4948. case taicpu(hp1).ops of
  4949. 1:
  4950. begin
  4951. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4952. if taicpu(hp1).oper[0]^.typ=top_reg then
  4953. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4954. end;
  4955. 2:
  4956. begin
  4957. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4958. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4959. (taicpu(hp1).opcode<>A_SHL) and
  4960. (taicpu(hp1).opcode<>A_SHR) and
  4961. (taicpu(hp1).opcode<>A_SAR) then
  4962. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4963. end;
  4964. else
  4965. internalerror(2018111801);
  4966. end;
  4967. {
  4968. ->
  4969. decw %si addw %dx,%si p
  4970. }
  4971. RemoveInstruction(hp2);
  4972. end;
  4973. end;
  4974. end;
  4975. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4976. GetNextInstruction(hp1, hp2) and
  4977. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4978. MatchOperand(Taicpu(p).oper[0]^,0) and
  4979. (Taicpu(p).oper[1]^.typ = top_reg) and
  4980. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4981. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4982. { mov reg1,0
  4983. bts reg1,operand1 --> mov reg1,operand2
  4984. or reg1,operand2 bts reg1,operand1}
  4985. begin
  4986. Taicpu(hp2).opcode:=A_MOV;
  4987. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4988. asml.remove(hp1);
  4989. insertllitem(hp2,hp2.next,hp1);
  4990. RemoveCurrentp(p, hp1);
  4991. Result:=true;
  4992. exit;
  4993. end;
  4994. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4995. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4996. GetNextInstruction(hp1, hp2) and
  4997. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4998. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4999. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  5000. { change
  5001. mov reg1,reg2
  5002. sub reg3,reg2
  5003. cmp reg3,reg1
  5004. into
  5005. mov reg1,reg2
  5006. sub reg3,reg2
  5007. }
  5008. begin
  5009. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  5010. RemoveInstruction(hp2);
  5011. Result:=true;
  5012. exit;
  5013. end;
  5014. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  5015. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  5016. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5017. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5018. begin
  5019. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  5020. {$ifdef x86_64}
  5021. { Convert:
  5022. movq x(ref),%reg64
  5023. shrq y,%reg64
  5024. To:
  5025. movl x+4(ref),%reg32
  5026. shrl y-32,%reg32 (Remove if y = 32)
  5027. }
  5028. if (taicpu(p).opsize = S_Q) and
  5029. (taicpu(hp1).opcode = A_SHR) and
  5030. (taicpu(hp1).oper[0]^.val >= 32) then
  5031. begin
  5032. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5033. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  5034. { Convert to 32-bit }
  5035. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5036. taicpu(p).opsize := S_L;
  5037. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  5038. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  5039. if (taicpu(hp1).oper[0]^.val = 32) then
  5040. begin
  5041. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  5042. RemoveInstruction(hp1);
  5043. end
  5044. else
  5045. begin
  5046. { This will potentially open up more arithmetic operations since
  5047. the peephole optimizer now has a big hint that only the lower
  5048. 32 bits are currently in use (and opcodes are smaller in size) }
  5049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  5050. taicpu(hp1).opsize := S_L;
  5051. Dec(taicpu(hp1).oper[0]^.val, 32);
  5052. DebugMsg(SPeepholeOptimization + PreMessage +
  5053. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  5054. end;
  5055. Result := True;
  5056. Exit;
  5057. end;
  5058. {$endif x86_64}
  5059. { Convert:
  5060. movl x(ref),%reg
  5061. shrl $24,%reg
  5062. To:
  5063. movzbl x+3(ref),%reg
  5064. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  5065. Also accept sar instead of shr, but convert to movsx instead of movzx
  5066. }
  5067. if taicpu(hp1).opcode = A_SHR then
  5068. MovUnaligned := A_MOVZX
  5069. else
  5070. MovUnaligned := A_MOVSX;
  5071. NewSize := S_NO;
  5072. NewOffset := 0;
  5073. case taicpu(p).opsize of
  5074. S_B:
  5075. { No valid combinations };
  5076. S_W:
  5077. if (taicpu(hp1).oper[0]^.val = 8) then
  5078. begin
  5079. NewSize := S_BW;
  5080. NewOffset := 1;
  5081. end;
  5082. S_L:
  5083. case taicpu(hp1).oper[0]^.val of
  5084. 16:
  5085. begin
  5086. NewSize := S_WL;
  5087. NewOffset := 2;
  5088. end;
  5089. 24:
  5090. begin
  5091. NewSize := S_BL;
  5092. NewOffset := 3;
  5093. end;
  5094. else
  5095. ;
  5096. end;
  5097. {$ifdef x86_64}
  5098. S_Q:
  5099. case taicpu(hp1).oper[0]^.val of
  5100. 32:
  5101. begin
  5102. if taicpu(hp1).opcode = A_SAR then
  5103. begin
  5104. { 32-bit to 64-bit is a distinct instruction }
  5105. MovUnaligned := A_MOVSXD;
  5106. NewSize := S_LQ;
  5107. NewOffset := 4;
  5108. end
  5109. else
  5110. { Should have been handled by MovShr2Mov above }
  5111. InternalError(2022081811);
  5112. end;
  5113. 48:
  5114. begin
  5115. NewSize := S_WQ;
  5116. NewOffset := 6;
  5117. end;
  5118. 56:
  5119. begin
  5120. NewSize := S_BQ;
  5121. NewOffset := 7;
  5122. end;
  5123. else
  5124. ;
  5125. end;
  5126. {$endif x86_64}
  5127. else
  5128. InternalError(2022081810);
  5129. end;
  5130. if (NewSize <> S_NO) and
  5131. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5132. begin
  5133. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5134. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5135. debug_op2str(MovUnaligned);
  5136. {$ifdef x86_64}
  5137. if MovUnaligned <> A_MOVSXD then
  5138. { Don't add size suffix for MOVSXD }
  5139. {$endif x86_64}
  5140. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5141. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5142. taicpu(p).opcode := MovUnaligned;
  5143. taicpu(p).opsize := NewSize;
  5144. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5145. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5146. RemoveInstruction(hp1);
  5147. Result := True;
  5148. Exit;
  5149. end;
  5150. end;
  5151. { Backward optimisation shared with OptPass2MOV }
  5152. if FuncMov2Func(p, hp1) then
  5153. begin
  5154. Result := True;
  5155. Exit;
  5156. end;
  5157. end;
  5158. function TX86AsmOptimizer.OptPass1MOVD(var p : tai) : boolean;
  5159. { This function also handles the 64-bit version, MOVQ }
  5160. var
  5161. hp1: tai;
  5162. begin
  5163. Result:=false;
  5164. { Change:
  5165. movd/q %xmm0, %reg
  5166. ...
  5167. movl/q %reg, (ref)
  5168. (dealloc %reg)
  5169. To:
  5170. movd/q %xmm0, (ref)
  5171. }
  5172. if MatchOpType(taicpu(p),top_reg,top_reg) and
  5173. (GetRegType(taicpu(p).oper[0]^.reg)=R_MMREGISTER) and
  5174. (GetRegType(taicpu(p).oper[1]^.reg)=R_INTREGISTER) and
  5175. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  5176. MatchInstruction(hp1, A_MOV, []) and
  5177. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  5178. (taicpu(hp1).oper[1]^.typ=top_ref) and
  5179. not RegInRef(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.ref^) then
  5180. begin
  5181. TransferUsedRegs(TmpUsedRegs);
  5182. UpdateUsedRegsBetween(TmpUsedRegs,p,hp1);
  5183. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  5184. begin
  5185. if (
  5186. { Instructions are always adjacent under -O2 and under }
  5187. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5188. (
  5189. (
  5190. (taicpu(hp1).oper[1]^.ref^.base=NR_NO) or
  5191. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.base,p,hp1)
  5192. ) and
  5193. (
  5194. (taicpu(hp1).oper[1]^.ref^.index=NR_NO) or
  5195. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.index,p,hp1)
  5196. )
  5197. )
  5198. ) then
  5199. begin
  5200. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1a)',p);
  5201. taicpu(p).loadref(1,taicpu(hp1).oper[1]^.ref^);
  5202. { loadref increases the reference count, so decrement it again }
  5203. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5204. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5205. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5206. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5207. RemoveInstruction(hp1);
  5208. Include(OptsToCheck, aoc_ForceNewIteration);
  5209. end
  5210. else if not RegModifiedBetween(taicpu(p).oper[0]^.reg,p,hp1) then
  5211. begin
  5212. { Still possible to optimise if hp1 is converted instead }
  5213. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1b)',hp1);
  5214. { Decrement the reference prior to replacing it }
  5215. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5216. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5217. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5218. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5219. taicpu(hp1).opcode:=taicpu(p).opcode;
  5220. taicpu(hp1).opsize:=taicpu(p).opsize;
  5221. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  5222. TransferUsedRegs(TmpUsedRegs);
  5223. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,TmpUsedRegs);
  5224. RemoveCurrentP(p);
  5225. Result:=True;
  5226. Exit;
  5227. end;
  5228. end;
  5229. end;
  5230. end;
  5231. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5232. var
  5233. hp1 : tai;
  5234. begin
  5235. Result:=false;
  5236. if taicpu(p).ops <> 2 then
  5237. exit;
  5238. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5239. GetNextInstruction(p,hp1) then
  5240. begin
  5241. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5242. (taicpu(hp1).ops = 2) then
  5243. begin
  5244. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5245. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5246. { movXX reg1, mem1 or movXX mem1, reg1
  5247. movXX mem2, reg2 movXX reg2, mem2}
  5248. begin
  5249. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5250. { movXX reg1, mem1 or movXX mem1, reg1
  5251. movXX mem2, reg1 movXX reg2, mem1}
  5252. begin
  5253. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5254. begin
  5255. { Removes the second statement from
  5256. movXX reg1, mem1/reg2
  5257. movXX mem1/reg2, reg1
  5258. }
  5259. if taicpu(p).oper[0]^.typ=top_reg then
  5260. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5261. { Removes the second statement from
  5262. movXX mem1/reg1, reg2
  5263. movXX reg2, mem1/reg1
  5264. }
  5265. if (taicpu(p).oper[1]^.typ=top_reg) and
  5266. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5267. begin
  5268. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5269. RemoveInstruction(hp1);
  5270. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5271. Result:=true;
  5272. exit;
  5273. end
  5274. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5275. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5276. begin
  5277. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5278. RemoveInstruction(hp1);
  5279. Result:=true;
  5280. exit;
  5281. end;
  5282. end
  5283. end;
  5284. end;
  5285. end;
  5286. end;
  5287. end;
  5288. {$ifndef i8086}
  5289. function TX86AsmOptimizer.OptPass1NOT(var p: tai): Boolean;
  5290. var
  5291. hp1, p_next: tai;
  5292. flags_used: Boolean;
  5293. procedure Do_NotAnd2Andn1;
  5294. var
  5295. tempoper: poper;
  5296. begin
  5297. { Change "and %reg1,%reg2" to "andn %reg2,%reg1,%reg2" }
  5298. taicpu(hp1).allocate_oper(3);
  5299. taicpu(hp1).ops:=3;
  5300. { Swap the 1st and 2nd operands by swapping their pointers }
  5301. tempoper:=taicpu(hp1).oper[1];
  5302. taicpu(hp1).oper[1]:=taicpu(hp1).oper[0];
  5303. taicpu(hp1).oper[0]:=tempoper;
  5304. taicpu(hp1).loadreg(2, tempoper^.reg);
  5305. taicpu(hp1).opcode:=A_ANDN;
  5306. end;
  5307. begin
  5308. Result:=False;
  5309. { Don't optimise this for size as ANDN is bigger than NOT and AND combined }
  5310. if not (cs_opt_size in current_settings.optimizerswitches) and
  5311. (CPUX86_HAS_BMI2 in cpu_capabilities[current_settings.optimizecputype]) then
  5312. begin
  5313. { Convert: To:
  5314. not %reg1 andn %reg2,%reg1,%reg2
  5315. and %reg1,%reg2 not %reg1
  5316. Or remove "not %reg1" completely if %reg1 is deallocated.
  5317. This breaks the dependency chain.
  5318. }
  5319. if (taicpu(p).oper[0]^.typ=top_reg) and
  5320. { ANDN only supports 32-bit and 64-bit }
  5321. (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5322. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) and
  5323. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5324. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[0]^.reg) and
  5325. (taicpu(hp1).oper[1]^.typ=top_reg) and
  5326. (taicpu(hp1).oper[1]^.reg<>taicpu(p).oper[0]^.reg) and
  5327. (
  5328. { p and hp1 are adjacent on -O2 and below }
  5329. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5330. not RegModifiedBetween(taicpu(hp1).oper[1]^.reg,p,hp1)
  5331. ) then
  5332. begin
  5333. p_next:=tai(p.Next);
  5334. TransferUsedRegs(TmpUsedRegs);
  5335. UpdateUsedRegsBetween(TmpUsedRegs, p_next, hp1);
  5336. { Make a note as to whether the flags are in use because
  5337. RegUsedAfterInstruction might change the state }
  5338. flags_used:=RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs);
  5339. if not RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  5340. begin
  5341. DebugMsg(SPeepholeOptimization + 'NotAnd2Andn 1 done', p);
  5342. Do_NotAnd2Andn1;
  5343. RemoveCurrentP(p, p_next);
  5344. Result:=True;
  5345. Exit;
  5346. end
  5347. else if not flags_used then
  5348. begin
  5349. DebugMsg(SPeepholeOptimization + 'NotAnd2AndnNot 1 done', p);
  5350. Do_NotAnd2Andn1;
  5351. asml.Remove(p);
  5352. asml.InsertAfter(p, hp1);
  5353. AllocRegBetween(taicpu(p).oper[0]^.reg, hp1, p, TmpUsedRegs);
  5354. { Make sure the pass 2 iteration continues from the
  5355. correct place, right after p }
  5356. p:=p_next;
  5357. Result:=True;
  5358. Exit;
  5359. end;
  5360. end;
  5361. end;
  5362. end;
  5363. {$endif not i8086}
  5364. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5365. var
  5366. hp1 : tai;
  5367. begin
  5368. result:=false;
  5369. { replace
  5370. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5371. MovX %mreg2,%mreg1
  5372. dealloc %mreg2
  5373. by
  5374. <Op>X %mreg2,%mreg1
  5375. ?
  5376. }
  5377. if GetNextInstruction(p,hp1) and
  5378. { we mix single and double opperations here because we assume that the compiler
  5379. generates vmovapd only after double operations and vmovaps only after single operations }
  5380. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5381. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5382. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5383. (taicpu(p).oper[0]^.typ=top_reg) then
  5384. begin
  5385. TransferUsedRegs(TmpUsedRegs);
  5386. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5387. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5388. begin
  5389. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5390. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5391. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5392. RemoveInstruction(hp1);
  5393. result:=true;
  5394. end;
  5395. end;
  5396. end;
  5397. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5398. var
  5399. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5400. JumpLabel, JumpLabel_dist: TAsmLabel;
  5401. FirstValue, SecondValue: TCGInt;
  5402. function OptimizeJump(var InputP: tai): Boolean;
  5403. var
  5404. TempBool: Boolean;
  5405. begin
  5406. Result := False;
  5407. TempBool := True;
  5408. if DoJumpOptimizations(InputP, TempBool) or
  5409. not TempBool then
  5410. begin
  5411. Result := True;
  5412. if Assigned(InputP) then
  5413. begin
  5414. { CollapseZeroDistJump will be set to the label or an align
  5415. before it after the jump if it optimises, whether or not
  5416. the label is live or dead }
  5417. if (InputP.typ = ait_align) or
  5418. (
  5419. (InputP.typ = ait_label) and
  5420. not (tai_label(InputP).labsym.is_used)
  5421. ) then
  5422. GetNextInstruction(InputP, InputP);
  5423. end;
  5424. Exit;
  5425. end;
  5426. end;
  5427. begin
  5428. Result := False;
  5429. if (taicpu(p).oper[0]^.typ = top_const) and
  5430. (taicpu(p).oper[0]^.val <> -1) then
  5431. begin
  5432. { Convert unsigned maximum constants to -1 to aid optimisation }
  5433. case taicpu(p).opsize of
  5434. S_B:
  5435. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5436. begin
  5437. taicpu(p).oper[0]^.val := -1;
  5438. Result := True;
  5439. Exit;
  5440. end;
  5441. S_W:
  5442. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5443. begin
  5444. taicpu(p).oper[0]^.val := -1;
  5445. Result := True;
  5446. Exit;
  5447. end;
  5448. S_L:
  5449. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5450. begin
  5451. taicpu(p).oper[0]^.val := -1;
  5452. Result := True;
  5453. Exit;
  5454. end;
  5455. {$ifdef x86_64}
  5456. S_Q:
  5457. { Storing anything greater than $7FFFFFFF is not possible so do
  5458. nothing };
  5459. {$endif x86_64}
  5460. else
  5461. InternalError(2021121001);
  5462. end;
  5463. end;
  5464. if GetNextInstruction(p, hp1) and
  5465. TrySwapMovCmp(p, hp1) then
  5466. begin
  5467. Result := True;
  5468. Exit;
  5469. end;
  5470. p_label := nil;
  5471. JumpLabel := nil;
  5472. if MatchInstruction(hp1, A_Jcc, []) then
  5473. begin
  5474. if OptimizeJump(hp1) then
  5475. begin
  5476. Result := True;
  5477. if Assigned(hp1) then
  5478. begin
  5479. { CollapseZeroDistJump will be set to the label or an align
  5480. before it after the jump if it optimises, whether or not
  5481. the label is live or dead }
  5482. if (hp1.typ = ait_align) or
  5483. (
  5484. (hp1.typ = ait_label) and
  5485. not (tai_label(hp1).labsym.is_used)
  5486. ) then
  5487. GetNextInstruction(hp1, hp1);
  5488. end;
  5489. TransferUsedRegs(TmpUsedRegs);
  5490. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5491. if not Assigned(hp1) or
  5492. (
  5493. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5494. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5495. ) then
  5496. begin
  5497. { No more conditional jumps; conditional statement is no longer required }
  5498. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5499. RemoveCurrentP(p);
  5500. end;
  5501. Exit;
  5502. end;
  5503. if IsJumpToLabel(taicpu(hp1)) then
  5504. begin
  5505. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5506. if Assigned(JumpLabel) then
  5507. p_label := getlabelwithsym(JumpLabel);
  5508. end;
  5509. end;
  5510. { Search for:
  5511. test $x,(reg/ref)
  5512. jne @lbl1
  5513. test $y,(reg/ref) (same register or reference)
  5514. jne @lbl1
  5515. Change to:
  5516. test $(x or y),(reg/ref)
  5517. jne @lbl1
  5518. (Note, this doesn't work with je instead of jne)
  5519. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5520. Also search for:
  5521. test $x,(reg/ref)
  5522. je @lbl1
  5523. ...
  5524. test $y,(reg/ref)
  5525. je/jne @lbl2
  5526. If (x or y) = x, then the second jump is deterministic
  5527. }
  5528. if (
  5529. (
  5530. (taicpu(p).oper[0]^.typ = top_const) or
  5531. (
  5532. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5533. (taicpu(p).oper[0]^.typ = top_reg) and
  5534. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5535. )
  5536. ) and
  5537. MatchInstruction(hp1, A_JCC, [])
  5538. ) then
  5539. begin
  5540. if (taicpu(p).oper[0]^.typ = top_reg) and
  5541. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5542. FirstValue := -1
  5543. else
  5544. FirstValue := taicpu(p).oper[0]^.val;
  5545. { If we have several test/jne's in a row, it might be the case that
  5546. the second label doesn't go to the same location, but the one
  5547. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5548. so accommodate for this with a while loop.
  5549. }
  5550. hp1_last := hp1;
  5551. while (
  5552. (
  5553. (taicpu(p).oper[1]^.typ = top_reg) and
  5554. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5555. ) or GetNextInstruction(hp1_last, p_dist)
  5556. ) and (p_dist.typ = ait_instruction) do
  5557. begin
  5558. if (
  5559. (
  5560. (taicpu(p_dist).opcode = A_TEST) and
  5561. (
  5562. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5563. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5564. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5565. )
  5566. ) or
  5567. (
  5568. { cmp 0,%reg = test %reg,%reg }
  5569. (taicpu(p_dist).opcode = A_CMP) and
  5570. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5571. )
  5572. ) and
  5573. { Make sure the destination operands are actually the same }
  5574. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5575. GetNextInstruction(p_dist, hp1_dist) and
  5576. MatchInstruction(hp1_dist, A_JCC, []) then
  5577. begin
  5578. if OptimizeJump(hp1_dist) then
  5579. begin
  5580. Result := True;
  5581. Exit;
  5582. end;
  5583. if
  5584. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5585. (
  5586. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5587. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5588. ) then
  5589. SecondValue := -1
  5590. else
  5591. SecondValue := taicpu(p_dist).oper[0]^.val;
  5592. { If both of the TEST constants are identical, delete the
  5593. second TEST that is unnecessary (be careful though, just
  5594. in case the flags are modified in between) }
  5595. if (FirstValue = SecondValue) then
  5596. begin
  5597. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5598. begin
  5599. { Since the second jump's condition is a subset of the first, we
  5600. know it will never branch because the first jump dominates it.
  5601. Get it out of the way now rather than wait for the jump
  5602. optimisations for a speed boost. }
  5603. if IsJumpToLabel(taicpu(hp1_dist)) then
  5604. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5605. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5606. RemoveInstruction(hp1_dist);
  5607. Result := True;
  5608. end
  5609. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5610. begin
  5611. { If the inverse of the first condition is a subset of the second,
  5612. the second one will definitely branch if the first one doesn't }
  5613. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5614. { We can remove the TEST instruction too }
  5615. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5616. RemoveInstruction(p_dist);
  5617. MakeUnconditional(taicpu(hp1_dist));
  5618. RemoveDeadCodeAfterJump(hp1_dist);
  5619. { Since the jump is now unconditional, we can't
  5620. continue any further with this particular
  5621. optimisation. The original TEST is still intact
  5622. though, so there might be something else we can
  5623. do }
  5624. Include(OptsToCheck, aoc_ForceNewIteration);
  5625. Break;
  5626. end;
  5627. if Result or
  5628. { If a jump wasn't removed or made unconditional, only
  5629. remove the identical TEST instruction if the flags
  5630. weren't modified }
  5631. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5632. begin
  5633. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5634. RemoveInstruction(p_dist);
  5635. { If the jump was removed or made unconditional, we
  5636. don't need to allocate NR_DEFAULTFLAGS over the
  5637. entire range }
  5638. if not Result then
  5639. begin
  5640. { Mark the flags as 'in use' over the entire range }
  5641. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5642. { Speed gain - continue search from the Jcc instruction }
  5643. hp1_last := hp1_dist;
  5644. { Only the TEST instruction was removed, and the
  5645. original was unchanged, so we can safely do
  5646. another iteration of the while loop }
  5647. Include(OptsToCheck, aoc_ForceNewIteration);
  5648. Continue;
  5649. end;
  5650. Exit;
  5651. end;
  5652. end;
  5653. hp1_last := nil;
  5654. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5655. (
  5656. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5657. { Always adjacent under -O2 and under }
  5658. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5659. (
  5660. GetNextInstruction(hp1, hp1_last) and
  5661. (hp1_last = p_dist)
  5662. )
  5663. ) and
  5664. (
  5665. (
  5666. { Test the following variant:
  5667. test $x,(reg/ref)
  5668. jne @lbl1
  5669. test $y,(reg/ref)
  5670. je @lbl2
  5671. @lbl1:
  5672. Becomes:
  5673. test $(x or y),(reg/ref)
  5674. je @lbl2
  5675. @lbl1: (may become a dead label)
  5676. }
  5677. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5678. GetNextInstruction(hp1_dist, hp1_last) and
  5679. (hp1_last = p_label)
  5680. ) or
  5681. (
  5682. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5683. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5684. then the second jump will never branch, so it can also be
  5685. removed regardless of where it goes }
  5686. (
  5687. (FirstValue = -1) or
  5688. (SecondValue = -1) or
  5689. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5690. )
  5691. )
  5692. ) then
  5693. begin
  5694. { Same jump location... can be a register since nothing's changed }
  5695. { If any of the entries are equivalent to test %reg,%reg, then the
  5696. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5697. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5698. if (hp1_last = p_label) then
  5699. begin
  5700. { Variant }
  5701. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5702. RemoveInstruction(p_dist);
  5703. if Assigned(JumpLabel) then
  5704. JumpLabel.decrefs;
  5705. RemoveInstruction(hp1);
  5706. end
  5707. else
  5708. begin
  5709. { Only remove the second test if no jumps or other conditional instructions follow }
  5710. TransferUsedRegs(TmpUsedRegs);
  5711. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5712. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5713. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5714. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5715. begin
  5716. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5717. RemoveInstruction(p_dist);
  5718. { Remove the first jump, not the second, to keep
  5719. any register deallocations between the second
  5720. TEST/JNE pair in the same place. Aids future
  5721. optimisation. }
  5722. if Assigned(JumpLabel) then
  5723. JumpLabel.decrefs;
  5724. RemoveInstruction(hp1);
  5725. end
  5726. else
  5727. begin
  5728. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5729. if IsJumpToLabel(taicpu(hp1_dist)) then
  5730. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5731. { Remove second jump in this instance }
  5732. RemoveInstruction(hp1_dist);
  5733. end;
  5734. end;
  5735. Result := True;
  5736. Exit;
  5737. end;
  5738. end;
  5739. if { If -O2 and under, it may stop on any old instruction }
  5740. (cs_opt_level3 in current_settings.optimizerswitches) and
  5741. (taicpu(p).oper[1]^.typ = top_reg) and
  5742. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5743. begin
  5744. hp1_last := p_dist;
  5745. Continue;
  5746. end;
  5747. Break;
  5748. end;
  5749. end;
  5750. { Search for:
  5751. test %reg,%reg
  5752. j(c1) @lbl1
  5753. ...
  5754. @lbl:
  5755. test %reg,%reg (same register)
  5756. j(c2) @lbl2
  5757. If c2 is a subset of c1, change to:
  5758. test %reg,%reg
  5759. j(c1) @lbl2
  5760. (@lbl1 may become a dead label as a result)
  5761. }
  5762. if (taicpu(p).oper[1]^.typ = top_reg) and
  5763. (taicpu(p).oper[0]^.typ = top_reg) and
  5764. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5765. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5766. Assigned(p_label) and
  5767. GetNextInstruction(p_label, p_dist) and
  5768. MatchInstruction(p_dist, A_TEST, []) and
  5769. { It's fine if the second test uses smaller sub-registers }
  5770. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5771. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5772. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5773. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5774. GetNextInstruction(p_dist, hp1_dist) and
  5775. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5776. begin
  5777. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5778. if JumpLabel = JumpLabel_dist then
  5779. { This is an infinite loop }
  5780. Exit;
  5781. { Best optimisation when the first condition is a subset (or equal) of the second }
  5782. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5783. begin
  5784. { Any registers used here will already be allocated }
  5785. if Assigned(JumpLabel) then
  5786. JumpLabel.DecRefs;
  5787. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5788. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5789. Result := True;
  5790. Exit;
  5791. end;
  5792. end;
  5793. end;
  5794. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5795. var
  5796. hp1, hp2: tai;
  5797. ActiveReg: TRegister;
  5798. OldOffset: asizeint;
  5799. ThisConst: TCGInt;
  5800. function RegDeallocated: Boolean;
  5801. begin
  5802. TransferUsedRegs(TmpUsedRegs);
  5803. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5804. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5805. end;
  5806. begin
  5807. result:=false;
  5808. hp1 := nil;
  5809. { replace
  5810. addX const,%reg1
  5811. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5812. dealloc %reg1
  5813. by
  5814. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5815. }
  5816. if MatchOpType(taicpu(p),top_const,top_reg) then
  5817. begin
  5818. ActiveReg := taicpu(p).oper[1]^.reg;
  5819. { Ensures the entire register was updated }
  5820. if (taicpu(p).opsize >= S_L) and
  5821. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5822. MatchInstruction(hp1,A_LEA,[]) and
  5823. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5824. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5825. (
  5826. { Cover the case where the register in the reference is also the destination register }
  5827. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5828. (
  5829. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5830. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5831. RegDeallocated
  5832. )
  5833. ) then
  5834. begin
  5835. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5836. {$push}
  5837. {$R-}{$Q-}
  5838. { Explicitly disable overflow checking for these offset calculation
  5839. as those do not matter for the final result }
  5840. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5841. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5842. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5843. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5844. {$pop}
  5845. {$ifdef x86_64}
  5846. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5847. begin
  5848. { Overflow; abort }
  5849. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5850. end
  5851. else
  5852. {$endif x86_64}
  5853. begin
  5854. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5855. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5856. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5857. RemoveCurrentP(p, hp1)
  5858. else
  5859. RemoveCurrentP(p);
  5860. result:=true;
  5861. Exit;
  5862. end;
  5863. end;
  5864. if (
  5865. { Save calling GetNextInstructionUsingReg again }
  5866. Assigned(hp1) or
  5867. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5868. ) and
  5869. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5870. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5871. begin
  5872. { Make sure the flags aren't in use by the second operation }
  5873. TransferUsedRegs(TmpUsedRegs);
  5874. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5875. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5876. begin
  5877. if taicpu(hp1).oper[0]^.typ = top_const then
  5878. begin
  5879. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5880. if taicpu(hp1).opcode = A_ADD then
  5881. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5882. else
  5883. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5884. Result := True;
  5885. { Handle any overflows }
  5886. case taicpu(p).opsize of
  5887. S_B:
  5888. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5889. S_W:
  5890. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5891. S_L:
  5892. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5893. {$ifdef x86_64}
  5894. S_Q:
  5895. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5896. { Overflow; abort }
  5897. Result := False
  5898. else
  5899. taicpu(p).oper[0]^.val := ThisConst;
  5900. {$endif x86_64}
  5901. else
  5902. InternalError(2021102610);
  5903. end;
  5904. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5905. if Result then
  5906. begin
  5907. if (taicpu(p).oper[0]^.val < 0) and
  5908. (
  5909. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5910. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5911. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5912. ) then
  5913. begin
  5914. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5915. taicpu(p).opcode := A_SUB;
  5916. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5917. end
  5918. else
  5919. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5920. RemoveInstruction(hp1);
  5921. end;
  5922. end
  5923. else
  5924. begin
  5925. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5926. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5927. Asml.Remove(p);
  5928. Asml.InsertAfter(p, hp1);
  5929. p := hp1;
  5930. Result := True;
  5931. Exit;
  5932. end;
  5933. end;
  5934. end;
  5935. if DoArithCombineOpt(p) then
  5936. Result:=true;
  5937. end;
  5938. end;
  5939. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5940. var
  5941. hp1, hp2: tai;
  5942. ref: Integer;
  5943. saveref: treference;
  5944. offsetcalc: Int64;
  5945. TempReg: TRegister;
  5946. Multiple: TCGInt;
  5947. Adjacent, IntermediateRegDiscarded: Boolean;
  5948. begin
  5949. Result:=false;
  5950. { play save and throw an error if LEA uses a seg register prefix,
  5951. this is most likely an error somewhere else }
  5952. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5953. internalerror(2022022001);
  5954. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5955. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5956. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5957. (
  5958. { do not mess with leas accessing the stack pointer
  5959. unless it's a null operation }
  5960. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5961. (
  5962. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5963. (taicpu(p).oper[0]^.ref^.offset = 0)
  5964. )
  5965. ) and
  5966. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5967. begin
  5968. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5969. begin
  5970. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5971. begin
  5972. taicpu(p).opcode := A_MOV;
  5973. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5974. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5975. end
  5976. else
  5977. begin
  5978. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5979. RemoveCurrentP(p);
  5980. end;
  5981. Result:=true;
  5982. exit;
  5983. end
  5984. else if (
  5985. { continue to use lea to adjust the stack pointer,
  5986. it is the recommended way, but only if not optimizing for size }
  5987. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5988. (cs_opt_size in current_settings.optimizerswitches)
  5989. ) and
  5990. { If the flags register is in use, don't change the instruction
  5991. to an ADD otherwise this will scramble the flags. [Kit] }
  5992. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5993. ConvertLEA(taicpu(p)) then
  5994. begin
  5995. Result:=true;
  5996. exit;
  5997. end;
  5998. end;
  5999. { Don't optimise if the stack or frame pointer is the destination register }
  6000. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  6001. Exit;
  6002. if GetNextInstruction(p,hp1) and
  6003. (hp1.typ=ait_instruction) then
  6004. begin
  6005. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6006. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6007. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  6008. begin
  6009. TransferUsedRegs(TmpUsedRegs);
  6010. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6011. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6012. begin
  6013. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6014. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  6015. RemoveInstruction(hp1);
  6016. result:=true;
  6017. exit;
  6018. end;
  6019. end;
  6020. { changes
  6021. lea <ref1>, reg1
  6022. <op> ...,<ref. with reg1>,...
  6023. to
  6024. <op> ...,<ref1>,... }
  6025. { find a reference which uses reg1 }
  6026. 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
  6027. ref:=0
  6028. 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
  6029. ref:=1
  6030. else
  6031. ref:=-1;
  6032. if (ref<>-1) and
  6033. { reg1 must be either the base or the index }
  6034. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  6035. begin
  6036. { reg1 can be removed from the reference }
  6037. saveref:=taicpu(hp1).oper[ref]^.ref^;
  6038. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  6039. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  6040. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  6041. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  6042. else
  6043. Internalerror(2019111201);
  6044. { check if the can insert all data of the lea into the second instruction }
  6045. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  6046. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  6047. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  6048. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  6049. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  6050. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  6051. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  6052. {$ifdef x86_64}
  6053. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  6054. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  6055. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  6056. )
  6057. {$endif x86_64}
  6058. then
  6059. begin
  6060. { reg1 might not used by the second instruction after it is remove from the reference }
  6061. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  6062. begin
  6063. TransferUsedRegs(TmpUsedRegs);
  6064. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6065. { reg1 is not updated so it might not be used afterwards }
  6066. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6067. begin
  6068. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  6069. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  6070. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6071. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6072. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6073. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  6074. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  6075. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  6076. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  6077. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  6078. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  6079. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6080. RemoveCurrentP(p, hp1);
  6081. result:=true;
  6082. exit;
  6083. end
  6084. end;
  6085. end;
  6086. { recover }
  6087. taicpu(hp1).oper[ref]^.ref^:=saveref;
  6088. end;
  6089. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  6090. if Adjacent or
  6091. { Check further ahead (up to 2 instructions ahead for -O2) }
  6092. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  6093. begin
  6094. { Check common LEA/LEA conditions }
  6095. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  6096. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  6097. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  6098. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  6099. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  6100. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  6101. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  6102. (
  6103. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  6104. calling it (since it calls GetNextInstruction) }
  6105. Adjacent or
  6106. (
  6107. (
  6108. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  6109. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  6110. ) and (
  6111. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  6112. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6113. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  6114. )
  6115. )
  6116. ) then
  6117. begin
  6118. TransferUsedRegs(TmpUsedRegs);
  6119. hp2 := p;
  6120. repeat
  6121. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6122. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  6123. IntermediateRegDiscarded :=
  6124. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  6125. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  6126. { changes
  6127. lea offset1(regX,scale), reg1
  6128. lea offset2(reg1,reg1), reg2
  6129. to
  6130. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  6131. and
  6132. lea offset1(regX,scale1), reg1
  6133. lea offset2(reg1,scale2), reg2
  6134. to
  6135. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  6136. and
  6137. lea offset1(regX,scale1), reg1
  6138. lea offset2(reg3,reg1,scale2), reg2
  6139. to
  6140. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  6141. ... so long as the final scale does not exceed 8
  6142. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  6143. }
  6144. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6145. (
  6146. { Don't optimise if size is a concern and the intermediate register remains in use }
  6147. IntermediateRegDiscarded or
  6148. (
  6149. not (cs_opt_size in current_settings.optimizerswitches) and
  6150. { If the intermediate register is not discarded, it must not
  6151. appear in the first LEA's reference. (Fixes #41166) }
  6152. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6153. )
  6154. ) and
  6155. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6156. (
  6157. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  6158. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6159. ) and (
  6160. (
  6161. { lea (reg1,scale2), reg2 variant }
  6162. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  6163. (
  6164. Adjacent or
  6165. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  6166. ) and
  6167. (
  6168. (
  6169. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  6170. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  6171. ) or (
  6172. { lea (regX,regX), reg1 variant }
  6173. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  6174. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  6175. )
  6176. )
  6177. ) or (
  6178. { lea (reg1,reg1), reg1 variant }
  6179. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6180. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  6181. )
  6182. ) then
  6183. begin
  6184. { Make everything homogeneous to make calculations easier }
  6185. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  6186. begin
  6187. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  6188. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  6189. taicpu(p).oper[0]^.ref^.scalefactor := 2
  6190. else
  6191. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  6192. taicpu(p).oper[0]^.ref^.base := NR_NO;
  6193. end;
  6194. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6195. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6196. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6197. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6198. begin
  6199. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6200. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  6201. begin
  6202. { Put the register to change in the index register }
  6203. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  6204. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  6205. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  6206. end;
  6207. { Change lea (reg,reg) to lea(,reg,2) }
  6208. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  6209. begin
  6210. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  6211. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  6212. end;
  6213. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  6214. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6215. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  6216. { Just to prevent miscalculations }
  6217. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  6218. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  6219. else
  6220. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  6221. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6222. if IntermediateRegDiscarded then
  6223. begin
  6224. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  6225. RemoveCurrentP(p);
  6226. end
  6227. else
  6228. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  6229. result:=true;
  6230. exit;
  6231. end;
  6232. end;
  6233. { changes
  6234. lea offset1(regX), reg1
  6235. lea offset2(reg1), reg2
  6236. to
  6237. lea offset1+offset2(regX), reg2 }
  6238. if (
  6239. { Don't optimise if size is a concern and the intermediate register remains in use }
  6240. IntermediateRegDiscarded or
  6241. (
  6242. not (cs_opt_size in current_settings.optimizerswitches) and
  6243. { If the intermediate register is not discarded, it must not
  6244. appear in the first LEA's reference. (Fixes #41166) }
  6245. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6246. )
  6247. ) and
  6248. (
  6249. (
  6250. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6251. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6252. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6253. ) or (
  6254. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6255. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6256. (
  6257. (
  6258. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6259. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6260. ) or (
  6261. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6262. (
  6263. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6264. (
  6265. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6266. (
  6267. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6268. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6269. )
  6270. )
  6271. )
  6272. )
  6273. )
  6274. )
  6275. ) then
  6276. begin
  6277. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6278. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6279. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6280. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6281. begin
  6282. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6283. begin
  6284. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6285. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6286. { if the register is used as index and base, we have to increase for base as well
  6287. and adapt base }
  6288. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6289. begin
  6290. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6291. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6292. end;
  6293. end
  6294. else
  6295. begin
  6296. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6297. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6298. end;
  6299. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6300. begin
  6301. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6302. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6303. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6304. { Catch the situation where the base = index
  6305. and treat this as *2. The scalefactor of
  6306. p will be 0 or 1 due to the conditional
  6307. checks above. Fixes i40647 }
  6308. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6309. else
  6310. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6311. end;
  6312. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6313. if IntermediateRegDiscarded then
  6314. begin
  6315. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6316. RemoveCurrentP(p);
  6317. end
  6318. else
  6319. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6320. result:=true;
  6321. exit;
  6322. end;
  6323. end;
  6324. end;
  6325. { Change:
  6326. leal/q $x(%reg1),%reg2
  6327. ...
  6328. shll/q $y,%reg2
  6329. To:
  6330. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6331. }
  6332. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6333. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6334. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6335. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6336. (taicpu(hp1).oper[0]^.val <= 3) then
  6337. begin
  6338. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6339. TransferUsedRegs(TmpUsedRegs);
  6340. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6341. if
  6342. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6343. (this works even if scalefactor is zero) }
  6344. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6345. { Ensure offset doesn't go out of bounds }
  6346. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6347. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6348. (
  6349. (
  6350. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6351. (
  6352. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6353. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6354. (
  6355. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6356. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6357. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6358. )
  6359. )
  6360. ) or (
  6361. (
  6362. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6363. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6364. ) and
  6365. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6366. )
  6367. ) then
  6368. begin
  6369. repeat
  6370. with taicpu(p).oper[0]^.ref^ do
  6371. begin
  6372. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6373. if index = base then
  6374. begin
  6375. if Multiple > 4 then
  6376. { Optimisation will no longer work because resultant
  6377. scale factor will exceed 8 }
  6378. Break;
  6379. base := NR_NO;
  6380. scalefactor := 2;
  6381. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6382. end
  6383. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6384. begin
  6385. { Scale factor only works on the index register }
  6386. index := base;
  6387. base := NR_NO;
  6388. end;
  6389. { For safety }
  6390. if scalefactor <= 1 then
  6391. begin
  6392. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6393. scalefactor := Multiple;
  6394. end
  6395. else
  6396. begin
  6397. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6398. scalefactor := scalefactor * Multiple;
  6399. end;
  6400. offset := offset * Multiple;
  6401. end;
  6402. RemoveInstruction(hp1);
  6403. Result := True;
  6404. Exit;
  6405. { This repeat..until loop exists for the benefit of Break }
  6406. until True;
  6407. end;
  6408. end;
  6409. end;
  6410. end;
  6411. end;
  6412. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6413. var
  6414. hp1 : tai;
  6415. SubInstr: Boolean;
  6416. ThisConst: TCGInt;
  6417. const
  6418. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6419. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6420. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6421. begin
  6422. Result := False;
  6423. if taicpu(p).oper[0]^.typ <> top_const then
  6424. { Should have been confirmed before calling }
  6425. InternalError(2021102601);
  6426. SubInstr := (taicpu(p).opcode = A_SUB);
  6427. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6428. GetLastInstruction(p, hp1) and
  6429. (hp1.typ = ait_instruction) and
  6430. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6431. begin
  6432. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6433. { Bad size }
  6434. InternalError(2022042001);
  6435. case taicpu(hp1).opcode Of
  6436. A_INC:
  6437. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6438. begin
  6439. if SubInstr then
  6440. ThisConst := taicpu(p).oper[0]^.val - 1
  6441. else
  6442. ThisConst := taicpu(p).oper[0]^.val + 1;
  6443. end
  6444. else
  6445. Exit;
  6446. A_DEC:
  6447. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6448. begin
  6449. if SubInstr then
  6450. ThisConst := taicpu(p).oper[0]^.val + 1
  6451. else
  6452. ThisConst := taicpu(p).oper[0]^.val - 1;
  6453. end
  6454. else
  6455. Exit;
  6456. A_SUB:
  6457. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6458. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6459. begin
  6460. if SubInstr then
  6461. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6462. else
  6463. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6464. end
  6465. else
  6466. Exit;
  6467. A_ADD:
  6468. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6469. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6470. begin
  6471. if SubInstr then
  6472. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6473. else
  6474. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6475. end
  6476. else
  6477. Exit;
  6478. else
  6479. Exit;
  6480. end;
  6481. { Check that the values are in range }
  6482. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6483. { Overflow; abort }
  6484. Exit;
  6485. if (ThisConst = 0) then
  6486. begin
  6487. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6488. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6489. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6490. RemoveInstruction(hp1);
  6491. hp1 := tai(p.next);
  6492. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6493. if not GetLastInstruction(hp1, p) then
  6494. p := hp1;
  6495. end
  6496. else
  6497. begin
  6498. if taicpu(hp1).opercnt=1 then
  6499. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6500. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6501. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6502. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6503. else
  6504. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6505. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6506. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6507. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6508. RemoveInstruction(hp1);
  6509. taicpu(p).loadconst(0, ThisConst);
  6510. end;
  6511. Result := True;
  6512. end;
  6513. end;
  6514. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6515. begin
  6516. Result := False;
  6517. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6518. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6519. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6520. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6521. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6522. (
  6523. (
  6524. (taicpu(hp1).opcode = A_TEST)
  6525. ) or (
  6526. (taicpu(hp1).opcode = A_CMP) and
  6527. { A sanity check more than anything }
  6528. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6529. )
  6530. ) then
  6531. begin
  6532. { change
  6533. mov mem, %reg
  6534. ...
  6535. cmp/test x, %reg / test %reg,%reg
  6536. (reg deallocated)
  6537. to
  6538. cmp/test x, mem / cmp 0, mem
  6539. }
  6540. TransferUsedRegs(TmpUsedRegs);
  6541. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6542. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6543. begin
  6544. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6545. if (taicpu(hp1).opcode = A_TEST) and
  6546. (
  6547. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6548. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6549. ) then
  6550. begin
  6551. taicpu(hp1).opcode := A_CMP;
  6552. taicpu(hp1).loadconst(0, 0);
  6553. end;
  6554. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6555. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6556. RemoveCurrentP(p);
  6557. if (p <> hp1) then
  6558. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6559. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6560. { Make sure the flags are allocated across the CMP instruction }
  6561. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6562. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6563. Result := True;
  6564. Exit;
  6565. end;
  6566. end;
  6567. end;
  6568. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6569. var
  6570. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6571. ThisReg, SecondReg: TRegister;
  6572. JumpLoc: TAsmLabel;
  6573. NewSize: TOpSize;
  6574. begin
  6575. Result := False;
  6576. {
  6577. Convert:
  6578. j<c> .L1
  6579. .L2:
  6580. mov 1,reg
  6581. jmp .L3 (or ret, although it might not be a RET yet)
  6582. .L1:
  6583. mov 0,reg
  6584. jmp .L3 (or ret)
  6585. ( As long as .L3 <> .L1 or .L2)
  6586. To:
  6587. mov 0,reg
  6588. set<not(c)> reg
  6589. jmp .L3 (or ret)
  6590. .L2:
  6591. mov 1,reg
  6592. jmp .L3 (or ret)
  6593. .L1:
  6594. mov 0,reg
  6595. jmp .L3 (or ret)
  6596. }
  6597. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6598. Exit;
  6599. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6600. if GetNextInstruction(hp_label, hp2) and
  6601. MatchInstruction(hp2,A_MOV,[]) and
  6602. (taicpu(hp2).oper[0]^.typ = top_const) and
  6603. (
  6604. (
  6605. (taicpu(hp2).oper[1]^.typ = top_reg)
  6606. {$ifdef i386}
  6607. { Under i386, ESI, EDI, EBP and ESP
  6608. don't have an 8-bit representation }
  6609. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6610. {$endif i386}
  6611. ) or (
  6612. {$ifdef i386}
  6613. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6614. {$endif i386}
  6615. (taicpu(hp2).opsize = S_B)
  6616. )
  6617. ) and
  6618. GetNextInstruction(hp2, hp3) and
  6619. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6620. (
  6621. (taicpu(hp3).opcode=A_RET) or
  6622. (
  6623. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6624. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6625. )
  6626. ) and
  6627. GetNextInstruction(hp3, hp4) and
  6628. FindLabel(JumpLoc, hp4) and
  6629. (
  6630. not (cs_opt_size in current_settings.optimizerswitches) or
  6631. { If the initial jump is the label's only reference, then it will
  6632. become a dead label if the other conditions are met and hence
  6633. remove at least 2 instructions, including a jump }
  6634. (JumpLoc.getrefs = 1)
  6635. ) and
  6636. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6637. that will be optimised out }
  6638. GetNextInstruction(hp4, hp5) and
  6639. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6640. (taicpu(hp5).oper[0]^.typ = top_const) and
  6641. (
  6642. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6643. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6644. ) and
  6645. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6646. GetNextInstruction(hp5,hp6) and
  6647. (
  6648. not (hp6.typ in [ait_align, ait_label]) or
  6649. SkipLabels(hp6, hp6)
  6650. ) and
  6651. (hp6.typ=ait_instruction) then
  6652. begin
  6653. { First, let's look at the two jumps that are hp3 and hp6 }
  6654. if not
  6655. (
  6656. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6657. (
  6658. (taicpu(hp6).opcode=A_RET) or
  6659. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6660. )
  6661. ) then
  6662. { If condition is False, then the JMP/RET instructions matched conventionally }
  6663. begin
  6664. { See if one of the jumps can be instantly converted into a RET }
  6665. if (taicpu(hp3).opcode=A_JMP) then
  6666. begin
  6667. { Reuse hp5 }
  6668. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6669. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6670. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6671. Exit;
  6672. if MatchInstruction(hp5, A_RET, []) then
  6673. begin
  6674. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6675. ConvertJumpToRET(hp3, hp5);
  6676. Result := True;
  6677. end
  6678. else
  6679. Exit;
  6680. end;
  6681. if (taicpu(hp6).opcode=A_JMP) then
  6682. begin
  6683. { Reuse hp5 }
  6684. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6685. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6686. Exit;
  6687. if MatchInstruction(hp5, A_RET, []) then
  6688. begin
  6689. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6690. ConvertJumpToRET(hp6, hp5);
  6691. Result := True;
  6692. end
  6693. else
  6694. Exit;
  6695. end;
  6696. if not
  6697. (
  6698. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6699. (
  6700. (taicpu(hp6).opcode=A_RET) or
  6701. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6702. )
  6703. ) then
  6704. { Still doesn't match }
  6705. Exit;
  6706. end;
  6707. if (taicpu(hp2).oper[0]^.val = 1) then
  6708. begin
  6709. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6710. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6711. end
  6712. else
  6713. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6714. if taicpu(hp2).opsize=S_B then
  6715. begin
  6716. if taicpu(hp2).oper[1]^.typ = top_reg then
  6717. begin
  6718. SecondReg := taicpu(hp2).oper[1]^.reg;
  6719. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6720. end
  6721. else
  6722. begin
  6723. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6724. SecondReg := NR_NO;
  6725. end;
  6726. hp_pos := p;
  6727. hp_allocstart := hp4;
  6728. end
  6729. else
  6730. begin
  6731. { Will be a register because the size can't be S_B otherwise }
  6732. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6733. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6734. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6735. if (cs_opt_size in current_settings.optimizerswitches) then
  6736. begin
  6737. { Favour using MOVZX when optimising for size }
  6738. case taicpu(hp2).opsize of
  6739. S_W:
  6740. NewSize := S_BW;
  6741. S_L:
  6742. NewSize := S_BL;
  6743. {$ifdef x86_64}
  6744. S_Q:
  6745. begin
  6746. NewSize := S_BL;
  6747. { Will implicitly zero-extend to 64-bit }
  6748. setsubreg(SecondReg, R_SUBD);
  6749. end;
  6750. {$endif x86_64}
  6751. else
  6752. InternalError(2022101301);
  6753. end;
  6754. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6755. { Inserting it right before p will guarantee that the flags are also tracked }
  6756. Asml.InsertBefore(hp5, p);
  6757. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6758. hp_pos := hp5;
  6759. hp_allocstart := hp4;
  6760. end
  6761. else
  6762. begin
  6763. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6764. { Inserting it right before p will guarantee that the flags are also tracked }
  6765. Asml.InsertBefore(hp5, p);
  6766. hp_pos := p;
  6767. hp_allocstart := hp5;
  6768. end;
  6769. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6770. end;
  6771. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6772. taicpu(hp4).condition := taicpu(p).condition;
  6773. asml.InsertBefore(hp4, hp_pos);
  6774. if taicpu(hp3).is_jmp then
  6775. begin
  6776. JumpLoc.decrefs;
  6777. MakeUnconditional(taicpu(p));
  6778. { This also increases the reference count }
  6779. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6780. end
  6781. else
  6782. ConvertJumpToRET(p, hp3);
  6783. if SecondReg <> NR_NO then
  6784. { Ensure the destination register is allocated over this region }
  6785. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6786. if (JumpLoc.getrefs = 0) then
  6787. RemoveDeadCodeAfterJump(hp3);
  6788. Result:=true;
  6789. exit;
  6790. end;
  6791. end;
  6792. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6793. var
  6794. hp1, hp2: tai;
  6795. ActiveReg: TRegister;
  6796. OldOffset: asizeint;
  6797. ThisConst: TCGInt;
  6798. function RegDeallocated: Boolean;
  6799. begin
  6800. TransferUsedRegs(TmpUsedRegs);
  6801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6802. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6803. end;
  6804. begin
  6805. Result:=false;
  6806. hp1 := nil;
  6807. { replace
  6808. subX const,%reg1
  6809. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6810. dealloc %reg1
  6811. by
  6812. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6813. }
  6814. if MatchOpType(taicpu(p),top_const,top_reg) then
  6815. begin
  6816. ActiveReg := taicpu(p).oper[1]^.reg;
  6817. { Ensures the entire register was updated }
  6818. if (taicpu(p).opsize >= S_L) and
  6819. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6820. MatchInstruction(hp1,A_LEA,[]) and
  6821. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6822. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6823. (
  6824. { Cover the case where the register in the reference is also the destination register }
  6825. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6826. (
  6827. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6828. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6829. RegDeallocated
  6830. )
  6831. ) then
  6832. begin
  6833. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6834. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6835. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6836. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6837. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6838. {$ifdef x86_64}
  6839. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6840. begin
  6841. { Overflow; abort }
  6842. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6843. end
  6844. else
  6845. {$endif x86_64}
  6846. begin
  6847. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6848. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6849. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6850. RemoveCurrentP(p, hp1)
  6851. else
  6852. RemoveCurrentP(p);
  6853. result:=true;
  6854. Exit;
  6855. end;
  6856. end;
  6857. if (
  6858. { Save calling GetNextInstructionUsingReg again }
  6859. Assigned(hp1) or
  6860. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6861. ) and
  6862. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6863. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6864. begin
  6865. { Make sure the flags aren't in use by the second operation }
  6866. TransferUsedRegs(TmpUsedRegs);
  6867. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6868. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6869. begin
  6870. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6871. begin
  6872. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6873. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6874. Result := True;
  6875. { Handle any overflows }
  6876. case taicpu(p).opsize of
  6877. S_B:
  6878. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6879. S_W:
  6880. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6881. S_L:
  6882. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6883. {$ifdef x86_64}
  6884. S_Q:
  6885. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6886. { Overflow; abort }
  6887. Result := False
  6888. else
  6889. taicpu(p).oper[0]^.val := ThisConst;
  6890. {$endif x86_64}
  6891. else
  6892. InternalError(2021102611);
  6893. end;
  6894. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6895. if Result then
  6896. begin
  6897. if (taicpu(p).oper[0]^.val < 0) and
  6898. (
  6899. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6900. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6901. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6902. ) then
  6903. begin
  6904. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6905. taicpu(p).opcode := A_SUB;
  6906. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6907. end
  6908. else
  6909. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6910. RemoveInstruction(hp1);
  6911. end;
  6912. end
  6913. else
  6914. begin
  6915. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6916. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6917. Asml.Remove(p);
  6918. Asml.InsertAfter(p, hp1);
  6919. p := hp1;
  6920. Result := True;
  6921. Exit;
  6922. end;
  6923. end;
  6924. end;
  6925. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6926. { * change "sub/add const1, reg" or "dec reg" followed by
  6927. "sub const2, reg" to one "sub ..., reg" }
  6928. {$ifdef i386}
  6929. if (taicpu(p).oper[0]^.val = 2) and
  6930. (ActiveReg = NR_ESP) and
  6931. { Don't do the sub/push optimization if the sub }
  6932. { comes from setting up the stack frame (JM) }
  6933. (not(GetLastInstruction(p,hp1)) or
  6934. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6935. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6936. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6937. begin
  6938. hp1 := tai(p.next);
  6939. while Assigned(hp1) and
  6940. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6941. not RegReadByInstruction(NR_ESP,hp1) and
  6942. not RegModifiedByInstruction(NR_ESP,hp1) do
  6943. hp1 := tai(hp1.next);
  6944. if Assigned(hp1) and
  6945. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6946. begin
  6947. taicpu(hp1).changeopsize(S_L);
  6948. if taicpu(hp1).oper[0]^.typ=top_reg then
  6949. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6950. hp1 := tai(p.next);
  6951. RemoveCurrentp(p, hp1);
  6952. Result:=true;
  6953. exit;
  6954. end;
  6955. end;
  6956. {$endif i386}
  6957. if DoArithCombineOpt(p) then
  6958. Result:=true;
  6959. end;
  6960. end;
  6961. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6962. var
  6963. TmpBool1,TmpBool2 : Boolean;
  6964. tmpref : treference;
  6965. hp1,hp2: tai;
  6966. mask, shiftval: tcgint;
  6967. begin
  6968. Result:=false;
  6969. { All these optimisations work on "shl/sal const,%reg" }
  6970. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6971. Exit;
  6972. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6973. (taicpu(p).oper[0]^.val <= 3) then
  6974. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6975. begin
  6976. { should we check the next instruction? }
  6977. TmpBool1 := True;
  6978. { have we found an add/sub which could be
  6979. integrated in the lea? }
  6980. TmpBool2 := False;
  6981. reference_reset(tmpref,2,[]);
  6982. TmpRef.index := taicpu(p).oper[1]^.reg;
  6983. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6984. while TmpBool1 and
  6985. GetNextInstruction(p, hp1) and
  6986. (tai(hp1).typ = ait_instruction) and
  6987. ((((taicpu(hp1).opcode = A_ADD) or
  6988. (taicpu(hp1).opcode = A_SUB)) and
  6989. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6990. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6991. (((taicpu(hp1).opcode = A_INC) or
  6992. (taicpu(hp1).opcode = A_DEC)) and
  6993. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6994. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6995. ((taicpu(hp1).opcode = A_LEA) and
  6996. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6997. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6998. (not GetNextInstruction(hp1,hp2) or
  6999. not instrReadsFlags(hp2)) Do
  7000. begin
  7001. TmpBool1 := False;
  7002. if taicpu(hp1).opcode=A_LEA then
  7003. begin
  7004. if (TmpRef.base = NR_NO) and
  7005. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  7006. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  7007. { Segment register isn't a concern here }
  7008. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  7009. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  7010. begin
  7011. TmpBool1 := True;
  7012. TmpBool2 := True;
  7013. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  7014. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  7015. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  7016. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  7017. RemoveInstruction(hp1);
  7018. end
  7019. end
  7020. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  7021. begin
  7022. TmpBool1 := True;
  7023. TmpBool2 := True;
  7024. case taicpu(hp1).opcode of
  7025. A_ADD:
  7026. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  7027. A_SUB:
  7028. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  7029. else
  7030. internalerror(2019050536);
  7031. end;
  7032. RemoveInstruction(hp1);
  7033. end
  7034. else
  7035. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  7036. (((taicpu(hp1).opcode = A_ADD) and
  7037. (TmpRef.base = NR_NO)) or
  7038. (taicpu(hp1).opcode = A_INC) or
  7039. (taicpu(hp1).opcode = A_DEC)) then
  7040. begin
  7041. TmpBool1 := True;
  7042. TmpBool2 := True;
  7043. case taicpu(hp1).opcode of
  7044. A_ADD:
  7045. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  7046. A_INC:
  7047. inc(TmpRef.offset);
  7048. A_DEC:
  7049. dec(TmpRef.offset);
  7050. else
  7051. internalerror(2019050535);
  7052. end;
  7053. RemoveInstruction(hp1);
  7054. end;
  7055. end;
  7056. if TmpBool2
  7057. {$ifndef x86_64}
  7058. or
  7059. ((current_settings.optimizecputype < cpu_Pentium2) and
  7060. (taicpu(p).oper[0]^.val <= 3) and
  7061. not(cs_opt_size in current_settings.optimizerswitches))
  7062. {$endif x86_64}
  7063. then
  7064. begin
  7065. if not(TmpBool2) and
  7066. (taicpu(p).oper[0]^.val=1) then
  7067. begin
  7068. taicpu(p).opcode := A_ADD;
  7069. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7070. end
  7071. else
  7072. begin
  7073. taicpu(p).opcode := A_LEA;
  7074. taicpu(p).loadref(0, TmpRef);
  7075. end;
  7076. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  7077. Result := True;
  7078. end;
  7079. end
  7080. {$ifndef x86_64}
  7081. else if (current_settings.optimizecputype < cpu_Pentium2) then
  7082. begin
  7083. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  7084. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  7085. (unlike shl, which is only Tairable in the U pipe) }
  7086. if taicpu(p).oper[0]^.val=1 then
  7087. begin
  7088. taicpu(p).opcode := A_ADD;
  7089. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7090. Result := True;
  7091. end
  7092. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  7093. "shl $3, %reg" to "lea (,%reg,8), %reg }
  7094. else if (taicpu(p).opsize = S_L) and
  7095. (taicpu(p).oper[0]^.val<= 3) then
  7096. begin
  7097. reference_reset(tmpref,2,[]);
  7098. TmpRef.index := taicpu(p).oper[1]^.reg;
  7099. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  7100. taicpu(p).opcode := A_LEA;
  7101. taicpu(p).loadref(0, TmpRef);
  7102. Result := True;
  7103. end;
  7104. end
  7105. {$endif x86_64}
  7106. else if
  7107. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  7108. (
  7109. (
  7110. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  7111. SetAndTest(hp1, hp2)
  7112. {$ifdef x86_64}
  7113. ) or
  7114. (
  7115. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7116. GetNextInstruction(hp1, hp2) and
  7117. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  7118. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7119. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  7120. {$endif x86_64}
  7121. )
  7122. ) and
  7123. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  7124. begin
  7125. { Change:
  7126. shl x, %reg1
  7127. mov -(1<<x), %reg2
  7128. and %reg2, %reg1
  7129. Or:
  7130. shl x, %reg1
  7131. and -(1<<x), %reg1
  7132. To just:
  7133. shl x, %reg1
  7134. Since the and operation only zeroes bits that are already zero from the shl operation
  7135. }
  7136. case taicpu(p).oper[0]^.val of
  7137. 8:
  7138. mask:=$FFFFFFFFFFFFFF00;
  7139. 16:
  7140. mask:=$FFFFFFFFFFFF0000;
  7141. 32:
  7142. mask:=$FFFFFFFF00000000;
  7143. 63:
  7144. { Constant pre-calculated to prevent overflow errors with Int64 }
  7145. mask:=$8000000000000000;
  7146. else
  7147. begin
  7148. if taicpu(p).oper[0]^.val >= 64 then
  7149. { Shouldn't happen realistically, since the register
  7150. is guaranteed to be set to zero at this point }
  7151. mask := 0
  7152. else
  7153. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  7154. end;
  7155. end;
  7156. if taicpu(hp1).oper[0]^.val = mask then
  7157. begin
  7158. { Everything checks out, perform the optimisation, as long as
  7159. the FLAGS register isn't being used}
  7160. TransferUsedRegs(TmpUsedRegs);
  7161. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7162. {$ifdef x86_64}
  7163. if (hp1 <> hp2) then
  7164. begin
  7165. { "shl/mov/and" version }
  7166. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7167. { Don't do the optimisation if the FLAGS register is in use }
  7168. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  7169. begin
  7170. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  7171. { Don't remove the 'mov' instruction if its register is used elsewhere }
  7172. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  7173. begin
  7174. RemoveInstruction(hp1);
  7175. Result := True;
  7176. end;
  7177. { Only set Result to True if the 'mov' instruction was removed }
  7178. RemoveInstruction(hp2);
  7179. end;
  7180. end
  7181. else
  7182. {$endif x86_64}
  7183. begin
  7184. { "shl/and" version }
  7185. { Don't do the optimisation if the FLAGS register is in use }
  7186. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  7187. begin
  7188. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  7189. RemoveInstruction(hp1);
  7190. Result := True;
  7191. end;
  7192. end;
  7193. Exit;
  7194. end
  7195. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  7196. begin
  7197. { Even if the mask doesn't allow for its removal, we might be
  7198. able to optimise the mask for the "shl/and" version, which
  7199. may permit other peephole optimisations }
  7200. {$ifdef DEBUG_AOPTCPU}
  7201. mask := taicpu(hp1).oper[0]^.val and mask;
  7202. if taicpu(hp1).oper[0]^.val <> mask then
  7203. begin
  7204. DebugMsg(
  7205. SPeepholeOptimization +
  7206. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  7207. ' to $' + debug_tostr(mask) +
  7208. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  7209. taicpu(hp1).oper[0]^.val := mask;
  7210. end;
  7211. {$else DEBUG_AOPTCPU}
  7212. { If debugging is off, just set the operand even if it's the same }
  7213. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  7214. {$endif DEBUG_AOPTCPU}
  7215. end;
  7216. end;
  7217. {
  7218. change
  7219. shl/sal const,reg
  7220. <op> ...(...,reg,1),...
  7221. into
  7222. <op> ...(...,reg,1 shl const),...
  7223. if const in 1..3
  7224. }
  7225. if MatchOpType(taicpu(p), top_const, top_reg) and
  7226. (taicpu(p).oper[0]^.val in [1..3]) and
  7227. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7228. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  7229. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  7230. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  7231. MatchOpType(taicpu(hp1),top_ref))
  7232. ) and
  7233. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  7234. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  7235. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  7236. begin
  7237. TransferUsedRegs(TmpUsedRegs);
  7238. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7239. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  7240. begin
  7241. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7242. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7243. RemoveCurrentP(p);
  7244. Result:=true;
  7245. exit;
  7246. end;
  7247. end;
  7248. if MatchOpType(taicpu(p), top_const, top_reg) and
  7249. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7250. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7251. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7252. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7253. begin
  7254. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7255. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7256. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7257. {$ifdef x86_64}
  7258. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7259. {$endif x86_64}
  7260. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7261. begin
  7262. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7263. taicpu(hp1).opcode:=A_MOV;
  7264. taicpu(hp1).oper[0]^.val:=0;
  7265. end
  7266. else
  7267. begin
  7268. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7269. taicpu(hp1).oper[0]^.val:=shiftval;
  7270. end;
  7271. RemoveCurrentP(p);
  7272. Result:=true;
  7273. exit;
  7274. end;
  7275. end;
  7276. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7277. begin
  7278. case shr_size of
  7279. S_B:
  7280. { No valid combinations }
  7281. Result := False;
  7282. S_W:
  7283. Result := (Shift >= 8) and (movz_size = S_BW);
  7284. S_L:
  7285. Result :=
  7286. (Shift >= 24) { Any opsize is valid for this shift } or
  7287. ((Shift >= 16) and (movz_size = S_WL));
  7288. {$ifdef x86_64}
  7289. S_Q:
  7290. Result :=
  7291. (Shift >= 56) { Any opsize is valid for this shift } or
  7292. ((Shift >= 48) and (movz_size = S_WL));
  7293. {$endif x86_64}
  7294. else
  7295. InternalError(2022081510);
  7296. end;
  7297. end;
  7298. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7299. var
  7300. hp1, hp2: tai;
  7301. IdentityMask, Shift: TCGInt;
  7302. LimitSize: Topsize;
  7303. DoNotMerge: Boolean;
  7304. begin
  7305. if not MatchInstruction(p, A_SHR, []) then
  7306. InternalError(2025040301);
  7307. Result := False;
  7308. DoNotMerge := False;
  7309. Shift := taicpu(p).oper[0]^.val;
  7310. LimitSize := taicpu(p).opsize;
  7311. hp1 := p;
  7312. repeat
  7313. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7314. Exit;
  7315. case taicpu(hp1).opcode of
  7316. A_AND:
  7317. { Detect:
  7318. shr x, %reg
  7319. and y, %reg
  7320. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7321. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7322. (Post-peephole only)
  7323. }
  7324. if PostPeephole and
  7325. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7326. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7327. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7328. begin
  7329. { Make sure the FLAGS register isn't in use }
  7330. TransferUsedRegs(TmpUsedRegs);
  7331. hp2 := p;
  7332. repeat
  7333. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7334. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7335. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7336. begin
  7337. { Generate the identity mask }
  7338. case taicpu(p).opsize of
  7339. S_B:
  7340. IdentityMask := $FF shr Shift;
  7341. S_W:
  7342. IdentityMask := $FFFF shr Shift;
  7343. S_L:
  7344. IdentityMask := $FFFFFFFF shr Shift;
  7345. {$ifdef x86_64}
  7346. S_Q:
  7347. { We need to force the operands to be unsigned 64-bit
  7348. integers otherwise the wrong value is generated }
  7349. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7350. {$endif x86_64}
  7351. else
  7352. InternalError(2022081501);
  7353. end;
  7354. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7355. begin
  7356. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7357. { All the possible 1 bits are covered, so we can remove the AND }
  7358. hp2 := tai(hp1.Previous);
  7359. RemoveInstruction(hp1);
  7360. { p wasn't actually changed, so don't set Result to True,
  7361. but a change was nonetheless made elsewhere }
  7362. Include(OptsToCheck, aoc_ForceNewIteration);
  7363. { Do another pass in case other AND or MOVZX instructions
  7364. follow }
  7365. hp1 := hp2;
  7366. Continue;
  7367. end;
  7368. end;
  7369. end;
  7370. A_TEST, A_CMP:
  7371. { Skip over relevant comparisons, but shift instructions must
  7372. now not be merged since the original value is being read }
  7373. begin
  7374. DoNotMerge := True;
  7375. Continue;
  7376. end;
  7377. A_Jcc:
  7378. { Skip over conditional jumps and relevant comparisons }
  7379. Continue;
  7380. A_MOVZX:
  7381. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7382. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7383. begin
  7384. { Since the original register is being read as is, subsequent
  7385. SHRs must not be merged at this point }
  7386. DoNotMerge := True;
  7387. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7388. begin
  7389. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7390. begin
  7391. { If the MOVZX instruction reads and writes the same register,
  7392. defer this to the post-peephole optimisation stage }
  7393. if PostPeephole then
  7394. begin
  7395. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7396. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7397. hp2 := tai(hp1.Previous);
  7398. RemoveInstruction(hp1);
  7399. hp1 := hp2;
  7400. end;
  7401. end
  7402. else { Different register target }
  7403. begin
  7404. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7405. taicpu(hp1).opcode := A_MOV;
  7406. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7407. case taicpu(hp1).opsize of
  7408. S_BW:
  7409. taicpu(hp1).opsize := S_W;
  7410. S_BL, S_WL:
  7411. taicpu(hp1).opsize := S_L;
  7412. else
  7413. InternalError(2022081503);
  7414. end;
  7415. { p itself hasn't changed, so no need to set Result to True }
  7416. Include(OptsToCheck, aoc_ForceNewIteration);
  7417. { See if there's anything afterwards that can be
  7418. optimised, since the input register hasn't changed }
  7419. Continue;
  7420. end;
  7421. Exit;
  7422. end
  7423. else if PostPeephole and
  7424. (Shift > 0) and
  7425. (taicpu(p).opsize = S_W) and
  7426. (taicpu(hp1).opsize = S_WL) and
  7427. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7428. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7429. begin
  7430. { Detect:
  7431. shr x, %ax (x > 0)
  7432. ...
  7433. movzwl %ax,%eax
  7434. -
  7435. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7436. But first, check to see if movzwl %ax,%eax can be removed...
  7437. }
  7438. hp2 := tai(hp1.Previous);
  7439. TransferUsedRegs(TmpUsedRegs);
  7440. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7441. if PostPeepholeOptMovZX(hp1) then
  7442. hp1 := hp2
  7443. else
  7444. begin
  7445. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7446. taicpu(hp1).opcode := A_CWDE;
  7447. taicpu(hp1).clearop(0);
  7448. taicpu(hp1).clearop(1);
  7449. taicpu(hp1).ops := 0;
  7450. end;
  7451. RestoreUsedRegs(TmpUsedRegs);
  7452. { Don't need to set aoc_ForceNewIteration if
  7453. PostPeepholeOptMovZX returned True because it's the
  7454. post-peephole stage }
  7455. end;
  7456. { Move onto the next instruction }
  7457. Continue;
  7458. end;
  7459. A_SHL, A_SAL, A_SHR:
  7460. if (taicpu(hp1).opsize <= LimitSize) and
  7461. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7462. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7463. begin
  7464. { Make sure the sizes don't exceed the register size limit
  7465. (measured by the shift value falling below the limit) }
  7466. if taicpu(hp1).opsize < LimitSize then
  7467. LimitSize := taicpu(hp1).opsize;
  7468. if taicpu(hp1).opcode = A_SHR then
  7469. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7470. else
  7471. begin
  7472. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7473. DoNotMerge := True;
  7474. end;
  7475. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7476. Exit;
  7477. { Since we've established that the combined shift is within
  7478. limits, we can actually combine the adjacent SHR
  7479. instructions even if they're different sizes }
  7480. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7481. begin
  7482. hp2 := tai(hp1.Previous);
  7483. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7484. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7485. RemoveInstruction(hp1);
  7486. hp1 := hp2;
  7487. { Though p has changed, only the constant has, and its
  7488. effects can still be detected on the next iteration of
  7489. the repeat..until loop }
  7490. Include(OptsToCheck, aoc_ForceNewIteration);
  7491. end;
  7492. { Move onto the next instruction }
  7493. Continue;
  7494. end;
  7495. else
  7496. ;
  7497. end;
  7498. { If the register isn't actually modified, move onto the next instruction,
  7499. but set DoNotMerge to True since the register is being read }
  7500. if (
  7501. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7502. the next instruction, whether or not it contains the register }
  7503. (cs_opt_level3 in current_settings.optimizerswitches) or
  7504. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7505. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7506. begin
  7507. DoNotMerge := True;
  7508. Continue;
  7509. end;
  7510. Break;
  7511. until False;
  7512. end;
  7513. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7514. begin
  7515. Result := False;
  7516. { All these optimisations work on "shr const,%reg" }
  7517. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7518. Exit;
  7519. Result := HandleSHRMerge(p, False);
  7520. end;
  7521. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7522. var
  7523. CurrentRef: TReference;
  7524. FullReg: TRegister;
  7525. hp1, hp2: tai;
  7526. begin
  7527. Result := False;
  7528. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7529. Exit;
  7530. { We assume you've checked if the operand is actually a reference by
  7531. this point. If it isn't, you'll most likely get an access violation }
  7532. CurrentRef := first_mov.oper[1]^.ref^;
  7533. { Memory must be aligned }
  7534. if (CurrentRef.offset mod 4) <> 0 then
  7535. Exit;
  7536. Inc(CurrentRef.offset);
  7537. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7538. if MatchOperand(second_mov.oper[0]^, 0) and
  7539. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7540. GetNextInstruction(second_mov, hp1) and
  7541. (hp1.typ = ait_instruction) and
  7542. (taicpu(hp1).opcode = A_MOV) and
  7543. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7544. (taicpu(hp1).oper[0]^.val = 0) then
  7545. begin
  7546. Inc(CurrentRef.offset);
  7547. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7548. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7549. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7550. begin
  7551. case taicpu(hp1).opsize of
  7552. S_B:
  7553. if GetNextInstruction(hp1, hp2) and
  7554. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7555. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7556. (taicpu(hp2).oper[0]^.val = 0) then
  7557. begin
  7558. Inc(CurrentRef.offset);
  7559. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7560. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7561. (taicpu(hp2).opsize = S_B) then
  7562. begin
  7563. RemoveInstruction(hp1);
  7564. RemoveInstruction(hp2);
  7565. first_mov.opsize := S_L;
  7566. if first_mov.oper[0]^.typ = top_reg then
  7567. begin
  7568. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7569. { Reuse second_mov as a MOVZX instruction }
  7570. second_mov.opcode := A_MOVZX;
  7571. second_mov.opsize := S_BL;
  7572. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7573. second_mov.loadreg(1, FullReg);
  7574. first_mov.oper[0]^.reg := FullReg;
  7575. asml.Remove(second_mov);
  7576. asml.InsertBefore(second_mov, first_mov);
  7577. end
  7578. else
  7579. { It's a value }
  7580. begin
  7581. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7582. RemoveInstruction(second_mov);
  7583. end;
  7584. Result := True;
  7585. Exit;
  7586. end;
  7587. end;
  7588. S_W:
  7589. begin
  7590. RemoveInstruction(hp1);
  7591. first_mov.opsize := S_L;
  7592. if first_mov.oper[0]^.typ = top_reg then
  7593. begin
  7594. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7595. { Reuse second_mov as a MOVZX instruction }
  7596. second_mov.opcode := A_MOVZX;
  7597. second_mov.opsize := S_BL;
  7598. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7599. second_mov.loadreg(1, FullReg);
  7600. first_mov.oper[0]^.reg := FullReg;
  7601. asml.Remove(second_mov);
  7602. asml.InsertBefore(second_mov, first_mov);
  7603. end
  7604. else
  7605. { It's a value }
  7606. begin
  7607. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7608. RemoveInstruction(second_mov);
  7609. end;
  7610. Result := True;
  7611. Exit;
  7612. end;
  7613. else
  7614. ;
  7615. end;
  7616. end;
  7617. end;
  7618. end;
  7619. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7620. { returns true if a "continue" should be done after this optimization }
  7621. var
  7622. hp1, hp2, hp3: tai;
  7623. begin
  7624. Result := false;
  7625. hp3 := nil;
  7626. if MatchOpType(taicpu(p),top_ref) and
  7627. GetNextInstruction(p, hp1) and
  7628. (hp1.typ = ait_instruction) and
  7629. (((taicpu(hp1).opcode = A_FLD) and
  7630. (taicpu(p).opcode = A_FSTP)) or
  7631. ((taicpu(p).opcode = A_FISTP) and
  7632. (taicpu(hp1).opcode = A_FILD))) and
  7633. MatchOpType(taicpu(hp1),top_ref) and
  7634. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7635. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7636. begin
  7637. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7638. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7639. GetNextInstruction(hp1, hp2) and
  7640. (((hp2.typ = ait_instruction) and
  7641. IsExitCode(hp2) and
  7642. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7643. not(assigned(current_procinfo.procdef.funcretsym) and
  7644. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7645. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7646. { fstp <temp>
  7647. fld <temp>
  7648. <dealloc> <temp>
  7649. }
  7650. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7651. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7652. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7653. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7654. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7655. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7656. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7657. )
  7658. )
  7659. ) then
  7660. begin
  7661. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7662. RemoveInstruction(hp1);
  7663. RemoveCurrentP(p, hp2);
  7664. { first case: exit code }
  7665. if hp2.typ = ait_instruction then
  7666. RemoveLastDeallocForFuncRes(p);
  7667. Result := true;
  7668. end
  7669. else
  7670. { we can do this only in fast math mode as fstp is rounding ...
  7671. ... still disabled as it breaks the compiler and/or rtl }
  7672. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7673. { ... or if another fstp equal to the first one follows }
  7674. GetNextInstruction(hp1,hp2) and
  7675. (hp2.typ = ait_instruction) and
  7676. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7677. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7678. begin
  7679. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7680. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7681. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7682. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7683. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7684. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7685. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7686. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7687. ) then
  7688. begin
  7689. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7690. RemoveCurrentP(p,hp2);
  7691. RemoveInstruction(hp1);
  7692. Result := true;
  7693. end
  7694. else if { fst can't store an extended/comp value }
  7695. (taicpu(p).opsize <> S_FX) and
  7696. (taicpu(p).opsize <> S_IQ) then
  7697. begin
  7698. if (taicpu(p).opcode = A_FSTP) then
  7699. taicpu(p).opcode := A_FST
  7700. else
  7701. taicpu(p).opcode := A_FIST;
  7702. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7703. RemoveInstruction(hp1);
  7704. Result := true;
  7705. end;
  7706. end;
  7707. end;
  7708. end;
  7709. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7710. var
  7711. hp1, hp2, hp3: tai;
  7712. begin
  7713. result:=false;
  7714. if MatchOpType(taicpu(p),top_reg) and
  7715. GetNextInstruction(p, hp1) and
  7716. (hp1.typ = Ait_Instruction) and
  7717. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7718. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7719. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7720. { change to
  7721. fld reg fxxx reg,st
  7722. fxxxp st, st1 (hp1)
  7723. Remark: non commutative operations must be reversed!
  7724. }
  7725. begin
  7726. case taicpu(hp1).opcode Of
  7727. A_FMULP,A_FADDP,
  7728. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7729. begin
  7730. case taicpu(hp1).opcode Of
  7731. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7732. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7733. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7734. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7735. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7736. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7737. else
  7738. internalerror(2019050534);
  7739. end;
  7740. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7741. taicpu(hp1).oper[1]^.reg := NR_ST;
  7742. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7743. RemoveCurrentP(p, hp1);
  7744. Result:=true;
  7745. exit;
  7746. end;
  7747. else
  7748. ;
  7749. end;
  7750. end
  7751. else
  7752. if MatchOpType(taicpu(p),top_ref) and
  7753. GetNextInstruction(p, hp2) and
  7754. (hp2.typ = Ait_Instruction) and
  7755. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7756. (taicpu(p).opsize in [S_FS, S_FL]) and
  7757. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7758. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7759. if GetLastInstruction(p, hp1) and
  7760. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7761. MatchOpType(taicpu(hp1),top_ref) and
  7762. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7763. if ((taicpu(hp2).opcode = A_FMULP) or
  7764. (taicpu(hp2).opcode = A_FADDP)) then
  7765. { change to
  7766. fld/fst mem1 (hp1) fld/fst mem1
  7767. fld mem1 (p) fadd/
  7768. faddp/ fmul st, st
  7769. fmulp st, st1 (hp2) }
  7770. begin
  7771. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7772. RemoveCurrentP(p, hp1);
  7773. if (taicpu(hp2).opcode = A_FADDP) then
  7774. taicpu(hp2).opcode := A_FADD
  7775. else
  7776. taicpu(hp2).opcode := A_FMUL;
  7777. taicpu(hp2).oper[1]^.reg := NR_ST;
  7778. end
  7779. else
  7780. { change to
  7781. fld/fst mem1 (hp1) fld/fst mem1
  7782. fld mem1 (p) fld st
  7783. }
  7784. begin
  7785. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7786. taicpu(p).changeopsize(S_FL);
  7787. taicpu(p).loadreg(0,NR_ST);
  7788. end
  7789. else
  7790. begin
  7791. case taicpu(hp2).opcode Of
  7792. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7793. { change to
  7794. fld/fst mem1 (hp1) fld/fst mem1
  7795. fld mem2 (p) fxxx mem2
  7796. fxxxp st, st1 (hp2) }
  7797. begin
  7798. case taicpu(hp2).opcode Of
  7799. A_FADDP: taicpu(p).opcode := A_FADD;
  7800. A_FMULP: taicpu(p).opcode := A_FMUL;
  7801. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7802. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7803. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7804. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7805. else
  7806. internalerror(2019050533);
  7807. end;
  7808. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7809. RemoveInstruction(hp2);
  7810. end
  7811. else
  7812. ;
  7813. end
  7814. end
  7815. end;
  7816. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7817. begin
  7818. Result := condition_in(cond1, cond2) or
  7819. { Not strictly subsets due to the actual flags checked, but because we're
  7820. comparing integers, E is a subset of AE and GE and their aliases }
  7821. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7822. end;
  7823. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7824. var
  7825. v: TCGInt;
  7826. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7827. FirstMatch, TempBool: Boolean;
  7828. NewReg: TRegister;
  7829. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7830. begin
  7831. Result:=false;
  7832. { All these optimisations need a next instruction }
  7833. if not GetNextInstruction(p, hp1) then
  7834. Exit;
  7835. true_hp1 := hp1;
  7836. { Search for:
  7837. cmp ###,###
  7838. j(c1) @lbl1
  7839. ...
  7840. @lbl:
  7841. cmp ###,### (same comparison as above)
  7842. j(c2) @lbl2
  7843. If c1 is a subset of c2, change to:
  7844. cmp ###,###
  7845. j(c1) @lbl2
  7846. (@lbl1 may become a dead label as a result)
  7847. }
  7848. { Also handle cases where there are multiple jumps in a row }
  7849. p_jump := hp1;
  7850. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7851. begin
  7852. Prefetch(p_jump.Next);
  7853. if IsJumpToLabel(taicpu(p_jump)) then
  7854. begin
  7855. { Do jump optimisations first in case the condition becomes
  7856. unnecessary }
  7857. TempBool := True;
  7858. if DoJumpOptimizations(p_jump, TempBool) or
  7859. not TempBool then
  7860. begin
  7861. if Assigned(p_jump) then
  7862. begin
  7863. { CollapseZeroDistJump will be set to the label or an align
  7864. before it after the jump if it optimises, whether or not
  7865. the label is live or dead }
  7866. if (p_jump.typ = ait_align) or
  7867. (
  7868. (p_jump.typ = ait_label) and
  7869. not (tai_label(p_jump).labsym.is_used)
  7870. ) then
  7871. GetNextInstruction(p_jump, p_jump);
  7872. end;
  7873. TransferUsedRegs(TmpUsedRegs);
  7874. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7875. if not Assigned(p_jump) or
  7876. (
  7877. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7878. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7879. ) then
  7880. begin
  7881. { No more conditional jumps; conditional statement is no longer required }
  7882. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7883. RemoveCurrentP(p);
  7884. Result := True;
  7885. Exit;
  7886. end;
  7887. hp1 := p_jump;
  7888. Include(OptsToCheck, aoc_ForceNewIteration);
  7889. Continue;
  7890. end;
  7891. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7892. if GetNextInstruction(p_jump, hp2) and
  7893. (
  7894. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7895. not TempBool
  7896. ) then
  7897. begin
  7898. hp1 := p_jump;
  7899. Include(OptsToCheck, aoc_ForceNewIteration);
  7900. Continue;
  7901. end;
  7902. p_label := nil;
  7903. if Assigned(JumpLabel) then
  7904. p_label := getlabelwithsym(JumpLabel);
  7905. if Assigned(p_label) and
  7906. GetNextInstruction(p_label, p_dist) and
  7907. MatchInstruction(p_dist, A_CMP, []) and
  7908. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7909. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7910. GetNextInstruction(p_dist, hp1_dist) and
  7911. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7912. begin
  7913. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7914. if JumpLabel = JumpLabel_dist then
  7915. { This is an infinite loop }
  7916. Exit;
  7917. { Best optimisation when the first condition is a subset (or equal) of the second }
  7918. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7919. begin
  7920. { Any registers used here will already be allocated }
  7921. if Assigned(JumpLabel) then
  7922. JumpLabel.DecRefs;
  7923. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7924. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7925. Include(OptsToCheck, aoc_ForceNewIteration);
  7926. { Don't exit yet. Since p and p_jump haven't actually been
  7927. removed, we can check for more on this iteration }
  7928. end
  7929. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7930. GetNextInstruction(hp1_dist, hp1_label) and
  7931. (hp1_label.typ = ait_label) then
  7932. begin
  7933. JumpLabel_far := tai_label(hp1_label).labsym;
  7934. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7935. { This is an infinite loop }
  7936. Exit;
  7937. if Assigned(JumpLabel_far) then
  7938. begin
  7939. { In this situation, if the first jump branches, the second one will never,
  7940. branch so change the destination label to after the second jump }
  7941. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7942. if Assigned(JumpLabel) then
  7943. JumpLabel.DecRefs;
  7944. JumpLabel_far.IncRefs;
  7945. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7946. Result := True;
  7947. { Don't exit yet. Since p and p_jump haven't actually been
  7948. removed, we can check for more on this iteration }
  7949. Continue;
  7950. end;
  7951. end;
  7952. end;
  7953. end;
  7954. { Search for:
  7955. cmp ###,###
  7956. j(c1) @lbl1
  7957. cmp ###,### (same as first)
  7958. Remove second cmp
  7959. }
  7960. if GetNextInstruction(p_jump, hp2) and
  7961. (
  7962. (
  7963. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7964. (
  7965. (
  7966. MatchOpType(taicpu(p), top_const, top_reg) and
  7967. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7968. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7969. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7970. ) or (
  7971. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7972. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7973. )
  7974. )
  7975. ) or (
  7976. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7977. MatchOperand(taicpu(p).oper[0]^, 0) and
  7978. (taicpu(p).oper[1]^.typ = top_reg) and
  7979. MatchInstruction(hp2, A_TEST, []) and
  7980. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7981. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7982. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7983. )
  7984. ) then
  7985. begin
  7986. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7987. TransferUsedRegs(TmpUsedRegs);
  7988. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7989. RemoveInstruction(hp2);
  7990. Result := True;
  7991. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7992. end
  7993. else
  7994. begin
  7995. { hp2 is the next instruction, so save time and just set p_jump
  7996. to it instead of calling GetNextInstruction below }
  7997. p_jump := hp2;
  7998. Continue;
  7999. end;
  8000. GetNextInstruction(p_jump, p_jump);
  8001. end;
  8002. if (
  8003. { Don't call GetNextInstruction again if we already have it }
  8004. (true_hp1 = p_jump) or
  8005. GetNextInstruction(p, hp1)
  8006. ) and
  8007. MatchInstruction(hp1, A_Jcc, []) and
  8008. IsJumpToLabel(taicpu(hp1)) and
  8009. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  8010. GetNextInstruction(hp1, hp2) then
  8011. begin
  8012. {
  8013. cmp x, y (or "cmp y, x")
  8014. je @lbl
  8015. mov x, y
  8016. @lbl:
  8017. (x and y can be constants, registers or references)
  8018. Change to:
  8019. mov x, y (x and y will always be equal in the end)
  8020. @lbl: (may beceome a dead label)
  8021. Also:
  8022. cmp x, y (or "cmp y, x")
  8023. jne @lbl
  8024. mov x, y
  8025. @lbl:
  8026. (x and y can be constants, registers or references)
  8027. Change to:
  8028. Absolutely nothing! (Except @lbl if it's still live)
  8029. }
  8030. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  8031. (
  8032. (
  8033. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  8034. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  8035. ) or (
  8036. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  8037. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  8038. )
  8039. ) and
  8040. GetNextInstruction(hp2, hp1_label) and
  8041. (hp1_label.typ = ait_label) and
  8042. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  8043. begin
  8044. tai_label(hp1_label).labsym.DecRefs;
  8045. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  8046. begin
  8047. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  8048. RemoveInstruction(hp2);
  8049. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  8050. end
  8051. else
  8052. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  8053. RemoveInstruction(hp1);
  8054. RemoveCurrentp(p, hp2);
  8055. Result := True;
  8056. Exit;
  8057. end;
  8058. {
  8059. Try to optimise the following:
  8060. cmp $x,### ($x and $y can be registers or constants)
  8061. je @lbl1 (only reference)
  8062. cmp $y,### (### are identical)
  8063. @Lbl:
  8064. sete %reg1
  8065. Change to:
  8066. cmp $x,###
  8067. sete %reg2 (allocate new %reg2)
  8068. cmp $y,###
  8069. sete %reg1
  8070. orb %reg2,%reg1
  8071. (dealloc %reg2)
  8072. This adds an instruction (so don't perform under -Os), but it removes
  8073. a conditional branch.
  8074. }
  8075. if not (cs_opt_size in current_settings.optimizerswitches) and
  8076. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  8077. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  8078. { The first operand of CMP instructions can only be a register or
  8079. immediate anyway, so no need to check }
  8080. GetNextInstruction(hp2, p_label) and
  8081. (p_label.typ = ait_label) and
  8082. (tai_label(p_label).labsym.getrefs = 1) and
  8083. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  8084. GetNextInstruction(p_label, p_dist) and
  8085. MatchInstruction(p_dist, A_SETcc, []) and
  8086. (taicpu(p_dist).condition in [C_E, C_Z]) and
  8087. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8088. begin
  8089. TransferUsedRegs(TmpUsedRegs);
  8090. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8091. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8092. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  8093. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  8094. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  8095. { Get the instruction after the SETcc instruction so we can
  8096. allocate a new register over the entire range }
  8097. GetNextInstruction(p_dist, hp1_dist) then
  8098. begin
  8099. { Register can appear in p if it's not used afterwards, so only
  8100. allocate between hp1 and hp1_dist }
  8101. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  8102. if NewReg <> NR_NO then
  8103. begin
  8104. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  8105. { Change the jump instruction into a SETcc instruction }
  8106. taicpu(hp1).opcode := A_SETcc;
  8107. taicpu(hp1).opsize := S_B;
  8108. taicpu(hp1).loadreg(0, NewReg);
  8109. { This is now a dead label }
  8110. tai_label(p_label).labsym.decrefs;
  8111. { Prefer adding before the next instruction so the FLAGS
  8112. register is deallicated first }
  8113. AsmL.InsertBefore(
  8114. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  8115. hp1_dist
  8116. );
  8117. Result := True;
  8118. { Don't exit yet, as p wasn't changed and hp1, while
  8119. modified, is still intact and might be optimised by the
  8120. SETcc optimisation below }
  8121. end;
  8122. end;
  8123. end;
  8124. end;
  8125. if (taicpu(p).oper[0]^.typ = top_const) and
  8126. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  8127. begin
  8128. if (taicpu(p).oper[0]^.val = 0) and
  8129. (taicpu(p).oper[1]^.typ = top_reg) then
  8130. begin
  8131. hp2 := p;
  8132. FirstMatch := True;
  8133. { When dealing with "cmp $0,%reg", only ZF and SF contain
  8134. anything meaningful once it's converted to "test %reg,%reg";
  8135. additionally, some jumps will always (or never) branch, so
  8136. evaluate every jump immediately following the
  8137. comparison, optimising the conditions if possible.
  8138. Similarly with SETcc... those that are always set to 0 or 1
  8139. are changed to MOV instructions }
  8140. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  8141. (
  8142. GetNextInstruction(hp2, hp1) and
  8143. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  8144. ) do
  8145. begin
  8146. Prefetch(hp1.Next);
  8147. FirstMatch := False;
  8148. case taicpu(hp1).condition of
  8149. C_B, C_C, C_NAE, C_O:
  8150. { For B/NAE:
  8151. Will never branch since an unsigned integer can never be below zero
  8152. For C/O:
  8153. Result cannot overflow because 0 is being subtracted
  8154. }
  8155. begin
  8156. if taicpu(hp1).opcode = A_Jcc then
  8157. begin
  8158. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  8159. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  8160. RemoveInstruction(hp1);
  8161. { Since hp1 was deleted, hp2 must not be updated }
  8162. Continue;
  8163. end
  8164. else
  8165. begin
  8166. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  8167. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  8168. taicpu(hp1).opcode := A_MOV;
  8169. taicpu(hp1).ops := 2;
  8170. taicpu(hp1).condition := C_None;
  8171. taicpu(hp1).opsize := S_B;
  8172. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8173. taicpu(hp1).loadconst(0, 0);
  8174. end;
  8175. end;
  8176. C_BE, C_NA:
  8177. begin
  8178. { Will only branch if equal to zero }
  8179. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  8180. taicpu(hp1).condition := C_E;
  8181. end;
  8182. C_A, C_NBE:
  8183. begin
  8184. { Will only branch if not equal to zero }
  8185. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  8186. taicpu(hp1).condition := C_NE;
  8187. end;
  8188. C_AE, C_NB, C_NC, C_NO:
  8189. begin
  8190. { Will always branch }
  8191. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  8192. if taicpu(hp1).opcode = A_Jcc then
  8193. begin
  8194. MakeUnconditional(taicpu(hp1));
  8195. { Any jumps/set that follow will now be dead code }
  8196. RemoveDeadCodeAfterJump(taicpu(hp1));
  8197. Break;
  8198. end
  8199. else
  8200. begin
  8201. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  8202. taicpu(hp1).opcode := A_MOV;
  8203. taicpu(hp1).ops := 2;
  8204. taicpu(hp1).condition := C_None;
  8205. taicpu(hp1).opsize := S_B;
  8206. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8207. taicpu(hp1).loadconst(0, 1);
  8208. end;
  8209. end;
  8210. C_None:
  8211. InternalError(2020012201);
  8212. C_P, C_PE, C_NP, C_PO:
  8213. { We can't handle parity checks and they should never be generated
  8214. after a general-purpose CMP (it's used in some floating-point
  8215. comparisons that don't use CMP) }
  8216. InternalError(2020012202);
  8217. else
  8218. { Zero/Equality, Sign, their complements and all of the
  8219. signed comparisons do not need to be converted };
  8220. end;
  8221. hp2 := hp1;
  8222. end;
  8223. { Convert the instruction to a TEST }
  8224. taicpu(p).opcode := A_TEST;
  8225. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8226. Result := True;
  8227. Exit;
  8228. end
  8229. else
  8230. begin
  8231. TransferUsedRegs(TmpUsedRegs);
  8232. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8233. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8234. begin
  8235. if (taicpu(p).oper[0]^.val = 1) and
  8236. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  8237. begin
  8238. { Convert; To:
  8239. cmp $1,r/m cmp $0,r/m
  8240. jl @lbl jle @lbl
  8241. (Also do inverted conditions)
  8242. }
  8243. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8244. taicpu(p).oper[0]^.val := 0;
  8245. if taicpu(hp1).condition in [C_L, C_NGE] then
  8246. taicpu(hp1).condition := C_LE
  8247. else
  8248. taicpu(hp1).condition := C_NLE;
  8249. { If the instruction is now "cmp $0,%reg", convert it to a
  8250. TEST (and effectively do the work of the "cmp $0,%reg" in
  8251. the block above)
  8252. }
  8253. if (taicpu(p).oper[1]^.typ = top_reg) then
  8254. begin
  8255. taicpu(p).opcode := A_TEST;
  8256. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8257. end;
  8258. Result := True;
  8259. Exit;
  8260. end
  8261. else if (taicpu(p).oper[1]^.typ = top_reg)
  8262. {$ifdef x86_64}
  8263. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8264. {$endif x86_64}
  8265. then
  8266. begin
  8267. { cmp register,$8000 neg register
  8268. je target --> jo target
  8269. .... only if register is deallocated before jump.}
  8270. case Taicpu(p).opsize of
  8271. S_B: v:=$80;
  8272. S_W: v:=$8000;
  8273. S_L: v:=qword($80000000);
  8274. else
  8275. internalerror(2013112905);
  8276. end;
  8277. if (taicpu(p).oper[0]^.val=v) and
  8278. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8279. begin
  8280. TransferUsedRegs(TmpUsedRegs);
  8281. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8282. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8283. begin
  8284. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8285. Taicpu(p).opcode:=A_NEG;
  8286. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8287. Taicpu(p).clearop(1);
  8288. Taicpu(p).ops:=1;
  8289. if Taicpu(hp1).condition=C_E then
  8290. Taicpu(hp1).condition:=C_O
  8291. else
  8292. Taicpu(hp1).condition:=C_NO;
  8293. Result:=true;
  8294. exit;
  8295. end;
  8296. end;
  8297. end;
  8298. end;
  8299. end;
  8300. end;
  8301. if TrySwapMovCmp(p, hp1) then
  8302. begin
  8303. Result := True;
  8304. Exit;
  8305. end;
  8306. end;
  8307. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8308. var
  8309. hp1: tai;
  8310. begin
  8311. {
  8312. remove the second (v)pxor from
  8313. pxor reg,reg
  8314. ...
  8315. pxor reg,reg
  8316. }
  8317. Result:=false;
  8318. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8319. MatchOpType(taicpu(p),top_reg,top_reg) and
  8320. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8321. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8322. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8323. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8324. begin
  8325. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8326. RemoveInstruction(hp1);
  8327. Result:=true;
  8328. Exit;
  8329. end
  8330. {
  8331. replace
  8332. pxor reg1,reg1
  8333. movapd/s reg1,reg2
  8334. dealloc reg1
  8335. by
  8336. pxor reg2,reg2
  8337. }
  8338. else if GetNextInstruction(p,hp1) and
  8339. { we mix single and double opperations here because we assume that the compiler
  8340. generates vmovapd only after double operations and vmovaps only after single operations }
  8341. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8342. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8343. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8344. (taicpu(p).oper[0]^.typ=top_reg) then
  8345. begin
  8346. TransferUsedRegs(TmpUsedRegs);
  8347. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8348. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8349. begin
  8350. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8351. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8352. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8353. RemoveInstruction(hp1);
  8354. result:=true;
  8355. end;
  8356. end;
  8357. end;
  8358. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8359. var
  8360. hp1: tai;
  8361. begin
  8362. {
  8363. remove the second (v)pxor from
  8364. (v)pxor reg,reg
  8365. ...
  8366. (v)pxor reg,reg
  8367. }
  8368. Result:=false;
  8369. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8370. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8371. begin
  8372. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8373. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8374. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8375. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8376. begin
  8377. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8378. RemoveInstruction(hp1);
  8379. Result:=true;
  8380. Exit;
  8381. end;
  8382. {$ifdef x86_64}
  8383. {
  8384. replace
  8385. vpxor reg1,reg1,reg1
  8386. vmov reg,mem
  8387. by
  8388. movq $0,mem
  8389. }
  8390. if GetNextInstruction(p,hp1) and
  8391. MatchInstruction(hp1,A_VMOVSD,[]) and
  8392. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8393. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8394. begin
  8395. TransferUsedRegs(TmpUsedRegs);
  8396. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8397. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8398. begin
  8399. taicpu(hp1).loadconst(0,0);
  8400. taicpu(hp1).opcode:=A_MOV;
  8401. taicpu(hp1).opsize:=S_Q;
  8402. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8403. RemoveCurrentP(p);
  8404. result:=true;
  8405. Exit;
  8406. end;
  8407. end;
  8408. {$endif x86_64}
  8409. end
  8410. {
  8411. replace
  8412. vpxor reg1,reg1,reg2
  8413. by
  8414. vpxor reg2,reg2,reg2
  8415. to avoid unncessary data dependencies
  8416. }
  8417. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8418. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8419. begin
  8420. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8421. { avoid unncessary data dependency }
  8422. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8423. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8424. result:=true;
  8425. exit;
  8426. end;
  8427. Result:=OptPass1VOP(p);
  8428. end;
  8429. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8430. var
  8431. hp1 : tai;
  8432. begin
  8433. result:=false;
  8434. { replace
  8435. IMul const,%mreg1,%mreg2
  8436. Mov %reg2,%mreg3
  8437. dealloc %mreg3
  8438. by
  8439. Imul const,%mreg1,%mreg23
  8440. }
  8441. if (taicpu(p).ops=3) and
  8442. GetNextInstruction(p,hp1) and
  8443. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8444. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8445. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8446. begin
  8447. TransferUsedRegs(TmpUsedRegs);
  8448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8449. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8450. begin
  8451. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8452. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8453. RemoveInstruction(hp1);
  8454. result:=true;
  8455. end;
  8456. end;
  8457. end;
  8458. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8459. var
  8460. hp1 : tai;
  8461. begin
  8462. result:=false;
  8463. { replace
  8464. IMul %reg0,%reg1,%reg2
  8465. Mov %reg2,%reg3
  8466. dealloc %reg2
  8467. by
  8468. Imul %reg0,%reg1,%reg3
  8469. }
  8470. if GetNextInstruction(p,hp1) and
  8471. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8472. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8473. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8474. begin
  8475. TransferUsedRegs(TmpUsedRegs);
  8476. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8477. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8478. begin
  8479. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8480. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8481. RemoveInstruction(hp1);
  8482. result:=true;
  8483. end;
  8484. end;
  8485. end;
  8486. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8487. var
  8488. hp1: tai;
  8489. begin
  8490. Result:=false;
  8491. { get rid of
  8492. (v)cvtss2sd reg0,<reg1,>reg2
  8493. (v)cvtss2sd reg2,<reg2,>reg0
  8494. }
  8495. if GetNextInstruction(p,hp1) and
  8496. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8497. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8498. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8499. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8500. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8501. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8502. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8503. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8504. )
  8505. ) then
  8506. begin
  8507. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8508. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8509. begin
  8510. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8511. RemoveCurrentP(p);
  8512. RemoveInstruction(hp1);
  8513. end
  8514. else
  8515. begin
  8516. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8517. if taicpu(hp1).opcode=A_CVTSD2SS then
  8518. begin
  8519. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8520. taicpu(p).opcode:=A_MOVAPS;
  8521. end
  8522. else
  8523. begin
  8524. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8525. taicpu(p).opcode:=A_VMOVAPS;
  8526. end;
  8527. taicpu(p).ops:=2;
  8528. RemoveInstruction(hp1);
  8529. end;
  8530. Result:=true;
  8531. Exit;
  8532. end;
  8533. end;
  8534. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8535. var
  8536. hp1, hp2, hp3, hp4, hp5: tai;
  8537. ThisReg: TRegister;
  8538. begin
  8539. Result := False;
  8540. if not GetNextInstruction(p,hp1) then
  8541. Exit;
  8542. {
  8543. convert
  8544. j<c> .L1
  8545. mov 1,reg
  8546. jmp .L2
  8547. .L1
  8548. mov 0,reg
  8549. .L2
  8550. into
  8551. mov 0,reg
  8552. set<not(c)> reg
  8553. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8554. would destroy the flag contents
  8555. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8556. executed at the same time as a previous comparison.
  8557. set<not(c)> reg
  8558. movzx reg, reg
  8559. }
  8560. if MatchInstruction(hp1,A_MOV,[]) and
  8561. (taicpu(hp1).oper[0]^.typ = top_const) and
  8562. (
  8563. (
  8564. (taicpu(hp1).oper[1]^.typ = top_reg)
  8565. {$ifdef i386}
  8566. { Under i386, ESI, EDI, EBP and ESP
  8567. don't have an 8-bit representation }
  8568. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8569. {$endif i386}
  8570. ) or (
  8571. {$ifdef i386}
  8572. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8573. {$endif i386}
  8574. (taicpu(hp1).opsize = S_B)
  8575. )
  8576. ) and
  8577. GetNextInstruction(hp1,hp2) and
  8578. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8579. GetNextInstruction(hp2,hp3) and
  8580. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8581. GetNextInstruction(hp3,hp4) and
  8582. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8583. (taicpu(hp4).oper[0]^.typ = top_const) and
  8584. (
  8585. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8586. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8587. ) and
  8588. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8589. GetNextInstruction(hp4,hp5) and
  8590. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8591. begin
  8592. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8593. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8594. tai_label(hp3).labsym.DecRefs;
  8595. { If this isn't the only reference to the middle label, we can
  8596. still make a saving - only that the first jump and everything
  8597. that follows will remain. }
  8598. if (tai_label(hp3).labsym.getrefs = 0) then
  8599. begin
  8600. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8601. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8602. else
  8603. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8604. { remove jump, first label and second MOV (also catching any aligns) }
  8605. repeat
  8606. if not GetNextInstruction(hp2, hp3) then
  8607. InternalError(2021040810);
  8608. RemoveInstruction(hp2);
  8609. hp2 := hp3;
  8610. until hp2 = hp5;
  8611. { Don't decrement reference count before the removal loop
  8612. above, otherwise GetNextInstruction won't stop on the
  8613. the label }
  8614. tai_label(hp5).labsym.DecRefs;
  8615. end
  8616. else
  8617. begin
  8618. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8619. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8620. else
  8621. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8622. end;
  8623. taicpu(p).opcode:=A_SETcc;
  8624. taicpu(p).opsize:=S_B;
  8625. taicpu(p).is_jmp:=False;
  8626. if taicpu(hp1).opsize=S_B then
  8627. begin
  8628. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8629. if taicpu(hp1).oper[1]^.typ = top_reg then
  8630. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8631. RemoveInstruction(hp1);
  8632. end
  8633. else
  8634. begin
  8635. { Will be a register because the size can't be S_B otherwise }
  8636. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8637. taicpu(p).loadreg(0, ThisReg);
  8638. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8639. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8640. begin
  8641. case taicpu(hp1).opsize of
  8642. S_W:
  8643. taicpu(hp1).opsize := S_BW;
  8644. S_L:
  8645. taicpu(hp1).opsize := S_BL;
  8646. {$ifdef x86_64}
  8647. S_Q:
  8648. begin
  8649. taicpu(hp1).opsize := S_BL;
  8650. { Change the destination register to 32-bit }
  8651. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8652. end;
  8653. {$endif x86_64}
  8654. else
  8655. InternalError(2021040820);
  8656. end;
  8657. taicpu(hp1).opcode := A_MOVZX;
  8658. taicpu(hp1).loadreg(0, ThisReg);
  8659. end
  8660. else
  8661. begin
  8662. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8663. { hp1 is already a MOV instruction with the correct register }
  8664. taicpu(hp1).loadconst(0, 0);
  8665. { Inserting it right before p will guarantee that the flags are also tracked }
  8666. asml.Remove(hp1);
  8667. asml.InsertBefore(hp1, p);
  8668. end;
  8669. end;
  8670. Result:=true;
  8671. exit;
  8672. end
  8673. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8674. Result := TryJccStcClcOpt(p, hp1)
  8675. else if (hp1.typ = ait_label) then
  8676. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8677. end;
  8678. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8679. var
  8680. hp1, hp2, hp3: tai;
  8681. SourceRef, TargetRef: TReference;
  8682. CurrentReg: TRegister;
  8683. begin
  8684. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8685. if not UseAVX then
  8686. InternalError(2021100501);
  8687. Result := False;
  8688. { Look for the following to simplify:
  8689. vmovdqa/u x(mem1), %xmmreg
  8690. vmovdqa/u %xmmreg, y(mem2)
  8691. vmovdqa/u x+16(mem1), %xmmreg
  8692. vmovdqa/u %xmmreg, y+16(mem2)
  8693. Change to:
  8694. vmovdqa/u x(mem1), %ymmreg
  8695. vmovdqa/u %ymmreg, y(mem2)
  8696. vpxor %ymmreg, %ymmreg, %ymmreg
  8697. ( The VPXOR instruction is to zero the upper half, thus removing the
  8698. need to call the potentially expensive VZEROUPPER instruction. Other
  8699. peephole optimisations can remove VPXOR if it's unnecessary )
  8700. }
  8701. TransferUsedRegs(TmpUsedRegs);
  8702. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8703. { NOTE: In the optimisations below, if the references dictate that an
  8704. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8705. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8706. if (taicpu(p).opsize = S_XMM) and
  8707. MatchOpType(taicpu(p), top_ref, top_reg) and
  8708. GetNextInstruction(p, hp1) and
  8709. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8710. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8711. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8712. begin
  8713. SourceRef := taicpu(p).oper[0]^.ref^;
  8714. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8715. if GetNextInstruction(hp1, hp2) and
  8716. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8717. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8718. begin
  8719. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8720. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8721. Inc(SourceRef.offset, 16);
  8722. { Reuse the register in the first block move }
  8723. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8724. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8725. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8726. begin
  8727. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8728. Inc(TargetRef.offset, 16);
  8729. if GetNextInstruction(hp2, hp3) and
  8730. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8731. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8732. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8733. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8734. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8735. begin
  8736. { Update the register tracking to the new size }
  8737. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8738. { Remember that the offsets are 16 ahead }
  8739. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8740. if not (
  8741. ((SourceRef.offset mod 32) = 16) and
  8742. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8743. ) then
  8744. taicpu(p).opcode := A_VMOVDQU;
  8745. taicpu(p).opsize := S_YMM;
  8746. taicpu(p).oper[1]^.reg := CurrentReg;
  8747. if not (
  8748. ((TargetRef.offset mod 32) = 16) and
  8749. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8750. ) then
  8751. taicpu(hp1).opcode := A_VMOVDQU;
  8752. taicpu(hp1).opsize := S_YMM;
  8753. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8754. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8755. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8756. if (pi_uses_ymm in current_procinfo.flags) then
  8757. RemoveInstruction(hp2)
  8758. else
  8759. begin
  8760. { Upper 128 bits will be set to zero; change to XMM
  8761. to avoid requirement of AVX2 }
  8762. setsubreg(CurrentReg, R_SUBMMX);
  8763. taicpu(hp2).opcode := A_VPXOR;
  8764. taicpu(hp2).opsize := S_XMM;
  8765. taicpu(hp2).loadreg(0, CurrentReg);
  8766. taicpu(hp2).loadreg(1, CurrentReg);
  8767. taicpu(hp2).loadreg(2, CurrentReg);
  8768. taicpu(hp2).ops := 3;
  8769. end;
  8770. RemoveInstruction(hp3);
  8771. Result := True;
  8772. Exit;
  8773. end;
  8774. end
  8775. else
  8776. begin
  8777. { See if the next references are 16 less rather than 16 greater }
  8778. Dec(SourceRef.offset, 32); { -16 the other way }
  8779. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8780. begin
  8781. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8782. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8783. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8784. GetNextInstruction(hp2, hp3) and
  8785. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8786. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8787. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8788. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8789. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8790. begin
  8791. { Update the register tracking to the new size }
  8792. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8793. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8794. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8795. if not(
  8796. ((SourceRef.offset mod 32) = 0) and
  8797. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8798. ) then
  8799. taicpu(hp2).opcode := A_VMOVDQU;
  8800. taicpu(hp2).opsize := S_YMM;
  8801. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8802. if not (
  8803. ((TargetRef.offset mod 32) = 0) and
  8804. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8805. ) then
  8806. taicpu(hp3).opcode := A_VMOVDQU;
  8807. taicpu(hp3).opsize := S_YMM;
  8808. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8809. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8810. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8811. if (pi_uses_ymm in current_procinfo.flags) then
  8812. RemoveInstruction(hp1)
  8813. else
  8814. begin
  8815. { Upper 128 bits will be set to zero; change to
  8816. XMM to avoid requirement of AVX2 }
  8817. setsubreg(CurrentReg, R_SUBMMX);
  8818. taicpu(hp1).opcode := A_VPXOR;
  8819. taicpu(hp1).opsize := S_XMM;
  8820. taicpu(hp1).loadreg(0, CurrentReg);
  8821. taicpu(hp1).loadreg(1, CurrentReg);
  8822. taicpu(hp1).loadreg(2, CurrentReg);
  8823. taicpu(hp1).ops := 3;
  8824. Asml.Remove(hp1);
  8825. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8826. end;
  8827. RemoveCurrentP(p, hp2);
  8828. Result := True;
  8829. Exit;
  8830. end;
  8831. end;
  8832. end;
  8833. end;
  8834. end;
  8835. end;
  8836. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8837. var
  8838. hp2, hp3, first_assignment: tai;
  8839. IncCount, OperIdx: Integer;
  8840. OrigLabel: TAsmLabel;
  8841. begin
  8842. Count := 0;
  8843. Result := False;
  8844. first_assignment := nil;
  8845. if (LoopCount >= 20) then
  8846. begin
  8847. { Guard against infinite loops }
  8848. Exit;
  8849. end;
  8850. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8851. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8852. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8853. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8854. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8855. Exit;
  8856. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8857. {
  8858. change
  8859. jmp .L1
  8860. ...
  8861. .L1:
  8862. mov ##, ## ( multiple movs possible )
  8863. jmp/ret
  8864. into
  8865. mov ##, ##
  8866. jmp/ret
  8867. }
  8868. if not Assigned(hp1) then
  8869. begin
  8870. hp1 := GetLabelWithSym(OrigLabel);
  8871. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8872. Exit;
  8873. end;
  8874. hp2 := hp1;
  8875. while Assigned(hp2) do
  8876. begin
  8877. if Assigned(hp2) and (hp2.typ = ait_label) then
  8878. SkipLabels(hp2,hp2);
  8879. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8880. Break;
  8881. case taicpu(hp2).opcode of
  8882. A_MOVSD:
  8883. begin
  8884. if taicpu(hp2).ops = 0 then
  8885. { Wrong MOVSD }
  8886. Break;
  8887. Inc(Count);
  8888. if Count >= 5 then
  8889. { Too many to be worthwhile }
  8890. Break;
  8891. GetNextInstruction(hp2, hp2);
  8892. Continue;
  8893. end;
  8894. A_MOV,
  8895. A_MOVD,
  8896. A_MOVQ,
  8897. A_MOVSX,
  8898. {$ifdef x86_64}
  8899. A_MOVSXD,
  8900. {$endif x86_64}
  8901. A_MOVZX,
  8902. A_MOVAPS,
  8903. A_MOVUPS,
  8904. A_MOVSS,
  8905. A_MOVAPD,
  8906. A_MOVUPD,
  8907. A_MOVDQA,
  8908. A_MOVDQU,
  8909. A_VMOVSS,
  8910. A_VMOVAPS,
  8911. A_VMOVUPS,
  8912. A_VMOVSD,
  8913. A_VMOVAPD,
  8914. A_VMOVUPD,
  8915. A_VMOVDQA,
  8916. A_VMOVDQU:
  8917. begin
  8918. Inc(Count);
  8919. if Count >= 5 then
  8920. { Too many to be worthwhile }
  8921. Break;
  8922. GetNextInstruction(hp2, hp2);
  8923. Continue;
  8924. end;
  8925. A_JMP:
  8926. begin
  8927. { Guard against infinite loops }
  8928. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8929. Exit;
  8930. { Analyse this jump first in case it also duplicates assignments }
  8931. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8932. begin
  8933. { Something did change! }
  8934. Result := True;
  8935. Inc(Count, IncCount);
  8936. if Count >= 5 then
  8937. begin
  8938. { Too many to be worthwhile }
  8939. Exit;
  8940. end;
  8941. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8942. Break;
  8943. end;
  8944. Result := True;
  8945. Break;
  8946. end;
  8947. A_RET:
  8948. begin
  8949. Result := True;
  8950. Break;
  8951. end;
  8952. else
  8953. Break;
  8954. end;
  8955. end;
  8956. if Result then
  8957. begin
  8958. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8959. if Count = 0 then
  8960. begin
  8961. Result := False;
  8962. Exit;
  8963. end;
  8964. TransferUsedRegs(TmpUsedRegs);
  8965. hp3 := p;
  8966. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8967. while True do
  8968. begin
  8969. if Assigned(hp1) and (hp1.typ = ait_label) then
  8970. SkipLabels(hp1,hp1);
  8971. case hp1.typ of
  8972. ait_regalloc:
  8973. if tai_regalloc(hp1).ratype = ra_dealloc then
  8974. begin
  8975. { Duplicate the register deallocation... }
  8976. hp3:=tai(hp1.getcopy);
  8977. if first_assignment = nil then
  8978. first_assignment := hp3;
  8979. asml.InsertBefore(hp3, p);
  8980. { ... but also reallocate it after the jump }
  8981. hp3:=tai(hp1.getcopy);
  8982. tai_regalloc(hp3).ratype := ra_alloc;
  8983. asml.InsertAfter(hp3, p);
  8984. end;
  8985. ait_instruction:
  8986. case taicpu(hp1).opcode of
  8987. A_JMP:
  8988. begin
  8989. { Change the original jump to the new destination }
  8990. OrigLabel.decrefs;
  8991. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8992. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8993. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8994. if not Assigned(first_assignment) then
  8995. InternalError(2021040810)
  8996. else
  8997. p := first_assignment;
  8998. Exit;
  8999. end;
  9000. A_RET:
  9001. begin
  9002. { Now change the jump into a RET instruction }
  9003. ConvertJumpToRET(p, hp1);
  9004. { Set p to the first duplicated assignment so it can get optimised if needs be }
  9005. if not Assigned(first_assignment) then
  9006. InternalError(2021040811)
  9007. else
  9008. p := first_assignment;
  9009. Exit;
  9010. end;
  9011. else
  9012. begin
  9013. { Duplicate the MOV instruction }
  9014. hp3:=tai(hp1.getcopy);
  9015. if first_assignment = nil then
  9016. first_assignment := hp3;
  9017. asml.InsertBefore(hp3, p);
  9018. { Make sure the compiler knows about any final registers written here }
  9019. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  9020. with taicpu(hp3).oper[OperIdx]^ do
  9021. begin
  9022. case typ of
  9023. top_ref:
  9024. begin
  9025. if (ref^.base <> NR_NO) and
  9026. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  9027. (
  9028. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  9029. (
  9030. { Allow the frame pointer if it's not being used by the procedure as such }
  9031. Assigned(current_procinfo) and
  9032. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  9033. )
  9034. )
  9035. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  9036. then
  9037. begin
  9038. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  9039. if not Assigned(first_assignment) then
  9040. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  9041. end;
  9042. if (ref^.index <> NR_NO) and
  9043. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  9044. (
  9045. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  9046. (
  9047. { Allow the frame pointer if it's not being used by the procedure as such }
  9048. Assigned(current_procinfo) and
  9049. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  9050. )
  9051. )
  9052. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  9053. (ref^.index <> ref^.base) then
  9054. begin
  9055. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  9056. if not Assigned(first_assignment) then
  9057. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  9058. end;
  9059. end;
  9060. top_reg:
  9061. begin
  9062. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  9063. if not Assigned(first_assignment) then
  9064. IncludeRegInUsedRegs(reg, UsedRegs);
  9065. end;
  9066. else
  9067. ;
  9068. end;
  9069. end;
  9070. end;
  9071. end;
  9072. else
  9073. InternalError(2021040720);
  9074. end;
  9075. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  9076. { Should have dropped out earlier }
  9077. InternalError(2021040710);
  9078. end;
  9079. end;
  9080. end;
  9081. const
  9082. WriteOp: array[0..3] of set of TInsChange = (
  9083. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  9084. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  9085. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  9086. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  9087. RegWriteFlags: array[0..7] of set of TInsChange = (
  9088. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  9089. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  9090. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  9091. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  9092. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  9093. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  9094. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  9095. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  9096. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  9097. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  9098. var
  9099. hp2: tai;
  9100. X: Integer;
  9101. begin
  9102. { If we have something like:
  9103. op ###,###
  9104. mov ###,###
  9105. Try to move the MOV instruction to before OP as long as OP and MOV don't
  9106. interfere in regards to what they write to.
  9107. NOTE: p must be a 2-operand instruction
  9108. }
  9109. Result := False;
  9110. if (hp1.typ <> ait_instruction) or
  9111. taicpu(hp1).is_jmp or
  9112. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  9113. Exit;
  9114. { NOP is a pipeline fence, likely marking the beginning of the function
  9115. epilogue, so drop out. Similarly, drop out if POP or RET are
  9116. encountered }
  9117. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  9118. Exit;
  9119. if (taicpu(hp1).opcode = A_MOVSD) and
  9120. (taicpu(hp1).ops = 0) then
  9121. { Wrong MOVSD }
  9122. Exit;
  9123. { Check for writes to specific registers first }
  9124. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9125. for X := 0 to 7 do
  9126. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  9127. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  9128. Exit;
  9129. for X := 0 to taicpu(hp1).ops - 1 do
  9130. begin
  9131. { Check to see if this operand writes to something }
  9132. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  9133. { And matches something in the CMP/TEST instruction }
  9134. (
  9135. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  9136. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  9137. (
  9138. { If it's a register, make sure the register written to doesn't
  9139. appear in the cmp instruction as part of a reference }
  9140. (taicpu(hp1).oper[X]^.typ = top_reg) and
  9141. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  9142. )
  9143. ) then
  9144. Exit;
  9145. end;
  9146. { Check p to make sure it doesn't write to something that affects hp1 }
  9147. { Check for writes to specific registers first }
  9148. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9149. for X := 0 to 7 do
  9150. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  9151. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  9152. Exit;
  9153. for X := 0 to taicpu(p).ops - 1 do
  9154. begin
  9155. { Check to see if this operand writes to something }
  9156. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  9157. { And matches something in hp1 }
  9158. (taicpu(p).oper[X]^.typ = top_reg) and
  9159. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  9160. Exit;
  9161. end;
  9162. { The instruction can be safely moved }
  9163. asml.Remove(hp1);
  9164. { Try to insert after the last instructions where the FLAGS register is not
  9165. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  9166. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  9167. asml.InsertBefore(hp1, hp2)
  9168. { Failing that, try to insert after the last instructions where the
  9169. FLAGS register is not yet in use }
  9170. else if GetLastInstruction(p, hp2) and
  9171. (
  9172. (hp2.typ <> ait_instruction) or
  9173. { Don't insert after an instruction that uses the flags when p doesn't use them }
  9174. RegInInstruction(NR_DEFAULTFLAGS, p) or
  9175. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  9176. ) then
  9177. asml.InsertAfter(hp1, hp2)
  9178. else
  9179. { Note, if p.Previous is nil (even if it should logically never be the
  9180. case), FindRegAllocBackward immediately exits with False and so we
  9181. safely land here (we can't just pass p because FindRegAllocBackward
  9182. immediately exits on an instruction). [Kit] }
  9183. asml.InsertBefore(hp1, p);
  9184. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  9185. { We can't trust UsedRegs because we're looking backwards, although we
  9186. know the registers are allocated after p at the very least, so manually
  9187. create tai_regalloc objects if needed }
  9188. for X := 0 to taicpu(hp1).ops - 1 do
  9189. case taicpu(hp1).oper[X]^.typ of
  9190. top_reg:
  9191. begin
  9192. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  9193. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  9194. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  9195. end;
  9196. top_ref:
  9197. begin
  9198. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  9199. begin
  9200. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  9201. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  9202. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  9203. end;
  9204. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  9205. begin
  9206. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  9207. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  9208. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  9209. end;
  9210. end;
  9211. else
  9212. ;
  9213. end;
  9214. Result := True;
  9215. end;
  9216. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  9217. var
  9218. hp2: tai;
  9219. X: Integer;
  9220. begin
  9221. { If we have something like:
  9222. cmp ###,%reg1
  9223. mov 0,%reg2
  9224. And no modified registers are shared, move the instruction to before
  9225. the comparison as this means it can be optimised without worrying
  9226. about the FLAGS register. (CMP/MOV is generated by
  9227. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  9228. As long as the second instruction doesn't use the flags or one of the
  9229. registers used by CMP or TEST (also check any references that use the
  9230. registers), then it can be moved prior to the comparison.
  9231. }
  9232. Result := False;
  9233. if not TrySwapMovOp(p, hp1) then
  9234. Exit;
  9235. if taicpu(hp1).opcode = A_LEA then
  9236. { The flags will be overwritten by the CMP/TEST instruction }
  9237. ConvertLEA(taicpu(hp1));
  9238. Result := True;
  9239. { Can we move it one further back? }
  9240. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  9241. { Check to see if CMP/TEST is a comparison against zero }
  9242. (
  9243. (
  9244. (taicpu(p).opcode = A_CMP) and
  9245. MatchOperand(taicpu(p).oper[0]^, 0)
  9246. ) or
  9247. (
  9248. (taicpu(p).opcode = A_TEST) and
  9249. (
  9250. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9251. MatchOperand(taicpu(p).oper[0]^, -1)
  9252. )
  9253. )
  9254. ) and
  9255. { These instructions set the zero flag if the result is zero }
  9256. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9257. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9258. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9259. TrySwapMovOp(hp2, hp1);
  9260. end;
  9261. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9262. var
  9263. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9264. JumpLabel: TAsmLabel;
  9265. TmpBool: Boolean;
  9266. begin
  9267. Result := False;
  9268. { Look for:
  9269. stc/clc
  9270. j(c) .L1
  9271. ...
  9272. .L1:
  9273. set(n)cb %reg
  9274. (flags deallocated)
  9275. j(c) .L2
  9276. Change to:
  9277. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9278. j(c) .L2
  9279. }
  9280. p_last := p;
  9281. while GetNextInstruction(p_last, hp1) and
  9282. (hp1.typ = ait_instruction) and
  9283. IsJumpToLabel(taicpu(hp1)) do
  9284. begin
  9285. if DoJumpOptimizations(hp1, TmpBool) then
  9286. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9287. Continue;
  9288. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9289. if not Assigned(JumpLabel) then
  9290. InternalError(2024012801);
  9291. { Optimise the J(c); stc/clc optimisation first since this will
  9292. get missed if the main optimisation takes place }
  9293. if (taicpu(hp1).opcode = A_JCC) then
  9294. begin
  9295. if GetNextInstruction(hp1, hp2) and
  9296. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9297. TryJccStcClcOpt(hp1, hp2) then
  9298. begin
  9299. Result := True;
  9300. Exit;
  9301. end;
  9302. hp2 := nil; { Suppress compiler warning }
  9303. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9304. { Make sure the flags aren't used again }
  9305. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9306. begin
  9307. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9308. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9309. begin
  9310. if (taicpu(p).opcode = A_STC) then
  9311. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9312. else
  9313. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9314. MakeUnconditional(taicpu(hp1));
  9315. { Move the jump to after the flag deallocations }
  9316. Asml.Remove(hp1);
  9317. Asml.InsertAfter(hp1, hp2);
  9318. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9319. Result := True;
  9320. Exit;
  9321. end
  9322. else
  9323. begin
  9324. if (taicpu(p).opcode = A_STC) then
  9325. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9326. else
  9327. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9328. { In this case, the jump is deterministic in that it will never be taken }
  9329. JumpLabel.DecRefs;
  9330. RemoveInstruction(hp1);
  9331. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9332. Result := True;
  9333. Exit;
  9334. end;
  9335. end;
  9336. end;
  9337. hp2 := nil; { Suppress compiler warning }
  9338. if
  9339. { Make sure the carry flag doesn't appear in the jump conditions }
  9340. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9341. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9342. GetNextInstruction(hp2, p_dist) and
  9343. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9344. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9345. begin
  9346. case taicpu(p_dist).opcode of
  9347. A_Jcc:
  9348. begin
  9349. if DoJumpOptimizations(p_dist, TmpBool) then
  9350. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9351. Continue;
  9352. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9353. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9354. begin
  9355. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9356. JumpLabel.decrefs;
  9357. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9358. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9359. Result := True;
  9360. Exit;
  9361. end
  9362. else if GetNextInstruction(p_dist, hp1_dist) and
  9363. (hp1_dist.typ = ait_label) then
  9364. begin
  9365. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9366. JumpLabel.decrefs;
  9367. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9368. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9369. Result := True;
  9370. Exit;
  9371. end;
  9372. end;
  9373. A_SETcc:
  9374. if { Make sure the flags aren't used again }
  9375. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9376. GetNextInstruction(hp2, hp1_dist) and
  9377. (hp1_dist.typ = ait_instruction) and
  9378. IsJumpToLabel(taicpu(hp1_dist)) and
  9379. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9380. { This works if hp1_dist or both are regular JMP instructions }
  9381. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9382. (
  9383. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9384. { Make sure the register isn't still in use, otherwise it
  9385. may get corrupted (fixes #40659) }
  9386. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9387. ) then
  9388. begin
  9389. taicpu(p).allocate_oper(2);
  9390. taicpu(p).ops := 2;
  9391. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9392. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9393. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9394. taicpu(p).opcode := A_MOV;
  9395. taicpu(p).opsize := S_B;
  9396. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9397. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9398. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9399. JumpLabel.decrefs;
  9400. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9401. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9402. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9403. (tai_regalloc(hp2).ratype = ra_alloc) then
  9404. begin
  9405. Asml.Remove(hp2);
  9406. Asml.InsertAfter(hp2, p);
  9407. end;
  9408. Result := True;
  9409. Exit;
  9410. end;
  9411. else
  9412. ;
  9413. end;
  9414. end;
  9415. p_last := hp1;
  9416. end;
  9417. end;
  9418. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9419. var
  9420. hp2, hp3: tai;
  9421. TempBool: Boolean;
  9422. begin
  9423. Result := False;
  9424. {
  9425. j(c) .L1
  9426. stc/clc
  9427. .L1:
  9428. jc/jnc .L2
  9429. (Flags deallocated)
  9430. Change to:
  9431. j)c) .L1
  9432. jmp .L2
  9433. .L1:
  9434. jc/jnc .L2
  9435. Then call DoJumpOptimizations to convert to:
  9436. j(nc) .L2
  9437. .L1: (may become a dead label)
  9438. jc/jnc .L2
  9439. }
  9440. if GetNextInstruction(hp1, hp2) and
  9441. (hp2.typ = ait_label) and
  9442. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9443. GetNextInstruction(hp2, hp3) and
  9444. MatchInstruction(hp3, A_Jcc, []) and
  9445. (
  9446. (
  9447. (taicpu(hp3).condition = C_C) and
  9448. (taicpu(hp1).opcode = A_STC)
  9449. ) or (
  9450. (taicpu(hp3).condition = C_NC) and
  9451. (taicpu(hp1).opcode = A_CLC)
  9452. )
  9453. ) and
  9454. { Make sure the flags aren't used again }
  9455. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9456. begin
  9457. taicpu(hp1).allocate_oper(1);
  9458. taicpu(hp1).ops := 1;
  9459. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9460. taicpu(hp1).opcode := A_JMP;
  9461. taicpu(hp1).is_jmp := True;
  9462. TempBool := True; { Prevent compiler warnings }
  9463. if DoJumpOptimizations(p, TempBool) then
  9464. Result := True
  9465. else
  9466. Include(OptsToCheck, aoc_ForceNewIteration);
  9467. end;
  9468. end;
  9469. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9470. begin
  9471. { This generally only executes under -O3 and above }
  9472. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9473. end;
  9474. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9475. var
  9476. hp1, hp2: tai;
  9477. FoundComparison: Boolean;
  9478. begin
  9479. { Run the pass 1 optimisations as well, since they may have some effect
  9480. after the CMOV blocks are created in OptPass2Jcc }
  9481. Result := False;
  9482. { Result := OptPass1CMOVcc(p);
  9483. if Result then
  9484. Exit;}
  9485. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9486. and make a slightly inefficent result on branching-type blocks, notably
  9487. when setting a function result then jumping to the function epilogue.
  9488. In this case, change:
  9489. cmov(c) %reg1,%reg2
  9490. j(c) @lbl
  9491. (%reg2 deallocated)
  9492. To:
  9493. mov %reg11,%reg2
  9494. j(c) @lbl
  9495. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9496. jump because if it's not present, we may end up with a jump that's
  9497. completely unrelated.
  9498. }
  9499. hp1 := p;
  9500. while GetNextInstruction(hp1, hp1) and
  9501. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9502. if (hp1.typ = ait_instruction) and
  9503. (taicpu(hp1).opcode = A_Jcc) and
  9504. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9505. begin
  9506. TransferUsedRegs(TmpUsedRegs);
  9507. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9508. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9509. (
  9510. { See if we can find a more distant instruction that overwrites
  9511. the destination register }
  9512. (cs_opt_level3 in current_settings.optimizerswitches) and
  9513. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9514. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9515. ) then
  9516. begin
  9517. if (taicpu(p).oper[0]^.typ = top_reg) then
  9518. begin
  9519. { Search backwards to see if the source register is set to a
  9520. constant }
  9521. FoundComparison := False;
  9522. hp1 := p;
  9523. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9524. begin
  9525. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9526. begin
  9527. FoundComparison := True;
  9528. Continue;
  9529. end;
  9530. { Once we find the CMP, TEST or similar instruction, we
  9531. have to stop if we find anything other than a MOV }
  9532. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9533. Break;
  9534. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9535. { Destination register was modified }
  9536. Break;
  9537. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9538. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9539. begin
  9540. { Found a constant! }
  9541. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9542. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9543. { The source register is no longer in use }
  9544. RemoveInstruction(hp1);
  9545. Break;
  9546. end;
  9547. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9548. { Some other instruction has modified the source register }
  9549. Break;
  9550. end;
  9551. end;
  9552. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9553. taicpu(p).opcode := A_MOV;
  9554. taicpu(p).condition := C_None;
  9555. { Rely on the post peephole stage to put the MOV before the
  9556. CMP/TEST instruction that appears prior }
  9557. Result := True;
  9558. Exit;
  9559. end;
  9560. end;
  9561. end;
  9562. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9563. function IsXCHGAcceptable: Boolean; inline;
  9564. begin
  9565. { Always accept if optimising for size }
  9566. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9567. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9568. than 3, so it becomes a saving compared to three MOVs with two of
  9569. them able to execute simultaneously. [Kit] }
  9570. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9571. end;
  9572. var
  9573. NewRef: TReference;
  9574. hp1, hp2, hp3: Tai;
  9575. {$ifndef x86_64}
  9576. hp4: tai;
  9577. OperIdx: Integer;
  9578. {$endif x86_64}
  9579. NewInstr : Taicpu;
  9580. DestLabel: TAsmLabel;
  9581. TempTracking: TAllUsedRegs;
  9582. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9583. var
  9584. NextInstr: tai;
  9585. NextPresent: Boolean;
  9586. begin
  9587. Result := False;
  9588. { be lazy, checking separately for sub would be slightly better }
  9589. if (taicpu(InputInstr).oper[0]^.typ = top_const) and
  9590. (abs(taicpu(InputInstr).oper[0]^.val)<=$7fffffff) then
  9591. begin
  9592. NextPresent := GetNextInstruction(InputInstr, NextInstr);
  9593. if NextPresent then
  9594. begin
  9595. { Try to avoid using TmpUsedRegs if possible (it's slow!) }
  9596. TransferUsedRegs(TmpUsedRegs);
  9597. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9598. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9599. end;
  9600. if (
  9601. not NextPresent or
  9602. (
  9603. { The FLAGS register isn't always tracked properly, so do not
  9604. perform this optimisation if a conditional statement follows }
  9605. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9606. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9607. )
  9608. ) then
  9609. begin
  9610. reference_reset(NewRef, 1, []);
  9611. NewRef.base := taicpu(p).oper[0]^.reg;
  9612. NewRef.scalefactor := 1;
  9613. if taicpu(InputInstr).opcode = A_ADD then
  9614. begin
  9615. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9616. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9617. end
  9618. else
  9619. begin
  9620. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9621. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9622. end;
  9623. taicpu(p).opcode := A_LEA;
  9624. taicpu(p).loadref(0, NewRef);
  9625. { For the sake of debugging, have the line info match the
  9626. arithmetic instruction rather than the MOV instruction }
  9627. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9628. RemoveInstruction(InputInstr);
  9629. Result := True;
  9630. end;
  9631. end;
  9632. end;
  9633. begin
  9634. Result:=false;
  9635. { This optimisation adds an instruction, so only do it for speed }
  9636. if not (cs_opt_size in current_settings.optimizerswitches) and
  9637. MatchOpType(taicpu(p), top_const, top_reg) and
  9638. (taicpu(p).oper[0]^.val = 0) then
  9639. begin
  9640. { To avoid compiler warning }
  9641. DestLabel := nil;
  9642. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9643. InternalError(2021040750);
  9644. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9645. Exit;
  9646. case hp1.typ of
  9647. ait_label:
  9648. begin
  9649. { Change:
  9650. mov $0,%reg mov $0,%reg
  9651. @Lbl1: @Lbl1:
  9652. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9653. je @Lbl2 jne @Lbl2
  9654. To: To:
  9655. mov $0,%reg mov $0,%reg
  9656. jmp @Lbl2 jmp @Lbl3
  9657. (align) (align)
  9658. @Lbl1: @Lbl1:
  9659. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9660. je @Lbl2 je @Lbl2
  9661. @Lbl3: <-- Only if label exists
  9662. (Not if it's optimised for size)
  9663. }
  9664. if not GetNextInstruction(hp1, hp2) then
  9665. Exit;
  9666. if (hp2.typ = ait_instruction) and
  9667. (
  9668. { Register sizes must exactly match }
  9669. (
  9670. (taicpu(hp2).opcode = A_CMP) and
  9671. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9672. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9673. ) or (
  9674. (taicpu(hp2).opcode = A_TEST) and
  9675. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9676. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9677. )
  9678. ) and GetNextInstruction(hp2, hp3) and
  9679. (hp3.typ = ait_instruction) and
  9680. (taicpu(hp3).opcode = A_JCC) and
  9681. (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
  9682. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9683. begin
  9684. { Check condition of jump }
  9685. { Always true? }
  9686. if condition_in(C_E, taicpu(hp3).condition) then
  9687. begin
  9688. { Copy label symbol and obtain matching label entry for the
  9689. conditional jump, as this will be our destination}
  9690. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9691. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9692. Result := True;
  9693. end
  9694. { Always false? }
  9695. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9696. begin
  9697. { This is only worth it if there's a jump to take }
  9698. case hp2.typ of
  9699. ait_instruction:
  9700. begin
  9701. if taicpu(hp2).opcode = A_JMP then
  9702. begin
  9703. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9704. { An unconditional jump follows the conditional jump which will always be false,
  9705. so use this jump's destination for the new jump }
  9706. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9707. Result := True;
  9708. end
  9709. else if taicpu(hp2).opcode = A_JCC then
  9710. begin
  9711. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9712. if condition_in(C_E, taicpu(hp2).condition) then
  9713. begin
  9714. { A second conditional jump follows the conditional jump which will always be false,
  9715. while the second jump is always True, so use this jump's destination for the new jump }
  9716. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9717. Result := True;
  9718. end;
  9719. { Don't risk it if the jump isn't always true (Result remains False) }
  9720. end;
  9721. end;
  9722. else
  9723. { If anything else don't optimise };
  9724. end;
  9725. end;
  9726. if Result then
  9727. begin
  9728. { Just so we have something to insert as a paremeter}
  9729. reference_reset(NewRef, 1, []);
  9730. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9731. { Now actually load the correct parameter (this also
  9732. increases the reference count) }
  9733. NewInstr.loadsymbol(0, DestLabel, 0);
  9734. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9735. begin
  9736. { Get instruction before original label (may not be p under -O3) }
  9737. if not GetLastInstruction(hp1, hp2) then
  9738. { Shouldn't fail here }
  9739. InternalError(2021040701);
  9740. end
  9741. else
  9742. hp2 := p;
  9743. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9744. AsmL.InsertAfter(NewInstr, hp2);
  9745. { Add new alignment field }
  9746. (* AsmL.InsertAfter(
  9747. cai_align.create_max(
  9748. current_settings.alignment.jumpalign,
  9749. current_settings.alignment.jumpalignskipmax
  9750. ),
  9751. NewInstr
  9752. ); *)
  9753. end;
  9754. Exit;
  9755. end;
  9756. end;
  9757. else
  9758. ;
  9759. end;
  9760. end;
  9761. if not GetNextInstruction(p, hp1) then
  9762. Exit;
  9763. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9764. begin
  9765. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9766. begin
  9767. Result := True;
  9768. Exit;
  9769. end;
  9770. { This optimisation is only effective on a second run of Pass 2,
  9771. hence -O3 or above.
  9772. Change:
  9773. mov %reg1,%reg2
  9774. cmp/test (contains %reg1)
  9775. mov x, %reg1
  9776. (another mov or a j(c))
  9777. To:
  9778. mov %reg1,%reg2
  9779. mov x, %reg1
  9780. cmp (%reg1 replaced with %reg2)
  9781. (another mov or a j(c))
  9782. The requirement of an additional MOV or a jump ensures there
  9783. isn't performance loss, since a j(c) will permit macro-fusion
  9784. with the cmp instruction, while another MOV likely means it's
  9785. not all being executed in a single cycle due to parallelisation.
  9786. }
  9787. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9788. MatchOpType(taicpu(p), top_reg, top_reg) and
  9789. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9790. GetNextInstruction(hp1, hp2) and
  9791. MatchInstruction(hp2, A_MOV, []) and
  9792. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9793. { Registers don't have to be the same size in this case }
  9794. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9795. GetNextInstruction(hp2, hp3) and
  9796. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9797. { Make sure the operands in the camparison can be safely replaced }
  9798. (
  9799. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9800. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9801. ) and
  9802. (
  9803. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9804. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9805. ) then
  9806. begin
  9807. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9808. AsmL.Remove(hp2);
  9809. AsmL.InsertAfter(hp2, p);
  9810. Result := True;
  9811. Exit;
  9812. end;
  9813. end;
  9814. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9815. begin
  9816. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9817. further, but we can't just put this jump optimisation in pass 1
  9818. because it tends to perform worse when conditional jumps are
  9819. nearby (e.g. when converting CMOV instructions). [Kit] }
  9820. CopyUsedRegs(TempTracking);
  9821. UpdateUsedRegs(tai(p.Next));
  9822. if OptPass2JMP(hp1) then
  9823. begin
  9824. { Restore register state }
  9825. RestoreUsedRegs(TempTracking);
  9826. ReleaseUsedRegs(TempTracking);
  9827. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9828. OptPass1MOV(p);
  9829. Result := True;
  9830. Exit;
  9831. end;
  9832. { If OptPass2JMP returned False, no optimisations were done to
  9833. the jump and there are no further optimisations that can be done
  9834. to the MOV instruction on this pass other than FuncMov2Func }
  9835. { Restore register state }
  9836. RestoreUsedRegs(TempTracking);
  9837. ReleaseUsedRegs(TempTracking);
  9838. Result := FuncMov2Func(p, hp1);
  9839. Exit;
  9840. end;
  9841. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9842. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9843. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9844. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9845. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9846. begin
  9847. { Change:
  9848. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9849. addl/q $x,%reg2 subl/q $x,%reg2
  9850. To:
  9851. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9852. }
  9853. if TryMovArith2Lea(hp1) then
  9854. begin
  9855. Result := True;
  9856. Exit;
  9857. end
  9858. else if
  9859. { Same as above, but also adds or subtracts to %reg2 in between.
  9860. It's still valid as long as the flags aren't in use }
  9861. (
  9862. (
  9863. MatchInstruction(hp1,A_ADD,A_SUB,A_LEA,[]) and
  9864. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9865. ) or
  9866. (
  9867. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, taicpu(hp1)) and
  9868. { If it's not modified, make sure it isn't read as is }
  9869. not RegReadByInstruction(taicpu(p).oper[1]^.reg, taicpu(hp1))
  9870. )
  9871. ) and
  9872. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9873. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9874. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg) and
  9875. TryMovArith2Lea(hp2) then
  9876. begin
  9877. Result := True;
  9878. Exit;
  9879. end;
  9880. end;
  9881. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9882. {$ifdef x86_64}
  9883. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9884. {$else x86_64}
  9885. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9886. {$endif x86_64}
  9887. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9888. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9889. { mov reg1, reg2 mov reg1, reg2
  9890. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9891. begin
  9892. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9893. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9894. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9895. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9896. TransferUsedRegs(TmpUsedRegs);
  9897. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9898. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9899. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9900. then
  9901. begin
  9902. RemoveCurrentP(p, hp1);
  9903. Result:=true;
  9904. end;
  9905. Exit;
  9906. end;
  9907. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9908. IsXCHGAcceptable and
  9909. { XCHG doesn't support 8-bit registers }
  9910. (taicpu(p).opsize <> S_B) and
  9911. MatchInstruction(hp1, A_MOV, []) and
  9912. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9913. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9914. GetNextInstruction(hp1, hp2) and
  9915. MatchInstruction(hp2, A_MOV, []) and
  9916. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9917. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9918. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9919. begin
  9920. { mov %reg1,%reg2
  9921. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9922. mov %reg2,%reg3
  9923. (%reg2 not used afterwards)
  9924. Note that xchg takes 3 cycles to execute, and generally mov's take
  9925. only one cycle apiece, but the first two mov's can be executed in
  9926. parallel, only taking 2 cycles overall. Older processors should
  9927. therefore only optimise for size. [Kit]
  9928. }
  9929. TransferUsedRegs(TmpUsedRegs);
  9930. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9931. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9932. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9933. begin
  9934. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9935. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9936. taicpu(hp1).opcode := A_XCHG;
  9937. RemoveCurrentP(p, hp1);
  9938. RemoveInstruction(hp2);
  9939. Result := True;
  9940. Exit;
  9941. end;
  9942. end;
  9943. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9944. MatchInstruction(hp1, A_SAR, []) then
  9945. begin
  9946. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9947. begin
  9948. { the use of %edx also covers the opsize being S_L }
  9949. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9950. begin
  9951. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9952. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9953. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9954. begin
  9955. { Change:
  9956. movl %eax,%edx
  9957. sarl $31,%edx
  9958. To:
  9959. cltd
  9960. }
  9961. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9962. RemoveInstruction(hp1);
  9963. taicpu(p).opcode := A_CDQ;
  9964. taicpu(p).opsize := S_NO;
  9965. taicpu(p).clearop(1);
  9966. taicpu(p).clearop(0);
  9967. taicpu(p).ops:=0;
  9968. Result := True;
  9969. Exit;
  9970. end
  9971. else if (cs_opt_size in current_settings.optimizerswitches) and
  9972. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9973. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9974. begin
  9975. { Change:
  9976. movl %edx,%eax
  9977. sarl $31,%edx
  9978. To:
  9979. movl %edx,%eax
  9980. cltd
  9981. Note that this creates a dependency between the two instructions,
  9982. so only perform if optimising for size.
  9983. }
  9984. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9985. taicpu(hp1).opcode := A_CDQ;
  9986. taicpu(hp1).opsize := S_NO;
  9987. taicpu(hp1).clearop(1);
  9988. taicpu(hp1).clearop(0);
  9989. taicpu(hp1).ops:=0;
  9990. Include(OptsToCheck, aoc_ForceNewIteration);
  9991. Exit;
  9992. end;
  9993. {$ifndef x86_64}
  9994. end
  9995. { Don't bother if CMOV is supported, because a more optimal
  9996. sequence would have been generated for the Abs() intrinsic }
  9997. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9998. { the use of %eax also covers the opsize being S_L }
  9999. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  10000. (taicpu(p).oper[0]^.reg = NR_EAX) and
  10001. (taicpu(p).oper[1]^.reg = NR_EDX) and
  10002. GetNextInstruction(hp1, hp2) and
  10003. MatchInstruction(hp2, A_XOR, [S_L]) and
  10004. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  10005. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  10006. GetNextInstruction(hp2, hp3) and
  10007. MatchInstruction(hp3, A_SUB, [S_L]) and
  10008. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  10009. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  10010. begin
  10011. { Change:
  10012. movl %eax,%edx
  10013. sarl $31,%eax
  10014. xorl %eax,%edx
  10015. subl %eax,%edx
  10016. (Instruction that uses %edx)
  10017. (%eax deallocated)
  10018. (%edx deallocated)
  10019. To:
  10020. cltd
  10021. xorl %edx,%eax <-- Note the registers have swapped
  10022. subl %edx,%eax
  10023. (Instruction that uses %eax) <-- %eax rather than %edx
  10024. }
  10025. TransferUsedRegs(TmpUsedRegs);
  10026. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10027. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10028. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10029. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  10030. begin
  10031. if GetNextInstruction(hp3, hp4) and
  10032. not RegModifiedByInstruction(NR_EDX, hp4) and
  10033. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  10034. begin
  10035. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  10036. taicpu(p).opcode := A_CDQ;
  10037. taicpu(p).clearop(1);
  10038. taicpu(p).clearop(0);
  10039. taicpu(p).ops:=0;
  10040. RemoveInstruction(hp1);
  10041. taicpu(hp2).loadreg(0, NR_EDX);
  10042. taicpu(hp2).loadreg(1, NR_EAX);
  10043. taicpu(hp3).loadreg(0, NR_EDX);
  10044. taicpu(hp3).loadreg(1, NR_EAX);
  10045. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  10046. { Convert references in the following instruction (hp4) from %edx to %eax }
  10047. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  10048. with taicpu(hp4).oper[OperIdx]^ do
  10049. case typ of
  10050. top_reg:
  10051. if getsupreg(reg) = RS_EDX then
  10052. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  10053. top_ref:
  10054. begin
  10055. if getsupreg(reg) = RS_EDX then
  10056. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  10057. if getsupreg(reg) = RS_EDX then
  10058. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  10059. end;
  10060. else
  10061. ;
  10062. end;
  10063. Result := True;
  10064. Exit;
  10065. end;
  10066. end;
  10067. {$else x86_64}
  10068. end;
  10069. end
  10070. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  10071. { the use of %rdx also covers the opsize being S_Q }
  10072. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  10073. begin
  10074. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  10075. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  10076. (taicpu(p).oper[1]^.reg = NR_RDX) then
  10077. begin
  10078. { Change:
  10079. movq %rax,%rdx
  10080. sarq $63,%rdx
  10081. To:
  10082. cqto
  10083. }
  10084. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  10085. RemoveInstruction(hp1);
  10086. taicpu(p).opcode := A_CQO;
  10087. taicpu(p).opsize := S_NO;
  10088. taicpu(p).clearop(1);
  10089. taicpu(p).clearop(0);
  10090. taicpu(p).ops:=0;
  10091. Result := True;
  10092. Exit;
  10093. end
  10094. else if (cs_opt_size in current_settings.optimizerswitches) and
  10095. (taicpu(p).oper[0]^.reg = NR_RDX) and
  10096. (taicpu(p).oper[1]^.reg = NR_RAX) then
  10097. begin
  10098. { Change:
  10099. movq %rdx,%rax
  10100. sarq $63,%rdx
  10101. To:
  10102. movq %rdx,%rax
  10103. cqto
  10104. Note that this creates a dependency between the two instructions,
  10105. so only perform if optimising for size.
  10106. }
  10107. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  10108. taicpu(hp1).opcode := A_CQO;
  10109. taicpu(hp1).opsize := S_NO;
  10110. taicpu(hp1).clearop(1);
  10111. taicpu(hp1).clearop(0);
  10112. taicpu(hp1).ops:=0;
  10113. Include(OptsToCheck, aoc_ForceNewIteration);
  10114. Exit;
  10115. {$endif x86_64}
  10116. end;
  10117. end;
  10118. end;
  10119. if MatchInstruction(hp1, A_MOV, []) and
  10120. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10121. { Though "GetNextInstruction" could be factored out, along with
  10122. the instructions that depend on hp2, it is an expensive call that
  10123. should be delayed for as long as possible, hence we do cheaper
  10124. checks first that are likely to be False. [Kit] }
  10125. begin
  10126. if (
  10127. (
  10128. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  10129. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  10130. (
  10131. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10132. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  10133. )
  10134. ) or
  10135. (
  10136. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  10137. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  10138. (
  10139. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10140. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  10141. )
  10142. )
  10143. ) and
  10144. GetNextInstruction(hp1, hp2) and
  10145. MatchInstruction(hp2, A_SAR, []) and
  10146. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  10147. begin
  10148. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  10149. begin
  10150. { Change:
  10151. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  10152. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  10153. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  10154. To:
  10155. movl r/m,%eax <- Note the change in register
  10156. cltd
  10157. }
  10158. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  10159. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  10160. taicpu(p).loadreg(1, NR_EAX);
  10161. taicpu(hp1).opcode := A_CDQ;
  10162. taicpu(hp1).clearop(1);
  10163. taicpu(hp1).clearop(0);
  10164. taicpu(hp1).ops:=0;
  10165. RemoveInstruction(hp2);
  10166. Include(OptsToCheck, aoc_ForceNewIteration);
  10167. (*
  10168. {$ifdef x86_64}
  10169. end
  10170. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  10171. { This code sequence does not get generated - however it might become useful
  10172. if and when 128-bit signed integer types make an appearance, so the code
  10173. is kept here for when it is eventually needed. [Kit] }
  10174. (
  10175. (
  10176. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  10177. (
  10178. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10179. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  10180. )
  10181. ) or
  10182. (
  10183. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  10184. (
  10185. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10186. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  10187. )
  10188. )
  10189. ) and
  10190. GetNextInstruction(hp1, hp2) and
  10191. MatchInstruction(hp2, A_SAR, [S_Q]) and
  10192. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  10193. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  10194. begin
  10195. { Change:
  10196. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  10197. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  10198. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  10199. To:
  10200. movq r/m,%rax <- Note the change in register
  10201. cqto
  10202. }
  10203. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  10204. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  10205. taicpu(p).loadreg(1, NR_RAX);
  10206. taicpu(hp1).opcode := A_CQO;
  10207. taicpu(hp1).clearop(1);
  10208. taicpu(hp1).clearop(0);
  10209. taicpu(hp1).ops:=0;
  10210. RemoveInstruction(hp2);
  10211. Include(OptsToCheck, aoc_ForceNewIteration);
  10212. {$endif x86_64}
  10213. *)
  10214. end;
  10215. end;
  10216. {$ifdef x86_64}
  10217. end;
  10218. if (taicpu(p).opsize = S_L) and
  10219. (taicpu(p).oper[1]^.typ = top_reg) and
  10220. (
  10221. MatchInstruction(hp1, A_MOV,[]) and
  10222. (taicpu(hp1).opsize = S_L) and
  10223. (taicpu(hp1).oper[1]^.typ = top_reg)
  10224. ) and (
  10225. GetNextInstruction(hp1, hp2) and
  10226. (tai(hp2).typ=ait_instruction) and
  10227. (taicpu(hp2).opsize = S_Q) and
  10228. (
  10229. (
  10230. MatchInstruction(hp2, A_ADD,[]) and
  10231. (taicpu(hp2).opsize = S_Q) and
  10232. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10233. (
  10234. (
  10235. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10236. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10237. ) or (
  10238. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10239. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10240. )
  10241. )
  10242. ) or (
  10243. MatchInstruction(hp2, A_LEA,[]) and
  10244. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  10245. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  10246. (
  10247. (
  10248. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10249. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10250. ) or (
  10251. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10252. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  10253. )
  10254. ) and (
  10255. (
  10256. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10257. ) or (
  10258. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10259. )
  10260. )
  10261. )
  10262. )
  10263. ) and (
  10264. GetNextInstruction(hp2, hp3) and
  10265. MatchInstruction(hp3, A_SHR,[]) and
  10266. (taicpu(hp3).opsize = S_Q) and
  10267. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10268. (taicpu(hp3).oper[0]^.val = 1) and
  10269. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10270. ) then
  10271. begin
  10272. { Change movl x, reg1d movl x, reg1d
  10273. movl y, reg2d movl y, reg2d
  10274. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10275. shrq $1, reg1q shrq $1, reg1q
  10276. ( reg1d and reg2d can be switched around in the first two instructions )
  10277. To movl x, reg1d
  10278. addl y, reg1d
  10279. rcrl $1, reg1d
  10280. This corresponds to the common expression (x + y) shr 1, where
  10281. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10282. smaller code, but won't account for x + y causing an overflow). [Kit]
  10283. }
  10284. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10285. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10286. begin
  10287. { Change first MOV command to have the same register as the final output }
  10288. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10289. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10290. Result := True;
  10291. end
  10292. else
  10293. begin
  10294. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10295. Include(OptsToCheck, aoc_ForceNewIteration);
  10296. end;
  10297. { Change second MOV command to an ADD command. This is easier than
  10298. converting the existing command because it means we don't have to
  10299. touch 'y', which might be a complicated reference, and also the
  10300. fact that the third command might either be ADD or LEA. [Kit] }
  10301. taicpu(hp1).opcode := A_ADD;
  10302. { Delete old ADD/LEA instruction }
  10303. RemoveInstruction(hp2);
  10304. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10305. taicpu(hp3).opcode := A_RCR;
  10306. taicpu(hp3).changeopsize(S_L);
  10307. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10308. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10309. called, so FuncMov2Func below is safe to call }
  10310. {$endif x86_64}
  10311. end;
  10312. {$ifdef x86_64}
  10313. { Note, this optimisation was moved from Pass 1 because the CMOV
  10314. optimisations in OptPass2Jcc fall foul of the loss of information
  10315. about the upper 32 bits of the target register. Fixes #41317. }
  10316. { Change:
  10317. movl %reg1l,%reg2l
  10318. movq %reg2q,%reg3q (%reg1 <> %reg3)
  10319. To:
  10320. movl %reg1l,%reg2l
  10321. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  10322. }
  10323. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10324. (taicpu(p).opsize = S_L) then
  10325. begin
  10326. TransferUsedRegs(TmpUsedRegs);
  10327. { Mark the start point for sequential calls to
  10328. GetNextInstructionUsingReg, RegModifiedBetween and
  10329. UpdateUsedRegsBetween in case this optimisation is run multiple
  10330. times }
  10331. hp2 := p;
  10332. repeat
  10333. if (
  10334. not(cs_opt_level3 in current_settings.optimizerswitches) or
  10335. { Look further ahead for this one }
  10336. GetNextInstructionUsingReg(hp2, hp1, taicpu(p).oper[1]^.reg)
  10337. ) and
  10338. MatchInstruction(hp1,A_MOV,[S_Q]) and
  10339. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp2, hp1) and
  10340. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10341. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  10342. begin
  10343. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp2.Next), hp1);
  10344. taicpu(hp1).opsize := S_L;
  10345. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  10346. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10347. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  10348. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  10349. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  10350. begin
  10351. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  10352. RemoveCurrentP(p);
  10353. Result := True;
  10354. Exit;
  10355. end;
  10356. { Initial instruction wasn't actually changed }
  10357. Include(OptsToCheck, aoc_ForceNewIteration);
  10358. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10359. begin
  10360. { GetNextInstructionUsingReg will return a different
  10361. instruction, so check this optimisation again }
  10362. { Update the start point for the next calls to
  10363. GetNextInstructionUsingReg, RegModifiedBetween and
  10364. UpdateUsedRegsBetween to grant a speed boost }
  10365. hp2 := hp1;
  10366. Continue; { Jump back to "repeat" }
  10367. end;
  10368. end;
  10369. Break;
  10370. until False;
  10371. end;
  10372. {$endif x86_64}
  10373. if FuncMov2Func(p, hp1) then
  10374. begin
  10375. Result := True;
  10376. Exit;
  10377. end;
  10378. end;
  10379. {$push}
  10380. {$q-}{$r-}
  10381. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10382. var
  10383. ThisReg: TRegister;
  10384. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10385. TargetSubReg: TSubRegister;
  10386. hp1, hp2: tai;
  10387. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10388. { Store list of found instructions so we don't have to call
  10389. GetNextInstructionUsingReg multiple times }
  10390. InstrList: array of taicpu;
  10391. InstrMax, Index: Integer;
  10392. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10393. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10394. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10395. WorkingValue: TCgInt;
  10396. PreMessage: string;
  10397. { Data flow analysis }
  10398. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10399. BitwiseOnly, OrXorUsed,
  10400. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10401. function CheckOverflowConditions: Boolean;
  10402. begin
  10403. Result := True;
  10404. if (TestValSignedMax > SignedUpperLimit) then
  10405. UpperSignedOverflow := True;
  10406. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10407. LowerSignedOverflow := True;
  10408. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10409. LowerUnsignedOverflow := True;
  10410. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10411. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10412. begin
  10413. { Absolute overflow }
  10414. Result := False;
  10415. Exit;
  10416. end;
  10417. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10418. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10419. ShiftDownOverflow := True;
  10420. if (TestValMin < 0) or (TestValMax < 0) then
  10421. begin
  10422. LowerUnsignedOverflow := True;
  10423. UpperUnsignedOverflow := True;
  10424. end;
  10425. end;
  10426. function AdjustInitialLoadAndSize: Boolean;
  10427. begin
  10428. Result := False;
  10429. if not p_removed then
  10430. begin
  10431. if TargetSize = MinSize then
  10432. begin
  10433. { Convert the input MOVZX to a MOV }
  10434. if (taicpu(p).oper[0]^.typ = top_reg) and
  10435. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10436. begin
  10437. { Or remove it completely! }
  10438. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10439. RemoveCurrentP(p);
  10440. p_removed := True;
  10441. end
  10442. else
  10443. begin
  10444. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10445. taicpu(p).opcode := A_MOV;
  10446. taicpu(p).oper[1]^.reg := ThisReg;
  10447. taicpu(p).opsize := TargetSize;
  10448. end;
  10449. Result := True;
  10450. end
  10451. else if TargetSize <> MaxSize then
  10452. begin
  10453. case MaxSize of
  10454. S_L:
  10455. if TargetSize = S_W then
  10456. begin
  10457. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10458. taicpu(p).opsize := S_BW;
  10459. taicpu(p).oper[1]^.reg := ThisReg;
  10460. Result := True;
  10461. end
  10462. else
  10463. InternalError(2020112341);
  10464. S_W:
  10465. if TargetSize = S_L then
  10466. begin
  10467. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10468. taicpu(p).opsize := S_BL;
  10469. taicpu(p).oper[1]^.reg := ThisReg;
  10470. Result := True;
  10471. end
  10472. else
  10473. InternalError(2020112342);
  10474. else
  10475. ;
  10476. end;
  10477. end
  10478. else if not hp1_removed and not RegInUse then
  10479. begin
  10480. { If we have something like:
  10481. movzbl (oper),%regd
  10482. add x, %regd
  10483. movzbl %regb, %regd
  10484. We can reduce the register size to the input of the final
  10485. movzbl instruction. Overflows won't have any effect.
  10486. }
  10487. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10488. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10489. begin
  10490. TargetSize := S_B;
  10491. setsubreg(ThisReg, R_SUBL);
  10492. Result := True;
  10493. end
  10494. else if (taicpu(p).opsize = S_WL) and
  10495. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10496. begin
  10497. TargetSize := S_W;
  10498. setsubreg(ThisReg, R_SUBW);
  10499. Result := True;
  10500. end;
  10501. if Result then
  10502. begin
  10503. { Convert the input MOVZX to a MOV }
  10504. if (taicpu(p).oper[0]^.typ = top_reg) and
  10505. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10506. begin
  10507. { Or remove it completely! }
  10508. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10509. RemoveCurrentP(p);
  10510. p_removed := True;
  10511. end
  10512. else
  10513. begin
  10514. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10515. taicpu(p).opcode := A_MOV;
  10516. taicpu(p).oper[1]^.reg := ThisReg;
  10517. taicpu(p).opsize := TargetSize;
  10518. end;
  10519. end;
  10520. end;
  10521. end;
  10522. end;
  10523. procedure AdjustFinalLoad;
  10524. begin
  10525. if not LowerUnsignedOverflow then
  10526. begin
  10527. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10528. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10529. begin
  10530. { Convert the output MOVZX to a MOV }
  10531. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10532. begin
  10533. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10534. if (MinSize = S_B) or
  10535. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10536. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10537. begin
  10538. { Remove it completely! }
  10539. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10540. { Be careful; if p = hp1 and p was also removed, p
  10541. will become a dangling pointer }
  10542. if p = hp1 then
  10543. begin
  10544. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10545. p_removed := True;
  10546. end
  10547. else
  10548. RemoveInstruction(hp1);
  10549. hp1_removed := True;
  10550. end;
  10551. end
  10552. else
  10553. begin
  10554. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10555. taicpu(hp1).opcode := A_MOV;
  10556. taicpu(hp1).oper[0]^.reg := ThisReg;
  10557. taicpu(hp1).opsize := TargetSize;
  10558. end;
  10559. end
  10560. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10561. begin
  10562. { Need to change the size of the output }
  10563. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10564. taicpu(hp1).oper[0]^.reg := ThisReg;
  10565. taicpu(hp1).opsize := S_BL;
  10566. end;
  10567. end;
  10568. end;
  10569. function CompressInstructions: Boolean;
  10570. var
  10571. LocalIndex: Integer;
  10572. begin
  10573. Result := False;
  10574. { The objective here is to try to find a combination that
  10575. removes one of the MOV/Z instructions. }
  10576. if (
  10577. (taicpu(p).oper[0]^.typ <> top_reg) or
  10578. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10579. ) and
  10580. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10581. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10582. begin
  10583. { Make a preference to remove the second MOVZX instruction }
  10584. case taicpu(hp1).opsize of
  10585. S_BL, S_WL:
  10586. begin
  10587. TargetSize := S_L;
  10588. TargetSubReg := R_SUBD;
  10589. end;
  10590. S_BW:
  10591. begin
  10592. TargetSize := S_W;
  10593. TargetSubReg := R_SUBW;
  10594. end;
  10595. else
  10596. InternalError(2020112302);
  10597. end;
  10598. end
  10599. else
  10600. begin
  10601. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10602. begin
  10603. { Exceeded lower bound but not upper bound }
  10604. TargetSize := MaxSize;
  10605. end
  10606. else if not LowerUnsignedOverflow then
  10607. begin
  10608. { Size didn't exceed lower bound }
  10609. TargetSize := MinSize;
  10610. end
  10611. else
  10612. Exit;
  10613. end;
  10614. case TargetSize of
  10615. S_B:
  10616. TargetSubReg := R_SUBL;
  10617. S_W:
  10618. TargetSubReg := R_SUBW;
  10619. S_L:
  10620. TargetSubReg := R_SUBD;
  10621. else
  10622. InternalError(2020112350);
  10623. end;
  10624. { Update the register to its new size }
  10625. setsubreg(ThisReg, TargetSubReg);
  10626. RegInUse := False;
  10627. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10628. begin
  10629. { Check to see if the active register is used afterwards;
  10630. if not, we can change it and make a saving. }
  10631. TransferUsedRegs(TmpUsedRegs);
  10632. { The target register may be marked as in use to cross
  10633. a jump to a distant label, so exclude it }
  10634. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10635. hp2 := p;
  10636. repeat
  10637. { Explicitly check for the excluded register (don't include the first
  10638. instruction as it may be reading from here }
  10639. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10640. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10641. begin
  10642. RegInUse := True;
  10643. Break;
  10644. end;
  10645. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10646. if not GetNextInstruction(hp2, hp2) then
  10647. InternalError(2020112340);
  10648. until (hp2 = hp1);
  10649. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10650. { We might still be able to get away with this }
  10651. RegInUse := not
  10652. (
  10653. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10654. (hp2.typ = ait_instruction) and
  10655. (
  10656. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10657. instruction that doesn't actually contain ThisReg }
  10658. (cs_opt_level3 in current_settings.optimizerswitches) or
  10659. RegInInstruction(ThisReg, hp2)
  10660. ) and
  10661. RegLoadedWithNewValue(ThisReg, hp2)
  10662. );
  10663. if not RegInUse then
  10664. begin
  10665. { Force the register size to the same as this instruction so it can be removed}
  10666. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10667. begin
  10668. TargetSize := S_L;
  10669. TargetSubReg := R_SUBD;
  10670. end
  10671. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10672. begin
  10673. TargetSize := S_W;
  10674. TargetSubReg := R_SUBW;
  10675. end;
  10676. ThisReg := taicpu(hp1).oper[1]^.reg;
  10677. setsubreg(ThisReg, TargetSubReg);
  10678. RegChanged := True;
  10679. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10680. TransferUsedRegs(TmpUsedRegs);
  10681. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10682. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10683. if p = hp1 then
  10684. begin
  10685. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10686. p_removed := True;
  10687. end
  10688. else
  10689. RemoveInstruction(hp1);
  10690. hp1_removed := True;
  10691. { Instruction will become "mov %reg,%reg" }
  10692. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10693. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10694. begin
  10695. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10696. RemoveCurrentP(p);
  10697. p_removed := True;
  10698. end
  10699. else
  10700. taicpu(p).oper[1]^.reg := ThisReg;
  10701. Result := True;
  10702. end
  10703. else
  10704. begin
  10705. if TargetSize <> MaxSize then
  10706. begin
  10707. { Since the register is in use, we have to force it to
  10708. MaxSize otherwise part of it may become undefined later on }
  10709. TargetSize := MaxSize;
  10710. case TargetSize of
  10711. S_B:
  10712. TargetSubReg := R_SUBL;
  10713. S_W:
  10714. TargetSubReg := R_SUBW;
  10715. S_L:
  10716. TargetSubReg := R_SUBD;
  10717. else
  10718. InternalError(2020112351);
  10719. end;
  10720. setsubreg(ThisReg, TargetSubReg);
  10721. end;
  10722. AdjustFinalLoad;
  10723. end;
  10724. end
  10725. else
  10726. AdjustFinalLoad;
  10727. Result := AdjustInitialLoadAndSize or Result;
  10728. { Now go through every instruction we found and change the
  10729. size. If TargetSize = MaxSize, then almost no changes are
  10730. needed and Result can remain False if it hasn't been set
  10731. yet.
  10732. If RegChanged is True, then the register requires changing
  10733. and so the point about TargetSize = MaxSize doesn't apply. }
  10734. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10735. begin
  10736. for LocalIndex := 0 to InstrMax do
  10737. begin
  10738. { If p_removed is true, then the original MOV/Z was removed
  10739. and removing the AND instruction may not be safe if it
  10740. appears first }
  10741. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10742. InternalError(2020112310);
  10743. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10744. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10745. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10746. InstrList[LocalIndex].opsize := TargetSize;
  10747. end;
  10748. Result := True;
  10749. end;
  10750. end;
  10751. begin
  10752. Result := False;
  10753. p_removed := False;
  10754. hp1_removed := False;
  10755. ThisReg := taicpu(p).oper[1]^.reg;
  10756. { Check for:
  10757. movs/z ###,%ecx (or %cx or %rcx)
  10758. ...
  10759. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10760. (dealloc %ecx)
  10761. Change to:
  10762. mov ###,%cl (if ### = %cl, then remove completely)
  10763. ...
  10764. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10765. }
  10766. if (getsupreg(ThisReg) = RS_ECX) and
  10767. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10768. (hp1.typ = ait_instruction) and
  10769. (
  10770. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10771. instruction that doesn't actually contain ECX }
  10772. (cs_opt_level3 in current_settings.optimizerswitches) or
  10773. RegInInstruction(NR_ECX, hp1) or
  10774. (
  10775. { It's common for the shift/rotate's read/write register to be
  10776. initialised in between, so under -O2 and under, search ahead
  10777. one more instruction
  10778. }
  10779. GetNextInstruction(hp1, hp1) and
  10780. (hp1.typ = ait_instruction) and
  10781. RegInInstruction(NR_ECX, hp1)
  10782. )
  10783. ) and
  10784. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10785. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10786. begin
  10787. TransferUsedRegs(TmpUsedRegs);
  10788. hp2 := p;
  10789. repeat
  10790. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10791. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10792. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10793. begin
  10794. case taicpu(p).opsize of
  10795. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10796. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10797. begin
  10798. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10799. RemoveCurrentP(p);
  10800. end
  10801. else
  10802. begin
  10803. taicpu(p).opcode := A_MOV;
  10804. taicpu(p).opsize := S_B;
  10805. taicpu(p).oper[1]^.reg := NR_CL;
  10806. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10807. end;
  10808. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10809. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10810. begin
  10811. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10812. RemoveCurrentP(p);
  10813. end
  10814. else
  10815. begin
  10816. taicpu(p).opcode := A_MOV;
  10817. taicpu(p).opsize := S_W;
  10818. taicpu(p).oper[1]^.reg := NR_CX;
  10819. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10820. end;
  10821. {$ifdef x86_64}
  10822. S_LQ:
  10823. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10824. begin
  10825. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10826. RemoveCurrentP(p);
  10827. end
  10828. else
  10829. begin
  10830. taicpu(p).opcode := A_MOV;
  10831. taicpu(p).opsize := S_L;
  10832. taicpu(p).oper[1]^.reg := NR_ECX;
  10833. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10834. end;
  10835. {$endif x86_64}
  10836. else
  10837. InternalError(2021120401);
  10838. end;
  10839. Result := True;
  10840. Exit;
  10841. end;
  10842. end;
  10843. { This is anything but quick! }
  10844. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10845. Exit;
  10846. SetLength(InstrList, 0);
  10847. InstrMax := -1;
  10848. case taicpu(p).opsize of
  10849. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10850. begin
  10851. {$if defined(i386) or defined(i8086)}
  10852. { If the target size is 8-bit, make sure we can actually encode it }
  10853. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10854. Exit;
  10855. {$endif i386 or i8086}
  10856. LowerLimit := $FF;
  10857. SignedLowerLimit := $7F;
  10858. SignedLowerLimitBottom := -128;
  10859. MinSize := S_B;
  10860. if taicpu(p).opsize = S_BW then
  10861. begin
  10862. MaxSize := S_W;
  10863. UpperLimit := $FFFF;
  10864. SignedUpperLimit := $7FFF;
  10865. SignedUpperLimitBottom := -32768;
  10866. end
  10867. else
  10868. begin
  10869. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10870. MaxSize := S_L;
  10871. UpperLimit := $FFFFFFFF;
  10872. SignedUpperLimit := $7FFFFFFF;
  10873. SignedUpperLimitBottom := -2147483648;
  10874. end;
  10875. end;
  10876. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10877. begin
  10878. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10879. LowerLimit := $FFFF;
  10880. SignedLowerLimit := $7FFF;
  10881. SignedLowerLimitBottom := -32768;
  10882. UpperLimit := $FFFFFFFF;
  10883. SignedUpperLimit := $7FFFFFFF;
  10884. SignedUpperLimitBottom := -2147483648;
  10885. MinSize := S_W;
  10886. MaxSize := S_L;
  10887. end;
  10888. {$ifdef x86_64}
  10889. S_LQ:
  10890. begin
  10891. { Both the lower and upper limits are set to 32-bit. If a limit
  10892. is breached, then optimisation is impossible }
  10893. LowerLimit := $FFFFFFFF;
  10894. SignedLowerLimit := $7FFFFFFF;
  10895. SignedLowerLimitBottom := -2147483648;
  10896. UpperLimit := $FFFFFFFF;
  10897. SignedUpperLimit := $7FFFFFFF;
  10898. SignedUpperLimitBottom := -2147483648;
  10899. MinSize := S_L;
  10900. MaxSize := S_L;
  10901. end;
  10902. {$endif x86_64}
  10903. else
  10904. InternalError(2020112301);
  10905. end;
  10906. TestValMin := 0;
  10907. TestValMax := LowerLimit;
  10908. TestValSignedMax := SignedLowerLimit;
  10909. TryShiftDownLimit := LowerLimit;
  10910. TryShiftDown := S_NO;
  10911. ShiftDownOverflow := False;
  10912. RegChanged := False;
  10913. BitwiseOnly := True;
  10914. OrXorUsed := False;
  10915. UpperSignedOverflow := False;
  10916. LowerSignedOverflow := False;
  10917. UpperUnsignedOverflow := False;
  10918. LowerUnsignedOverflow := False;
  10919. hp1 := p;
  10920. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10921. (hp1.typ = ait_instruction) and
  10922. (
  10923. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10924. instruction that doesn't actually contain ThisReg }
  10925. (cs_opt_level3 in current_settings.optimizerswitches) or
  10926. { This allows this Movx optimisation to work through the SETcc instructions
  10927. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10928. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10929. skip over these SETcc instructions). }
  10930. (taicpu(hp1).opcode = A_SETcc) or
  10931. RegInInstruction(ThisReg, hp1)
  10932. ) do
  10933. begin
  10934. case taicpu(hp1).opcode of
  10935. A_INC,A_DEC:
  10936. begin
  10937. { Has to be an exact match on the register }
  10938. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10939. Break;
  10940. if taicpu(hp1).opcode = A_INC then
  10941. begin
  10942. Inc(TestValMin);
  10943. Inc(TestValMax);
  10944. Inc(TestValSignedMax);
  10945. end
  10946. else
  10947. begin
  10948. Dec(TestValMin);
  10949. Dec(TestValMax);
  10950. Dec(TestValSignedMax);
  10951. end;
  10952. end;
  10953. A_TEST, A_CMP:
  10954. begin
  10955. if (
  10956. { Too high a risk of non-linear behaviour that breaks DFA
  10957. here, unless it's cmp $0,%reg, which is equivalent to
  10958. test %reg,%reg }
  10959. OrXorUsed and
  10960. (taicpu(hp1).opcode = A_CMP) and
  10961. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10962. ) or
  10963. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10964. { Has to be an exact match on the register }
  10965. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10966. (
  10967. { Permit "test %reg,%reg" }
  10968. (taicpu(hp1).opcode = A_TEST) and
  10969. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10970. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10971. ) or
  10972. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10973. { Make sure the comparison value is not smaller than the
  10974. smallest allowed signed value for the minimum size (e.g.
  10975. -128 for 8-bit) }
  10976. not (
  10977. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10978. { Is it in the negative range? }
  10979. (
  10980. (taicpu(hp1).oper[0]^.val < 0) and
  10981. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10982. )
  10983. ) then
  10984. Break;
  10985. { Check to see if the active register is used afterwards }
  10986. TransferUsedRegs(TmpUsedRegs);
  10987. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10988. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10989. begin
  10990. { Make sure the comparison or any previous instructions
  10991. hasn't pushed the test values outside of the range of
  10992. MinSize }
  10993. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10994. begin
  10995. { Exceeded lower bound but not upper bound }
  10996. Exit;
  10997. end
  10998. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10999. begin
  11000. { Size didn't exceed lower bound }
  11001. TargetSize := MinSize;
  11002. end
  11003. else
  11004. Break;
  11005. case TargetSize of
  11006. S_B:
  11007. TargetSubReg := R_SUBL;
  11008. S_W:
  11009. TargetSubReg := R_SUBW;
  11010. S_L:
  11011. TargetSubReg := R_SUBD;
  11012. else
  11013. InternalError(2021051002);
  11014. end;
  11015. if TargetSize <> MaxSize then
  11016. begin
  11017. { Update the register to its new size }
  11018. setsubreg(ThisReg, TargetSubReg);
  11019. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  11020. taicpu(hp1).oper[1]^.reg := ThisReg;
  11021. taicpu(hp1).opsize := TargetSize;
  11022. { Convert the input MOVZX to a MOV if necessary }
  11023. AdjustInitialLoadAndSize;
  11024. if (InstrMax >= 0) then
  11025. begin
  11026. for Index := 0 to InstrMax do
  11027. begin
  11028. { If p_removed is true, then the original MOV/Z was removed
  11029. and removing the AND instruction may not be safe if it
  11030. appears first }
  11031. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  11032. InternalError(2020112311);
  11033. if InstrList[Index].oper[0]^.typ = top_reg then
  11034. InstrList[Index].oper[0]^.reg := ThisReg;
  11035. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  11036. InstrList[Index].opsize := MinSize;
  11037. end;
  11038. end;
  11039. Result := True;
  11040. end;
  11041. Exit;
  11042. end;
  11043. end;
  11044. A_SETcc:
  11045. begin
  11046. { This allows this Movx optimisation to work through the SETcc instructions
  11047. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  11048. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  11049. skip over these SETcc instructions). }
  11050. if (cs_opt_level3 in current_settings.optimizerswitches) or
  11051. { Of course, break out if the current register is used }
  11052. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  11053. Break
  11054. else
  11055. { We must use Continue so the instruction doesn't get added
  11056. to InstrList }
  11057. Continue;
  11058. end;
  11059. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  11060. begin
  11061. if
  11062. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  11063. { Has to be an exact match on the register }
  11064. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  11065. (
  11066. (
  11067. (taicpu(hp1).oper[0]^.typ = top_const) and
  11068. (
  11069. (
  11070. (taicpu(hp1).opcode = A_SHL) and
  11071. (
  11072. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  11073. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  11074. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  11075. )
  11076. ) or (
  11077. (taicpu(hp1).opcode <> A_SHL) and
  11078. (
  11079. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11080. { Is it in the negative range? }
  11081. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  11082. )
  11083. )
  11084. )
  11085. ) or (
  11086. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  11087. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  11088. )
  11089. ) then
  11090. Break;
  11091. { Only process OR and XOR if there are only bitwise operations,
  11092. since otherwise they can too easily fool the data flow
  11093. analysis (they can cause non-linear behaviour) }
  11094. case taicpu(hp1).opcode of
  11095. A_ADD:
  11096. begin
  11097. if OrXorUsed then
  11098. { Too high a risk of non-linear behaviour that breaks DFA here }
  11099. Break
  11100. else
  11101. BitwiseOnly := False;
  11102. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11103. begin
  11104. TestValMin := TestValMin * 2;
  11105. TestValMax := TestValMax * 2;
  11106. TestValSignedMax := TestValSignedMax * 2;
  11107. end
  11108. else
  11109. begin
  11110. WorkingValue := taicpu(hp1).oper[0]^.val;
  11111. TestValMin := TestValMin + WorkingValue;
  11112. TestValMax := TestValMax + WorkingValue;
  11113. TestValSignedMax := TestValSignedMax + WorkingValue;
  11114. end;
  11115. end;
  11116. A_SUB:
  11117. begin
  11118. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11119. begin
  11120. TestValMin := 0;
  11121. TestValMax := 0;
  11122. TestValSignedMax := 0;
  11123. end
  11124. else
  11125. begin
  11126. if OrXorUsed then
  11127. { Too high a risk of non-linear behaviour that breaks DFA here }
  11128. Break
  11129. else
  11130. BitwiseOnly := False;
  11131. WorkingValue := taicpu(hp1).oper[0]^.val;
  11132. TestValMin := TestValMin - WorkingValue;
  11133. TestValMax := TestValMax - WorkingValue;
  11134. TestValSignedMax := TestValSignedMax - WorkingValue;
  11135. end;
  11136. end;
  11137. A_AND:
  11138. if (taicpu(hp1).oper[0]^.typ = top_const) then
  11139. begin
  11140. { we might be able to go smaller if AND appears first }
  11141. if InstrMax = -1 then
  11142. case MinSize of
  11143. S_B:
  11144. ;
  11145. S_W:
  11146. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  11147. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  11148. begin
  11149. TryShiftDown := S_B;
  11150. TryShiftDownLimit := $FF;
  11151. end;
  11152. S_L:
  11153. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  11154. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  11155. begin
  11156. TryShiftDown := S_B;
  11157. TryShiftDownLimit := $FF;
  11158. end
  11159. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  11160. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  11161. begin
  11162. TryShiftDown := S_W;
  11163. TryShiftDownLimit := $FFFF;
  11164. end;
  11165. else
  11166. InternalError(2020112320);
  11167. end;
  11168. WorkingValue := taicpu(hp1).oper[0]^.val;
  11169. TestValMin := TestValMin and WorkingValue;
  11170. TestValMax := TestValMax and WorkingValue;
  11171. TestValSignedMax := TestValSignedMax and WorkingValue;
  11172. end;
  11173. A_OR:
  11174. begin
  11175. if not BitwiseOnly then
  11176. Break;
  11177. OrXorUsed := True;
  11178. WorkingValue := taicpu(hp1).oper[0]^.val;
  11179. TestValMin := TestValMin or WorkingValue;
  11180. TestValMax := TestValMax or WorkingValue;
  11181. TestValSignedMax := TestValSignedMax or WorkingValue;
  11182. end;
  11183. A_XOR:
  11184. begin
  11185. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11186. begin
  11187. TestValMin := 0;
  11188. TestValMax := 0;
  11189. TestValSignedMax := 0;
  11190. end
  11191. else
  11192. begin
  11193. if not BitwiseOnly then
  11194. Break;
  11195. OrXorUsed := True;
  11196. WorkingValue := taicpu(hp1).oper[0]^.val;
  11197. TestValMin := TestValMin xor WorkingValue;
  11198. TestValMax := TestValMax xor WorkingValue;
  11199. TestValSignedMax := TestValSignedMax xor WorkingValue;
  11200. end;
  11201. end;
  11202. A_SHL:
  11203. begin
  11204. BitwiseOnly := False;
  11205. WorkingValue := taicpu(hp1).oper[0]^.val;
  11206. TestValMin := TestValMin shl WorkingValue;
  11207. TestValMax := TestValMax shl WorkingValue;
  11208. TestValSignedMax := TestValSignedMax shl WorkingValue;
  11209. end;
  11210. A_SHR,
  11211. { The first instruction was MOVZX, so the value won't be negative }
  11212. A_SAR:
  11213. begin
  11214. if InstrMax <> -1 then
  11215. BitwiseOnly := False
  11216. else
  11217. { we might be able to go smaller if SHR appears first }
  11218. case MinSize of
  11219. S_B:
  11220. ;
  11221. S_W:
  11222. if (taicpu(hp1).oper[0]^.val >= 8) then
  11223. begin
  11224. TryShiftDown := S_B;
  11225. TryShiftDownLimit := $FF;
  11226. TryShiftDownSignedLimit := $7F;
  11227. TryShiftDownSignedLimitLower := -128;
  11228. end;
  11229. S_L:
  11230. if (taicpu(hp1).oper[0]^.val >= 24) then
  11231. begin
  11232. TryShiftDown := S_B;
  11233. TryShiftDownLimit := $FF;
  11234. TryShiftDownSignedLimit := $7F;
  11235. TryShiftDownSignedLimitLower := -128;
  11236. end
  11237. else if (taicpu(hp1).oper[0]^.val >= 16) then
  11238. begin
  11239. TryShiftDown := S_W;
  11240. TryShiftDownLimit := $FFFF;
  11241. TryShiftDownSignedLimit := $7FFF;
  11242. TryShiftDownSignedLimitLower := -32768;
  11243. end;
  11244. else
  11245. InternalError(2020112321);
  11246. end;
  11247. WorkingValue := taicpu(hp1).oper[0]^.val;
  11248. if taicpu(hp1).opcode = A_SAR then
  11249. begin
  11250. TestValMin := SarInt64(TestValMin, WorkingValue);
  11251. TestValMax := SarInt64(TestValMax, WorkingValue);
  11252. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  11253. end
  11254. else
  11255. begin
  11256. TestValMin := TestValMin shr WorkingValue;
  11257. TestValMax := TestValMax shr WorkingValue;
  11258. TestValSignedMax := TestValSignedMax shr WorkingValue;
  11259. end;
  11260. end;
  11261. else
  11262. InternalError(2020112303);
  11263. end;
  11264. end;
  11265. (*
  11266. A_IMUL:
  11267. case taicpu(hp1).ops of
  11268. 2:
  11269. begin
  11270. if not MatchOpType(hp1, top_reg, top_reg) or
  11271. { Has to be an exact match on the register }
  11272. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  11273. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  11274. Break;
  11275. TestValMin := TestValMin * TestValMin;
  11276. TestValMax := TestValMax * TestValMax;
  11277. TestValSignedMax := TestValSignedMax * TestValMax;
  11278. end;
  11279. 3:
  11280. begin
  11281. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11282. { Has to be an exact match on the register }
  11283. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11284. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11285. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11286. { Is it in the negative range? }
  11287. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11288. Break;
  11289. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  11290. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  11291. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  11292. end;
  11293. else
  11294. Break;
  11295. end;
  11296. A_IDIV:
  11297. case taicpu(hp1).ops of
  11298. 3:
  11299. begin
  11300. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11301. { Has to be an exact match on the register }
  11302. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11303. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11304. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11305. { Is it in the negative range? }
  11306. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11307. Break;
  11308. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  11309. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  11310. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  11311. end;
  11312. else
  11313. Break;
  11314. end;
  11315. *)
  11316. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11317. begin
  11318. { If there are no instructions in between, then we might be able to make a saving }
  11319. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11320. Break;
  11321. { We have something like:
  11322. movzbw %dl,%dx
  11323. ...
  11324. movswl %dx,%edx
  11325. Change the latter to a zero-extension then enter the
  11326. A_MOVZX case branch.
  11327. }
  11328. {$ifdef x86_64}
  11329. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11330. begin
  11331. { this becomes a zero extension from 32-bit to 64-bit, but
  11332. the upper 32 bits are already zero, so just delete the
  11333. instruction }
  11334. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11335. RemoveInstruction(hp1);
  11336. Result := True;
  11337. Exit;
  11338. end
  11339. else
  11340. {$endif x86_64}
  11341. begin
  11342. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11343. taicpu(hp1).opcode := A_MOVZX;
  11344. {$ifdef x86_64}
  11345. case taicpu(hp1).opsize of
  11346. S_BQ:
  11347. begin
  11348. taicpu(hp1).opsize := S_BL;
  11349. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11350. end;
  11351. S_WQ:
  11352. begin
  11353. taicpu(hp1).opsize := S_WL;
  11354. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11355. end;
  11356. S_LQ:
  11357. begin
  11358. taicpu(hp1).opcode := A_MOV;
  11359. taicpu(hp1).opsize := S_L;
  11360. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11361. { In this instance, we need to break out because the
  11362. instruction is no longer MOVZX or MOVSXD }
  11363. Result := True;
  11364. Exit;
  11365. end;
  11366. else
  11367. ;
  11368. end;
  11369. {$endif x86_64}
  11370. Result := CompressInstructions;
  11371. Exit;
  11372. end;
  11373. end;
  11374. A_MOVZX:
  11375. begin
  11376. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11377. Break;
  11378. if (InstrMax = -1) then
  11379. begin
  11380. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11381. begin
  11382. { Optimise around i40003 }
  11383. { Check to see if the active register is used afterwards }
  11384. TransferUsedRegs(TmpUsedRegs);
  11385. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  11386. if (
  11387. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) or
  11388. not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs)
  11389. ) and
  11390. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11391. {$ifndef x86_64}
  11392. and (
  11393. (taicpu(p).oper[0]^.typ <> top_reg) or
  11394. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11395. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11396. )
  11397. {$endif not x86_64}
  11398. then
  11399. begin
  11400. if (taicpu(p).oper[0]^.typ = top_reg) then
  11401. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11402. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11403. taicpu(p).opsize := S_BL;
  11404. { Only remove if the active register is overwritten }
  11405. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11406. begin
  11407. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11408. RemoveInstruction(hp1);
  11409. end;
  11410. Result := True;
  11411. Exit;
  11412. end;
  11413. end
  11414. else
  11415. begin
  11416. { Will return false if the second parameter isn't ThisReg
  11417. (can happen on -O2 and under) }
  11418. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11419. begin
  11420. { The two MOVZX instructions are adjacent, so remove the first one }
  11421. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11422. RemoveCurrentP(p);
  11423. Result := True;
  11424. Exit;
  11425. end;
  11426. Break;
  11427. end;
  11428. end;
  11429. Result := CompressInstructions;
  11430. Exit;
  11431. end;
  11432. else
  11433. { This includes ADC, SBB and IDIV }
  11434. Break;
  11435. end;
  11436. if not CheckOverflowConditions then
  11437. Break;
  11438. { Contains highest index (so instruction count - 1) }
  11439. Inc(InstrMax);
  11440. if InstrMax > High(InstrList) then
  11441. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11442. InstrList[InstrMax] := taicpu(hp1);
  11443. end;
  11444. end;
  11445. {$pop}
  11446. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11447. var
  11448. hp1 : tai;
  11449. begin
  11450. Result:=false;
  11451. if (taicpu(p).ops >= 2) and
  11452. ((taicpu(p).oper[0]^.typ = top_const) or
  11453. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11454. (taicpu(p).oper[1]^.typ = top_reg) and
  11455. ((taicpu(p).ops = 2) or
  11456. ((taicpu(p).oper[2]^.typ = top_reg) and
  11457. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11458. GetLastInstruction(p,hp1) and
  11459. MatchInstruction(hp1,A_MOV,[]) and
  11460. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11461. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11462. begin
  11463. TransferUsedRegs(TmpUsedRegs);
  11464. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11465. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11466. { change
  11467. mov reg1,reg2
  11468. imul y,reg2 to imul y,reg1,reg2 }
  11469. begin
  11470. taicpu(p).ops := 3;
  11471. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11472. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11473. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11474. RemoveInstruction(hp1);
  11475. result:=true;
  11476. end;
  11477. end;
  11478. end;
  11479. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11480. var
  11481. ThisLabel: TAsmLabel;
  11482. begin
  11483. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11484. ThisLabel.decrefs;
  11485. taicpu(p).condition := C_None;
  11486. taicpu(p).opcode := A_RET;
  11487. taicpu(p).is_jmp := false;
  11488. taicpu(p).ops := taicpu(ret_p).ops;
  11489. case taicpu(ret_p).ops of
  11490. 0:
  11491. taicpu(p).clearop(0);
  11492. 1:
  11493. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11494. else
  11495. internalerror(2016041301);
  11496. end;
  11497. { If the original label is now dead, it might turn out that the label
  11498. immediately follows p. As a result, everything beyond it, which will
  11499. be just some final register configuration and a RET instruction, is
  11500. now dead code. [Kit] }
  11501. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11502. running RemoveDeadCodeAfterJump for each RET instruction, because
  11503. this optimisation rarely happens and most RETs appear at the end of
  11504. routines where there is nothing that can be stripped. [Kit] }
  11505. if not ThisLabel.is_used then
  11506. RemoveDeadCodeAfterJump(p);
  11507. end;
  11508. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11509. var
  11510. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11511. Unconditional, PotentialModified: Boolean;
  11512. OperPtr: POper;
  11513. NewRef: TReference;
  11514. InstrList: array of taicpu;
  11515. InstrMax, Index: Integer;
  11516. const
  11517. {$ifdef DEBUG_AOPTCPU}
  11518. SNoFlags: shortstring = ' so the flags aren''t modified';
  11519. {$else DEBUG_AOPTCPU}
  11520. SNoFlags = '';
  11521. {$endif DEBUG_AOPTCPU}
  11522. begin
  11523. Result:=false;
  11524. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11525. begin
  11526. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11527. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11528. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11529. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11530. GetNextInstruction(hp1, hp2) and
  11531. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11532. { Change from: To:
  11533. set(C) %reg j(~C) label
  11534. test %reg,%reg/cmp $0,%reg
  11535. je label
  11536. set(C) %reg j(C) label
  11537. test %reg,%reg/cmp $0,%reg
  11538. jne label
  11539. (Also do something similar with sete/setne instead of je/jne)
  11540. }
  11541. begin
  11542. { Before we do anything else, we need to check the instructions
  11543. in between SETcc and TEST to make sure they don't modify the
  11544. FLAGS register - if -O2 or under, there won't be any
  11545. instructions between SET and TEST }
  11546. TransferUsedRegs(TmpUsedRegs);
  11547. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11548. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11549. begin
  11550. next := p;
  11551. SetLength(InstrList, 0);
  11552. InstrMax := -1;
  11553. PotentialModified := False;
  11554. { Make a note of every instruction that modifies the FLAGS
  11555. register }
  11556. while GetNextInstruction(next, next) and (next <> hp1) do
  11557. begin
  11558. if next.typ <> ait_instruction then
  11559. { GetNextInstructionUsingReg should have returned False }
  11560. InternalError(2021051701);
  11561. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11562. begin
  11563. case taicpu(next).opcode of
  11564. A_SETcc,
  11565. A_CMOVcc,
  11566. A_Jcc:
  11567. begin
  11568. if PotentialModified then
  11569. { Not safe because the flags were modified earlier }
  11570. Exit
  11571. else
  11572. { Condition is the same as the initial SETcc, so this is safe
  11573. (don't add to instruction list though) }
  11574. Continue;
  11575. end;
  11576. A_ADD:
  11577. begin
  11578. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11579. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11580. (taicpu(next).oper[1]^.typ <> top_reg) or
  11581. { Must write to a register }
  11582. (taicpu(next).oper[0]^.typ = top_ref) then
  11583. { Require a constant or a register }
  11584. Exit;
  11585. PotentialModified := True;
  11586. end;
  11587. A_SUB:
  11588. begin
  11589. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11590. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11591. (taicpu(next).oper[1]^.typ <> top_reg) or
  11592. { Must write to a register }
  11593. (taicpu(next).oper[0]^.typ <> top_const) or
  11594. (taicpu(next).oper[0]^.val = $80000000) then
  11595. { Can't subtract a register with LEA - also
  11596. check that the value isn't -2^31, as this
  11597. can't be negated }
  11598. Exit;
  11599. PotentialModified := True;
  11600. end;
  11601. A_SAL,
  11602. A_SHL:
  11603. begin
  11604. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11605. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11606. (taicpu(next).oper[1]^.typ <> top_reg) or
  11607. { Must write to a register }
  11608. (taicpu(next).oper[0]^.typ <> top_const) or
  11609. (taicpu(next).oper[0]^.val < 0) or
  11610. (taicpu(next).oper[0]^.val > 3) then
  11611. Exit;
  11612. PotentialModified := True;
  11613. end;
  11614. A_IMUL:
  11615. begin
  11616. if (taicpu(next).ops <> 3) or
  11617. (taicpu(next).oper[1]^.typ <> top_reg) or
  11618. { Must write to a register }
  11619. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11620. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11621. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11622. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11623. Exit
  11624. else
  11625. PotentialModified := True;
  11626. end;
  11627. else
  11628. { Don't know how to change this, so abort }
  11629. Exit;
  11630. end;
  11631. { Contains highest index (so instruction count - 1) }
  11632. Inc(InstrMax);
  11633. if InstrMax > High(InstrList) then
  11634. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11635. InstrList[InstrMax] := taicpu(next);
  11636. end;
  11637. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11638. end;
  11639. if not Assigned(next) or (next <> hp1) then
  11640. { It should be equal to hp1 }
  11641. InternalError(2021051702);
  11642. { Cycle through each instruction and check to see if we can
  11643. change them to versions that don't modify the flags }
  11644. if (InstrMax >= 0) then
  11645. begin
  11646. for Index := 0 to InstrMax do
  11647. case InstrList[Index].opcode of
  11648. A_ADD:
  11649. begin
  11650. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11651. InstrList[Index].opcode := A_LEA;
  11652. reference_reset(NewRef, 1, []);
  11653. NewRef.base := InstrList[Index].oper[1]^.reg;
  11654. if InstrList[Index].oper[0]^.typ = top_reg then
  11655. begin
  11656. NewRef.index := InstrList[Index].oper[0]^.reg;
  11657. NewRef.scalefactor := 1;
  11658. end
  11659. else
  11660. NewRef.offset := InstrList[Index].oper[0]^.val;
  11661. InstrList[Index].loadref(0, NewRef);
  11662. end;
  11663. A_SUB:
  11664. begin
  11665. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11666. InstrList[Index].opcode := A_LEA;
  11667. reference_reset(NewRef, 1, []);
  11668. NewRef.base := InstrList[Index].oper[1]^.reg;
  11669. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11670. InstrList[Index].loadref(0, NewRef);
  11671. end;
  11672. A_SHL,
  11673. A_SAL:
  11674. begin
  11675. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11676. InstrList[Index].opcode := A_LEA;
  11677. reference_reset(NewRef, 1, []);
  11678. NewRef.index := InstrList[Index].oper[1]^.reg;
  11679. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11680. InstrList[Index].loadref(0, NewRef);
  11681. end;
  11682. A_IMUL:
  11683. begin
  11684. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11685. InstrList[Index].opcode := A_LEA;
  11686. reference_reset(NewRef, 1, []);
  11687. NewRef.index := InstrList[Index].oper[1]^.reg;
  11688. case InstrList[Index].oper[0]^.val of
  11689. 2, 4, 8:
  11690. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11691. else {3, 5 and 9}
  11692. begin
  11693. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11694. NewRef.base := InstrList[Index].oper[1]^.reg;
  11695. end;
  11696. end;
  11697. InstrList[Index].loadref(0, NewRef);
  11698. end;
  11699. else
  11700. InternalError(2021051710);
  11701. end;
  11702. end;
  11703. { Mark the FLAGS register as used across this whole block }
  11704. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11705. end;
  11706. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11707. JumpC := taicpu(hp2).condition;
  11708. Unconditional := False;
  11709. if conditions_equal(JumpC, C_E) then
  11710. SetC := inverse_cond(taicpu(p).condition)
  11711. else if conditions_equal(JumpC, C_NE) then
  11712. SetC := taicpu(p).condition
  11713. else
  11714. { We've got something weird here (and inefficent) }
  11715. begin
  11716. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11717. SetC := C_NONE;
  11718. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11719. if condition_in(C_AE, JumpC) then
  11720. Unconditional := True
  11721. else
  11722. { Not sure what to do with this jump - drop out }
  11723. Exit;
  11724. end;
  11725. RemoveInstruction(hp1);
  11726. if Unconditional then
  11727. MakeUnconditional(taicpu(hp2))
  11728. else
  11729. begin
  11730. if SetC = C_NONE then
  11731. InternalError(2018061402);
  11732. taicpu(hp2).SetCondition(SetC);
  11733. end;
  11734. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11735. TmpUsedRegs }
  11736. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11737. begin
  11738. RemoveCurrentp(p, hp2);
  11739. if taicpu(hp2).opcode = A_SETcc then
  11740. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11741. else
  11742. begin
  11743. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11744. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11745. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11746. end;
  11747. end
  11748. else
  11749. if taicpu(hp2).opcode = A_SETcc then
  11750. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11751. else
  11752. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11753. Result := True;
  11754. end
  11755. else if
  11756. { Make sure the instructions are adjacent }
  11757. (
  11758. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11759. GetNextInstruction(p, hp1)
  11760. ) and
  11761. MatchInstruction(hp1, A_MOV, [S_B]) and
  11762. { Writing to memory is allowed }
  11763. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11764. begin
  11765. {
  11766. Watch out for sequences such as:
  11767. set(c)b %regb
  11768. movb %regb,(ref)
  11769. movb $0,1(ref)
  11770. movb $0,2(ref)
  11771. movb $0,3(ref)
  11772. Much more efficient to turn it into:
  11773. movl $0,%regl
  11774. set(c)b %regb
  11775. movl %regl,(ref)
  11776. Or:
  11777. set(c)b %regb
  11778. movzbl %regb,%regl
  11779. movl %regl,(ref)
  11780. }
  11781. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11782. GetNextInstruction(hp1, hp2) and
  11783. MatchInstruction(hp2, A_MOV, [S_B]) and
  11784. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11785. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11786. begin
  11787. { Don't do anything else except set Result to True }
  11788. end
  11789. else
  11790. begin
  11791. if taicpu(p).oper[0]^.typ = top_reg then
  11792. begin
  11793. TransferUsedRegs(TmpUsedRegs);
  11794. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11795. end;
  11796. { If it's not a register, it's a memory address }
  11797. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11798. begin
  11799. { Even if the register is still in use, we can minimise the
  11800. pipeline stall by changing the MOV into another SETcc. }
  11801. taicpu(hp1).opcode := A_SETcc;
  11802. taicpu(hp1).condition := taicpu(p).condition;
  11803. if taicpu(hp1).oper[1]^.typ = top_ref then
  11804. begin
  11805. { Swapping the operand pointers like this is probably a
  11806. bit naughty, but it is far faster than using loadoper
  11807. to transfer the reference from oper[1] to oper[0] if
  11808. you take into account the extra procedure calls and
  11809. the memory allocation and deallocation required }
  11810. OperPtr := taicpu(hp1).oper[1];
  11811. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11812. taicpu(hp1).oper[0] := OperPtr;
  11813. end
  11814. else
  11815. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11816. taicpu(hp1).clearop(1);
  11817. taicpu(hp1).ops := 1;
  11818. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11819. end
  11820. else
  11821. begin
  11822. if taicpu(hp1).oper[1]^.typ = top_reg then
  11823. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11824. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11825. RemoveInstruction(hp1);
  11826. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11827. end
  11828. end;
  11829. Result := True;
  11830. end;
  11831. end;
  11832. end;
  11833. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11834. var
  11835. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11836. TargetReg: TRegister;
  11837. condition, inverted_condition: TAsmCond;
  11838. FoundMOV: Boolean;
  11839. begin
  11840. Result := False;
  11841. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11842. create the most optimial instructions possible due to limited
  11843. register availability, and there are situations where two
  11844. complementary "simple" CMOV blocks are created which, after the fact
  11845. can be merged into a "double" block. For example:
  11846. movw $257,%ax
  11847. movw $2,%r8w
  11848. xorl r9d,%r9d
  11849. testw $16,18(%rcx)
  11850. cmovew %ax,%dx
  11851. cmovew %r8w,%bx
  11852. cmovel %r9d,%r14d
  11853. movw $1283,%ax
  11854. movw $4,%r8w
  11855. movl $9,%r9d
  11856. cmovnew %ax,%dx
  11857. cmovnew %r8w,%bx
  11858. cmovnel %r9d,%r14d
  11859. The CMOVNE instructions at the end can be removed, and the
  11860. destination registers copied into the MOV instructions directly
  11861. above them, before finally being moved to before the first CMOVE
  11862. instructions, to produce:
  11863. movw $257,%ax
  11864. movw $2,%r8w
  11865. xorl r9d,%r9d
  11866. testw $16,18(%rcx)
  11867. movw $1283,%dx
  11868. movw $4,%bx
  11869. movl $9,%r14d
  11870. cmovew %ax,%dx
  11871. cmovew %r8w,%bx
  11872. cmovel %r9d,%r14d
  11873. Which can then be later optimised to:
  11874. movw $257,%ax
  11875. movw $2,%r8w
  11876. xorl r9d,%r9d
  11877. movw $1283,%dx
  11878. movw $4,%bx
  11879. movl $9,%r14d
  11880. testw $16,18(%rcx)
  11881. cmovew %ax,%dx
  11882. cmovew %r8w,%bx
  11883. cmovel %r9d,%r14d
  11884. }
  11885. TargetReg := taicpu(hp1).oper[1]^.reg;
  11886. condition := taicpu(hp1).condition;
  11887. inverted_condition := inverse_cond(condition);
  11888. pFirstMov := nil;
  11889. pLastMov := nil;
  11890. pCMOV := nil;
  11891. if (p.typ = ait_instruction) then
  11892. pCond := p
  11893. else if not GetNextInstruction(p, pCond) then
  11894. InternalError(2024012501);
  11895. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11896. { We should get the CMP or TEST instructeion }
  11897. InternalError(2024012502);
  11898. if (
  11899. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11900. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11901. ) then
  11902. begin
  11903. { We have to tread carefully here, hence why we're not using
  11904. GetNextInstructionUsingReg... we can only accept MOV and other
  11905. CMOV instructions. Anything else and we must drop out}
  11906. hp2 := hp1;
  11907. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11908. begin
  11909. if (hp2.typ <> ait_instruction) then
  11910. Exit;
  11911. case taicpu(hp2).opcode of
  11912. A_MOV:
  11913. begin
  11914. if not Assigned(pFirstMov) then
  11915. pFirstMov := hp2;
  11916. pLastMOV := hp2;
  11917. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11918. { Something different - drop out }
  11919. Exit;
  11920. { Otherwise, leave it for now }
  11921. end;
  11922. A_CMOVcc:
  11923. begin
  11924. if taicpu(hp2).condition = inverted_condition then
  11925. begin
  11926. { We found what we're looking for }
  11927. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11928. begin
  11929. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11930. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11931. begin
  11932. pCMOV := hp2;
  11933. Break;
  11934. end
  11935. else
  11936. { Unsafe reference - drop out }
  11937. Exit;
  11938. end;
  11939. end
  11940. else if taicpu(hp2).condition <> condition then
  11941. { Something weird - drop out }
  11942. Exit;
  11943. end;
  11944. else
  11945. { Invalid }
  11946. Exit;
  11947. end;
  11948. end;
  11949. if not Assigned(pCMOV) then
  11950. { No complementary CMOV found }
  11951. Exit;
  11952. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11953. begin
  11954. { Don't need to do anything special or search for a matching MOV }
  11955. Asml.Remove(pCMOV);
  11956. if RegInInstruction(TargetReg, pCond) then
  11957. { Make sure we don't overwrite the register if it's being used in the condition }
  11958. Asml.InsertAfter(pCMOV, pCond)
  11959. else
  11960. Asml.InsertBefore(pCMOV, pCond);
  11961. taicpu(pCMOV).opcode := A_MOV;
  11962. taicpu(pCMOV).condition := C_None;
  11963. { Don't need to worry about allocating new registers in these cases }
  11964. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11965. Result := True;
  11966. Exit;
  11967. end
  11968. else
  11969. begin
  11970. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11971. FoundMOV := False;
  11972. { Search for the MOV that sets the target register }
  11973. hp2 := pFirstMov;
  11974. repeat
  11975. if (taicpu(hp2).opcode = A_MOV) and
  11976. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11977. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11978. begin
  11979. { Change the destination }
  11980. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11981. if not FoundMOV then
  11982. begin
  11983. FoundMOV := True;
  11984. { Make sure the register is allocated }
  11985. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11986. end;
  11987. hp1 := tai(hp2.Previous);
  11988. Asml.Remove(hp2);
  11989. if RegInInstruction(TargetReg, pCond) then
  11990. { Make sure we don't overwrite the register if it's being used in the condition }
  11991. Asml.InsertAfter(hp2, pCond)
  11992. else
  11993. Asml.InsertBefore(hp2, pCond);
  11994. if (hp2 = pLastMov) then
  11995. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11996. Break;
  11997. hp2 := hp1;
  11998. end;
  11999. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  12000. if FoundMOV then
  12001. { Delete the CMOV }
  12002. RemoveInstruction(pCMOV)
  12003. else
  12004. begin
  12005. { If no MOV was found, we have to actually move and transmute the CMOV }
  12006. Asml.Remove(pCMOV);
  12007. if RegInInstruction(TargetReg, pCond) then
  12008. { Make sure we don't overwrite the register if it's being used in the condition }
  12009. Asml.InsertAfter(pCMOV, pCond)
  12010. else
  12011. Asml.InsertBefore(pCMOV, pCond);
  12012. taicpu(pCMOV).opcode := A_MOV;
  12013. taicpu(pCMOV).condition := C_None;
  12014. end;
  12015. Result := True;
  12016. Exit;
  12017. end;
  12018. end;
  12019. end;
  12020. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  12021. var
  12022. hp1, hp2, pCond: tai;
  12023. begin
  12024. Result := False;
  12025. { Search ahead for CMOV instructions }
  12026. if (cs_opt_level2 in current_settings.optimizerswitches) then
  12027. begin
  12028. hp1 := p;
  12029. hp2 := p;
  12030. pCond := nil; { To prevent compiler warnings }
  12031. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  12032. DEFAULTFLAGS }
  12033. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  12034. (tai_regalloc(pCond).ratype = ra_dealloc) then
  12035. pCond := p;
  12036. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  12037. begin
  12038. if (hp1.typ <> ait_instruction) then
  12039. { Break out on markers and labels etc. }
  12040. Break;
  12041. case taicpu(hp1).opcode of
  12042. A_MOV:
  12043. { Ignore regular MOVs unless they are obviously not related
  12044. to a CMOV block }
  12045. if taicpu(hp1).oper[1]^.typ <> top_reg then
  12046. Break;
  12047. A_CMOVcc:
  12048. if TryCmpCMovOpts(pCond, hp1) then
  12049. begin
  12050. hp1 := hp2;
  12051. { p itself isn't changed, and we're still inside a
  12052. while loop to catch subsequent CMOVs, so just flag
  12053. a new iteration }
  12054. Include(OptsToCheck, aoc_ForceNewIteration);
  12055. Continue;
  12056. end;
  12057. else
  12058. { Drop out if we find anything else }
  12059. Break;
  12060. end;
  12061. hp2 := hp1;
  12062. end;
  12063. end;
  12064. end;
  12065. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  12066. var
  12067. hp1, hp2, pCond: tai;
  12068. SourceReg, TargetReg: TRegister;
  12069. begin
  12070. Result := False;
  12071. { In some situations, we end up with an inefficient arrangement of
  12072. instructions in the form of:
  12073. or %reg1,%reg2
  12074. (%reg1 deallocated)
  12075. test %reg2,%reg2
  12076. mov x,%reg2
  12077. we may be able to swap and rearrange the registers to produce:
  12078. or %reg2,%reg1
  12079. mov x,%reg2
  12080. test %reg1,%reg1
  12081. (%reg1 deallocated)
  12082. }
  12083. if (cs_opt_level3 in current_settings.optimizerswitches) and
  12084. (taicpu(p).oper[1]^.typ = top_reg) and
  12085. (
  12086. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  12087. MatchOperand(taicpu(p).oper[0]^, -1)
  12088. ) and
  12089. GetNextInstruction(p, hp1) and
  12090. MatchInstruction(hp1, A_MOV, []) and
  12091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12092. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12093. begin
  12094. TargetReg := taicpu(p).oper[1]^.reg;
  12095. { Now look backwards to find a simple commutative operation: ADD,
  12096. IMUL (2-register version), OR, AND or XOR - whose destination
  12097. register is the same as TEST }
  12098. hp2 := p;
  12099. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  12100. if RegInInstruction(TargetReg, hp2) then
  12101. begin
  12102. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  12103. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12104. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  12105. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  12106. begin
  12107. SourceReg := taicpu(hp2).oper[0]^.reg;
  12108. if
  12109. { Make sure the MOV doesn't use the other register }
  12110. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  12111. { And make sure the source register is not used afterwards }
  12112. not RegInUsedRegs(SourceReg, UsedRegs) then
  12113. begin
  12114. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  12115. taicpu(hp2).oper[0]^.reg := TargetReg;
  12116. taicpu(hp2).oper[1]^.reg := SourceReg;
  12117. if taicpu(p).oper[0]^.typ = top_reg then
  12118. taicpu(p).oper[0]^.reg := SourceReg;
  12119. taicpu(p).oper[1]^.reg := SourceReg;
  12120. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  12121. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  12122. Include(OptsToCheck, aoc_ForceNewIteration);
  12123. { We can still check the following optimisations since
  12124. the instruction is still a TEST }
  12125. end;
  12126. end;
  12127. Break;
  12128. end;
  12129. end;
  12130. { Search ahead3 for CMOV instructions }
  12131. if (cs_opt_level2 in current_settings.optimizerswitches) then
  12132. begin
  12133. hp1 := p;
  12134. hp2 := p;
  12135. pCond := nil; { To prevent compiler warnings }
  12136. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  12137. DEFAULTFLAGS }
  12138. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  12139. (tai_regalloc(pCond).ratype = ra_dealloc) then
  12140. pCond := p;
  12141. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  12142. begin
  12143. if (hp1.typ <> ait_instruction) then
  12144. { Break out on markers and labels etc. }
  12145. Break;
  12146. case taicpu(hp1).opcode of
  12147. A_MOV:
  12148. { Ignore regular MOVs unless they are obviously not related
  12149. to a CMOV block }
  12150. if taicpu(hp1).oper[1]^.typ <> top_reg then
  12151. Break;
  12152. A_CMOVcc:
  12153. if TryCmpCMovOpts(pCond, hp1) then
  12154. begin
  12155. hp1 := hp2;
  12156. { p itself isn't changed, and we're still inside a
  12157. while loop to catch subsequent CMOVs, so just flag
  12158. a new iteration }
  12159. Include(OptsToCheck, aoc_ForceNewIteration);
  12160. Continue;
  12161. end;
  12162. else
  12163. { Drop out if we find anything else }
  12164. Break;
  12165. end;
  12166. hp2 := hp1;
  12167. end;
  12168. end;
  12169. end;
  12170. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  12171. var
  12172. hp1: tai;
  12173. Count: Integer;
  12174. OrigLabel: TAsmLabel;
  12175. begin
  12176. result := False;
  12177. { Sometimes, the optimisations below can permit this }
  12178. RemoveDeadCodeAfterJump(p);
  12179. 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
  12180. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  12181. begin
  12182. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12183. { Also a side-effect of optimisations }
  12184. if CollapseZeroDistJump(p, OrigLabel) then
  12185. begin
  12186. Result := True;
  12187. Exit;
  12188. end;
  12189. hp1 := GetLabelWithSym(OrigLabel);
  12190. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  12191. begin
  12192. if taicpu(hp1).opcode = A_RET then
  12193. begin
  12194. {
  12195. change
  12196. jmp .L1
  12197. ...
  12198. .L1:
  12199. ret
  12200. into
  12201. ret
  12202. }
  12203. begin
  12204. ConvertJumpToRET(p, hp1);
  12205. result:=true;
  12206. end;
  12207. end
  12208. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  12209. not (cs_opt_size in current_settings.optimizerswitches) and
  12210. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  12211. begin
  12212. Result := True;
  12213. Exit;
  12214. end;
  12215. end;
  12216. end;
  12217. end;
  12218. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  12219. begin
  12220. Result := assigned(p) and
  12221. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  12222. (taicpu(p).oper[1]^.typ = top_reg) and
  12223. (
  12224. (taicpu(p).oper[0]^.typ = top_reg) or
  12225. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  12226. it is not expected that this can cause a seg. violation }
  12227. (
  12228. (taicpu(p).oper[0]^.typ = top_ref) and
  12229. { TODO: Can we detect which references become constants at this
  12230. stage so we don't have to do a blanket ban? }
  12231. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  12232. (
  12233. IsRefSafe(taicpu(p).oper[0]^.ref) or
  12234. (
  12235. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  12236. not RefModified and
  12237. { If the reference also appears in the condition, then we know it's safe, otherwise
  12238. any kind of access violation would have occurred already }
  12239. Assigned(cond_p) and
  12240. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12241. (cond_p.typ = ait_instruction) and
  12242. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  12243. { Just consider 2-operand comparison instructions for now to be safe }
  12244. (taicpu(cond_p).ops = 2) and
  12245. (
  12246. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  12247. (
  12248. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  12249. { Don't risk identical registers but different offsets, as we may have constructs
  12250. such as buffer streams with things like length fields that indicate whether
  12251. any more data follows. And there are probably some contrived examples where
  12252. writing to offsets behind the one being read also lead to access violations }
  12253. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  12254. (
  12255. { Check that we're not modifying a register that appears in the reference }
  12256. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  12257. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  12258. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  12259. )
  12260. )
  12261. )
  12262. )
  12263. )
  12264. )
  12265. );
  12266. end;
  12267. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  12268. begin
  12269. { Update integer registers, ignoring deallocations }
  12270. repeat
  12271. while assigned(p) and
  12272. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  12273. (p.typ = ait_label) or
  12274. ((p.typ = ait_marker) and
  12275. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  12276. p := tai(p.next);
  12277. while assigned(p) and
  12278. (p.typ=ait_RegAlloc) Do
  12279. begin
  12280. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  12281. begin
  12282. case tai_regalloc(p).ratype of
  12283. ra_alloc :
  12284. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  12285. else
  12286. ;
  12287. end;
  12288. end;
  12289. p := tai(p.next);
  12290. end;
  12291. until not(assigned(p)) or
  12292. (not(p.typ in SkipInstr) and
  12293. not((p.typ = ait_label) and
  12294. labelCanBeSkipped(tai_label(p))));
  12295. end;
  12296. {$ifndef 8086}
  12297. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  12298. begin
  12299. Result := False;
  12300. EndJump := nil;
  12301. BlockStop := nil;
  12302. while (BlockStart <> fOptimizer.BlockEnd) and
  12303. { stop on labels }
  12304. (BlockStart.typ <> ait_label) do
  12305. begin
  12306. { Keep track of all integer registers that are used }
  12307. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  12308. if BlockStart.typ = ait_instruction then
  12309. begin
  12310. if (taicpu(BlockStart).opcode = A_JMP) then
  12311. begin
  12312. if not IsJumpToLabel(taicpu(BlockStart)) or
  12313. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  12314. Exit;
  12315. EndJump := BlockStart;
  12316. Break;
  12317. end
  12318. { Check to see if we have a valid MOV instruction instead }
  12319. else if (taicpu(BlockStart).opcode <> A_MOV) or
  12320. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  12321. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12322. begin
  12323. Exit;
  12324. end
  12325. else
  12326. { This will be a valid MOV }
  12327. fAllocationRange := BlockStart;
  12328. end;
  12329. OneBeforeBlock := BlockStart;
  12330. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12331. end;
  12332. if (BlockStart = fOptimizer.BlockEnd) then
  12333. Exit;
  12334. BlockStop := BlockStart;
  12335. Result := True;
  12336. end;
  12337. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12338. var
  12339. hp1: tai;
  12340. RefModified: Boolean;
  12341. begin
  12342. Result := 0;
  12343. hp1 := BlockStart;
  12344. RefModified := False; { As long as the condition is inverted, this can be reset }
  12345. while assigned(hp1) and
  12346. (hp1 <> BlockStop) do
  12347. begin
  12348. case hp1.typ of
  12349. ait_instruction:
  12350. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12351. begin
  12352. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12353. begin
  12354. Inc(Result);
  12355. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12356. Assigned(fCondition) and
  12357. { Will have 2 operands }
  12358. (
  12359. (
  12360. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12361. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12362. ) or
  12363. (
  12364. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12365. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12366. )
  12367. ) then
  12368. { It is no longer safe to use the reference in the condition.
  12369. this prevents problems such as:
  12370. mov (%reg),%reg
  12371. mov (%reg),...
  12372. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12373. (fixes #40165)
  12374. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12375. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12376. }
  12377. RefModified := True;
  12378. end
  12379. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12380. { CMOV with constants grows the code size }
  12381. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12382. begin
  12383. { Register was reserved by TryCMOVConst and
  12384. stored on ConstRegs }
  12385. end
  12386. else
  12387. begin
  12388. Result := -1;
  12389. Exit;
  12390. end;
  12391. end
  12392. else
  12393. begin
  12394. Result := -1;
  12395. Exit;
  12396. end;
  12397. else
  12398. { Most likely an align };
  12399. end;
  12400. fOptimizer.GetNextInstruction(hp1, hp1);
  12401. end;
  12402. end;
  12403. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12404. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12405. (this is done as a separate stage because the double types are extensions of the branching type,
  12406. but we can't discount the conditional jump until the last step) }
  12407. procedure EvaluateBranchingType;
  12408. begin
  12409. Inc(CMOVScore);
  12410. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12411. { Too many instructions to be worthwhile }
  12412. fState := tsInvalid;
  12413. end;
  12414. var
  12415. hp1: tai;
  12416. Count: Integer;
  12417. begin
  12418. { Table of valid CMOV block types
  12419. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12420. ---------- --------- --------- --------- --------- ---------
  12421. tsSimple X Yes X X X
  12422. tsDetour = 1st X X X X
  12423. tsBranching <> Mid Yes X X X
  12424. tsDouble End-label Yes * Yes X Yes
  12425. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12426. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12427. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12428. * Only one reference allowed
  12429. }
  12430. hp1 := nil; { To prevent compiler warnings }
  12431. Optimizer.CopyUsedRegs(RegisterTracking);
  12432. fOptimizer := Optimizer;
  12433. fLabel := AFirstLabel;
  12434. CMOVScore := 0;
  12435. ConstCount := 0;
  12436. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12437. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12438. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12439. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12440. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12441. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12442. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12443. fInsertionPoint := p_initialjump;
  12444. fCondition := nil;
  12445. fInitialJump := p_initialjump;
  12446. fFirstMovBlock := p_initialmov;
  12447. fFirstMovBlockStop := nil;
  12448. fSecondJump := nil;
  12449. fSecondMovBlock := nil;
  12450. fSecondMovBlockStop := nil;
  12451. fMidLabel := nil;
  12452. fSecondJump := nil;
  12453. fSecondMovBlock := nil;
  12454. fEndLabel := nil;
  12455. fAllocationRange := nil;
  12456. { Assume it all goes horribly wrong! }
  12457. fState := tsInvalid;
  12458. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12459. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12460. MatchInstruction(fCondition, [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
  12461. begin
  12462. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12463. for Count := 0 to 1 do
  12464. with taicpu(fCondition).oper[Count]^ do
  12465. case typ of
  12466. top_reg:
  12467. if getregtype(reg) = R_INTREGISTER then
  12468. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12469. top_ref:
  12470. begin
  12471. if
  12472. {$ifdef x86_64}
  12473. (ref^.base <> NR_RIP) and
  12474. {$endif x86_64}
  12475. (ref^.base <> NR_NO) then
  12476. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12477. if (ref^.index <> NR_NO) then
  12478. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12479. end
  12480. else
  12481. ;
  12482. end;
  12483. { When inserting instructions before hp_prev, try to insert them
  12484. before the allocation of the FLAGS register }
  12485. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12486. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12487. { If not found, set it equal to the condition so it's something sensible }
  12488. fInsertionPoint := fCondition;
  12489. { When dealing with a comparison against zero, take note of the
  12490. instruction before it to see if we can move instructions further
  12491. back in order to benefit PostPeepholeOptTestOr.
  12492. }
  12493. if (
  12494. (
  12495. (taicpu(fCondition).opcode = A_CMP) and
  12496. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12497. ) or
  12498. (
  12499. (taicpu(fCondition).opcode = A_TEST) and
  12500. (
  12501. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12502. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12503. )
  12504. )
  12505. ) and
  12506. Optimizer.GetLastInstruction(fCondition, hp1) then
  12507. begin
  12508. { These instructions set the zero flag if the result is zero }
  12509. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12510. begin
  12511. fInsertionPoint := hp1;
  12512. { Also mark all the registers in this previous instruction
  12513. as 'in use', even if they've just been deallocated }
  12514. for Count := 0 to 1 do
  12515. with taicpu(hp1).oper[Count]^ do
  12516. case typ of
  12517. top_reg:
  12518. if getregtype(reg) = R_INTREGISTER then
  12519. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12520. top_ref:
  12521. begin
  12522. if
  12523. {$ifdef x86_64}
  12524. (ref^.base <> NR_RIP) and
  12525. {$endif x86_64}
  12526. (ref^.base <> NR_NO) then
  12527. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12528. if (ref^.index <> NR_NO) then
  12529. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12530. end
  12531. else
  12532. ;
  12533. end;
  12534. end;
  12535. end;
  12536. end
  12537. else
  12538. fCondition := nil;
  12539. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12540. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12541. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12542. { If not found, set it equal to p so it's something sensible }
  12543. fInsertionPoint := hp1;
  12544. hp1 := p_initialmov;
  12545. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12546. Exit;
  12547. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12548. if (hp1.typ <> ait_label) then { should be on a jump }
  12549. begin
  12550. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12551. { Need a label afterwards }
  12552. Exit;
  12553. end
  12554. else
  12555. fMidLabel := hp1;
  12556. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12557. { Not the correct label }
  12558. fMidLabel := nil;
  12559. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12560. { If there's neither a 2nd jump nor correct label, then it's invalid
  12561. (see above table) }
  12562. Exit;
  12563. { Analyse the first block of MOVs more closely }
  12564. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12565. if Assigned(fSecondJump) then
  12566. begin
  12567. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12568. begin
  12569. fState := tsDetour
  12570. end
  12571. else
  12572. begin
  12573. { Need the correct mid-label for this one }
  12574. if not Assigned(fMidLabel) then
  12575. Exit;
  12576. fState := tsBranching;
  12577. end;
  12578. end
  12579. else
  12580. { No jump. but mid-label is present }
  12581. fState := tsSimple;
  12582. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12583. begin
  12584. { Invalid or too many instructions to be worthwhile }
  12585. fState := tsInvalid;
  12586. Exit;
  12587. end;
  12588. { check further for
  12589. jCC xxx
  12590. <several movs 1>
  12591. jmp yyy
  12592. xxx:
  12593. <several movs 2>
  12594. yyy:
  12595. etc.
  12596. }
  12597. if (fState = tsBranching) and
  12598. { Estimate for required savings for extra jump }
  12599. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12600. { Only one reference is allowed for double blocks }
  12601. (AFirstLabel.getrefs = 1) then
  12602. begin
  12603. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12604. fSecondMovBlock := hp1;
  12605. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12606. begin
  12607. EvaluateBranchingType;
  12608. Exit;
  12609. end;
  12610. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12611. if (hp1.typ <> ait_label) then { should be on a jump }
  12612. begin
  12613. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12614. begin
  12615. { Need a label afterwards }
  12616. EvaluateBranchingType;
  12617. Exit;
  12618. end;
  12619. end
  12620. else
  12621. fEndLabel := hp1;
  12622. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12623. { Second jump doesn't go to the end }
  12624. fEndLabel := nil;
  12625. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12626. begin
  12627. { If there's neither a 3rd jump nor correct end label, then it's
  12628. not a invalid double block, but is a valid single branching
  12629. block (see above table) }
  12630. EvaluateBranchingType;
  12631. Exit;
  12632. end;
  12633. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12634. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12635. { Invalid or too many instructions to be worthwhile }
  12636. Exit;
  12637. Inc(CMOVScore, Count);
  12638. if Assigned(fThirdJump) then
  12639. begin
  12640. if not Assigned(fSecondJump) then
  12641. fState := tsDoubleSecondBranching
  12642. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12643. fState := tsDoubleBranchSame
  12644. else
  12645. fState := tsDoubleBranchDifferent;
  12646. end
  12647. else
  12648. fState := tsDouble;
  12649. end;
  12650. if fState = tsBranching then
  12651. EvaluateBranchingType;
  12652. end;
  12653. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12654. new register to store the constant }
  12655. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12656. var
  12657. RegSize: TSubRegister;
  12658. CurrentVal: TCGInt;
  12659. ANewReg: TRegister;
  12660. X: ShortInt;
  12661. begin
  12662. Result := False;
  12663. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12664. Exit;
  12665. if ConstCount >= MAX_CMOV_REGISTERS then
  12666. { Arrays are full }
  12667. Exit;
  12668. { Remember that CMOV can't encode 8-bit registers }
  12669. case taicpu(p).opsize of
  12670. S_W:
  12671. RegSize := R_SUBW;
  12672. S_L:
  12673. RegSize := R_SUBD;
  12674. {$ifdef x86_64}
  12675. S_Q:
  12676. RegSize := R_SUBQ;
  12677. {$endif x86_64}
  12678. else
  12679. InternalError(2021100401);
  12680. end;
  12681. { See if the value has already been reserved for another CMOV instruction }
  12682. CurrentVal := taicpu(p).oper[0]^.val;
  12683. for X := 0 to ConstCount - 1 do
  12684. if ConstVals[X] = CurrentVal then
  12685. begin
  12686. ConstRegs[ConstCount] := ConstRegs[X];
  12687. ConstSizes[ConstCount] := RegSize;
  12688. ConstVals[ConstCount] := CurrentVal;
  12689. Inc(ConstCount);
  12690. Inc(Count);
  12691. Result := True;
  12692. Exit;
  12693. end;
  12694. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12695. if ANewReg = NR_NO then
  12696. { No free registers }
  12697. Exit;
  12698. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12699. up vying for the same register }
  12700. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12701. ConstRegs[ConstCount] := ANewReg;
  12702. ConstSizes[ConstCount] := RegSize;
  12703. ConstVals[ConstCount] := CurrentVal;
  12704. Inc(ConstCount);
  12705. Inc(Count);
  12706. Result := True;
  12707. end;
  12708. destructor TCMOVTracking.Done;
  12709. begin
  12710. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12711. end;
  12712. procedure TCMOVTracking.Process(out new_p: tai);
  12713. var
  12714. Count, Writes: LongInt;
  12715. RegMatch: Boolean;
  12716. hp1, hp_new: tai;
  12717. inverted_condition, condition: TAsmCond;
  12718. begin
  12719. if (fState in [tsInvalid, tsProcessed]) then
  12720. InternalError(2023110701);
  12721. { Repurpose RegisterTracking to mark registers that we've defined }
  12722. RegisterTracking[R_INTREGISTER].Clear;
  12723. Count := 0;
  12724. Writes := 0;
  12725. condition := taicpu(fInitialJump).condition;
  12726. inverted_condition := inverse_cond(condition);
  12727. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12728. doesn't get CMOVs in this case }
  12729. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12730. begin
  12731. { Include the jump in the flag tracking }
  12732. if Assigned(fThirdJump) then
  12733. begin
  12734. if (fState = tsDoubleBranchSame) then
  12735. begin
  12736. { Will be an unconditional jump, so track to the instruction before it }
  12737. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12738. InternalError(2023110710);
  12739. end
  12740. else
  12741. hp1 := fThirdJump;
  12742. end
  12743. else
  12744. hp1 := fSecondMovBlockStop;
  12745. end
  12746. else
  12747. begin
  12748. { Include a conditional jump in the flag tracking }
  12749. if Assigned(fSecondJump) then
  12750. begin
  12751. if (fState = tsDetour) then
  12752. begin
  12753. { Will be an unconditional jump, so track to the instruction before it }
  12754. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12755. InternalError(2023110711);
  12756. end
  12757. else
  12758. hp1 := fSecondJump;
  12759. end
  12760. else
  12761. hp1 := fFirstMovBlockStop;
  12762. end;
  12763. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12764. { Process the second set of MOVs first, because if a destination
  12765. register is shared between the first and second MOV sets, it is more
  12766. efficient to turn the first one into a MOV instruction and place it
  12767. before the CMP if possible, but we won't know which registers are
  12768. shared until we've processed at least one list, so we might as well
  12769. make it the second one since that won't be modified again. }
  12770. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12771. begin
  12772. hp1 := fSecondMovBlock;
  12773. repeat
  12774. if not Assigned(hp1) then
  12775. InternalError(2018062902);
  12776. if (hp1.typ = ait_instruction) then
  12777. begin
  12778. { Extra safeguard }
  12779. if (taicpu(hp1).opcode <> A_MOV) then
  12780. InternalError(2018062903);
  12781. { Note: tsDoubleBranchDifferent is essentially identical to
  12782. tsBranching and the 2nd block is best left largely
  12783. untouched, but we need to evaluate which registers the MOVs
  12784. write to in order to track what would be complementary CMOV
  12785. pairs that can be further optimised. [Kit] }
  12786. if fState <> tsDoubleBranchDifferent then
  12787. begin
  12788. if taicpu(hp1).oper[0]^.typ = top_const then
  12789. begin
  12790. RegMatch := False;
  12791. for Count := 0 to ConstCount - 1 do
  12792. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12793. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12794. begin
  12795. RegMatch := True;
  12796. { If it's in RegisterTracking, then this register
  12797. is being used more than once and hence has
  12798. already had its value defined (it gets added to
  12799. UsedRegs through AllocRegBetween below) }
  12800. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12801. begin
  12802. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12803. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12804. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12805. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12806. ConstMovs[Count] := hp_new;
  12807. end
  12808. else
  12809. { We just need an instruction between hp_prev and hp1
  12810. where we know the register is marked as in use }
  12811. hp_new := fSecondMovBlock;
  12812. { Keep track of largest write for this register so it can be optimised later }
  12813. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12814. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12815. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12816. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12817. Break;
  12818. end;
  12819. if not RegMatch then
  12820. InternalError(2021100411);
  12821. end;
  12822. taicpu(hp1).opcode := A_CMOVcc;
  12823. taicpu(hp1).condition := condition;
  12824. end;
  12825. { Store these writes to search for duplicates later on }
  12826. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12827. Inc(Writes);
  12828. end;
  12829. fOptimizer.GetNextInstruction(hp1, hp1);
  12830. until (hp1 = fSecondMovBlockStop);
  12831. end;
  12832. { Now do the first set of MOVs }
  12833. hp1 := fFirstMovBlock;
  12834. repeat
  12835. if not Assigned(hp1) then
  12836. InternalError(2018062904);
  12837. if (hp1.typ = ait_instruction) then
  12838. begin
  12839. RegMatch := False;
  12840. { Extra safeguard }
  12841. if (taicpu(hp1).opcode <> A_MOV) then
  12842. InternalError(2018062905);
  12843. { Search through the RegWrites list to see if there are any
  12844. opposing CMOV pairs that write to the same register }
  12845. for Count := 0 to Writes - 1 do
  12846. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12847. begin
  12848. { We have a match. Keep this as a MOV }
  12849. { Move ahead in preparation }
  12850. fOptimizer.GetNextInstruction(hp1, hp1);
  12851. RegMatch := True;
  12852. Break;
  12853. end;
  12854. if RegMatch then
  12855. Continue;
  12856. if taicpu(hp1).oper[0]^.typ = top_const then
  12857. begin
  12858. for Count := 0 to ConstCount - 1 do
  12859. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12860. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12861. begin
  12862. RegMatch := True;
  12863. { If it's in RegisterTracking, then this register is
  12864. being used more than once and hence has already had
  12865. its value defined (it gets added to UsedRegs through
  12866. AllocRegBetween below) }
  12867. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12868. begin
  12869. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12870. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12871. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12872. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12873. ConstMovs[Count] := hp_new;
  12874. end
  12875. else
  12876. { We just need an instruction between hp_prev and hp1
  12877. where we know the register is marked as in use }
  12878. hp_new := fFirstMovBlock;
  12879. { Keep track of largest write for this register so it can be optimised later }
  12880. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12881. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12882. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12883. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12884. Break;
  12885. end;
  12886. if not RegMatch then
  12887. InternalError(2021100412);
  12888. end;
  12889. taicpu(hp1).opcode := A_CMOVcc;
  12890. taicpu(hp1).condition := inverted_condition;
  12891. if (fState = tsDoubleBranchDifferent) then
  12892. begin
  12893. { Store these writes to search for duplicates later on }
  12894. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12895. Inc(Writes);
  12896. end;
  12897. end;
  12898. fOptimizer.GetNextInstruction(hp1, hp1);
  12899. until (hp1 = fFirstMovBlockStop);
  12900. { Update initialisation MOVs to the smallest possible size }
  12901. for Count := 0 to ConstCount - 1 do
  12902. if Assigned(ConstMovs[Count]) then
  12903. begin
  12904. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12905. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12906. end;
  12907. case fState of
  12908. tsSimple:
  12909. begin
  12910. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12911. { No branch to delete }
  12912. end;
  12913. tsDetour:
  12914. begin
  12915. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12916. { Preserve jump }
  12917. end;
  12918. tsBranching, tsDoubleBranchDifferent:
  12919. begin
  12920. if (fState = tsBranching) then
  12921. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12922. else
  12923. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12924. taicpu(fSecondJump).opcode := A_JCC;
  12925. taicpu(fSecondJump).condition := inverted_condition;
  12926. end;
  12927. tsDouble, tsDoubleBranchSame:
  12928. begin
  12929. if (fState = tsDouble) then
  12930. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12931. else
  12932. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12933. { Delete second jump }
  12934. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12935. fOptimizer.RemoveInstruction(fSecondJump);
  12936. end;
  12937. tsDoubleSecondBranching:
  12938. begin
  12939. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12940. { Delete second jump, preserve third jump as conditional }
  12941. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12942. fOptimizer.RemoveInstruction(fSecondJump);
  12943. taicpu(fThirdJump).opcode := A_JCC;
  12944. taicpu(fThirdJump).condition := condition;
  12945. end;
  12946. else
  12947. InternalError(2023110720);
  12948. end;
  12949. { Now we can safely decrement the reference count }
  12950. tasmlabel(fLabel).decrefs;
  12951. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12952. { Remove the original jump }
  12953. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12954. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12955. fState := tsProcessed;
  12956. end;
  12957. {$endif 8086}
  12958. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12959. var
  12960. hp1,hp2: tai;
  12961. carryadd_opcode : TAsmOp;
  12962. symbol: TAsmSymbol;
  12963. increg, tmpreg: TRegister;
  12964. {$ifndef i8086}
  12965. CMOVTracking: PCMOVTracking;
  12966. hp3,hp4,hp5: tai;
  12967. {$endif i8086}
  12968. TempBool: Boolean;
  12969. begin
  12970. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12971. DoJumpOptimizations(p, TempBool) then
  12972. Exit(True);
  12973. result:=false;
  12974. if GetNextInstruction(p,hp1) then
  12975. begin
  12976. if (hp1.typ=ait_label) then
  12977. begin
  12978. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12979. Exit;
  12980. end
  12981. else if (hp1.typ<>ait_instruction) then
  12982. Exit;
  12983. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12984. if (
  12985. (
  12986. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12987. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12988. (Taicpu(hp1).oper[0]^.val=1)
  12989. ) or
  12990. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12991. ) and
  12992. GetNextInstruction(hp1,hp2) and
  12993. FindLabel(TAsmLabel(symbol), hp2) then
  12994. { jb @@1 cmc
  12995. inc/dec operand --> adc/sbb operand,0
  12996. @@1:
  12997. ... and ...
  12998. jnb @@1
  12999. inc/dec operand --> adc/sbb operand,0
  13000. @@1: }
  13001. begin
  13002. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  13003. begin
  13004. case taicpu(hp1).opcode of
  13005. A_INC,
  13006. A_ADD:
  13007. carryadd_opcode:=A_ADC;
  13008. A_DEC,
  13009. A_SUB:
  13010. carryadd_opcode:=A_SBB;
  13011. else
  13012. InternalError(2021011001);
  13013. end;
  13014. Taicpu(p).clearop(0);
  13015. Taicpu(p).ops:=0;
  13016. Taicpu(p).is_jmp:=false;
  13017. Taicpu(p).opcode:=A_CMC;
  13018. Taicpu(p).condition:=C_NONE;
  13019. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  13020. Taicpu(hp1).ops:=2;
  13021. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  13022. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  13023. else
  13024. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  13025. Taicpu(hp1).loadconst(0,0);
  13026. Taicpu(hp1).opcode:=carryadd_opcode;
  13027. result:=true;
  13028. exit;
  13029. end
  13030. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  13031. begin
  13032. case taicpu(hp1).opcode of
  13033. A_INC,
  13034. A_ADD:
  13035. carryadd_opcode:=A_ADC;
  13036. A_DEC,
  13037. A_SUB:
  13038. carryadd_opcode:=A_SBB;
  13039. else
  13040. InternalError(2021011002);
  13041. end;
  13042. Taicpu(hp1).ops:=2;
  13043. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  13044. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  13045. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  13046. else
  13047. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  13048. Taicpu(hp1).loadconst(0,0);
  13049. Taicpu(hp1).opcode:=carryadd_opcode;
  13050. RemoveCurrentP(p, hp1);
  13051. result:=true;
  13052. exit;
  13053. end
  13054. {
  13055. jcc @@1 setcc tmpreg
  13056. inc/dec/add/sub operand -> (movzx tmpreg)
  13057. @@1: add/sub tmpreg,operand
  13058. While this increases code size slightly, it makes the code much faster if the
  13059. jump is unpredictable
  13060. }
  13061. else if not(cs_opt_size in current_settings.optimizerswitches) then
  13062. begin
  13063. { search for an available register which is volatile }
  13064. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  13065. if increg <> NR_NO then
  13066. begin
  13067. { We don't need to check if tmpreg is in hp1 or not, because
  13068. it will be marked as in use at p (if not, this is
  13069. indictive of a compiler bug). }
  13070. TAsmLabel(symbol).decrefs;
  13071. Taicpu(p).clearop(0);
  13072. Taicpu(p).ops:=1;
  13073. Taicpu(p).is_jmp:=false;
  13074. Taicpu(p).opcode:=A_SETcc;
  13075. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  13076. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  13077. Taicpu(p).loadreg(0,increg);
  13078. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  13079. begin
  13080. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  13081. R_SUBW:
  13082. begin
  13083. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  13084. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  13085. end;
  13086. R_SUBD:
  13087. begin
  13088. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  13089. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  13090. end;
  13091. {$ifdef x86_64}
  13092. R_SUBQ:
  13093. begin
  13094. { MOVZX doesn't have a 64-bit variant, because
  13095. the 32-bit version implicitly zeroes the
  13096. upper 32-bits of the destination register }
  13097. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  13098. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  13099. setsubreg(tmpreg, R_SUBQ);
  13100. end;
  13101. {$endif x86_64}
  13102. else
  13103. Internalerror(2020030601);
  13104. end;
  13105. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  13106. asml.InsertAfter(hp2,p);
  13107. end
  13108. else
  13109. tmpreg := increg;
  13110. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  13111. begin
  13112. Taicpu(hp1).ops:=2;
  13113. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  13114. end;
  13115. Taicpu(hp1).loadreg(0,tmpreg);
  13116. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  13117. Result := True;
  13118. { p is no longer a Jcc instruction, so exit }
  13119. Exit;
  13120. end;
  13121. end;
  13122. end;
  13123. { Detect the following:
  13124. jmp<cond> @Lbl1
  13125. jmp @Lbl2
  13126. ...
  13127. @Lbl1:
  13128. ret
  13129. Change to:
  13130. jmp<inv_cond> @Lbl2
  13131. ret
  13132. }
  13133. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13134. begin
  13135. hp2:=getlabelwithsym(TAsmLabel(symbol));
  13136. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  13137. MatchInstruction(hp2,A_RET,[S_NO]) then
  13138. begin
  13139. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  13140. { Change label address to that of the unconditional jump }
  13141. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  13142. TAsmLabel(symbol).DecRefs;
  13143. taicpu(hp1).opcode := A_RET;
  13144. taicpu(hp1).is_jmp := false;
  13145. taicpu(hp1).ops := taicpu(hp2).ops;
  13146. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  13147. case taicpu(hp2).ops of
  13148. 0:
  13149. taicpu(hp1).clearop(0);
  13150. 1:
  13151. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  13152. else
  13153. internalerror(2016041302);
  13154. end;
  13155. end;
  13156. {$ifndef i8086}
  13157. end
  13158. {
  13159. convert
  13160. j<c> .L1
  13161. mov 1,reg
  13162. jmp .L2
  13163. .L1
  13164. mov 0,reg
  13165. .L2
  13166. into
  13167. mov 0,reg
  13168. set<not(c)> reg
  13169. take care of alignment and that the mov 0,reg is not converted into a xor as this
  13170. would destroy the flag contents
  13171. }
  13172. else if MatchInstruction(hp1,A_MOV,[]) and
  13173. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13174. {$ifdef i386}
  13175. (
  13176. { Under i386, ESI, EDI, EBP and ESP
  13177. don't have an 8-bit representation }
  13178. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  13179. ) and
  13180. {$endif i386}
  13181. (taicpu(hp1).oper[0]^.val=1) and
  13182. GetNextInstruction(hp1,hp2) and
  13183. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  13184. GetNextInstruction(hp2,hp3) and
  13185. (hp3.typ=ait_label) and
  13186. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  13187. (tai_label(hp3).labsym.getrefs=1) and
  13188. GetNextInstruction(hp3,hp4) and
  13189. MatchInstruction(hp4,A_MOV,[]) and
  13190. MatchOpType(taicpu(hp4),top_const,top_reg) and
  13191. (taicpu(hp4).oper[0]^.val=0) and
  13192. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  13193. GetNextInstruction(hp4,hp5) and
  13194. (hp5.typ=ait_label) and
  13195. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  13196. (tai_label(hp5).labsym.getrefs=1) then
  13197. begin
  13198. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  13199. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  13200. { remove last label }
  13201. RemoveInstruction(hp5);
  13202. { remove second label }
  13203. RemoveInstruction(hp3);
  13204. { remove jmp }
  13205. RemoveInstruction(hp2);
  13206. if taicpu(hp1).opsize=S_B then
  13207. RemoveInstruction(hp1)
  13208. else
  13209. taicpu(hp1).loadconst(0,0);
  13210. taicpu(hp4).opcode:=A_SETcc;
  13211. taicpu(hp4).opsize:=S_B;
  13212. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  13213. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  13214. taicpu(hp4).opercnt:=1;
  13215. taicpu(hp4).ops:=1;
  13216. taicpu(hp4).freeop(1);
  13217. RemoveCurrentP(p);
  13218. Result:=true;
  13219. exit;
  13220. end
  13221. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  13222. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  13223. begin
  13224. { check for
  13225. jCC xxx
  13226. <several movs>
  13227. xxx:
  13228. Also spot:
  13229. Jcc xxx
  13230. <several movs>
  13231. jmp xxx
  13232. Change to:
  13233. <several cmovs with inverted condition>
  13234. jmp xxx (only for the 2nd case)
  13235. }
  13236. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  13237. if CMOVTracking^.State <> tsInvalid then
  13238. begin
  13239. CMovTracking^.Process(p);
  13240. Result := True;
  13241. end;
  13242. CMOVTracking^.Done;
  13243. {$endif i8086}
  13244. end;
  13245. end;
  13246. end;
  13247. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  13248. var
  13249. hp1,hp2,hp3: tai;
  13250. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  13251. NewSize: TOpSize;
  13252. NewRegSize: TSubRegister;
  13253. Limit: TCgInt;
  13254. SwapOper: POper;
  13255. begin
  13256. result:=false;
  13257. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  13258. GetNextInstruction(p,hp1) and
  13259. (hp1.typ = ait_instruction);
  13260. if reg_and_hp1_is_instr and
  13261. (
  13262. (taicpu(hp1).opcode <> A_LEA) or
  13263. { If the LEA instruction can be converted into an arithmetic instruction,
  13264. it may be possible to then fold it. }
  13265. (
  13266. { If the flags register is in use, don't change the instruction
  13267. to an ADD otherwise this will scramble the flags. [Kit] }
  13268. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13269. ConvertLEA(taicpu(hp1))
  13270. )
  13271. ) and
  13272. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  13273. GetNextInstruction(hp1,hp2) and
  13274. MatchInstruction(hp2,A_MOV,[]) and
  13275. (taicpu(hp2).oper[0]^.typ = top_reg) and
  13276. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  13277. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  13278. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  13279. {$ifdef i386}
  13280. { not all registers have byte size sub registers on i386 }
  13281. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  13282. {$endif i386}
  13283. (((taicpu(hp1).ops=2) and
  13284. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  13285. ((taicpu(hp1).ops=1) and
  13286. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  13287. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  13288. begin
  13289. { change movsX/movzX reg/ref, reg2
  13290. add/sub/or/... reg3/$const, reg2
  13291. mov reg2 reg/ref
  13292. to add/sub/or/... reg3/$const, reg/ref }
  13293. { by example:
  13294. movswl %si,%eax movswl %si,%eax p
  13295. decl %eax addl %edx,%eax hp1
  13296. movw %ax,%si movw %ax,%si hp2
  13297. ->
  13298. movswl %si,%eax movswl %si,%eax p
  13299. decw %eax addw %edx,%eax hp1
  13300. movw %ax,%si movw %ax,%si hp2
  13301. }
  13302. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  13303. {
  13304. ->
  13305. movswl %si,%eax movswl %si,%eax p
  13306. decw %si addw %dx,%si hp1
  13307. movw %ax,%si movw %ax,%si hp2
  13308. }
  13309. case taicpu(hp1).ops of
  13310. 1:
  13311. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  13312. 2:
  13313. begin
  13314. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  13315. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  13316. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  13317. end;
  13318. else
  13319. internalerror(2008042702);
  13320. end;
  13321. {
  13322. ->
  13323. decw %si addw %dx,%si p
  13324. }
  13325. DebugMsg(SPeepholeOptimization + 'var3',p);
  13326. RemoveCurrentP(p, hp1);
  13327. RemoveInstruction(hp2);
  13328. Result := True;
  13329. Exit;
  13330. end;
  13331. if reg_and_hp1_is_instr and
  13332. (taicpu(hp1).opcode = A_MOV) and
  13333. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13334. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13335. {$ifdef x86_64}
  13336. { check for implicit extension to 64 bit }
  13337. or
  13338. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13339. (taicpu(hp1).opsize=S_Q) and
  13340. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13341. )
  13342. {$endif x86_64}
  13343. )
  13344. then
  13345. begin
  13346. { change
  13347. movx %reg1,%reg2
  13348. mov %reg2,%reg3
  13349. dealloc %reg2
  13350. into
  13351. movx %reg,%reg3
  13352. }
  13353. TransferUsedRegs(TmpUsedRegs);
  13354. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13355. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13356. begin
  13357. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13358. {$ifdef x86_64}
  13359. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13360. (taicpu(hp1).opsize=S_Q) then
  13361. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13362. else
  13363. {$endif x86_64}
  13364. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13365. RemoveInstruction(hp1);
  13366. Result := True;
  13367. Exit;
  13368. end;
  13369. end;
  13370. if reg_and_hp1_is_instr and
  13371. ((taicpu(hp1).opcode=A_MOV) or
  13372. (taicpu(hp1).opcode=A_ADD) or
  13373. (taicpu(hp1).opcode=A_SUB) or
  13374. (taicpu(hp1).opcode=A_CMP) or
  13375. (taicpu(hp1).opcode=A_OR) or
  13376. (taicpu(hp1).opcode=A_XOR) or
  13377. (taicpu(hp1).opcode=A_AND)
  13378. ) and
  13379. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13380. begin
  13381. AndTest := (taicpu(hp1).opcode=A_AND) and
  13382. GetNextInstruction(hp1, hp2) and
  13383. (hp2.typ = ait_instruction) and
  13384. (
  13385. (
  13386. (taicpu(hp2).opcode=A_TEST) and
  13387. (
  13388. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13389. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13390. (
  13391. { If the AND and TEST instructions share a constant, this is also valid }
  13392. (taicpu(hp1).oper[0]^.typ = top_const) and
  13393. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13394. )
  13395. ) and
  13396. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13397. ) or
  13398. (
  13399. (taicpu(hp2).opcode=A_CMP) and
  13400. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13401. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13402. )
  13403. );
  13404. { change
  13405. movx (oper),%reg2
  13406. and $x,%reg2
  13407. test %reg2,%reg2
  13408. dealloc %reg2
  13409. into
  13410. op %reg1,%reg3
  13411. if the second op accesses only the bits stored in reg1
  13412. }
  13413. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13414. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13415. (taicpu(hp1).oper[0]^.typ = top_const) and
  13416. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13417. AndTest then
  13418. begin
  13419. { Check if the AND constant is in range }
  13420. case taicpu(p).opsize of
  13421. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13422. begin
  13423. NewSize := S_B;
  13424. Limit := $FF;
  13425. end;
  13426. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13427. begin
  13428. NewSize := S_W;
  13429. Limit := $FFFF;
  13430. end;
  13431. {$ifdef x86_64}
  13432. S_LQ:
  13433. begin
  13434. NewSize := S_L;
  13435. Limit := $FFFFFFFF;
  13436. end;
  13437. {$endif x86_64}
  13438. else
  13439. InternalError(2021120303);
  13440. end;
  13441. if (
  13442. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13443. { Check for negative operands }
  13444. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13445. ) and
  13446. GetNextInstruction(hp2,hp3) and
  13447. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13448. (taicpu(hp3).condition in [C_E,C_NE]) then
  13449. begin
  13450. TransferUsedRegs(TmpUsedRegs);
  13451. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13452. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13453. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13454. begin
  13455. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13456. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13457. taicpu(hp1).opcode := A_TEST;
  13458. taicpu(hp1).opsize := NewSize;
  13459. RemoveInstruction(hp2);
  13460. RemoveCurrentP(p, hp1);
  13461. Result:=true;
  13462. exit;
  13463. end;
  13464. end;
  13465. end;
  13466. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13467. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13468. (taicpu(hp1).opsize=S_B)) or
  13469. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13470. (taicpu(hp1).opsize=S_W))
  13471. {$ifdef x86_64}
  13472. or ((taicpu(p).opsize=S_LQ) and
  13473. (taicpu(hp1).opsize=S_L))
  13474. {$endif x86_64}
  13475. ) and
  13476. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13477. begin
  13478. { change
  13479. movx %reg1,%reg2
  13480. op %reg2,%reg3
  13481. dealloc %reg2
  13482. into
  13483. op %reg1,%reg3
  13484. if the second op accesses only the bits stored in reg1
  13485. }
  13486. TransferUsedRegs(TmpUsedRegs);
  13487. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13488. if AndTest then
  13489. begin
  13490. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13491. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13492. end
  13493. else
  13494. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13495. if not RegUsed then
  13496. begin
  13497. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13498. if taicpu(p).oper[0]^.typ=top_reg then
  13499. begin
  13500. case taicpu(hp1).opsize of
  13501. S_B:
  13502. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13503. S_W:
  13504. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13505. S_L:
  13506. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13507. else
  13508. Internalerror(2020102301);
  13509. end;
  13510. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13511. end
  13512. else
  13513. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13514. RemoveCurrentP(p);
  13515. if AndTest then
  13516. RemoveInstruction(hp2);
  13517. result:=true;
  13518. exit;
  13519. end;
  13520. end
  13521. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13522. (
  13523. { Bitwise operations only }
  13524. (taicpu(hp1).opcode=A_AND) or
  13525. (taicpu(hp1).opcode=A_TEST) or
  13526. (
  13527. (taicpu(hp1).oper[0]^.typ = top_const) and
  13528. (
  13529. (taicpu(hp1).opcode=A_OR) or
  13530. (taicpu(hp1).opcode=A_XOR)
  13531. )
  13532. )
  13533. ) and
  13534. (
  13535. (taicpu(hp1).oper[0]^.typ = top_const) or
  13536. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13537. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13538. ) then
  13539. begin
  13540. { change
  13541. movx %reg2,%reg2
  13542. op const,%reg2
  13543. into
  13544. op const,%reg2 (smaller version)
  13545. movx %reg2,%reg2
  13546. also change
  13547. movx %reg1,%reg2
  13548. and/test (oper),%reg2
  13549. dealloc %reg2
  13550. into
  13551. and/test (oper),%reg1
  13552. }
  13553. case taicpu(p).opsize of
  13554. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13555. begin
  13556. NewSize := S_B;
  13557. NewRegSize := R_SUBL;
  13558. Limit := $FF;
  13559. end;
  13560. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13561. begin
  13562. NewSize := S_W;
  13563. NewRegSize := R_SUBW;
  13564. Limit := $FFFF;
  13565. end;
  13566. {$ifdef x86_64}
  13567. S_LQ:
  13568. begin
  13569. NewSize := S_L;
  13570. NewRegSize := R_SUBD;
  13571. Limit := $FFFFFFFF;
  13572. end;
  13573. {$endif x86_64}
  13574. else
  13575. Internalerror(2021120302);
  13576. end;
  13577. TransferUsedRegs(TmpUsedRegs);
  13578. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13579. if AndTest then
  13580. begin
  13581. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13582. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13583. end
  13584. else
  13585. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13586. if
  13587. (
  13588. (taicpu(p).opcode = A_MOVZX) and
  13589. (
  13590. (taicpu(hp1).opcode=A_AND) or
  13591. (taicpu(hp1).opcode=A_TEST)
  13592. ) and
  13593. not (
  13594. { If both are references, then the final instruction will have
  13595. both operands as references, which is not allowed }
  13596. (taicpu(p).oper[0]^.typ = top_ref) and
  13597. (taicpu(hp1).oper[0]^.typ = top_ref)
  13598. ) and
  13599. not RegUsed
  13600. ) or
  13601. (
  13602. (
  13603. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13604. not RegUsed
  13605. ) and
  13606. (taicpu(p).oper[0]^.typ = top_reg) and
  13607. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13608. (taicpu(hp1).oper[0]^.typ = top_const) and
  13609. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13610. ) then
  13611. begin
  13612. {$if defined(i386) or defined(i8086)}
  13613. { If the target size is 8-bit, make sure we can actually encode it }
  13614. 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
  13615. Exit;
  13616. {$endif i386 or i8086}
  13617. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13618. taicpu(hp1).opsize := NewSize;
  13619. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13620. if AndTest then
  13621. begin
  13622. RemoveInstruction(hp2);
  13623. if not RegUsed then
  13624. begin
  13625. taicpu(hp1).opcode := A_TEST;
  13626. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13627. begin
  13628. { Make sure the reference is the second operand }
  13629. SwapOper := taicpu(hp1).oper[0];
  13630. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13631. taicpu(hp1).oper[1] := SwapOper;
  13632. end;
  13633. end;
  13634. end;
  13635. case taicpu(hp1).oper[0]^.typ of
  13636. top_reg:
  13637. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13638. top_const:
  13639. { For the AND/TEST case }
  13640. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13641. else
  13642. ;
  13643. end;
  13644. if RegUsed then
  13645. begin
  13646. AsmL.Remove(p);
  13647. AsmL.InsertAfter(p, hp1);
  13648. p := hp1;
  13649. end
  13650. else
  13651. RemoveCurrentP(p, hp1);
  13652. result:=true;
  13653. exit;
  13654. end;
  13655. end;
  13656. end;
  13657. if reg_and_hp1_is_instr and
  13658. (taicpu(p).oper[0]^.typ = top_reg) and
  13659. (
  13660. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13661. ) and
  13662. (taicpu(hp1).oper[0]^.typ = top_const) and
  13663. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13664. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13665. { Minimum shift value allowed is the bit difference between the sizes }
  13666. (taicpu(hp1).oper[0]^.val >=
  13667. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13668. 8 * (
  13669. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13670. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13671. )
  13672. ) then
  13673. begin
  13674. { For:
  13675. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13676. shl/sal ##, %reg1
  13677. Remove the movsx/movzx instruction if the shift overwrites the
  13678. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13679. }
  13680. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13681. RemoveCurrentP(p, hp1);
  13682. Result := True;
  13683. Exit;
  13684. end
  13685. else if reg_and_hp1_is_instr and
  13686. (taicpu(p).oper[0]^.typ = top_reg) and
  13687. (
  13688. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13689. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13690. ) and
  13691. (taicpu(hp1).oper[0]^.typ = top_const) and
  13692. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13693. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13694. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13695. (taicpu(hp1).oper[0]^.val <
  13696. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13697. 8 * (
  13698. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13699. )
  13700. ) then
  13701. begin
  13702. { For:
  13703. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13704. sar ##, %reg1 shr ##, %reg1
  13705. Move the shift to before the movx instruction if the shift value
  13706. is not too large.
  13707. }
  13708. asml.Remove(hp1);
  13709. asml.InsertBefore(hp1, p);
  13710. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13711. case taicpu(p).opsize of
  13712. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13713. taicpu(hp1).opsize := S_B;
  13714. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13715. taicpu(hp1).opsize := S_W;
  13716. {$ifdef x86_64}
  13717. S_LQ:
  13718. taicpu(hp1).opsize := S_L;
  13719. {$endif}
  13720. else
  13721. InternalError(2020112401);
  13722. end;
  13723. if (taicpu(hp1).opcode = A_SHR) then
  13724. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13725. else
  13726. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13727. Result := True;
  13728. end;
  13729. if reg_and_hp1_is_instr and
  13730. (taicpu(p).oper[0]^.typ = top_reg) and
  13731. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13732. (
  13733. (taicpu(hp1).opcode = taicpu(p).opcode)
  13734. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13735. {$ifdef x86_64}
  13736. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13737. {$endif x86_64}
  13738. ) then
  13739. begin
  13740. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13741. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13742. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13743. begin
  13744. {
  13745. For example:
  13746. movzbw %al,%ax
  13747. movzwl %ax,%eax
  13748. Compress into:
  13749. movzbl %al,%eax
  13750. }
  13751. RegUsed := False;
  13752. case taicpu(p).opsize of
  13753. S_BW:
  13754. case taicpu(hp1).opsize of
  13755. S_WL:
  13756. begin
  13757. taicpu(p).opsize := S_BL;
  13758. RegUsed := True;
  13759. end;
  13760. {$ifdef x86_64}
  13761. S_WQ:
  13762. begin
  13763. if taicpu(p).opcode = A_MOVZX then
  13764. begin
  13765. taicpu(p).opsize := S_BL;
  13766. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13767. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13768. end
  13769. else
  13770. taicpu(p).opsize := S_BQ;
  13771. RegUsed := True;
  13772. end;
  13773. {$endif x86_64}
  13774. else
  13775. ;
  13776. end;
  13777. {$ifdef x86_64}
  13778. S_BL:
  13779. case taicpu(hp1).opsize of
  13780. S_LQ:
  13781. begin
  13782. if taicpu(p).opcode = A_MOVZX then
  13783. begin
  13784. taicpu(p).opsize := S_BL;
  13785. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13786. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13787. end
  13788. else
  13789. taicpu(p).opsize := S_BQ;
  13790. RegUsed := True;
  13791. end;
  13792. else
  13793. ;
  13794. end;
  13795. S_WL:
  13796. case taicpu(hp1).opsize of
  13797. S_LQ:
  13798. begin
  13799. if taicpu(p).opcode = A_MOVZX then
  13800. begin
  13801. taicpu(p).opsize := S_WL;
  13802. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13803. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13804. end
  13805. else
  13806. taicpu(p).opsize := S_WQ;
  13807. RegUsed := True;
  13808. end;
  13809. else
  13810. ;
  13811. end;
  13812. {$endif x86_64}
  13813. else
  13814. ;
  13815. end;
  13816. if RegUsed then
  13817. begin
  13818. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13819. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13820. RemoveInstruction(hp1);
  13821. Result := True;
  13822. Exit;
  13823. end;
  13824. end;
  13825. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13826. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13827. GetNextInstruction(hp1, hp2) and
  13828. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13829. (
  13830. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13831. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13832. {$ifdef x86_64}
  13833. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13834. {$endif x86_64}
  13835. ) and
  13836. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13837. (
  13838. (
  13839. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13840. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13841. ) or
  13842. (
  13843. { Only allow the operands in reverse order for TEST instructions }
  13844. (taicpu(hp2).opcode = A_TEST) and
  13845. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13846. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13847. )
  13848. ) then
  13849. begin
  13850. {
  13851. For example:
  13852. movzbl %al,%eax
  13853. movzbl (ref),%edx
  13854. andl %edx,%eax
  13855. (%edx deallocated)
  13856. Change to:
  13857. andb (ref),%al
  13858. movzbl %al,%eax
  13859. Rules are:
  13860. - First two instructions have the same opcode and opsize
  13861. - First instruction's operands are the same super-register
  13862. - Second instruction operates on a different register
  13863. - Third instruction is AND, OR, XOR or TEST
  13864. - Third instruction's operands are the destination registers of the first two instructions
  13865. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13866. - Second instruction's destination register is deallocated afterwards
  13867. }
  13868. TransferUsedRegs(TmpUsedRegs);
  13869. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13870. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13871. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13872. begin
  13873. case taicpu(p).opsize of
  13874. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13875. NewSize := S_B;
  13876. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13877. NewSize := S_W;
  13878. {$ifdef x86_64}
  13879. S_LQ:
  13880. NewSize := S_L;
  13881. {$endif x86_64}
  13882. else
  13883. InternalError(2021120301);
  13884. end;
  13885. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13886. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13887. taicpu(hp2).opsize := NewSize;
  13888. RemoveInstruction(hp1);
  13889. { With TEST, it's best to keep the MOVX instruction at the top }
  13890. if (taicpu(hp2).opcode <> A_TEST) then
  13891. begin
  13892. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13893. asml.Remove(p);
  13894. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13895. asml.InsertAfter(p, hp2);
  13896. p := hp2;
  13897. end
  13898. else
  13899. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13900. Result := True;
  13901. Exit;
  13902. end;
  13903. end;
  13904. end;
  13905. if taicpu(p).opcode=A_MOVZX then
  13906. begin
  13907. { removes superfluous And's after movzx's }
  13908. if reg_and_hp1_is_instr and
  13909. (taicpu(hp1).opcode = A_AND) and
  13910. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13911. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13912. {$ifdef x86_64}
  13913. { check for implicit extension to 64 bit }
  13914. or
  13915. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13916. (taicpu(hp1).opsize=S_Q) and
  13917. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13918. )
  13919. {$endif x86_64}
  13920. )
  13921. then
  13922. begin
  13923. case taicpu(p).opsize Of
  13924. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13925. if (taicpu(hp1).oper[0]^.val = $ff) then
  13926. begin
  13927. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13928. RemoveInstruction(hp1);
  13929. Result:=true;
  13930. exit;
  13931. end;
  13932. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13933. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13934. begin
  13935. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13936. RemoveInstruction(hp1);
  13937. Result:=true;
  13938. exit;
  13939. end;
  13940. {$ifdef x86_64}
  13941. S_LQ:
  13942. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13943. begin
  13944. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13945. RemoveInstruction(hp1);
  13946. Result:=true;
  13947. exit;
  13948. end;
  13949. {$endif x86_64}
  13950. else
  13951. ;
  13952. end;
  13953. { we cannot get rid of the and, but can we get rid of the movz ?}
  13954. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13955. begin
  13956. case taicpu(p).opsize Of
  13957. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13958. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13959. begin
  13960. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13961. RemoveCurrentP(p,hp1);
  13962. Result:=true;
  13963. exit;
  13964. end;
  13965. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13966. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13967. begin
  13968. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13969. RemoveCurrentP(p,hp1);
  13970. Result:=true;
  13971. exit;
  13972. end;
  13973. {$ifdef x86_64}
  13974. S_LQ:
  13975. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13976. begin
  13977. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13978. RemoveCurrentP(p,hp1);
  13979. Result:=true;
  13980. exit;
  13981. end;
  13982. {$endif x86_64}
  13983. else
  13984. ;
  13985. end;
  13986. end;
  13987. end;
  13988. { changes some movzx constructs to faster synonyms (all examples
  13989. are given with eax/ax, but are also valid for other registers)}
  13990. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13991. begin
  13992. case taicpu(p).opsize of
  13993. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13994. (the machine code is equivalent to movzbl %al,%eax), but the
  13995. code generator still generates that assembler instruction and
  13996. it is silently converted. This should probably be checked.
  13997. [Kit] }
  13998. S_BW:
  13999. begin
  14000. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  14001. (
  14002. not IsMOVZXAcceptable
  14003. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  14004. or (
  14005. (cs_opt_size in current_settings.optimizerswitches) and
  14006. (taicpu(p).oper[1]^.reg = NR_AX)
  14007. )
  14008. ) then
  14009. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  14010. begin
  14011. DebugMsg(SPeepholeOptimization + 'var7',p);
  14012. taicpu(p).opcode := A_AND;
  14013. taicpu(p).changeopsize(S_W);
  14014. taicpu(p).loadConst(0,$ff);
  14015. Result := True;
  14016. end
  14017. else if not IsMOVZXAcceptable and
  14018. GetNextInstruction(p, hp1) and
  14019. (tai(hp1).typ = ait_instruction) and
  14020. (taicpu(hp1).opcode = A_AND) and
  14021. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14022. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14023. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  14024. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  14025. begin
  14026. DebugMsg(SPeepholeOptimization + 'var8',p);
  14027. taicpu(p).opcode := A_MOV;
  14028. taicpu(p).changeopsize(S_W);
  14029. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  14030. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14031. Result := True;
  14032. end;
  14033. end;
  14034. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  14035. S_BL:
  14036. if not IsMOVZXAcceptable then
  14037. begin
  14038. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  14039. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  14040. begin
  14041. DebugMsg(SPeepholeOptimization + 'var9',p);
  14042. taicpu(p).opcode := A_AND;
  14043. taicpu(p).changeopsize(S_L);
  14044. taicpu(p).loadConst(0,$ff);
  14045. Result := True;
  14046. end
  14047. else if GetNextInstruction(p, hp1) and
  14048. (tai(hp1).typ = ait_instruction) and
  14049. (taicpu(hp1).opcode = A_AND) and
  14050. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14051. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14052. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  14053. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  14054. begin
  14055. DebugMsg(SPeepholeOptimization + 'var10',p);
  14056. taicpu(p).opcode := A_MOV;
  14057. taicpu(p).changeopsize(S_L);
  14058. { do not use R_SUBWHOLE
  14059. as movl %rdx,%eax
  14060. is invalid in assembler PM }
  14061. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14062. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14063. Result := True;
  14064. end;
  14065. end;
  14066. {$endif i8086}
  14067. S_WL:
  14068. if not IsMOVZXAcceptable then
  14069. begin
  14070. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  14071. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  14072. begin
  14073. DebugMsg(SPeepholeOptimization + 'var11',p);
  14074. taicpu(p).opcode := A_AND;
  14075. taicpu(p).changeopsize(S_L);
  14076. taicpu(p).loadConst(0,$ffff);
  14077. Result := True;
  14078. end
  14079. else if GetNextInstruction(p, hp1) and
  14080. (tai(hp1).typ = ait_instruction) and
  14081. (taicpu(hp1).opcode = A_AND) and
  14082. (taicpu(hp1).oper[0]^.typ = top_const) and
  14083. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14084. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14085. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  14086. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  14087. begin
  14088. DebugMsg(SPeepholeOptimization + 'var12',p);
  14089. taicpu(p).opcode := A_MOV;
  14090. taicpu(p).changeopsize(S_L);
  14091. { do not use R_SUBWHOLE
  14092. as movl %rdx,%eax
  14093. is invalid in assembler PM }
  14094. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14095. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  14096. Result := True;
  14097. end;
  14098. end;
  14099. else
  14100. InternalError(2017050705);
  14101. end;
  14102. end
  14103. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  14104. begin
  14105. if GetNextInstruction(p, hp1) and
  14106. (tai(hp1).typ = ait_instruction) and
  14107. (taicpu(hp1).opcode = A_AND) and
  14108. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14109. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14110. begin
  14111. case taicpu(p).opsize Of
  14112. S_BL:
  14113. if (taicpu(hp1).opsize <> S_L) or
  14114. (taicpu(hp1).oper[0]^.val > $FF) then
  14115. begin
  14116. DebugMsg(SPeepholeOptimization + 'var13',p);
  14117. taicpu(hp1).changeopsize(S_L);
  14118. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14119. Include(OptsToCheck, aoc_ForceNewIteration);
  14120. end;
  14121. S_WL:
  14122. if (taicpu(hp1).opsize <> S_L) or
  14123. (taicpu(hp1).oper[0]^.val > $FFFF) then
  14124. begin
  14125. DebugMsg(SPeepholeOptimization + 'var14',p);
  14126. taicpu(hp1).changeopsize(S_L);
  14127. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  14128. Include(OptsToCheck, aoc_ForceNewIteration);
  14129. end;
  14130. S_BW:
  14131. if (taicpu(hp1).opsize <> S_W) or
  14132. (taicpu(hp1).oper[0]^.val > $FF) then
  14133. begin
  14134. DebugMsg(SPeepholeOptimization + 'var15',p);
  14135. taicpu(hp1).changeopsize(S_W);
  14136. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14137. Include(OptsToCheck, aoc_ForceNewIteration);
  14138. end;
  14139. else
  14140. Internalerror(2017050704)
  14141. end;
  14142. end;
  14143. end;
  14144. end;
  14145. end;
  14146. {$ifdef x86_64}
  14147. function TX86AsmOptimizer.DoZeroUpper32Opt(var mov_p: tai; var and_p: tai): Boolean;
  14148. var
  14149. hp1, old_hp1: tai;
  14150. FullSourceReg, FullTargetReg: TRegister;
  14151. begin
  14152. if (mov_p.typ<>ait_instruction) or
  14153. (taicpu(mov_p).opsize<>S_L) or
  14154. not MatchOpType(taicpu(mov_p),top_reg,top_reg) then
  14155. InternalError(2025062801);
  14156. Result:=False;
  14157. FullSourceReg:=taicpu(mov_p).oper[0]^.reg; setsubreg(FullSourceReg, R_SUBQ);
  14158. FullTargetReg:=taicpu(mov_p).oper[1]^.reg; setsubreg(FullTargetReg, R_SUBQ);
  14159. { Mark the registers in the MOV command as "used" }
  14160. IncludeRegInUsedRegs(FullSourceReg,UsedRegs);
  14161. IncludeRegInUsedRegs(FullTargetReg,UsedRegs);
  14162. { This is a little hack to get DeepMOVOpt to replace the full 64-bit
  14163. registers. The MOV instruction will be put back as it was afterwards
  14164. (unless it got removed). }
  14165. taicpu(mov_p).oper[0]^.reg:=FullSourceReg;
  14166. taicpu(mov_p).oper[1]^.reg:=FullTargetReg;
  14167. { Start after the and_p otherwise that instruction will be considered
  14168. to have modified the source register }
  14169. old_hp1:=and_p;
  14170. while GetNextInstructionUsingReg(old_hp1,hp1,FullTargetReg) and
  14171. (hp1.typ=ait_instruction) do
  14172. begin
  14173. if RegReadByInstruction(FullTargetReg,hp1) and
  14174. not RegModifiedBetween(FullSourceReg,old_hp1,hp1) and
  14175. DeepMOVOpt(taicpu(mov_p),taicpu(hp1)) then
  14176. begin
  14177. { A change has occurred, just not in mov_p }
  14178. Include(OptsToCheck, aoc_ForceNewIteration);
  14179. TransferUsedRegs(TmpUsedRegs);
  14180. UpdateUsedRegsBetween(TmpUsedRegs,tai(mov_p.Next), hp1);
  14181. if not RegUsedAfterInstruction(FullTargetReg,hp1,TmpUsedRegs) and
  14182. { Just in case something didn't get modified (e.g. an
  14183. implicit register) }
  14184. not RegReadByInstruction(FullTargetReg,hp1) then
  14185. begin
  14186. { We can remove the original MOV }
  14187. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3d done',mov_p);
  14188. RemoveCurrentP(mov_p);
  14189. Result := True;
  14190. Exit;
  14191. end;
  14192. end
  14193. else
  14194. Break;
  14195. old_hp1:=hp1;
  14196. end;
  14197. { Put the MOV instruction back as it was }
  14198. setsubreg(taicpu(mov_p).oper[0]^.reg,R_SUBD);
  14199. setsubreg(taicpu(mov_p).oper[1]^.reg,R_SUBD);
  14200. end;
  14201. {$endif x86_64}
  14202. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  14203. var
  14204. hp1, hp2 : tai;
  14205. MaskLength : Cardinal;
  14206. MaskedBits : TCgInt;
  14207. ActiveReg : TRegister;
  14208. begin
  14209. Result:=false;
  14210. { There are no optimisations for reference targets }
  14211. if (taicpu(p).oper[1]^.typ <> top_reg) then
  14212. Exit;
  14213. { Saves on a bunch of dereferences }
  14214. ActiveReg := taicpu(p).oper[1]^.reg;
  14215. while GetNextInstruction(p, hp1) and
  14216. (hp1.typ = ait_instruction) do
  14217. begin
  14218. if (taicpu(p).oper[0]^.typ = top_const) then
  14219. begin
  14220. case taicpu(hp1).opcode of
  14221. A_AND:
  14222. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14223. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14224. { the second register must contain the first one, so compare their subreg types }
  14225. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  14226. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  14227. { change
  14228. and const1, reg
  14229. and const2, reg
  14230. to
  14231. and (const1 and const2), reg
  14232. }
  14233. begin
  14234. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  14235. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  14236. RemoveCurrentP(p, hp1);
  14237. Result:=true;
  14238. exit;
  14239. end;
  14240. A_CMP:
  14241. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  14242. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  14243. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  14244. { Just check that the condition on the next instruction is compatible }
  14245. GetNextInstruction(hp1, hp2) and
  14246. (hp2.typ = ait_instruction) and
  14247. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  14248. then
  14249. { change
  14250. and 2^n, reg
  14251. cmp 2^n, reg
  14252. j(c) / set(c) / cmov(c) (c is equal or not equal)
  14253. to
  14254. and 2^n, reg
  14255. test reg, reg
  14256. j(~c) / set(~c) / cmov(~c)
  14257. }
  14258. begin
  14259. { Keep TEST instruction in, rather than remove it, because
  14260. it may trigger other optimisations such as MovAndTest2Test }
  14261. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  14262. taicpu(hp1).opcode := A_TEST;
  14263. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  14264. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  14265. Result := True;
  14266. Exit;
  14267. end
  14268. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  14269. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14270. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  14271. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  14272. { change
  14273. and $ff/$ff/$ffff, reg
  14274. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  14275. dealloc reg
  14276. to
  14277. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  14278. }
  14279. begin
  14280. TransferUsedRegs(TmpUsedRegs);
  14281. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14282. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  14283. begin
  14284. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  14285. case taicpu(p).oper[0]^.val of
  14286. $ff:
  14287. begin
  14288. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  14289. taicpu(hp1).opsize:=S_B;
  14290. end;
  14291. $ffff:
  14292. begin
  14293. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  14294. taicpu(hp1).opsize:=S_W;
  14295. end;
  14296. $ffffffff:
  14297. begin
  14298. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  14299. taicpu(hp1).opsize:=S_L;
  14300. end;
  14301. else
  14302. Internalerror(2023030401);
  14303. end;
  14304. RemoveCurrentP(p);
  14305. Result := True;
  14306. Exit;
  14307. end;
  14308. end;
  14309. A_MOVZX:
  14310. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  14311. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  14312. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14313. (
  14314. (
  14315. (taicpu(p).opsize=S_W) and
  14316. (taicpu(hp1).opsize=S_BW)
  14317. ) or
  14318. (
  14319. (taicpu(p).opsize=S_L) and
  14320. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  14321. )
  14322. {$ifdef x86_64}
  14323. or
  14324. (
  14325. (taicpu(p).opsize=S_Q) and
  14326. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  14327. )
  14328. {$endif x86_64}
  14329. ) then
  14330. begin
  14331. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14332. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  14333. ) or
  14334. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14335. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  14336. then
  14337. begin
  14338. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  14339. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  14340. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  14341. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  14342. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  14343. }
  14344. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  14345. RemoveInstruction(hp1);
  14346. { See if there are other optimisations possible }
  14347. Continue;
  14348. end;
  14349. end;
  14350. A_SHL:
  14351. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14352. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  14353. begin
  14354. {$ifopt R+}
  14355. {$define RANGE_WAS_ON}
  14356. {$R-}
  14357. {$endif}
  14358. { get length of potential and mask }
  14359. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  14360. { really a mask? }
  14361. {$ifdef RANGE_WAS_ON}
  14362. {$R+}
  14363. {$endif}
  14364. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  14365. { unmasked part shifted out? }
  14366. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  14367. begin
  14368. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  14369. RemoveCurrentP(p, hp1);
  14370. Result:=true;
  14371. exit;
  14372. end;
  14373. end;
  14374. A_SHR:
  14375. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14376. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  14377. (taicpu(hp1).oper[0]^.val <= 63) then
  14378. begin
  14379. { Does SHR combined with the AND cover all the bits?
  14380. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  14381. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  14382. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  14383. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  14384. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  14385. begin
  14386. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  14387. RemoveCurrentP(p, hp1);
  14388. Result := True;
  14389. Exit;
  14390. end;
  14391. end;
  14392. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14393. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14394. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14395. begin
  14396. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14397. (
  14398. (
  14399. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14400. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14401. ) or (
  14402. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14403. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14404. {$ifdef x86_64}
  14405. ) or (
  14406. (taicpu(hp1).opsize = S_LQ) and
  14407. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14408. {$endif x86_64}
  14409. )
  14410. ) then
  14411. begin
  14412. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14413. begin
  14414. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14415. RemoveInstruction(hp1);
  14416. { See if there are other optimisations possible }
  14417. Continue;
  14418. end;
  14419. { The super-registers are the same though.
  14420. Note that this change by itself doesn't improve
  14421. code speed, but it opens up other optimisations. }
  14422. {$ifdef x86_64}
  14423. { Convert 64-bit register to 32-bit }
  14424. case taicpu(hp1).opsize of
  14425. S_BQ:
  14426. begin
  14427. taicpu(hp1).opsize := S_BL;
  14428. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14429. end;
  14430. S_WQ:
  14431. begin
  14432. taicpu(hp1).opsize := S_WL;
  14433. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14434. end
  14435. else
  14436. ;
  14437. end;
  14438. {$endif x86_64}
  14439. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14440. taicpu(hp1).opcode := A_MOVZX;
  14441. { See if there are other optimisations possible }
  14442. Continue;
  14443. end;
  14444. end;
  14445. else
  14446. ;
  14447. end;
  14448. end
  14449. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14450. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14451. begin
  14452. {$ifdef x86_64}
  14453. if (taicpu(p).opsize = S_Q) then
  14454. begin
  14455. { Never necessary }
  14456. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14457. RemoveCurrentP(p, hp1);
  14458. Result := True;
  14459. Exit;
  14460. end;
  14461. {$endif x86_64}
  14462. { Forward check to determine necessity of and %reg,%reg }
  14463. TransferUsedRegs(TmpUsedRegs);
  14464. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14465. case taicpu(hp1).opcode of
  14466. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14467. if (
  14468. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14469. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14470. ) and
  14471. (
  14472. (taicpu(hp1).opcode <> A_MOV) or
  14473. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14474. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14475. ) and
  14476. not (
  14477. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14478. (taicpu(hp1).opcode = A_MOV) and
  14479. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14480. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14481. ) and
  14482. (
  14483. (
  14484. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14485. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14486. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14487. ) or
  14488. (
  14489. {$ifdef x86_64}
  14490. (
  14491. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14492. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14493. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14494. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14495. ) and
  14496. {$endif x86_64}
  14497. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14498. )
  14499. ) then
  14500. begin
  14501. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14502. RemoveCurrentP(p, hp1);
  14503. Result := True;
  14504. Exit;
  14505. end;
  14506. A_ADD,
  14507. A_AND,
  14508. A_BSF,
  14509. A_BSR,
  14510. A_BTC,
  14511. A_BTR,
  14512. A_BTS,
  14513. A_OR,
  14514. A_SUB,
  14515. A_XOR:
  14516. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14517. if (
  14518. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14519. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14520. ) and
  14521. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14522. begin
  14523. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14524. RemoveCurrentP(p, hp1);
  14525. Result := True;
  14526. Exit;
  14527. end;
  14528. A_CMP,
  14529. A_TEST:
  14530. if (
  14531. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14532. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14533. ) and
  14534. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14535. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14536. begin
  14537. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14538. RemoveCurrentP(p, hp1);
  14539. Result := True;
  14540. Exit;
  14541. end;
  14542. A_BSWAP,
  14543. A_NEG,
  14544. A_NOT:
  14545. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14546. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14547. begin
  14548. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14549. RemoveCurrentP(p, hp1);
  14550. Result := True;
  14551. Exit;
  14552. end;
  14553. else
  14554. ;
  14555. end;
  14556. end;
  14557. if (taicpu(hp1).is_jmp) and
  14558. (taicpu(hp1).opcode<>A_JMP) and
  14559. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14560. begin
  14561. { change
  14562. and x, reg
  14563. jxx
  14564. to
  14565. test x, reg
  14566. jxx
  14567. if reg is deallocated before the
  14568. jump, but only if it's a conditional jump (PFV)
  14569. }
  14570. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14571. taicpu(p).opcode := A_TEST;
  14572. Exit;
  14573. end;
  14574. Break;
  14575. end;
  14576. { Lone AND tests }
  14577. if (taicpu(p).oper[0]^.typ = top_const) then
  14578. begin
  14579. {
  14580. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14581. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14582. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14583. }
  14584. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14585. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14586. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14587. begin
  14588. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14589. if taicpu(p).opsize = S_L then
  14590. begin
  14591. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14592. Result := True;
  14593. end;
  14594. end;
  14595. end;
  14596. { Backward check to determine necessity of and %reg,%reg }
  14597. if (taicpu(p).oper[0]^.typ = top_reg) and
  14598. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14599. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14600. begin
  14601. hp2:=p;
  14602. while GetLastInstruction(hp2, hp2) and
  14603. (cs_opt_level3 in current_settings.optimizerswitches) and
  14604. (hp2.typ=ait_instruction) and
  14605. not RegModifiedByInstruction(ActiveReg,hp2) do { loop };
  14606. if Assigned(hp2) and
  14607. RegModifiedByInstruction(ActiveReg,hp2) and { Also checks if hp2 is an instruction }
  14608. { Check size of instruction to determine if the AND is effectively
  14609. a null operation }
  14610. (
  14611. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14612. { Note: Don't include S_Q }
  14613. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14614. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14615. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14616. ) then
  14617. begin
  14618. { AND %reg,%reg is unnecessary to zero the upper 32 bits. }
  14619. DebugMsg(SPeepholeOptimization + 'AND %reg,%reg proven unnecessary after backward search (And2Nop)', p);
  14620. RemoveCurrentP(p, hp1);
  14621. Result:=True;
  14622. Exit;
  14623. end;
  14624. end;
  14625. end;
  14626. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14627. var
  14628. hp1, hp2: tai;
  14629. NewRef: TReference;
  14630. Distance: Cardinal;
  14631. TempTracking: TAllUsedRegs;
  14632. DoAddMov2Lea: Boolean;
  14633. { This entire nested function is used in an if-statement below, but we
  14634. want to avoid all the used reg transfers and GetNextInstruction calls
  14635. until we really have to check }
  14636. function MemRegisterNotUsedLater: Boolean; inline;
  14637. var
  14638. hp2: tai;
  14639. begin
  14640. TransferUsedRegs(TmpUsedRegs);
  14641. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14642. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14643. else
  14644. { p and hp1 will be adjacent }
  14645. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14646. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14647. end;
  14648. begin
  14649. Result := False;
  14650. DoAddMov2Lea:=false;
  14651. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14652. (taicpu(p).oper[1]^.typ = top_reg) then
  14653. begin
  14654. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14655. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14656. (hp1.typ <> ait_instruction) or
  14657. not
  14658. (
  14659. (cs_opt_level3 in current_settings.optimizerswitches) or
  14660. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14661. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14662. ) then
  14663. Exit;
  14664. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14665. addq $x, %rax
  14666. movq %rax, %rdx
  14667. sarq $63, %rdx
  14668. (%rax still in use)
  14669. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14670. leaq $x(%rax),%rdx
  14671. addq $x, %rax
  14672. sarq $63, %rdx
  14673. ...which is okay since it breaks the dependency chain between
  14674. addq and movq, but if OptPass2MOV is called first:
  14675. addq $x, %rax
  14676. cqto
  14677. ...which is better in all ways, taking only 2 cycles to execute
  14678. and much smaller in code size.
  14679. }
  14680. { The extra register tracking is quite strenuous }
  14681. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14682. MatchInstruction(hp1, A_MOV, []) then
  14683. begin
  14684. { Update the register tracking to the MOV instruction }
  14685. CopyUsedRegs(TempTracking);
  14686. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14687. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14688. else
  14689. { p and hp1 will be adjacent }
  14690. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14691. hp2 := hp1;
  14692. if OptPass2MOV(hp1) then
  14693. Include(OptsToCheck, aoc_ForceNewIteration);
  14694. { Reset the tracking to the current instruction }
  14695. RestoreUsedRegs(TempTracking);
  14696. ReleaseUsedRegs(TempTracking);
  14697. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14698. OptPass2ADD get called again }
  14699. if (hp1 <> hp2) then
  14700. begin
  14701. Result := True;
  14702. Exit;
  14703. end;
  14704. end;
  14705. { Change:
  14706. add %reg2,%reg1
  14707. (%reg2 not modified in between)
  14708. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14709. To:
  14710. mov/s/z #(%reg1,%reg2),%reg1
  14711. }
  14712. if (taicpu(p).oper[0]^.typ = top_reg) and
  14713. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14714. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14715. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14716. (
  14717. (
  14718. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14719. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14720. { r/esp cannot be an index }
  14721. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14722. ) or (
  14723. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14724. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14725. )
  14726. ) and (
  14727. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14728. (
  14729. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14730. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14731. MemRegisterNotUsedLater
  14732. )
  14733. ) then
  14734. begin
  14735. if (
  14736. { Instructions are guaranteed to be adjacent on -O2 and under }
  14737. (cs_opt_level3 in current_settings.optimizerswitches) and
  14738. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14739. ) then
  14740. begin
  14741. { If the other register is used in between, move the MOV
  14742. instruction to right after the ADD instruction so a
  14743. saving can still be made }
  14744. Asml.Remove(hp1);
  14745. Asml.InsertAfter(hp1, p);
  14746. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14747. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14748. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14749. RemoveCurrentp(p, hp1);
  14750. end
  14751. else
  14752. begin
  14753. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14754. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14755. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14756. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14757. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14758. { hp1 may not be the immediate next instruction under -O3 }
  14759. RemoveCurrentp(p)
  14760. else
  14761. RemoveCurrentp(p, hp1);
  14762. end;
  14763. Result := True;
  14764. Exit;
  14765. end;
  14766. { Change:
  14767. addl/q $x,%reg1
  14768. movl/q %reg1,%reg2
  14769. To:
  14770. leal/q $x(%reg1),%reg2
  14771. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14772. Breaks the dependency chain.
  14773. }
  14774. if (taicpu(p).oper[0]^.typ = top_const) and
  14775. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14776. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14777. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14778. (
  14779. { Instructions are guaranteed to be adjacent on -O2 and under }
  14780. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14781. (
  14782. { If the flags are used, don't make the optimisation,
  14783. otherwise they will be scrambled. Fixes #41148 }
  14784. (
  14785. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14786. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14787. ) and
  14788. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14789. )
  14790. ) then
  14791. begin
  14792. TransferUsedRegs(TmpUsedRegs);
  14793. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14794. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14795. else
  14796. { p and hp1 will be adjacent }
  14797. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14798. if (
  14799. SetAndTest(
  14800. (
  14801. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14802. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14803. ),
  14804. DoAddMov2Lea
  14805. ) or
  14806. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14807. not (cs_opt_size in current_settings.optimizerswitches)
  14808. ) then
  14809. begin
  14810. { Change the MOV instruction to a LEA instruction, and update the
  14811. first operand }
  14812. reference_reset(NewRef, 1, []);
  14813. NewRef.base := taicpu(p).oper[1]^.reg;
  14814. NewRef.scalefactor := 1;
  14815. { if the destination reg is the same as the ADD register,
  14816. and we keep the ADD instruction, do not add the offset
  14817. to LEA instruction, otherwise the reg gets increased by 2 times the offset value }
  14818. if DoAddMov2Lea or not MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^.reg) then
  14819. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14820. taicpu(hp1).opcode := A_LEA;
  14821. taicpu(hp1).loadref(0, NewRef);
  14822. if DoAddMov2Lea then
  14823. begin
  14824. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14825. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14826. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14827. { hp1 may not be the immediate next instruction under -O3 }
  14828. RemoveCurrentp(p)
  14829. else
  14830. RemoveCurrentp(p, hp1);
  14831. end
  14832. else
  14833. begin
  14834. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14835. { Move what is now the LEA instruction to before the ADD instruction }
  14836. Asml.Remove(hp1);
  14837. Asml.InsertBefore(hp1, p);
  14838. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14839. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14840. p := hp1;
  14841. end;
  14842. Result := True;
  14843. end;
  14844. end;
  14845. end;
  14846. end;
  14847. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14848. var
  14849. SubReg: TSubRegister;
  14850. hp1, hp2: tai;
  14851. CallJmp: Boolean;
  14852. begin
  14853. Result := False;
  14854. CallJmp := False;
  14855. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14856. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14857. with taicpu(p).oper[0]^.ref^ do
  14858. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14859. if (offset = 0) then
  14860. begin
  14861. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14862. begin
  14863. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14864. taicpu(p).opcode := A_ADD;
  14865. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14866. Result := True;
  14867. end
  14868. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14869. begin
  14870. if (base <> NR_NO) then
  14871. begin
  14872. if (scalefactor <= 1) then
  14873. begin
  14874. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14875. taicpu(p).opcode := A_ADD;
  14876. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14877. Result := True;
  14878. end;
  14879. end
  14880. else
  14881. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14882. if (scalefactor in [2, 4, 8]) then
  14883. begin
  14884. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14885. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14886. taicpu(p).opcode := A_SHL;
  14887. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14888. Result := True;
  14889. end;
  14890. end;
  14891. end
  14892. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14893. lot of latency, so break off the offset if %reg3 is used soon
  14894. afterwards }
  14895. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14896. { If 3-component addresses don't have additional latency, don't
  14897. perform this optimisation }
  14898. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14899. GetNextInstruction(p, hp1) and
  14900. (hp1.typ = ait_instruction) and
  14901. (
  14902. (
  14903. { Permit jumps and calls since they have a larger degree of overhead }
  14904. (
  14905. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14906. (
  14907. { ... unless the register specifies the location }
  14908. (taicpu(hp1).ops > 0) and
  14909. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14910. )
  14911. ) and
  14912. (
  14913. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14914. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14915. )
  14916. )
  14917. or
  14918. (
  14919. { Check up to two instructions ahead }
  14920. GetNextInstruction(hp1, hp2) and
  14921. (hp2.typ = ait_instruction) and
  14922. (
  14923. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14924. (
  14925. { Same as above }
  14926. (taicpu(hp2).ops > 0) and
  14927. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14928. )
  14929. ) and
  14930. (
  14931. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14932. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14933. )
  14934. )
  14935. ) then
  14936. begin
  14937. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14938. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14939. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14940. offset := 0;
  14941. if Assigned(symbol) or Assigned(relsymbol) then
  14942. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14943. else
  14944. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14945. { Inserting before the next instruction rather than after the
  14946. current instruction gives more accurate register tracking }
  14947. asml.InsertBefore(hp2, hp1);
  14948. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14949. Result := True;
  14950. end;
  14951. end;
  14952. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14953. var
  14954. hp1, hp2: tai;
  14955. NewRef: TReference;
  14956. Distance: Cardinal;
  14957. TempTracking: TAllUsedRegs;
  14958. DoSubMov2Lea: Boolean;
  14959. begin
  14960. Result := False;
  14961. DoSubMov2Lea:=false;
  14962. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14963. MatchOpType(taicpu(p),top_const,top_reg) then
  14964. begin
  14965. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14966. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14967. (hp1.typ <> ait_instruction) or
  14968. not
  14969. (
  14970. (cs_opt_level3 in current_settings.optimizerswitches) or
  14971. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14972. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14973. ) then
  14974. Exit;
  14975. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14976. subq $x, %rax
  14977. movq %rax, %rdx
  14978. sarq $63, %rdx
  14979. (%rax still in use)
  14980. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14981. leaq $-x(%rax),%rdx
  14982. movq $x, %rax
  14983. sarq $63, %rdx
  14984. ...which is okay since it breaks the dependency chain between
  14985. subq and movq, but if OptPass2MOV is called first:
  14986. subq $x, %rax
  14987. cqto
  14988. ...which is better in all ways, taking only 2 cycles to execute
  14989. and much smaller in code size.
  14990. }
  14991. { The extra register tracking is quite strenuous }
  14992. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14993. MatchInstruction(hp1, A_MOV, []) then
  14994. begin
  14995. { Update the register tracking to the MOV instruction }
  14996. CopyUsedRegs(TempTracking);
  14997. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14998. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14999. else
  15000. { p and hp1 will be adjacent }
  15001. UpdateUsedRegs(UsedRegs, tai(p.Next));
  15002. hp2 := hp1;
  15003. if OptPass2MOV(hp1) then
  15004. Include(OptsToCheck, aoc_ForceNewIteration);
  15005. { Reset the tracking to the current instruction }
  15006. RestoreUsedRegs(TempTracking);
  15007. ReleaseUsedRegs(TempTracking);
  15008. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  15009. OptPass2SUB get called again }
  15010. if (hp1 <> hp2) then
  15011. begin
  15012. Result := True;
  15013. Exit;
  15014. end;
  15015. end;
  15016. { Change:
  15017. subl/q $x,%reg1
  15018. movl/q %reg1,%reg2
  15019. To:
  15020. leal/q $-x(%reg1),%reg2
  15021. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  15022. Breaks the dependency chain and potentially permits the removal of
  15023. a CMP instruction if one follows.
  15024. }
  15025. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  15026. (taicpu(hp1).oper[1]^.typ = top_reg) and
  15027. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  15028. (
  15029. { Instructions are guaranteed to be adjacent on -O2 and under }
  15030. not (cs_opt_level3 in current_settings.optimizerswitches) or
  15031. (
  15032. { If the flags are used, don't make the optimisation,
  15033. otherwise they will be scrambled. Fixes #41148 }
  15034. (
  15035. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  15036. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  15037. ) and
  15038. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  15039. )
  15040. ) then
  15041. begin
  15042. TransferUsedRegs(TmpUsedRegs);
  15043. if (cs_opt_level3 in current_settings.optimizerswitches) then
  15044. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  15045. else
  15046. { p and hp1 will be adjacent }
  15047. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15048. if (
  15049. SetAndTest(
  15050. (
  15051. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  15052. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  15053. ),
  15054. DoSubMov2Lea
  15055. ) or
  15056. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  15057. not (cs_opt_size in current_settings.optimizerswitches)
  15058. ) then
  15059. begin
  15060. { Change the MOV instruction to a LEA instruction, and update the
  15061. first operand }
  15062. reference_reset(NewRef, 1, []);
  15063. NewRef.base := taicpu(p).oper[1]^.reg;
  15064. NewRef.scalefactor := 1;
  15065. { if the destination reg is the same as the SUB register,
  15066. and we keep the ADD instruction, do not substract the offset
  15067. to LEA instruction, otherwise the reg gets decreased by 2 times the offset value }
  15068. if DoSubMov2Lea or not MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^.reg) then
  15069. NewRef.offset := -taicpu(p).oper[0]^.val;
  15070. taicpu(hp1).opcode := A_LEA;
  15071. taicpu(hp1).loadref(0, NewRef);
  15072. if DoSubMov2Lea then
  15073. begin
  15074. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  15075. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  15076. if (cs_opt_level3 in current_settings.optimizerswitches) then
  15077. { hp1 may not be the immediate next instruction under -O3 }
  15078. RemoveCurrentp(p)
  15079. else
  15080. RemoveCurrentp(p, hp1);
  15081. end
  15082. else
  15083. begin
  15084. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  15085. { Move what is now the LEA instruction to before the SUB instruction }
  15086. Asml.Remove(hp1);
  15087. Asml.InsertBefore(hp1, p);
  15088. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15089. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  15090. p := hp1;
  15091. end;
  15092. Result := True;
  15093. end;
  15094. end;
  15095. end;
  15096. end;
  15097. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  15098. begin
  15099. { we can skip all instructions not messing with the stack pointer }
  15100. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  15101. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  15102. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  15103. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  15104. ({(taicpu(hp1).ops=0) or }
  15105. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  15106. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  15107. ) and }
  15108. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  15109. )
  15110. ) do
  15111. GetNextInstruction(hp1,hp1);
  15112. Result:=assigned(hp1);
  15113. end;
  15114. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  15115. var
  15116. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  15117. begin
  15118. Result:=false;
  15119. {$ifdef x86_64}
  15120. { Change:
  15121. lea x(%reg1d,%reg2d),%reg3d
  15122. To:
  15123. lea x(%reg1q,%reg2q),%reg3d
  15124. Reduces the number of bytes of machine code
  15125. }
  15126. if (getsubreg(taicpu(p).oper[1]^.reg)=R_SUBD) and
  15127. (
  15128. (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) or
  15129. (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD)
  15130. ) then
  15131. begin
  15132. DebugMsg(SPeepholeOptimization + 'Changed 32-bit registers in reference to 64-bit (reduces instruction size)', p);
  15133. if (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) then
  15134. setsubreg(taicpu(p).oper[0]^.ref^.base,R_SUBQ);
  15135. if (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD) then
  15136. setsubreg(taicpu(p).oper[0]^.ref^.index,R_SUBQ);
  15137. { No reason to set Result to true }
  15138. end;
  15139. {$endif x86_64}
  15140. hp5:=nil;
  15141. hp6:=nil;
  15142. hp7:=nil;
  15143. hp8:=nil;
  15144. { replace
  15145. leal(q) x(<stackpointer>),<stackpointer>
  15146. <optional .seh_stackalloc ...>
  15147. <optional .seh_endprologue ...>
  15148. call procname
  15149. <optional NOP>
  15150. leal(q) -x(<stackpointer>),<stackpointer>
  15151. <optional VZEROUPPER>
  15152. ret
  15153. by
  15154. jmp procname
  15155. but do it only on level 4 because it destroys stack back traces
  15156. }
  15157. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15158. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  15159. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  15160. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  15161. { the -8, -24, -40 are not required, but bail out early if possible,
  15162. higher values are unlikely }
  15163. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  15164. (taicpu(p).oper[0]^.ref^.offset=-24) or
  15165. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  15166. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  15167. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  15168. GetNextInstruction(p, hp1) and
  15169. { Take a copy of hp1 }
  15170. SetAndTest(hp1, hp4) and
  15171. { trick to skip label }
  15172. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  15173. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  15174. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  15175. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  15176. SkipSimpleInstructions(hp1) and
  15177. MatchInstruction(hp1,A_CALL,[S_NO]) and
  15178. GetNextInstruction(hp1, hp2) and
  15179. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  15180. { skip nop instruction on win64 }
  15181. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  15182. SetAndTest(hp2,hp6) and
  15183. GetNextInstruction(hp2,hp2) and
  15184. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  15185. ) and
  15186. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  15187. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  15188. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  15189. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  15190. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  15191. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  15192. { Segment register will be NR_NO }
  15193. GetNextInstruction(hp2, hp3) and
  15194. { trick to skip label }
  15195. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  15196. (MatchInstruction(hp3,A_RET,[S_NO]) or
  15197. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  15198. SetAndTest(hp3,hp5) and
  15199. GetNextInstruction(hp3,hp3) and
  15200. MatchInstruction(hp3,A_RET,[S_NO])
  15201. )
  15202. ) and
  15203. (taicpu(hp3).ops=0) then
  15204. begin
  15205. taicpu(hp1).opcode := A_JMP;
  15206. taicpu(hp1).is_jmp := true;
  15207. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  15208. { search for the stackalloc directive and remove it }
  15209. hp7:=tai(p.next);
  15210. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  15211. begin
  15212. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  15213. begin
  15214. { sanity check }
  15215. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  15216. Internalerror(2024012201);
  15217. hp8:=tai(hp7.next);
  15218. RemoveInstruction(tai(hp7));
  15219. hp7:=hp8;
  15220. break;
  15221. end
  15222. else
  15223. hp7:=tai(hp7.next);
  15224. end;
  15225. RemoveCurrentP(p, hp4);
  15226. RemoveInstruction(hp2);
  15227. RemoveInstruction(hp3);
  15228. { if there is a vzeroupper instruction then move it before the jmp }
  15229. if Assigned(hp5) then
  15230. begin
  15231. AsmL.Remove(hp5);
  15232. ASmL.InsertBefore(hp5,hp1)
  15233. end;
  15234. { remove nop on win64 }
  15235. if Assigned(hp6) then
  15236. RemoveInstruction(hp6);
  15237. Result:=true;
  15238. end;
  15239. end;
  15240. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  15241. {$ifdef x86_64}
  15242. var
  15243. hp1, hp2, hp3, hp4, hp5: tai;
  15244. {$endif x86_64}
  15245. begin
  15246. Result:=false;
  15247. {$ifdef x86_64}
  15248. hp5:=nil;
  15249. { replace
  15250. push %rax
  15251. call procname
  15252. pop %rcx
  15253. ret
  15254. by
  15255. jmp procname
  15256. but do it only on level 4 because it destroys stack back traces
  15257. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  15258. for all supported calling conventions
  15259. }
  15260. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15261. MatchOpType(taicpu(p),top_reg) and
  15262. (taicpu(p).oper[0]^.reg=NR_RAX) and
  15263. GetNextInstruction(p, hp1) and
  15264. { Take a copy of hp1 }
  15265. SetAndTest(hp1, hp4) and
  15266. { trick to skip label }
  15267. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  15268. SkipSimpleInstructions(hp1) and
  15269. MatchInstruction(hp1,A_CALL,[S_NO]) and
  15270. GetNextInstruction(hp1, hp2) and
  15271. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  15272. MatchOpType(taicpu(hp2),top_reg) and
  15273. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  15274. GetNextInstruction(hp2, hp3) and
  15275. { trick to skip label }
  15276. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  15277. (MatchInstruction(hp3,A_RET,[S_NO]) or
  15278. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  15279. SetAndTest(hp3,hp5) and
  15280. GetNextInstruction(hp3,hp3) and
  15281. MatchInstruction(hp3,A_RET,[S_NO])
  15282. )
  15283. ) and
  15284. (taicpu(hp3).ops=0) then
  15285. begin
  15286. taicpu(hp1).opcode := A_JMP;
  15287. taicpu(hp1).is_jmp := true;
  15288. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  15289. RemoveCurrentP(p, hp4);
  15290. RemoveInstruction(hp2);
  15291. RemoveInstruction(hp3);
  15292. if Assigned(hp5) then
  15293. begin
  15294. AsmL.Remove(hp5);
  15295. ASmL.InsertBefore(hp5,hp1)
  15296. end;
  15297. Result:=true;
  15298. end;
  15299. {$endif x86_64}
  15300. end;
  15301. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  15302. var
  15303. Value, RegName: string;
  15304. hp1: tai;
  15305. begin
  15306. Result:=false;
  15307. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  15308. begin
  15309. case taicpu(p).oper[0]^.val of
  15310. 0:
  15311. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  15312. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15313. (
  15314. { See if we can still convert the instruction }
  15315. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15316. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15317. ) then
  15318. begin
  15319. { change "mov $0,%reg" into "xor %reg,%reg" }
  15320. taicpu(p).opcode := A_XOR;
  15321. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  15322. Result := True;
  15323. {$ifdef x86_64}
  15324. end
  15325. else if (taicpu(p).opsize = S_Q) then
  15326. begin
  15327. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15328. { The actual optimization }
  15329. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15330. taicpu(p).changeopsize(S_L);
  15331. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15332. Result := True;
  15333. end;
  15334. $1..$FFFFFFFF:
  15335. begin
  15336. { Code size reduction by J. Gareth "Kit" Moreton }
  15337. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  15338. case taicpu(p).opsize of
  15339. S_Q:
  15340. begin
  15341. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15342. Value := debug_tostr(taicpu(p).oper[0]^.val);
  15343. { The actual optimization }
  15344. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15345. taicpu(p).changeopsize(S_L);
  15346. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15347. Result := True;
  15348. end;
  15349. else
  15350. { Do nothing };
  15351. end;
  15352. {$endif x86_64}
  15353. end;
  15354. -1:
  15355. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  15356. if (cs_opt_size in current_settings.optimizerswitches) and
  15357. (taicpu(p).opsize <> S_B) and
  15358. (
  15359. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15360. (
  15361. { See if we can still convert the instruction }
  15362. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15363. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15364. )
  15365. ) then
  15366. begin
  15367. { change "mov $-1,%reg" into "or $-1,%reg" }
  15368. { NOTES:
  15369. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  15370. - This operation creates a false dependency on the register, so only do it when optimising for size
  15371. - 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
  15372. }
  15373. taicpu(p).opcode := A_OR;
  15374. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  15375. Result := True;
  15376. end;
  15377. else
  15378. { Do nothing };
  15379. end;
  15380. end;
  15381. end;
  15382. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  15383. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  15384. begin
  15385. Result := False;
  15386. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  15387. Exit;
  15388. { For sizes less than S_L, the byte size is equal or larger with BTx,
  15389. so don't bother optimising }
  15390. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  15391. Exit;
  15392. if (taicpu(p).oper[0]^.typ <> top_const) or
  15393. { If the value can fit into an 8-bit signed integer, a smaller
  15394. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  15395. falls within this range }
  15396. (
  15397. (taicpu(p).oper[0]^.val > -128) and
  15398. (taicpu(p).oper[0]^.val <= 127)
  15399. ) then
  15400. Exit;
  15401. { If we're optimising for size, this is acceptable }
  15402. if (cs_opt_size in current_settings.optimizerswitches) then
  15403. Exit(True);
  15404. if (taicpu(p).oper[1]^.typ = top_reg) and
  15405. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15406. Exit(True);
  15407. if (taicpu(p).oper[1]^.typ <> top_reg) and
  15408. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15409. Exit(True);
  15410. end;
  15411. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  15412. var
  15413. hp1: tai;
  15414. Value: TCGInt;
  15415. begin
  15416. Result := False;
  15417. if MatchOpType(taicpu(p), top_const, top_reg) then
  15418. begin
  15419. { Detect:
  15420. andw x, %ax (0 <= x < $8000)
  15421. ...
  15422. movzwl %ax,%eax
  15423. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15424. }
  15425. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15426. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15427. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15428. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15429. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15430. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15431. begin
  15432. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15433. taicpu(hp1).opcode := A_CWDE;
  15434. taicpu(hp1).clearop(0);
  15435. taicpu(hp1).clearop(1);
  15436. taicpu(hp1).ops := 0;
  15437. { A change was made, but not with p, so don't set Result, but
  15438. notify the compiler that a change was made }
  15439. Include(OptsToCheck, aoc_ForceNewIteration);
  15440. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15441. end;
  15442. end;
  15443. { If "not x" is a power of 2 (popcnt = 1), change:
  15444. and $x, %reg/ref
  15445. To:
  15446. btr lb(x), %reg/ref
  15447. }
  15448. if IsBTXAcceptable(p) and
  15449. (
  15450. { Make sure a TEST doesn't follow that plays with the register }
  15451. not GetNextInstruction(p, hp1) or
  15452. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15453. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15454. ) then
  15455. begin
  15456. {$push}{$R-}{$Q-}
  15457. { Value is a sign-extended 32-bit integer - just correct it
  15458. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15459. checks to see if this operand is an immediate. }
  15460. Value := not taicpu(p).oper[0]^.val;
  15461. {$pop}
  15462. {$ifdef x86_64}
  15463. if taicpu(p).opsize = S_L then
  15464. {$endif x86_64}
  15465. Value := Value and $FFFFFFFF;
  15466. if (PopCnt(QWord(Value)) = 1) then
  15467. begin
  15468. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15469. taicpu(p).opcode := A_BTR;
  15470. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15471. Result := True;
  15472. Exit;
  15473. end;
  15474. end;
  15475. end;
  15476. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15477. begin
  15478. Result := False;
  15479. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15480. Exit;
  15481. { Convert:
  15482. movswl %ax,%eax -> cwtl
  15483. movslq %eax,%rax -> cdqe
  15484. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15485. refer to the same opcode and depends only on the assembler's
  15486. current operand-size attribute. [Kit]
  15487. }
  15488. with taicpu(p) do
  15489. case opsize of
  15490. S_WL:
  15491. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15492. begin
  15493. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15494. opcode := A_CWDE;
  15495. clearop(0);
  15496. clearop(1);
  15497. ops := 0;
  15498. Result := True;
  15499. end;
  15500. {$ifdef x86_64}
  15501. S_LQ:
  15502. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15503. begin
  15504. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15505. opcode := A_CDQE;
  15506. clearop(0);
  15507. clearop(1);
  15508. ops := 0;
  15509. Result := True;
  15510. end;
  15511. {$endif x86_64}
  15512. else
  15513. ;
  15514. end;
  15515. end;
  15516. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15517. var
  15518. hp1: tai;
  15519. begin
  15520. Result := False;
  15521. { All these optimisations work on "shr const,%reg" }
  15522. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15523. Exit;
  15524. if HandleSHRMerge(p, True) then
  15525. begin
  15526. Result := True;
  15527. Exit;
  15528. end;
  15529. { Detect the following (looking backwards):
  15530. shr %cl,%reg
  15531. shr x, %reg
  15532. Swap the two SHR instructions to minimise a pipeline stall.
  15533. }
  15534. if GetLastInstruction(p, hp1) and
  15535. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15536. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15537. { First operand will be %cl }
  15538. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15539. { Just to be sure }
  15540. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15541. begin
  15542. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15543. { Moving the entries this way ensures the register tracking remains correct }
  15544. Asml.Remove(p);
  15545. Asml.InsertBefore(p, hp1);
  15546. p := hp1;
  15547. { Don't set Result to True because the current instruction is now
  15548. "shr %cl,%reg" and there's nothing more we can do with it }
  15549. end;
  15550. end;
  15551. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15552. var
  15553. hp1, hp2: tai;
  15554. Opposite, SecondOpposite: TAsmOp;
  15555. NewCond: TAsmCond;
  15556. begin
  15557. Result := False;
  15558. { Change:
  15559. add/sub 128,(dest)
  15560. To:
  15561. sub/add -128,(dest)
  15562. This generaally takes fewer bytes to encode because -128 can be stored
  15563. in a signed byte, whereas +128 cannot.
  15564. }
  15565. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15566. begin
  15567. if taicpu(p).opcode = A_ADD then
  15568. Opposite := A_SUB
  15569. else
  15570. Opposite := A_ADD;
  15571. { Be careful if the flags are in use, because the CF flag inverts
  15572. when changing from ADD to SUB and vice versa }
  15573. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15574. GetNextInstruction(p, hp1) then
  15575. begin
  15576. TransferUsedRegs(TmpUsedRegs);
  15577. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15578. hp2 := hp1;
  15579. { Scan ahead to check if everything's safe }
  15580. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15581. begin
  15582. if (hp1.typ <> ait_instruction) then
  15583. { Probably unsafe since the flags are still in use }
  15584. Exit;
  15585. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15586. { Stop searching at an unconditional jump }
  15587. Break;
  15588. if not
  15589. (
  15590. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15591. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15592. ) and
  15593. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15594. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15595. Exit;
  15596. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15597. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15598. { Move to the next instruction }
  15599. GetNextInstruction(hp1, hp1);
  15600. end;
  15601. while Assigned(hp2) and (hp2 <> hp1) do
  15602. begin
  15603. NewCond := C_None;
  15604. case taicpu(hp2).condition of
  15605. C_A, C_NBE:
  15606. NewCond := C_BE;
  15607. C_B, C_C, C_NAE:
  15608. NewCond := C_AE;
  15609. C_AE, C_NB, C_NC:
  15610. NewCond := C_B;
  15611. C_BE, C_NA:
  15612. NewCond := C_A;
  15613. else
  15614. { No change needed };
  15615. end;
  15616. if NewCond <> C_None then
  15617. begin
  15618. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15619. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15620. taicpu(hp2).condition := NewCond;
  15621. end
  15622. else
  15623. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15624. begin
  15625. { Because of the flipping of the carry bit, to ensure
  15626. the operation remains equivalent, ADC becomes SBB
  15627. and vice versa, and the constant is not-inverted.
  15628. If multiple ADCs or SBBs appear in a row, each one
  15629. changed causes the carry bit to invert, so they all
  15630. need to be flipped }
  15631. if taicpu(hp2).opcode = A_ADC then
  15632. SecondOpposite := A_SBB
  15633. else
  15634. SecondOpposite := A_ADC;
  15635. if taicpu(hp2).oper[0]^.typ <> top_const then
  15636. { Should have broken out of this optimisation already }
  15637. InternalError(2021112901);
  15638. 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]^) + ' -> ' +
  15639. 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);
  15640. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15641. taicpu(hp2).opcode := SecondOpposite;
  15642. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15643. end;
  15644. { Move to the next instruction }
  15645. GetNextInstruction(hp2, hp2);
  15646. end;
  15647. if (hp2 <> hp1) then
  15648. InternalError(2021111501);
  15649. end;
  15650. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15651. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15652. taicpu(p).opcode := Opposite;
  15653. taicpu(p).oper[0]^.val := -128;
  15654. { No further optimisations can be made on this instruction, so move
  15655. onto the next one to save time }
  15656. p := tai(p.Next);
  15657. UpdateUsedRegs(p);
  15658. Result := True;
  15659. Exit;
  15660. end;
  15661. { Detect:
  15662. add/sub %reg2,(dest)
  15663. add/sub x, (dest)
  15664. (dest can be a register or a reference)
  15665. Swap the instructions to minimise a pipeline stall. This reverses the
  15666. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15667. optimisations could be made.
  15668. }
  15669. if (taicpu(p).oper[0]^.typ = top_reg) and
  15670. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15671. (
  15672. (
  15673. (taicpu(p).oper[1]^.typ = top_reg) and
  15674. { We can try searching further ahead if we're writing to a register }
  15675. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15676. ) or
  15677. (
  15678. (taicpu(p).oper[1]^.typ = top_ref) and
  15679. GetNextInstruction(p, hp1)
  15680. )
  15681. ) and
  15682. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15683. (taicpu(hp1).oper[0]^.typ = top_const) and
  15684. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15685. begin
  15686. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15687. TransferUsedRegs(TmpUsedRegs);
  15688. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15689. hp2 := p;
  15690. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15691. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15692. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15693. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15694. begin
  15695. asml.remove(hp1);
  15696. asml.InsertBefore(hp1, p);
  15697. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15698. Result := True;
  15699. end;
  15700. end;
  15701. end;
  15702. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15703. var
  15704. hp1: tai;
  15705. begin
  15706. Result:=false;
  15707. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15708. while GetNextInstruction(p, hp1) and
  15709. TrySwapMovCmp(p, hp1) do
  15710. begin
  15711. if MatchInstruction(hp1, A_MOV, []) then
  15712. begin
  15713. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15714. begin
  15715. { A little hacky, but since CMP doesn't read the flags, only
  15716. modify them, it's safe if they get scrambled by MOV -> XOR }
  15717. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15718. Result := PostPeepholeOptMov(hp1);
  15719. {$ifdef x86_64}
  15720. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15721. { Used to shrink instruction size }
  15722. PostPeepholeOptXor(hp1);
  15723. {$endif x86_64}
  15724. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15725. end
  15726. else
  15727. begin
  15728. Result := PostPeepholeOptMov(hp1);
  15729. {$ifdef x86_64}
  15730. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15731. { Used to shrink instruction size }
  15732. PostPeepholeOptXor(hp1);
  15733. {$endif x86_64}
  15734. end;
  15735. end;
  15736. { Enabling this flag is actually a null operation, but it marks
  15737. the code as 'modified' during this pass }
  15738. Include(OptsToCheck, aoc_ForceNewIteration);
  15739. end;
  15740. { change "cmp $0, %reg" to "test %reg, %reg" }
  15741. if MatchOpType(taicpu(p),top_const,top_reg) and
  15742. (taicpu(p).oper[0]^.val = 0) then
  15743. begin
  15744. taicpu(p).opcode := A_TEST;
  15745. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15746. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15747. Result:=true;
  15748. end;
  15749. end;
  15750. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15751. var
  15752. IsTestConstX, IsValid : Boolean;
  15753. hp1,hp2 : tai;
  15754. begin
  15755. Result:=false;
  15756. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15757. if (taicpu(p).opcode = A_TEST) then
  15758. while GetNextInstruction(p, hp1) and
  15759. TrySwapMovCmp(p, hp1) do
  15760. begin
  15761. if MatchInstruction(hp1, A_MOV, []) then
  15762. begin
  15763. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15764. begin
  15765. { A little hacky, but since TEST doesn't read the flags, only
  15766. modify them, it's safe if they get scrambled by MOV -> XOR }
  15767. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15768. Result := PostPeepholeOptMov(hp1);
  15769. {$ifdef x86_64}
  15770. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15771. { Used to shrink instruction size }
  15772. PostPeepholeOptXor(hp1);
  15773. {$endif x86_64}
  15774. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15775. end
  15776. else
  15777. begin
  15778. Result := PostPeepholeOptMov(hp1);
  15779. {$ifdef x86_64}
  15780. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15781. { Used to shrink instruction size }
  15782. PostPeepholeOptXor(hp1);
  15783. {$endif x86_64}
  15784. end;
  15785. end;
  15786. { Enabling this flag is actually a null operation, but it marks
  15787. the code as 'modified' during this pass }
  15788. Include(OptsToCheck, aoc_ForceNewIteration);
  15789. end;
  15790. { If x is a power of 2 (popcnt = 1), change:
  15791. or $x, %reg/ref
  15792. To:
  15793. bts lb(x), %reg/ref
  15794. }
  15795. if (taicpu(p).opcode = A_OR) and
  15796. IsBTXAcceptable(p) and
  15797. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15798. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15799. (
  15800. { Don't optimise if a test instruction follows }
  15801. not GetNextInstruction(p, hp1) or
  15802. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15803. ) then
  15804. begin
  15805. 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);
  15806. taicpu(p).opcode := A_BTS;
  15807. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15808. Result := True;
  15809. Exit;
  15810. end;
  15811. { If x is a power of 2 (popcnt = 1), change:
  15812. test $x, %reg/ref
  15813. je / sete / cmove (or jne / setne)
  15814. To:
  15815. bt lb(x), %reg/ref
  15816. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15817. }
  15818. if (taicpu(p).opcode = A_TEST) and
  15819. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15820. (taicpu(p).oper[0]^.typ = top_const) and
  15821. (
  15822. (cs_opt_size in current_settings.optimizerswitches) or
  15823. (
  15824. (taicpu(p).oper[1]^.typ = top_reg) and
  15825. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15826. ) or
  15827. (
  15828. (taicpu(p).oper[1]^.typ <> top_reg) and
  15829. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15830. )
  15831. ) and
  15832. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15833. { For sizes less than S_L, the byte size is equal or larger with BT,
  15834. so don't bother optimising }
  15835. (taicpu(p).opsize >= S_L) then
  15836. begin
  15837. IsValid := True;
  15838. { Check the next set of instructions, watching the FLAGS register
  15839. and the conditions used }
  15840. TransferUsedRegs(TmpUsedRegs);
  15841. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15842. hp1 := p;
  15843. hp2 := nil;
  15844. while GetNextInstruction(hp1, hp1) do
  15845. begin
  15846. if not Assigned(hp2) then
  15847. { The first instruction after TEST }
  15848. hp2 := hp1;
  15849. if (hp1.typ <> ait_instruction) then
  15850. begin
  15851. { If the flags are no longer in use, everything is fine }
  15852. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15853. IsValid := False;
  15854. Break;
  15855. end;
  15856. case taicpu(hp1).condition of
  15857. C_None:
  15858. begin
  15859. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15860. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15861. { Something is not quite normal, so play safe and don't change }
  15862. IsValid := False;
  15863. Break;
  15864. end;
  15865. C_E, C_Z, C_NE, C_NZ:
  15866. { This is fine };
  15867. else
  15868. begin
  15869. { Unsupported condition }
  15870. IsValid := False;
  15871. Break;
  15872. end;
  15873. end;
  15874. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15875. end;
  15876. if IsValid then
  15877. begin
  15878. while hp2 <> hp1 do
  15879. begin
  15880. case taicpu(hp2).condition of
  15881. C_Z, C_E:
  15882. taicpu(hp2).condition := C_NC;
  15883. C_NZ, C_NE:
  15884. taicpu(hp2).condition := C_C;
  15885. else
  15886. { Should not get this by this point }
  15887. InternalError(2022110701);
  15888. end;
  15889. GetNextInstruction(hp2, hp2);
  15890. end;
  15891. 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);
  15892. taicpu(p).opcode := A_BT;
  15893. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15894. Result := True;
  15895. Exit;
  15896. end;
  15897. end;
  15898. { removes the line marked with (x) from the sequence
  15899. and/or/xor/add/sub/... $x, %y
  15900. test/or %y, %y | test $-1, %y (x)
  15901. j(n)z _Label
  15902. as the first instruction already adjusts the ZF
  15903. %y operand may also be a reference }
  15904. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15905. MatchOperand(taicpu(p).oper[0]^,-1);
  15906. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15907. GetLastInstruction(p, hp1) and
  15908. (tai(hp1).typ = ait_instruction) and
  15909. GetNextInstruction(p,hp2) and
  15910. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15911. case taicpu(hp1).opcode Of
  15912. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15913. { These two instructions set the zero flag if the result is zero }
  15914. A_POPCNT, A_LZCNT:
  15915. begin
  15916. if (
  15917. { With POPCNT, an input of zero will set the zero flag
  15918. because the population count of zero is zero }
  15919. (taicpu(hp1).opcode = A_POPCNT) and
  15920. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15921. (
  15922. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15923. { Faster than going through the second half of the 'or'
  15924. condition below }
  15925. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15926. )
  15927. ) or (
  15928. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15929. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15930. { and in case of carry for A(E)/B(E)/C/NC }
  15931. (
  15932. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15933. (
  15934. (taicpu(hp1).opcode <> A_ADD) and
  15935. (taicpu(hp1).opcode <> A_SUB) and
  15936. (taicpu(hp1).opcode <> A_LZCNT)
  15937. )
  15938. )
  15939. ) then
  15940. begin
  15941. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15942. RemoveCurrentP(p, hp2);
  15943. Result:=true;
  15944. Exit;
  15945. end;
  15946. end;
  15947. A_SHL, A_SAL, A_SHR, A_SAR:
  15948. begin
  15949. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15950. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15951. { therefore, it's only safe to do this optimization for }
  15952. { shifts by a (nonzero) constant }
  15953. (taicpu(hp1).oper[0]^.typ = top_const) and
  15954. (taicpu(hp1).oper[0]^.val <> 0) and
  15955. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15956. { and in case of carry for A(E)/B(E)/C/NC }
  15957. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15958. begin
  15959. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15960. RemoveCurrentP(p, hp2);
  15961. Result:=true;
  15962. Exit;
  15963. end;
  15964. end;
  15965. A_DEC, A_INC, A_NEG:
  15966. begin
  15967. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15968. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15969. { and in case of carry for A(E)/B(E)/C/NC }
  15970. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15971. begin
  15972. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15973. RemoveCurrentP(p, hp2);
  15974. Result:=true;
  15975. Exit;
  15976. end;
  15977. end;
  15978. A_ANDN, A_BZHI:
  15979. begin
  15980. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15981. { Only the zero and sign flags are consistent with what the result is }
  15982. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15983. begin
  15984. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15985. RemoveCurrentP(p, hp2);
  15986. Result:=true;
  15987. Exit;
  15988. end;
  15989. end;
  15990. A_BEXTR:
  15991. begin
  15992. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15993. { Only the zero flag is set }
  15994. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15995. begin
  15996. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15997. RemoveCurrentP(p, hp2);
  15998. Result:=true;
  15999. Exit;
  16000. end;
  16001. end;
  16002. else
  16003. ;
  16004. end; { case }
  16005. { change "test $-1,%reg" into "test %reg,%reg" }
  16006. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  16007. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  16008. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  16009. if MatchInstruction(p, A_OR, []) and
  16010. { Can only match if they're both registers }
  16011. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  16012. begin
  16013. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  16014. taicpu(p).opcode := A_TEST;
  16015. { No need to set Result to True, as we've done all the optimisations we can }
  16016. end;
  16017. end;
  16018. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  16019. var
  16020. hp1,hp3 : tai;
  16021. {$ifndef x86_64}
  16022. hp2 : taicpu;
  16023. {$endif x86_64}
  16024. begin
  16025. Result:=false;
  16026. hp3:=nil;
  16027. {$ifndef x86_64}
  16028. { don't do this on modern CPUs, this really hurts them due to
  16029. broken call/ret pairing }
  16030. if (current_settings.optimizecputype < cpu_Pentium2) and
  16031. not(cs_create_pic in current_settings.moduleswitches) and
  16032. GetNextInstruction(p, hp1) and
  16033. MatchInstruction(hp1,A_JMP,[S_NO]) and
  16034. MatchOpType(taicpu(hp1),top_ref) and
  16035. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  16036. begin
  16037. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  16038. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  16039. InsertLLItem(p.previous, p, hp2);
  16040. taicpu(p).opcode := A_JMP;
  16041. taicpu(p).is_jmp := true;
  16042. RemoveInstruction(hp1);
  16043. Result:=true;
  16044. end
  16045. else
  16046. {$endif x86_64}
  16047. { replace
  16048. call procname
  16049. ret
  16050. by
  16051. jmp procname
  16052. but do it only on level 4 because it destroys stack back traces
  16053. else if the subroutine is marked as no return, remove the ret
  16054. }
  16055. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  16056. (po_noreturn in current_procinfo.procdef.procoptions)) and
  16057. GetNextInstruction(p, hp1) and
  16058. (MatchInstruction(hp1,A_RET,[S_NO]) or
  16059. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  16060. SetAndTest(hp1,hp3) and
  16061. GetNextInstruction(hp1,hp1) and
  16062. MatchInstruction(hp1,A_RET,[S_NO])
  16063. )
  16064. ) and
  16065. (taicpu(hp1).ops=0) then
  16066. begin
  16067. if (cs_opt_level4 in current_settings.optimizerswitches) and
  16068. { we might destroy stack alignment here if we do not do a call }
  16069. (target_info.stackalign<=sizeof(SizeUInt)) then
  16070. begin
  16071. taicpu(p).opcode := A_JMP;
  16072. taicpu(p).is_jmp := true;
  16073. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  16074. end
  16075. else
  16076. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  16077. RemoveInstruction(hp1);
  16078. if Assigned(hp3) then
  16079. begin
  16080. AsmL.Remove(hp3);
  16081. AsmL.InsertBefore(hp3,p)
  16082. end;
  16083. Result:=true;
  16084. end;
  16085. end;
  16086. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  16087. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  16088. begin
  16089. case OpSize of
  16090. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  16091. Result := (Val <= $FF) and (Val >= -128);
  16092. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  16093. Result := (Val <= $FFFF) and (Val >= -32768);
  16094. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  16095. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  16096. else
  16097. Result := True;
  16098. end;
  16099. end;
  16100. var
  16101. hp1, hp2 : tai;
  16102. SizeChange: Boolean;
  16103. PreMessage: string;
  16104. begin
  16105. Result := False;
  16106. if (taicpu(p).oper[0]^.typ = top_reg) and
  16107. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  16108. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  16109. begin
  16110. { Change (using movzbl %al,%eax as an example):
  16111. movzbl %al, %eax movzbl %al, %eax
  16112. cmpl x, %eax testl %eax,%eax
  16113. To:
  16114. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  16115. movzbl %al, %eax movzbl %al, %eax
  16116. Smaller instruction and minimises pipeline stall as the CPU
  16117. doesn't have to wait for the register to get zero-extended. [Kit]
  16118. Also allow if the smaller of the two registers is being checked,
  16119. as this still removes the false dependency.
  16120. }
  16121. if
  16122. (
  16123. (
  16124. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  16125. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  16126. ) or (
  16127. { If MatchOperand returns True, they must both be registers }
  16128. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  16129. )
  16130. ) and
  16131. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  16132. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  16133. begin
  16134. 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);
  16135. asml.Remove(hp1);
  16136. asml.InsertBefore(hp1, p);
  16137. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  16138. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  16139. begin
  16140. taicpu(hp1).opcode := A_TEST;
  16141. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  16142. end;
  16143. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  16144. case taicpu(p).opsize of
  16145. S_BW, S_BL:
  16146. begin
  16147. SizeChange := taicpu(hp1).opsize <> S_B;
  16148. taicpu(hp1).changeopsize(S_B);
  16149. end;
  16150. S_WL:
  16151. begin
  16152. SizeChange := taicpu(hp1).opsize <> S_W;
  16153. taicpu(hp1).changeopsize(S_W);
  16154. end
  16155. else
  16156. InternalError(2020112701);
  16157. end;
  16158. UpdateUsedRegs(tai(p.Next));
  16159. { Check if the register is used aferwards - if not, we can
  16160. remove the movzx instruction completely }
  16161. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  16162. begin
  16163. { Hp1 is a better position than p for debugging purposes }
  16164. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  16165. RemoveCurrentp(p, hp1);
  16166. Result := True;
  16167. end;
  16168. if SizeChange then
  16169. DebugMsg(SPeepholeOptimization + PreMessage +
  16170. 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)
  16171. else
  16172. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  16173. Exit;
  16174. end;
  16175. { Change (using movzwl %ax,%eax as an example):
  16176. movzwl %ax, %eax
  16177. movb %al, (dest) (Register is smaller than read register in movz)
  16178. To:
  16179. movb %al, (dest) (Move one back to avoid a false dependency)
  16180. movzwl %ax, %eax
  16181. }
  16182. if (taicpu(hp1).opcode = A_MOV) and
  16183. (taicpu(hp1).oper[0]^.typ = top_reg) and
  16184. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  16185. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  16186. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  16187. begin
  16188. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  16189. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  16190. asml.Remove(hp1);
  16191. asml.InsertBefore(hp1, p);
  16192. if taicpu(hp1).oper[1]^.typ = top_reg then
  16193. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  16194. { Check if the register is used aferwards - if not, we can
  16195. remove the movzx instruction completely }
  16196. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  16197. begin
  16198. { Hp1 is a better position than p for debugging purposes }
  16199. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  16200. RemoveCurrentp(p, hp1);
  16201. Result := True;
  16202. end;
  16203. Exit;
  16204. end;
  16205. end;
  16206. end;
  16207. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  16208. var
  16209. hp1: tai;
  16210. {$ifdef x86_64}
  16211. PreMessage, RegName: string;
  16212. {$endif x86_64}
  16213. begin
  16214. Result := False;
  16215. { If x is a power of 2 (popcnt = 1), change:
  16216. xor $x, %reg/ref
  16217. To:
  16218. btc lb(x), %reg/ref
  16219. }
  16220. if IsBTXAcceptable(p) and
  16221. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  16222. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  16223. (
  16224. { Don't optimise if a test instruction follows }
  16225. not GetNextInstruction(p, hp1) or
  16226. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  16227. ) then
  16228. begin
  16229. 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);
  16230. taicpu(p).opcode := A_BTC;
  16231. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  16232. Result := True;
  16233. Exit;
  16234. end;
  16235. {$ifdef x86_64}
  16236. { Code size reduction by J. Gareth "Kit" Moreton }
  16237. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  16238. as this removes the REX prefix }
  16239. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  16240. Exit;
  16241. if taicpu(p).oper[0]^.typ <> top_reg then
  16242. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  16243. InternalError(2018011500);
  16244. case taicpu(p).opsize of
  16245. S_Q:
  16246. begin
  16247. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  16248. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  16249. { The actual optimization }
  16250. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  16251. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  16252. taicpu(p).changeopsize(S_L);
  16253. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  16254. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  16255. end;
  16256. else
  16257. ;
  16258. end;
  16259. {$endif x86_64}
  16260. end;
  16261. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  16262. var
  16263. XReg: TRegister;
  16264. begin
  16265. Result := False;
  16266. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  16267. Smaller encoding and slightly faster on some platforms (also works for
  16268. ZMM-sized registers) }
  16269. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  16270. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  16271. begin
  16272. XReg := taicpu(p).oper[0]^.reg;
  16273. if (taicpu(p).oper[1]^.reg = XReg) then
  16274. begin
  16275. taicpu(p).changeopsize(S_XMM);
  16276. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  16277. if (cs_opt_size in current_settings.optimizerswitches) then
  16278. begin
  16279. { Change input registers to %xmm0 to reduce size. Note that
  16280. there's a risk of a false dependency doing this, so only
  16281. optimise for size here }
  16282. XReg := NR_XMM0;
  16283. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  16284. end
  16285. else
  16286. begin
  16287. setsubreg(XReg, R_SUBMMX);
  16288. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  16289. end;
  16290. taicpu(p).oper[0]^.reg := XReg;
  16291. taicpu(p).oper[1]^.reg := XReg;
  16292. Result := True;
  16293. end;
  16294. end;
  16295. end;
  16296. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  16297. var
  16298. hp1, p_new: tai;
  16299. begin
  16300. Result := False;
  16301. { Check for:
  16302. ret
  16303. .Lbl:
  16304. ret
  16305. Remove first 'ret'
  16306. }
  16307. if GetNextInstruction(p, hp1) and
  16308. { Remember where the label is }
  16309. SetAndTest(hp1, p_new) and
  16310. (hp1.typ in [ait_align, ait_label]) and
  16311. SkipLabels(hp1, hp1) and
  16312. MatchInstruction(hp1, A_RET, []) and
  16313. { To be safe, make sure the RET instructions are identical }
  16314. (taicpu(p).ops = taicpu(hp1).ops) and
  16315. (
  16316. (taicpu(p).ops = 0) or
  16317. (
  16318. (taicpu(p).ops = 1) and
  16319. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  16320. )
  16321. ) then
  16322. begin
  16323. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  16324. UpdateUsedRegs(tai(p.Next));
  16325. RemoveCurrentP(p, p_new);
  16326. Result := True;
  16327. Exit;
  16328. end;
  16329. end;
  16330. function TX86AsmOptimizer.PostPeepholeOptRORX(var p: tai): Boolean;
  16331. begin
  16332. Result := False;
  16333. { Change: To:
  16334. rorx #x,%reg,%reg ror #x,%reg
  16335. (Smaller instruction size)
  16336. }
  16337. if MatchOperand(taicpu(p).oper[1]^,taicpu(p).oper[2]^.reg) and
  16338. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  16339. begin
  16340. taicpu(p).opcode:=A_ROR;
  16341. taicpu(p).ops:=2;
  16342. taicpu(p).clearop(2);
  16343. end;
  16344. end;
  16345. function TX86AsmOptimizer.PostPeepholeOptSARXSHLXSHRX(var p: tai): Boolean;
  16346. begin
  16347. Result := False;
  16348. { Change: bTo:
  16349. shlx %ecx,%reg,%reg shl %cl,%reg
  16350. (Smaller instruction size)
  16351. Same with SARX and SHRX (and when using %rcx for 64-bit)
  16352. }
  16353. if (getsupreg(taicpu(p).oper[0]^.reg)=RS_ECX) and
  16354. MatchOperand(taicpu(p).oper[1]^,taicpu(p).oper[2]^.reg) and
  16355. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  16356. begin
  16357. case taicpu(p).opcode of
  16358. A_SARX: taicpu(p).opcode:=A_SAR;
  16359. A_SHLX: taicpu(p).opcode:=A_SHL;
  16360. A_SHRX: taicpu(p).opcode:=A_SHR;
  16361. else
  16362. InternalError(2025090501);
  16363. end;
  16364. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  16365. taicpu(p).ops:=2;
  16366. taicpu(p).clearop(2);
  16367. end;
  16368. end;
  16369. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  16370. var
  16371. OperIdx: Integer;
  16372. begin
  16373. for OperIdx := 0 to p.ops - 1 do
  16374. if p.oper[OperIdx]^.typ = top_ref then
  16375. optimize_ref(p.oper[OperIdx]^.ref^, False);
  16376. end;
  16377. end.