aoptx86.pas 701 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  76. { Attempts to allocate a volatile integer register for use between p and hp,
  77. using AUsedRegs for the current register usage information. Returns NR_NO
  78. if no free register could be found }
  79. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  80. { Attempts to allocate a volatile MM register for use between p and hp,
  81. using AUsedRegs for the current register usage information. Returns NR_NO
  82. if no free register could be found }
  83. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  84. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  85. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  86. { checks whether reading the value in reg1 depends on the value of reg2. This
  87. is very similar to SuperRegisterEquals, except it takes into account that
  88. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  89. depend on the value in AH). }
  90. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  91. { Replaces all references to AOldReg in a memory reference to ANewReg }
  92. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Replaces all references to AOldReg in an operand to ANewReg }
  94. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  95. { Replaces all references to AOldReg in an instruction to ANewReg,
  96. except where the register is being written }
  97. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  99. or writes to a global symbol }
  100. class function IsRefSafe(const ref: PReference): Boolean; static;
  101. { Returns true if the given MOV instruction can be safely converted to CMOV }
  102. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  103. { Like UpdateUsedRegs, but ignores deallocations }
  104. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  105. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  106. class function IsBTXAcceptable(p : tai) : boolean; static;
  107. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  108. conversion was successful }
  109. function ConvertLEA(const p : taicpu): Boolean;
  110. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  111. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  112. procedure DebugMsg(const s : string; p : tai);inline;
  113. class function IsExitCode(p : tai) : boolean; static;
  114. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  115. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  116. procedure RemoveLastDeallocForFuncRes(p : tai);
  117. function DoArithCombineOpt(var p : tai) : Boolean;
  118. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  119. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  120. function PrePeepholeOptSxx(var p : tai) : boolean;
  121. function PrePeepholeOptIMUL(var p : tai) : boolean;
  122. function PrePeepholeOptAND(var p : tai) : boolean;
  123. function OptPass1Test(var p: tai): boolean;
  124. function OptPass1Add(var p: tai): boolean;
  125. function OptPass1AND(var p : tai) : boolean;
  126. function OptPass1_V_MOVAP(var p : tai) : boolean;
  127. function OptPass1VOP(var p : tai) : boolean;
  128. function OptPass1MOV(var p : tai) : boolean;
  129. function OptPass1Movx(var p : tai) : boolean;
  130. function OptPass1MOVXX(var p : tai) : boolean;
  131. function OptPass1OP(var p : tai) : boolean;
  132. function OptPass1LEA(var p : tai) : boolean;
  133. function OptPass1Sub(var p : tai) : boolean;
  134. function OptPass1SHLSAL(var p : tai) : boolean;
  135. function OptPass1SHR(var p : tai) : boolean;
  136. function OptPass1FSTP(var p : tai) : boolean;
  137. function OptPass1FLD(var p : tai) : boolean;
  138. function OptPass1Cmp(var p : tai) : boolean;
  139. function OptPass1PXor(var p : tai) : boolean;
  140. function OptPass1VPXor(var p: tai): boolean;
  141. function OptPass1Imul(var p : tai) : boolean;
  142. function OptPass1Jcc(var p : tai) : boolean;
  143. function OptPass1SHXX(var p: tai): boolean;
  144. function OptPass1VMOVDQ(var p: tai): Boolean;
  145. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  146. function OptPass2Movx(var p : tai): Boolean;
  147. function OptPass2MOV(var p : tai) : boolean;
  148. function OptPass2Imul(var p : tai) : boolean;
  149. function OptPass2Jmp(var p : tai) : boolean;
  150. function OptPass2Jcc(var p : tai) : boolean;
  151. function OptPass2Lea(var p: tai): Boolean;
  152. function OptPass2SUB(var p: tai): Boolean;
  153. function OptPass2ADD(var p : tai): Boolean;
  154. function OptPass2SETcc(var p : tai) : boolean;
  155. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  156. function PostPeepholeOptMov(var p : tai) : Boolean;
  157. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  158. function PostPeepholeOptXor(var p : tai) : Boolean;
  159. function PostPeepholeOptAnd(var p : tai) : boolean;
  160. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  161. function PostPeepholeOptCmp(var p : tai) : Boolean;
  162. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  163. function PostPeepholeOptCall(var p : tai) : Boolean;
  164. function PostPeepholeOptLea(var p : tai) : Boolean;
  165. function PostPeepholeOptPush(var p: tai): Boolean;
  166. function PostPeepholeOptShr(var p : tai) : boolean;
  167. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  168. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  169. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  170. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  171. function TrySwapMovOp(var p, hp1: tai): Boolean;
  172. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  173. { Processor-dependent reference optimisation }
  174. class procedure OptimizeRefs(var p: taicpu); static;
  175. end;
  176. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  179. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  180. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  181. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  182. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  183. {$if max_operands>2}
  184. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  185. {$endif max_operands>2}
  186. function RefsEqual(const r1, r2: treference): boolean;
  187. { Note that Result is set to True if the references COULD overlap but the
  188. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  189. might still overlap because %reg2 could be equal to %reg1-4 }
  190. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  191. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  192. { returns true, if ref is a reference using only the registers passed as base and index
  193. and having an offset }
  194. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  195. implementation
  196. uses
  197. cutils,verbose,
  198. systems,
  199. globals,
  200. cpuinfo,
  201. procinfo,
  202. paramgr,
  203. aasmbase,
  204. aoptbase,aoptutils,
  205. symconst,symsym,
  206. cgx86,
  207. itcpugas;
  208. {$ifdef DEBUG_AOPTCPU}
  209. const
  210. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  211. {$else DEBUG_AOPTCPU}
  212. { Empty strings help the optimizer to remove string concatenations that won't
  213. ever appear to the user on release builds. [Kit] }
  214. const
  215. SPeepholeOptimization = '';
  216. {$endif DEBUG_AOPTCPU}
  217. LIST_STEP_SIZE = 4;
  218. {$ifndef 8086}
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. {$endif 8086}
  222. type
  223. TJumpTrackingItem = class(TLinkedListItem)
  224. private
  225. FSymbol: TAsmSymbol;
  226. FRefs: LongInt;
  227. public
  228. constructor Create(ASymbol: TAsmSymbol);
  229. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  230. property Symbol: TAsmSymbol read FSymbol;
  231. property Refs: LongInt read FRefs;
  232. end;
  233. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  234. begin
  235. inherited Create;
  236. FSymbol := ASymbol;
  237. FRefs := 0;
  238. end;
  239. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  240. begin
  241. Inc(FRefs);
  242. end;
  243. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  244. begin
  245. result :=
  246. (instr.typ = ait_instruction) and
  247. (taicpu(instr).opcode = op) and
  248. ((opsize = []) or (taicpu(instr).opsize in opsize));
  249. end;
  250. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  251. begin
  252. result :=
  253. (instr.typ = ait_instruction) and
  254. ((taicpu(instr).opcode = op1) or
  255. (taicpu(instr).opcode = op2)
  256. ) and
  257. ((opsize = []) or (taicpu(instr).opsize in opsize));
  258. end;
  259. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  260. begin
  261. result :=
  262. (instr.typ = ait_instruction) and
  263. ((taicpu(instr).opcode = op1) or
  264. (taicpu(instr).opcode = op2) or
  265. (taicpu(instr).opcode = op3)
  266. ) and
  267. ((opsize = []) or (taicpu(instr).opsize in opsize));
  268. end;
  269. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  270. const opsize : topsizes) : boolean;
  271. var
  272. op : TAsmOp;
  273. begin
  274. result:=false;
  275. if (instr.typ <> ait_instruction) or
  276. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  277. exit;
  278. for op in ops do
  279. begin
  280. if taicpu(instr).opcode = op then
  281. begin
  282. result:=true;
  283. exit;
  284. end;
  285. end;
  286. end;
  287. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  288. begin
  289. result := (oper.typ = top_reg) and (oper.reg = reg);
  290. end;
  291. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  292. begin
  293. result := (oper.typ = top_const) and (oper.val = a);
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  296. begin
  297. result := oper1.typ = oper2.typ;
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=oper1.val = oper2.val;
  302. top_reg:
  303. Result:=oper1.reg = oper2.reg;
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  306. else
  307. internalerror(2013102801);
  308. end
  309. end;
  310. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  311. begin
  312. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  313. if result then
  314. case oper1.typ of
  315. top_const:
  316. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  317. top_reg:
  318. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  319. top_ref:
  320. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  321. else
  322. internalerror(2020052401);
  323. end
  324. end;
  325. function RefsEqual(const r1, r2: treference): boolean;
  326. begin
  327. RefsEqual :=
  328. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  329. (r1.relsymbol = r2.relsymbol) and
  330. (r1.segment = r2.segment) and (r1.base = r2.base) and
  331. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  332. (r1.offset = r2.offset) and
  333. (r1.volatility + r2.volatility = []);
  334. end;
  335. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  336. begin
  337. if (r1.symbol<>r2.symbol) then
  338. { If the index registers are different, there's a chance one could
  339. be set so it equals the other symbol }
  340. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  341. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  342. (r1.relsymbol = r2.relsymbol) and
  343. (r1.segment = r2.segment) and (r1.base = r2.base) and
  344. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  345. (r1.volatility + r2.volatility = []) then
  346. { In this case, it all depends on the offsets }
  347. Exit(abs(r1.offset - r2.offset) < Range);
  348. { There's a chance things MIGHT overlap, so take no chances }
  349. Result := True;
  350. end;
  351. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  352. begin
  353. Result:=(ref.offset=0) and
  354. (ref.scalefactor in [0,1]) and
  355. (ref.segment=NR_NO) and
  356. (ref.symbol=nil) and
  357. (ref.relsymbol=nil) and
  358. ((base=NR_INVALID) or
  359. (ref.base=base)) and
  360. ((index=NR_INVALID) or
  361. (ref.index=index)) and
  362. (ref.volatility=[]);
  363. end;
  364. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  365. begin
  366. Result:=(ref.scalefactor in [0,1]) and
  367. (ref.segment=NR_NO) and
  368. (ref.symbol=nil) and
  369. (ref.relsymbol=nil) and
  370. ((base=NR_INVALID) or
  371. (ref.base=base)) and
  372. ((index=NR_INVALID) or
  373. (ref.index=index)) and
  374. (ref.volatility=[]);
  375. end;
  376. function InstrReadsFlags(p: tai): boolean;
  377. begin
  378. InstrReadsFlags := true;
  379. case p.typ of
  380. ait_instruction:
  381. if InsProp[taicpu(p).opcode].Ch*
  382. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  383. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  384. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  385. exit;
  386. ait_label:
  387. exit;
  388. else
  389. ;
  390. end;
  391. InstrReadsFlags := false;
  392. end;
  393. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  394. begin
  395. Next:=Current;
  396. repeat
  397. Result:=GetNextInstruction(Next,Next);
  398. until not (Result) or
  399. not(cs_opt_level3 in current_settings.optimizerswitches) or
  400. (Next.typ<>ait_instruction) or
  401. RegInInstruction(reg,Next) or
  402. is_calljmp(taicpu(Next).opcode);
  403. end;
  404. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  405. var
  406. GetNextResult: Boolean;
  407. begin
  408. Result:=0;
  409. Next:=Current;
  410. repeat
  411. GetNextResult := GetNextInstruction(Next,Next);
  412. if GetNextResult then
  413. Inc(Result)
  414. else
  415. { Must return zero upon hitting the end of the linked list without a match }
  416. Result := 0;
  417. until not (GetNextResult) or
  418. not(cs_opt_level3 in current_settings.optimizerswitches) or
  419. (Next.typ<>ait_instruction) or
  420. RegInInstruction(reg,Next) or
  421. is_calljmp(taicpu(Next).opcode);
  422. end;
  423. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  424. procedure TrackJump(Symbol: TAsmSymbol);
  425. var
  426. Search: TJumpTrackingItem;
  427. begin
  428. { See if an entry already exists in our jump tracking list
  429. (faster to search backwards due to the higher chance of
  430. matching destinations) }
  431. Search := TJumpTrackingItem(JumpTracking.Last);
  432. while Assigned(Search) do
  433. begin
  434. if Search.Symbol = Symbol then
  435. begin
  436. { Found it - remove it so it can be pushed to the front }
  437. JumpTracking.Remove(Search);
  438. Break;
  439. end;
  440. Search := TJumpTrackingItem(Search.Previous);
  441. end;
  442. if not Assigned(Search) then
  443. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  444. JumpTracking.Concat(Search);
  445. Search.IncRefs;
  446. end;
  447. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  448. var
  449. Search: TJumpTrackingItem;
  450. begin
  451. Result := False;
  452. { See if this label appears in the tracking list }
  453. Search := TJumpTrackingItem(JumpTracking.Last);
  454. while Assigned(Search) do
  455. begin
  456. if Search.Symbol = Symbol then
  457. begin
  458. { Found it - let's see what we can discover }
  459. if Search.Symbol.getrefs = Search.Refs then
  460. begin
  461. { Success - all the references are accounted for }
  462. JumpTracking.Remove(Search);
  463. Search.Free;
  464. { It is logically impossible for CrossJump to be false here
  465. because we must have run into a conditional jump for
  466. this label at some point }
  467. if not CrossJump then
  468. InternalError(2022041710);
  469. if JumpTracking.First = nil then
  470. { Tracking list is now empty - no more cross jumps }
  471. CrossJump := False;
  472. Result := True;
  473. Exit;
  474. end;
  475. { If the references don't match, it's possible to enter
  476. this label through other means, so drop out }
  477. Exit;
  478. end;
  479. Search := TJumpTrackingItem(Search.Previous);
  480. end;
  481. end;
  482. var
  483. Next_Label: tai;
  484. begin
  485. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  486. Next := Current;
  487. repeat
  488. Result := GetNextInstruction(Next,Next);
  489. if not Result then
  490. Break;
  491. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  492. if is_calljmpuncondret(taicpu(Next).opcode) then
  493. begin
  494. if (taicpu(Next).opcode = A_JMP) and
  495. { Remove dead code now to save time }
  496. RemoveDeadCodeAfterJump(taicpu(Next)) then
  497. { A jump was removed, but not the current instruction, and
  498. Result doesn't necessarily translate into an optimisation
  499. routine's Result, so use the "Force New Iteration" flag so
  500. mark a new pass }
  501. Include(OptsToCheck, aoc_ForceNewIteration);
  502. if not Assigned(JumpTracking) then
  503. begin
  504. { Cross-label optimisations often causes other optimisations
  505. to perform worse because they're not given the chance to
  506. optimise locally. In this case, don't do the cross-label
  507. optimisations yet, but flag them as a potential possibility
  508. for the next iteration of Pass 1 }
  509. if not NotFirstIteration then
  510. Include(OptsToCheck, aoc_ForceNewIteration);
  511. end
  512. else if IsJumpToLabel(taicpu(Next)) and
  513. GetNextInstruction(Next, Next_Label) then
  514. begin
  515. { If we have JMP .lbl, and the label after it has all of its
  516. references tracked, then this is probably an if-else style of
  517. block and we can keep tracking. If the label for this jump
  518. then appears later and is fully tracked, then it's the end
  519. of the if-else blocks and the code paths converge (thus
  520. marking the end of the cross-jump) }
  521. if (Next_Label.typ = ait_label) then
  522. begin
  523. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  524. begin
  525. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  526. Next := Next_Label;
  527. { CrossJump gets set to false by LabelAccountedFor if the
  528. list is completely emptied (as it indicates that all
  529. code paths have converged). We could avoid this nuance
  530. by moving the TrackJump call to before the
  531. LabelAccountedFor call, but this is slower in situations
  532. where LabelAccountedFor would return False due to the
  533. creation of a new object that is not used and destroyed
  534. soon after. }
  535. CrossJump := True;
  536. Continue;
  537. end;
  538. end
  539. else if (Next_Label.typ <> ait_marker) then
  540. { We just did a RemoveDeadCodeAfterJump, so either we find
  541. a label, the end of the procedure or some kind of marker}
  542. InternalError(2022041720);
  543. end;
  544. Result := False;
  545. Exit;
  546. end
  547. else
  548. begin
  549. if not Assigned(JumpTracking) then
  550. begin
  551. { Cross-label optimisations often causes other optimisations
  552. to perform worse because they're not given the chance to
  553. optimise locally. In this case, don't do the cross-label
  554. optimisations yet, but flag them as a potential possibility
  555. for the next iteration of Pass 1 }
  556. if not NotFirstIteration then
  557. Include(OptsToCheck, aoc_ForceNewIteration);
  558. end
  559. else if IsJumpToLabel(taicpu(Next)) then
  560. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  561. else
  562. { Conditional jumps should always be a jump to label }
  563. InternalError(2022041701);
  564. CrossJump := True;
  565. Continue;
  566. end;
  567. if Next.typ = ait_label then
  568. begin
  569. if not Assigned(JumpTracking) then
  570. begin
  571. { Cross-label optimisations often causes other optimisations
  572. to perform worse because they're not given the chance to
  573. optimise locally. In this case, don't do the cross-label
  574. optimisations yet, but flag them as a potential possibility
  575. for the next iteration of Pass 1 }
  576. if not NotFirstIteration then
  577. Include(OptsToCheck, aoc_ForceNewIteration);
  578. end
  579. else if LabelAccountedFor(tai_label(Next).labsym) then
  580. Continue;
  581. { If we reach here, we're at a label that hasn't been seen before
  582. (or JumpTracking was nil) }
  583. Break;
  584. end;
  585. until not Result or
  586. not (cs_opt_level3 in current_settings.optimizerswitches) or
  587. not (Next.typ in [ait_label, ait_instruction]) or
  588. RegInInstruction(reg,Next);
  589. end;
  590. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  591. begin
  592. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  593. begin
  594. Result:=GetNextInstruction(Current,Next);
  595. exit;
  596. end;
  597. Next:=tai(Current.Next);
  598. Result:=false;
  599. while assigned(Next) do
  600. begin
  601. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  602. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  603. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  604. exit
  605. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  606. begin
  607. Result:=true;
  608. exit;
  609. end;
  610. Next:=tai(Next.Next);
  611. end;
  612. end;
  613. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  614. begin
  615. Result:=RegReadByInstruction(reg,hp);
  616. end;
  617. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  618. var
  619. p: taicpu;
  620. opcount: longint;
  621. begin
  622. RegReadByInstruction := false;
  623. if hp.typ <> ait_instruction then
  624. exit;
  625. p := taicpu(hp);
  626. case p.opcode of
  627. A_CALL:
  628. regreadbyinstruction := true;
  629. A_IMUL:
  630. case p.ops of
  631. 1:
  632. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  633. (
  634. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  635. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  636. );
  637. 2,3:
  638. regReadByInstruction :=
  639. reginop(reg,p.oper[0]^) or
  640. reginop(reg,p.oper[1]^);
  641. else
  642. InternalError(2019112801);
  643. end;
  644. A_MUL:
  645. begin
  646. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  647. (
  648. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  649. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  650. );
  651. end;
  652. A_IDIV,A_DIV:
  653. begin
  654. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  655. (
  656. (getregtype(reg)=R_INTREGISTER) and
  657. (
  658. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  659. )
  660. );
  661. end;
  662. else
  663. begin
  664. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  665. begin
  666. RegReadByInstruction := false;
  667. exit;
  668. end;
  669. for opcount := 0 to p.ops-1 do
  670. if (p.oper[opCount]^.typ = top_ref) and
  671. RegInRef(reg,p.oper[opcount]^.ref^) then
  672. begin
  673. RegReadByInstruction := true;
  674. exit
  675. end;
  676. { special handling for SSE MOVSD }
  677. if (p.opcode=A_MOVSD) and (p.ops>0) then
  678. begin
  679. if p.ops<>2 then
  680. internalerror(2017042702);
  681. regReadByInstruction := reginop(reg,p.oper[0]^) or
  682. (
  683. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  684. );
  685. exit;
  686. end;
  687. with insprop[p.opcode] do
  688. begin
  689. case getregtype(reg) of
  690. R_INTREGISTER:
  691. begin
  692. case getsupreg(reg) of
  693. RS_EAX:
  694. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  695. begin
  696. RegReadByInstruction := true;
  697. exit
  698. end;
  699. RS_ECX:
  700. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  701. begin
  702. RegReadByInstruction := true;
  703. exit
  704. end;
  705. RS_EDX:
  706. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  707. begin
  708. RegReadByInstruction := true;
  709. exit
  710. end;
  711. RS_EBX:
  712. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  713. begin
  714. RegReadByInstruction := true;
  715. exit
  716. end;
  717. RS_ESP:
  718. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  719. begin
  720. RegReadByInstruction := true;
  721. exit
  722. end;
  723. RS_EBP:
  724. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  725. begin
  726. RegReadByInstruction := true;
  727. exit
  728. end;
  729. RS_ESI:
  730. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  731. begin
  732. RegReadByInstruction := true;
  733. exit
  734. end;
  735. RS_EDI:
  736. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  737. begin
  738. RegReadByInstruction := true;
  739. exit
  740. end;
  741. end;
  742. end;
  743. R_MMREGISTER:
  744. begin
  745. case getsupreg(reg) of
  746. RS_XMM0:
  747. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  748. begin
  749. RegReadByInstruction := true;
  750. exit
  751. end;
  752. end;
  753. end;
  754. else
  755. ;
  756. end;
  757. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  758. begin
  759. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  760. begin
  761. case p.condition of
  762. C_A,C_NBE, { CF=0 and ZF=0 }
  763. C_BE,C_NA: { CF=1 or ZF=1 }
  764. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  765. C_AE,C_NB,C_NC, { CF=0 }
  766. C_B,C_NAE,C_C: { CF=1 }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  768. C_NE,C_NZ, { ZF=0 }
  769. C_E,C_Z: { ZF=1 }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  771. C_G,C_NLE, { ZF=0 and SF=OF }
  772. C_LE,C_NG: { ZF=1 or SF<>OF }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  774. C_GE,C_NL, { SF=OF }
  775. C_L,C_NGE: { SF<>OF }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  777. C_NO, { OF=0 }
  778. C_O: { OF=1 }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  780. C_NP,C_PO, { PF=0 }
  781. C_P,C_PE: { PF=1 }
  782. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  783. C_NS, { SF=0 }
  784. C_S: { SF=1 }
  785. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  786. else
  787. internalerror(2017042701);
  788. end;
  789. if RegReadByInstruction then
  790. exit;
  791. end;
  792. case getsubreg(reg) of
  793. R_SUBW,R_SUBD,R_SUBQ:
  794. RegReadByInstruction :=
  795. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  796. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  797. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  798. R_SUBFLAGCARRY:
  799. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  800. R_SUBFLAGPARITY:
  801. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGAUXILIARY:
  803. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGZERO:
  805. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGSIGN:
  807. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGOVERFLOW:
  809. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGINTERRUPT:
  811. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGDIRECTION:
  813. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. else
  815. internalerror(2017042601);
  816. end;
  817. exit;
  818. end;
  819. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  820. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  821. (p.oper[0]^.reg=p.oper[1]^.reg) then
  822. exit;
  823. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  824. begin
  825. RegReadByInstruction := true;
  826. exit
  827. end;
  828. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  829. begin
  830. RegReadByInstruction := true;
  831. exit
  832. end;
  833. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  834. begin
  835. RegReadByInstruction := true;
  836. exit
  837. end;
  838. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  839. begin
  840. RegReadByInstruction := true;
  841. exit
  842. end;
  843. end;
  844. end;
  845. end;
  846. end;
  847. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  848. begin
  849. result:=false;
  850. if p1.typ<>ait_instruction then
  851. exit;
  852. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  853. exit(true);
  854. if (getregtype(reg)=R_INTREGISTER) and
  855. { change information for xmm movsd are not correct }
  856. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  857. begin
  858. { Handle instructions that behave differently depending on the size and operand count }
  859. case taicpu(p1).opcode of
  860. A_MUL, A_DIV, A_IDIV:
  861. if taicpu(p1).opsize = S_B then
  862. Result := (getsupreg(Reg) = RS_EAX)
  863. else
  864. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  865. A_IMUL:
  866. if taicpu(p1).ops = 1 then
  867. begin
  868. if taicpu(p1).opsize = S_B then
  869. Result := (getsupreg(Reg) = RS_EAX)
  870. else
  871. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  872. end;
  873. { If ops are greater than 1, call inherited method }
  874. else
  875. case getsupreg(reg) of
  876. { RS_EAX = RS_RAX on x86-64 }
  877. RS_EAX:
  878. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. RS_ECX:
  880. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_EDX:
  882. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EBX:
  884. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_ESP:
  886. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_EBP:
  888. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_ESI:
  890. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_EDI:
  892. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. end;
  897. if result then
  898. exit;
  899. end
  900. else if getregtype(reg)=R_MMREGISTER then
  901. begin
  902. case getsupreg(reg) of
  903. RS_XMM0:
  904. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  905. else
  906. ;
  907. end;
  908. if result then
  909. exit;
  910. end
  911. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  912. begin
  913. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  914. exit(true);
  915. case getsubreg(reg) of
  916. R_SUBFLAGCARRY:
  917. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  918. R_SUBFLAGPARITY:
  919. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGAUXILIARY:
  921. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGZERO:
  923. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGSIGN:
  925. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGOVERFLOW:
  927. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGINTERRUPT:
  929. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGDIRECTION:
  931. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBW,R_SUBD,R_SUBQ:
  933. { Everything except the direction bits }
  934. Result:=
  935. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  936. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  937. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  938. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  939. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  940. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  941. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  942. else
  943. ;
  944. end;
  945. if result then
  946. exit;
  947. end
  948. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  949. exit(true);
  950. Result:=inherited RegInInstruction(Reg, p1);
  951. end;
  952. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  953. const
  954. WriteOps: array[0..3] of set of TInsChange =
  955. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  956. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  957. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  958. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  959. var
  960. OperIdx: Integer;
  961. begin
  962. Result := False;
  963. if p1.typ <> ait_instruction then
  964. exit;
  965. with insprop[taicpu(p1).opcode] do
  966. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  967. begin
  968. case getsubreg(reg) of
  969. R_SUBW,R_SUBD,R_SUBQ:
  970. Result :=
  971. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  972. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  973. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  974. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  975. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  976. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  977. R_SUBFLAGCARRY:
  978. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGPARITY:
  980. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGAUXILIARY:
  982. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGZERO:
  984. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGSIGN:
  986. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGOVERFLOW:
  988. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGINTERRUPT:
  990. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGDIRECTION:
  992. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. else
  994. internalerror(2017042602);
  995. end;
  996. exit;
  997. end;
  998. case taicpu(p1).opcode of
  999. A_CALL:
  1000. { We could potentially set Result to False if the register in
  1001. question is non-volatile for the subroutine's calling convention,
  1002. but this would require detecting the calling convention in use and
  1003. also assuming that the routine doesn't contain malformed assembly
  1004. language, for example... so it could only be done under -O4 as it
  1005. would be considered a side-effect. [Kit] }
  1006. Result := True;
  1007. A_MOVSD:
  1008. { special handling for SSE MOVSD }
  1009. if (taicpu(p1).ops>0) then
  1010. begin
  1011. if taicpu(p1).ops<>2 then
  1012. internalerror(2017042703);
  1013. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1014. end;
  1015. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1016. so fix it here (FK)
  1017. }
  1018. A_VMOVSS,
  1019. A_VMOVSD:
  1020. begin
  1021. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1022. exit;
  1023. end;
  1024. A_MUL, A_DIV, A_IDIV:
  1025. begin
  1026. if taicpu(p1).opsize = S_B then
  1027. Result := (getsupreg(Reg) = RS_EAX)
  1028. else
  1029. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1030. end;
  1031. A_IMUL:
  1032. begin
  1033. if taicpu(p1).ops = 1 then
  1034. begin
  1035. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1036. end
  1037. else
  1038. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1039. Exit;
  1040. end;
  1041. else
  1042. ;
  1043. end;
  1044. if Result then
  1045. exit;
  1046. with insprop[taicpu(p1).opcode] do
  1047. begin
  1048. if getregtype(reg)=R_INTREGISTER then
  1049. begin
  1050. case getsupreg(reg) of
  1051. RS_EAX:
  1052. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1053. begin
  1054. Result := True;
  1055. exit
  1056. end;
  1057. RS_ECX:
  1058. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1059. begin
  1060. Result := True;
  1061. exit
  1062. end;
  1063. RS_EDX:
  1064. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1065. begin
  1066. Result := True;
  1067. exit
  1068. end;
  1069. RS_EBX:
  1070. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1071. begin
  1072. Result := True;
  1073. exit
  1074. end;
  1075. RS_ESP:
  1076. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1077. begin
  1078. Result := True;
  1079. exit
  1080. end;
  1081. RS_EBP:
  1082. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1083. begin
  1084. Result := True;
  1085. exit
  1086. end;
  1087. RS_ESI:
  1088. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1089. begin
  1090. Result := True;
  1091. exit
  1092. end;
  1093. RS_EDI:
  1094. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1095. begin
  1096. Result := True;
  1097. exit
  1098. end;
  1099. end;
  1100. end;
  1101. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1102. if (WriteOps[OperIdx]*Ch<>[]) and
  1103. { The register doesn't get modified inside a reference }
  1104. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1105. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1106. begin
  1107. Result := true;
  1108. exit
  1109. end;
  1110. end;
  1111. end;
  1112. {$ifdef DEBUG_AOPTCPU}
  1113. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1114. begin
  1115. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1116. end;
  1117. function debug_tostr(i: tcgint): string; inline;
  1118. begin
  1119. Result := tostr(i);
  1120. end;
  1121. function debug_hexstr(i: tcgint): string;
  1122. begin
  1123. Result := '0x';
  1124. case i of
  1125. 0..$FF:
  1126. Result := Result + hexstr(i, 2);
  1127. $100..$FFFF:
  1128. Result := Result + hexstr(i, 4);
  1129. $10000..$FFFFFF:
  1130. Result := Result + hexstr(i, 6);
  1131. $1000000..$FFFFFFFF:
  1132. Result := Result + hexstr(i, 8);
  1133. else
  1134. Result := Result + hexstr(i, 16);
  1135. end;
  1136. end;
  1137. function debug_regname(r: TRegister): string; inline;
  1138. begin
  1139. Result := '%' + std_regname(r);
  1140. end;
  1141. { Debug output function - creates a string representation of an operator }
  1142. function debug_operstr(oper: TOper): string;
  1143. begin
  1144. case oper.typ of
  1145. top_const:
  1146. Result := '$' + debug_tostr(oper.val);
  1147. top_reg:
  1148. Result := debug_regname(oper.reg);
  1149. top_ref:
  1150. begin
  1151. if oper.ref^.offset <> 0 then
  1152. Result := debug_tostr(oper.ref^.offset) + '('
  1153. else
  1154. Result := '(';
  1155. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1156. begin
  1157. Result := Result + debug_regname(oper.ref^.base);
  1158. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1159. Result := Result + ',' + debug_regname(oper.ref^.index);
  1160. end
  1161. else
  1162. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1163. Result := Result + debug_regname(oper.ref^.index);
  1164. if (oper.ref^.scalefactor > 1) then
  1165. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1166. else
  1167. Result := Result + ')';
  1168. end;
  1169. else
  1170. Result := '[UNKNOWN]';
  1171. end;
  1172. end;
  1173. function debug_op2str(opcode: tasmop): string; inline;
  1174. begin
  1175. Result := std_op2str[opcode];
  1176. end;
  1177. function debug_opsize2str(opsize: topsize): string; inline;
  1178. begin
  1179. Result := gas_opsize2str[opsize];
  1180. end;
  1181. {$else DEBUG_AOPTCPU}
  1182. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1183. begin
  1184. end;
  1185. function debug_tostr(i: tcgint): string; inline;
  1186. begin
  1187. Result := '';
  1188. end;
  1189. function debug_hexstr(i: tcgint): string; inline;
  1190. begin
  1191. Result := '';
  1192. end;
  1193. function debug_regname(r: TRegister): string; inline;
  1194. begin
  1195. Result := '';
  1196. end;
  1197. function debug_operstr(oper: TOper): string; inline;
  1198. begin
  1199. Result := '';
  1200. end;
  1201. function debug_op2str(opcode: tasmop): string; inline;
  1202. begin
  1203. Result := '';
  1204. end;
  1205. function debug_opsize2str(opsize: topsize): string; inline;
  1206. begin
  1207. Result := '';
  1208. end;
  1209. {$endif DEBUG_AOPTCPU}
  1210. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1211. begin
  1212. {$ifdef x86_64}
  1213. { Always fine on x86-64 }
  1214. Result := True;
  1215. {$else x86_64}
  1216. Result :=
  1217. {$ifdef i8086}
  1218. (current_settings.cputype >= cpu_386) and
  1219. {$endif i8086}
  1220. (
  1221. { Always accept if optimising for size }
  1222. (cs_opt_size in current_settings.optimizerswitches) or
  1223. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1224. (current_settings.optimizecputype >= cpu_Pentium2)
  1225. );
  1226. {$endif x86_64}
  1227. end;
  1228. { Attempts to allocate a volatile integer register for use between p and hp,
  1229. using AUsedRegs for the current register usage information. Returns NR_NO
  1230. if no free register could be found }
  1231. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1232. var
  1233. RegSet: TCPURegisterSet;
  1234. CurrentSuperReg: Integer;
  1235. CurrentReg: TRegister;
  1236. Currentp: tai;
  1237. Breakout: Boolean;
  1238. begin
  1239. Result := NR_NO;
  1240. RegSet :=
  1241. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1242. current_procinfo.saved_regs_int;
  1243. (*
  1244. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1245. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1246. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1247. *)
  1248. for CurrentSuperReg in RegSet do
  1249. begin
  1250. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1251. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1252. {$if defined(i386) or defined(i8086)}
  1253. { If the target size is 8-bit, make sure we can actually encode it }
  1254. and (
  1255. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1256. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1257. )
  1258. {$endif i386 or i8086}
  1259. then
  1260. begin
  1261. Currentp := p;
  1262. Breakout := False;
  1263. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1264. begin
  1265. case Currentp.typ of
  1266. ait_instruction:
  1267. begin
  1268. if RegInInstruction(CurrentReg, Currentp) then
  1269. begin
  1270. Breakout := True;
  1271. Break;
  1272. end;
  1273. { Cannot allocate across an unconditional jump }
  1274. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1275. Exit;
  1276. end;
  1277. ait_marker:
  1278. { Don't try anything more if a marker is hit }
  1279. Exit;
  1280. ait_regalloc:
  1281. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1282. begin
  1283. Breakout := True;
  1284. Break;
  1285. end;
  1286. else
  1287. ;
  1288. end;
  1289. end;
  1290. if Breakout then
  1291. { Try the next register }
  1292. Continue;
  1293. { We have a free register available }
  1294. Result := CurrentReg;
  1295. if not DontAlloc then
  1296. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1297. Exit;
  1298. end;
  1299. end;
  1300. end;
  1301. { Attempts to allocate a volatile MM register for use between p and hp,
  1302. using AUsedRegs for the current register usage information. Returns NR_NO
  1303. if no free register could be found }
  1304. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1305. var
  1306. RegSet: TCPURegisterSet;
  1307. CurrentSuperReg: Integer;
  1308. CurrentReg: TRegister;
  1309. Currentp: tai;
  1310. Breakout: Boolean;
  1311. begin
  1312. Result := NR_NO;
  1313. RegSet :=
  1314. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1315. current_procinfo.saved_regs_mm;
  1316. for CurrentSuperReg in RegSet do
  1317. begin
  1318. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1319. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1320. begin
  1321. Currentp := p;
  1322. Breakout := False;
  1323. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1324. begin
  1325. case Currentp.typ of
  1326. ait_instruction:
  1327. begin
  1328. if RegInInstruction(CurrentReg, Currentp) then
  1329. begin
  1330. Breakout := True;
  1331. Break;
  1332. end;
  1333. { Cannot allocate across an unconditional jump }
  1334. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1335. Exit;
  1336. end;
  1337. ait_marker:
  1338. { Don't try anything more if a marker is hit }
  1339. Exit;
  1340. ait_regalloc:
  1341. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1342. begin
  1343. Breakout := True;
  1344. Break;
  1345. end;
  1346. else
  1347. ;
  1348. end;
  1349. end;
  1350. if Breakout then
  1351. { Try the next register }
  1352. Continue;
  1353. { We have a free register available }
  1354. Result := CurrentReg;
  1355. if not DontAlloc then
  1356. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1357. Exit;
  1358. end;
  1359. end;
  1360. end;
  1361. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1362. begin
  1363. if not SuperRegistersEqual(reg1,reg2) then
  1364. exit(false);
  1365. if getregtype(reg1)<>R_INTREGISTER then
  1366. exit(true); {because SuperRegisterEqual is true}
  1367. case getsubreg(reg1) of
  1368. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1369. higher, it preserves the high bits, so the new value depends on
  1370. reg2's previous value. In other words, it is equivalent to doing:
  1371. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1372. R_SUBL:
  1373. exit(getsubreg(reg2)=R_SUBL);
  1374. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1375. higher, it actually does a:
  1376. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1377. R_SUBH:
  1378. exit(getsubreg(reg2)=R_SUBH);
  1379. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1380. bits of reg2:
  1381. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1382. R_SUBW:
  1383. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1384. { a write to R_SUBD always overwrites every other subregister,
  1385. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1386. R_SUBD,
  1387. R_SUBQ:
  1388. exit(true);
  1389. else
  1390. internalerror(2017042801);
  1391. end;
  1392. end;
  1393. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1394. begin
  1395. if not SuperRegistersEqual(reg1,reg2) then
  1396. exit(false);
  1397. if getregtype(reg1)<>R_INTREGISTER then
  1398. exit(true); {because SuperRegisterEqual is true}
  1399. case getsubreg(reg1) of
  1400. R_SUBL:
  1401. exit(getsubreg(reg2)<>R_SUBH);
  1402. R_SUBH:
  1403. exit(getsubreg(reg2)<>R_SUBL);
  1404. R_SUBW,
  1405. R_SUBD,
  1406. R_SUBQ:
  1407. exit(true);
  1408. else
  1409. internalerror(2017042802);
  1410. end;
  1411. end;
  1412. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1413. var
  1414. hp1 : tai;
  1415. l : TCGInt;
  1416. begin
  1417. result:=false;
  1418. if not(GetNextInstruction(p, hp1)) then
  1419. exit;
  1420. { changes the code sequence
  1421. shr/sar const1, x
  1422. shl const2, x
  1423. to
  1424. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1425. if (taicpu(p).oper[0]^.typ = top_const) and
  1426. MatchInstruction(hp1,A_SHL,[]) and
  1427. (taicpu(hp1).oper[0]^.typ = top_const) and
  1428. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1429. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1430. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1431. begin
  1432. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1433. not(cs_opt_size in current_settings.optimizerswitches) then
  1434. begin
  1435. { shr/sar const1, %reg
  1436. shl const2, %reg
  1437. with const1 > const2 }
  1438. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1439. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1440. taicpu(hp1).opcode := A_AND;
  1441. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1442. case taicpu(p).opsize Of
  1443. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1444. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1445. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1446. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1447. else
  1448. Internalerror(2017050703)
  1449. end;
  1450. end
  1451. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1452. not(cs_opt_size in current_settings.optimizerswitches) then
  1453. begin
  1454. { shr/sar const1, %reg
  1455. shl const2, %reg
  1456. with const1 < const2 }
  1457. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1458. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1459. taicpu(p).opcode := A_AND;
  1460. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1461. case taicpu(p).opsize Of
  1462. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1463. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1464. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1465. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1466. else
  1467. Internalerror(2017050702)
  1468. end;
  1469. end
  1470. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1471. begin
  1472. { shr/sar const1, %reg
  1473. shl const2, %reg
  1474. with const1 = const2 }
  1475. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1476. taicpu(p).opcode := A_AND;
  1477. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1478. case taicpu(p).opsize Of
  1479. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1480. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1481. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1482. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1483. else
  1484. Internalerror(2017050701)
  1485. end;
  1486. RemoveInstruction(hp1);
  1487. end;
  1488. end;
  1489. end;
  1490. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1491. var
  1492. opsize : topsize;
  1493. hp1, hp2 : tai;
  1494. tmpref : treference;
  1495. ShiftValue : Cardinal;
  1496. BaseValue : TCGInt;
  1497. begin
  1498. result:=false;
  1499. opsize:=taicpu(p).opsize;
  1500. { changes certain "imul const, %reg"'s to lea sequences }
  1501. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1502. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1503. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1504. if (taicpu(p).oper[0]^.val = 1) then
  1505. if (taicpu(p).ops = 2) then
  1506. { remove "imul $1, reg" }
  1507. begin
  1508. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1509. Result := RemoveCurrentP(p);
  1510. end
  1511. else
  1512. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1513. begin
  1514. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1515. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1516. asml.InsertAfter(hp1, p);
  1517. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1518. RemoveCurrentP(p, hp1);
  1519. Result := True;
  1520. end
  1521. else if ((taicpu(p).ops <= 2) or
  1522. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1523. not(cs_opt_size in current_settings.optimizerswitches) and
  1524. (not(GetNextInstruction(p, hp1)) or
  1525. not((tai(hp1).typ = ait_instruction) and
  1526. ((taicpu(hp1).opcode=A_Jcc) and
  1527. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1528. begin
  1529. {
  1530. imul X, reg1, reg2 to
  1531. lea (reg1,reg1,Y), reg2
  1532. shl ZZ,reg2
  1533. imul XX, reg1 to
  1534. lea (reg1,reg1,YY), reg1
  1535. shl ZZ,reg2
  1536. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1537. it does not exist as a separate optimization target in FPC though.
  1538. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1539. at most two zeros
  1540. }
  1541. reference_reset(tmpref,1,[]);
  1542. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1543. begin
  1544. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1545. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1546. TmpRef.base := taicpu(p).oper[1]^.reg;
  1547. TmpRef.index := taicpu(p).oper[1]^.reg;
  1548. if not(BaseValue in [3,5,9]) then
  1549. Internalerror(2018110101);
  1550. TmpRef.ScaleFactor := BaseValue-1;
  1551. if (taicpu(p).ops = 2) then
  1552. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1553. else
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1555. AsmL.InsertAfter(hp1,p);
  1556. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1557. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1558. RemoveCurrentP(p, hp1);
  1559. if ShiftValue>0 then
  1560. begin
  1561. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1562. AsmL.InsertAfter(hp2,hp1);
  1563. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1564. end;
  1565. Result := True;
  1566. end;
  1567. end;
  1568. end;
  1569. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1570. begin
  1571. Result := False;
  1572. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1573. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1574. begin
  1575. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1576. taicpu(p).opcode := A_MOV;
  1577. Result := True;
  1578. end;
  1579. end;
  1580. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1581. var
  1582. p: taicpu absolute hp; { Implicit typecast }
  1583. i: Integer;
  1584. begin
  1585. Result := False;
  1586. if not assigned(hp) or
  1587. (hp.typ <> ait_instruction) then
  1588. Exit;
  1589. Prefetch(insprop[p.opcode]);
  1590. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1591. with insprop[p.opcode] do
  1592. begin
  1593. case getsubreg(reg) of
  1594. R_SUBW,R_SUBD,R_SUBQ:
  1595. Result:=
  1596. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1597. uncommon flags are checked first }
  1598. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1599. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1600. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1601. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1604. R_SUBFLAGCARRY:
  1605. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1606. R_SUBFLAGPARITY:
  1607. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGAUXILIARY:
  1609. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGZERO:
  1611. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGSIGN:
  1613. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGOVERFLOW:
  1615. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGINTERRUPT:
  1617. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGDIRECTION:
  1619. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1620. else
  1621. internalerror(2017050501);
  1622. end;
  1623. exit;
  1624. end;
  1625. { Handle special cases first }
  1626. case p.opcode of
  1627. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1628. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1629. begin
  1630. Result :=
  1631. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1632. (p.oper[1]^.typ = top_reg) and
  1633. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1634. (
  1635. (p.oper[0]^.typ = top_const) or
  1636. (
  1637. (p.oper[0]^.typ = top_reg) and
  1638. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1639. ) or (
  1640. (p.oper[0]^.typ = top_ref) and
  1641. not RegInRef(reg,p.oper[0]^.ref^)
  1642. )
  1643. );
  1644. end;
  1645. A_MUL, A_IMUL:
  1646. Result :=
  1647. (
  1648. (p.ops=3) and { IMUL only }
  1649. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1650. (
  1651. (
  1652. (p.oper[1]^.typ=top_reg) and
  1653. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1654. ) or (
  1655. (p.oper[1]^.typ=top_ref) and
  1656. not RegInRef(reg,p.oper[1]^.ref^)
  1657. )
  1658. )
  1659. ) or (
  1660. (
  1661. (p.ops=1) and
  1662. (
  1663. (
  1664. (
  1665. (p.oper[0]^.typ=top_reg) and
  1666. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1667. )
  1668. ) or (
  1669. (p.oper[0]^.typ=top_ref) and
  1670. not RegInRef(reg,p.oper[0]^.ref^)
  1671. )
  1672. ) and (
  1673. (
  1674. (p.opsize=S_B) and
  1675. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1676. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1677. ) or (
  1678. (p.opsize=S_W) and
  1679. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1680. ) or (
  1681. (p.opsize=S_L) and
  1682. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1683. {$ifdef x86_64}
  1684. ) or (
  1685. (p.opsize=S_Q) and
  1686. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1687. {$endif x86_64}
  1688. )
  1689. )
  1690. )
  1691. );
  1692. A_CBW:
  1693. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1694. {$ifndef x86_64}
  1695. A_LDS:
  1696. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1697. A_LES:
  1698. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. {$endif not x86_64}
  1700. A_LFS:
  1701. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1702. A_LGS:
  1703. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LSS:
  1705. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1707. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1708. A_LODSB:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1710. A_LODSW:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1712. {$ifdef x86_64}
  1713. A_LODSQ:
  1714. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1715. {$endif x86_64}
  1716. A_LODSD:
  1717. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1718. A_FSTSW, A_FNSTSW:
  1719. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1720. else
  1721. begin
  1722. with insprop[p.opcode] do
  1723. begin
  1724. if (
  1725. { xor %reg,%reg etc. is classed as a new value }
  1726. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1727. MatchOpType(p, top_reg, top_reg) and
  1728. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1729. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1730. ) then
  1731. begin
  1732. Result := True;
  1733. Exit;
  1734. end;
  1735. { Make sure the entire register is overwritten }
  1736. if (getregtype(reg) = R_INTREGISTER) then
  1737. begin
  1738. if (p.ops > 0) then
  1739. begin
  1740. if RegInOp(reg, p.oper[0]^) then
  1741. begin
  1742. if (p.oper[0]^.typ = top_ref) then
  1743. begin
  1744. if RegInRef(reg, p.oper[0]^.ref^) then
  1745. begin
  1746. Result := False;
  1747. Exit;
  1748. end;
  1749. end
  1750. else if (p.oper[0]^.typ = top_reg) then
  1751. begin
  1752. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1753. begin
  1754. Result := False;
  1755. Exit;
  1756. end
  1757. else if ([Ch_WOp1]*Ch<>[]) then
  1758. begin
  1759. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1760. Result := True
  1761. else
  1762. begin
  1763. Result := False;
  1764. Exit;
  1765. end;
  1766. end;
  1767. end;
  1768. end;
  1769. if (p.ops > 1) then
  1770. begin
  1771. if RegInOp(reg, p.oper[1]^) then
  1772. begin
  1773. if (p.oper[1]^.typ = top_ref) then
  1774. begin
  1775. if RegInRef(reg, p.oper[1]^.ref^) then
  1776. begin
  1777. Result := False;
  1778. Exit;
  1779. end;
  1780. end
  1781. else if (p.oper[1]^.typ = top_reg) then
  1782. begin
  1783. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1784. begin
  1785. Result := False;
  1786. Exit;
  1787. end
  1788. else if ([Ch_WOp2]*Ch<>[]) then
  1789. begin
  1790. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1791. Result := True
  1792. else
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end;
  1798. end;
  1799. end;
  1800. if (p.ops > 2) then
  1801. begin
  1802. if RegInOp(reg, p.oper[2]^) then
  1803. begin
  1804. if (p.oper[2]^.typ = top_ref) then
  1805. begin
  1806. if RegInRef(reg, p.oper[2]^.ref^) then
  1807. begin
  1808. Result := False;
  1809. Exit;
  1810. end;
  1811. end
  1812. else if (p.oper[2]^.typ = top_reg) then
  1813. begin
  1814. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1815. begin
  1816. Result := False;
  1817. Exit;
  1818. end
  1819. else if ([Ch_WOp3]*Ch<>[]) then
  1820. begin
  1821. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1822. Result := True
  1823. else
  1824. begin
  1825. Result := False;
  1826. Exit;
  1827. end;
  1828. end;
  1829. end;
  1830. end;
  1831. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1832. begin
  1833. if (p.oper[3]^.typ = top_ref) then
  1834. begin
  1835. if RegInRef(reg, p.oper[3]^.ref^) then
  1836. begin
  1837. Result := False;
  1838. Exit;
  1839. end;
  1840. end
  1841. else if (p.oper[3]^.typ = top_reg) then
  1842. begin
  1843. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1844. begin
  1845. Result := False;
  1846. Exit;
  1847. end
  1848. else if ([Ch_WOp4]*Ch<>[]) then
  1849. begin
  1850. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1851. Result := True
  1852. else
  1853. begin
  1854. Result := False;
  1855. Exit;
  1856. end;
  1857. end;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1864. case getsupreg(reg) of
  1865. RS_EAX:
  1866. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1867. begin
  1868. Result := True;
  1869. Exit;
  1870. end;
  1871. RS_ECX:
  1872. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1873. begin
  1874. Result := True;
  1875. Exit;
  1876. end;
  1877. RS_EDX:
  1878. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1879. begin
  1880. Result := True;
  1881. Exit;
  1882. end;
  1883. RS_EBX:
  1884. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1885. begin
  1886. Result := True;
  1887. Exit;
  1888. end;
  1889. RS_ESP:
  1890. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1891. begin
  1892. Result := True;
  1893. Exit;
  1894. end;
  1895. RS_EBP:
  1896. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1897. begin
  1898. Result := True;
  1899. Exit;
  1900. end;
  1901. RS_ESI:
  1902. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1903. begin
  1904. Result := True;
  1905. Exit;
  1906. end;
  1907. RS_EDI:
  1908. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1909. begin
  1910. Result := True;
  1911. Exit;
  1912. end;
  1913. else
  1914. ;
  1915. end;
  1916. end;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1922. var
  1923. hp2,hp3 : tai;
  1924. begin
  1925. { some x86-64 issue a NOP before the real exit code }
  1926. if MatchInstruction(p,A_NOP,[]) then
  1927. GetNextInstruction(p,p);
  1928. result:=assigned(p) and (p.typ=ait_instruction) and
  1929. ((taicpu(p).opcode = A_RET) or
  1930. ((taicpu(p).opcode=A_LEAVE) and
  1931. GetNextInstruction(p,hp2) and
  1932. MatchInstruction(hp2,A_RET,[S_NO])
  1933. ) or
  1934. (((taicpu(p).opcode=A_LEA) and
  1935. MatchOpType(taicpu(p),top_ref,top_reg) and
  1936. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1937. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1938. ) and
  1939. GetNextInstruction(p,hp2) and
  1940. MatchInstruction(hp2,A_RET,[S_NO])
  1941. ) or
  1942. ((((taicpu(p).opcode=A_MOV) and
  1943. MatchOpType(taicpu(p),top_reg,top_reg) and
  1944. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1945. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1946. ((taicpu(p).opcode=A_LEA) and
  1947. MatchOpType(taicpu(p),top_ref,top_reg) and
  1948. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1949. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1950. )
  1951. ) and
  1952. GetNextInstruction(p,hp2) and
  1953. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1954. MatchOpType(taicpu(hp2),top_reg) and
  1955. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1956. GetNextInstruction(hp2,hp3) and
  1957. MatchInstruction(hp3,A_RET,[S_NO])
  1958. )
  1959. );
  1960. end;
  1961. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1962. begin
  1963. isFoldableArithOp := False;
  1964. case hp1.opcode of
  1965. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1966. isFoldableArithOp :=
  1967. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1968. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1969. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1970. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[1]^.reg = reg);
  1972. A_INC,A_DEC,A_NEG,A_NOT:
  1973. isFoldableArithOp :=
  1974. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1975. (taicpu(hp1).oper[0]^.reg = reg);
  1976. else
  1977. ;
  1978. end;
  1979. end;
  1980. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1981. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1982. var
  1983. hp2: tai;
  1984. begin
  1985. hp2 := p;
  1986. repeat
  1987. hp2 := tai(hp2.previous);
  1988. if assigned(hp2) and
  1989. (hp2.typ = ait_regalloc) and
  1990. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1991. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1992. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1993. begin
  1994. RemoveInstruction(hp2);
  1995. break;
  1996. end;
  1997. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1998. end;
  1999. begin
  2000. case current_procinfo.procdef.returndef.typ of
  2001. arraydef,recorddef,pointerdef,
  2002. stringdef,enumdef,procdef,objectdef,errordef,
  2003. filedef,setdef,procvardef,
  2004. classrefdef,forwarddef:
  2005. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2006. orddef:
  2007. if current_procinfo.procdef.returndef.size <> 0 then
  2008. begin
  2009. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2010. { for int64/qword }
  2011. if current_procinfo.procdef.returndef.size = 8 then
  2012. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2013. end;
  2014. else
  2015. ;
  2016. end;
  2017. end;
  2018. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2019. var
  2020. hp1,hp2 : tai;
  2021. begin
  2022. result:=false;
  2023. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2024. begin
  2025. { vmova* reg1,reg1
  2026. =>
  2027. <nop> }
  2028. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2029. begin
  2030. RemoveCurrentP(p);
  2031. result:=true;
  2032. exit;
  2033. end;
  2034. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2035. (hp1.typ = ait_instruction) and
  2036. (
  2037. { Under -O2 and below, the instructions are always adjacent }
  2038. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2039. (taicpu(hp1).ops <= 1) or
  2040. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2041. { If reg1 = reg3, reg1 must not be modified in between }
  2042. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2043. ) then
  2044. begin
  2045. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2046. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2047. begin
  2048. { vmova* reg1,reg2
  2049. ...
  2050. vmova* reg2,reg3
  2051. dealloc reg2
  2052. =>
  2053. vmova* reg1,reg3 }
  2054. TransferUsedRegs(TmpUsedRegs);
  2055. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2056. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2057. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2058. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2059. begin
  2060. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2061. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2064. RemoveInstruction(hp1);
  2065. result:=true;
  2066. exit;
  2067. end;
  2068. { special case:
  2069. vmova* reg1,<op>
  2070. ...
  2071. vmova* <op>,reg1
  2072. =>
  2073. vmova* reg1,<op> }
  2074. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2075. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2076. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2077. ) then
  2078. begin
  2079. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2080. RemoveInstruction(hp1);
  2081. result:=true;
  2082. exit;
  2083. end
  2084. end
  2085. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2086. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2087. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2088. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2089. ) and
  2090. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2091. begin
  2092. { vmova* reg1,reg2
  2093. ...
  2094. vmovs* reg2,<op>
  2095. dealloc reg2
  2096. =>
  2097. vmovs* reg1,<op> }
  2098. TransferUsedRegs(TmpUsedRegs);
  2099. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2100. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2101. begin
  2102. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2103. taicpu(p).opcode:=taicpu(hp1).opcode;
  2104. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2105. TransferUsedRegs(TmpUsedRegs);
  2106. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2107. RemoveInstruction(hp1);
  2108. result:=true;
  2109. exit;
  2110. end
  2111. end;
  2112. if MatchInstruction(hp1,[A_VFMADDPD,
  2113. A_VFMADD132PD,
  2114. A_VFMADD132PS,
  2115. A_VFMADD132SD,
  2116. A_VFMADD132SS,
  2117. A_VFMADD213PD,
  2118. A_VFMADD213PS,
  2119. A_VFMADD213SD,
  2120. A_VFMADD213SS,
  2121. A_VFMADD231PD,
  2122. A_VFMADD231PS,
  2123. A_VFMADD231SD,
  2124. A_VFMADD231SS,
  2125. A_VFMADDSUB132PD,
  2126. A_VFMADDSUB132PS,
  2127. A_VFMADDSUB213PD,
  2128. A_VFMADDSUB213PS,
  2129. A_VFMADDSUB231PD,
  2130. A_VFMADDSUB231PS,
  2131. A_VFMSUB132PD,
  2132. A_VFMSUB132PS,
  2133. A_VFMSUB132SD,
  2134. A_VFMSUB132SS,
  2135. A_VFMSUB213PD,
  2136. A_VFMSUB213PS,
  2137. A_VFMSUB213SD,
  2138. A_VFMSUB213SS,
  2139. A_VFMSUB231PD,
  2140. A_VFMSUB231PS,
  2141. A_VFMSUB231SD,
  2142. A_VFMSUB231SS,
  2143. A_VFMSUBADD132PD,
  2144. A_VFMSUBADD132PS,
  2145. A_VFMSUBADD213PD,
  2146. A_VFMSUBADD213PS,
  2147. A_VFMSUBADD231PD,
  2148. A_VFMSUBADD231PS,
  2149. A_VFNMADD132PD,
  2150. A_VFNMADD132PS,
  2151. A_VFNMADD132SD,
  2152. A_VFNMADD132SS,
  2153. A_VFNMADD213PD,
  2154. A_VFNMADD213PS,
  2155. A_VFNMADD213SD,
  2156. A_VFNMADD213SS,
  2157. A_VFNMADD231PD,
  2158. A_VFNMADD231PS,
  2159. A_VFNMADD231SD,
  2160. A_VFNMADD231SS,
  2161. A_VFNMSUB132PD,
  2162. A_VFNMSUB132PS,
  2163. A_VFNMSUB132SD,
  2164. A_VFNMSUB132SS,
  2165. A_VFNMSUB213PD,
  2166. A_VFNMSUB213PS,
  2167. A_VFNMSUB213SD,
  2168. A_VFNMSUB213SS,
  2169. A_VFNMSUB231PD,
  2170. A_VFNMSUB231PS,
  2171. A_VFNMSUB231SD,
  2172. A_VFNMSUB231SS],[S_NO]) and
  2173. { we mix single and double opperations here because we assume that the compiler
  2174. generates vmovapd only after double operations and vmovaps only after single operations }
  2175. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2176. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2177. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2178. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2179. begin
  2180. TransferUsedRegs(TmpUsedRegs);
  2181. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2182. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2183. begin
  2184. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2185. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2186. RemoveCurrentP(p)
  2187. else
  2188. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2189. RemoveInstruction(hp2);
  2190. end;
  2191. end
  2192. else if (hp1.typ = ait_instruction) and
  2193. (((taicpu(p).opcode=A_MOVAPS) and
  2194. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2195. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2196. ((taicpu(p).opcode=A_MOVAPD) and
  2197. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2198. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2199. ) and
  2200. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2201. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2202. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2203. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2204. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2205. { change
  2206. movapX reg,reg2
  2207. addsX/subsX/... reg3, reg2
  2208. movapX reg2,reg
  2209. to
  2210. addsX/subsX/... reg3,reg
  2211. }
  2212. begin
  2213. TransferUsedRegs(TmpUsedRegs);
  2214. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2215. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2216. begin
  2217. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2218. debug_op2str(taicpu(p).opcode)+' '+
  2219. debug_op2str(taicpu(hp1).opcode)+' '+
  2220. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2221. { we cannot eliminate the first move if
  2222. the operations uses the same register for source and dest }
  2223. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2224. { Remember that hp1 is not necessarily the immediate
  2225. next instruction }
  2226. RemoveCurrentP(p);
  2227. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2228. RemoveInstruction(hp2);
  2229. result:=true;
  2230. end;
  2231. end
  2232. else if (hp1.typ = ait_instruction) and
  2233. (((taicpu(p).opcode=A_VMOVAPD) and
  2234. (taicpu(hp1).opcode=A_VCOMISD)) or
  2235. ((taicpu(p).opcode=A_VMOVAPS) and
  2236. ((taicpu(hp1).opcode=A_VCOMISS))
  2237. )
  2238. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2239. { change
  2240. movapX reg,reg1
  2241. vcomisX reg1,reg1
  2242. to
  2243. vcomisX reg,reg
  2244. }
  2245. begin
  2246. TransferUsedRegs(TmpUsedRegs);
  2247. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2248. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2249. begin
  2250. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2251. debug_op2str(taicpu(p).opcode)+' '+
  2252. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2253. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2254. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2255. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2256. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2257. RemoveCurrentP(p);
  2258. result:=true;
  2259. exit;
  2260. end;
  2261. end
  2262. end;
  2263. end;
  2264. end;
  2265. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2266. var
  2267. hp1 : tai;
  2268. begin
  2269. result:=false;
  2270. { replace
  2271. V<Op>X %mreg1,%mreg2,%mreg3
  2272. VMovX %mreg3,%mreg4
  2273. dealloc %mreg3
  2274. by
  2275. V<Op>X %mreg1,%mreg2,%mreg4
  2276. ?
  2277. }
  2278. if GetNextInstruction(p,hp1) and
  2279. { we mix single and double operations here because we assume that the compiler
  2280. generates vmovapd only after double operations and vmovaps only after single operations }
  2281. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2282. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2283. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2284. begin
  2285. TransferUsedRegs(TmpUsedRegs);
  2286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2287. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2288. begin
  2289. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2290. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2291. RemoveInstruction(hp1);
  2292. result:=true;
  2293. end;
  2294. end;
  2295. end;
  2296. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2297. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2298. begin
  2299. Result := False;
  2300. { For safety reasons, only check for exact register matches }
  2301. { Check base register }
  2302. if (ref.base = AOldReg) then
  2303. begin
  2304. ref.base := ANewReg;
  2305. Result := True;
  2306. end;
  2307. { Check index register }
  2308. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2309. begin
  2310. ref.index := ANewReg;
  2311. Result := True;
  2312. end;
  2313. end;
  2314. { Replaces all references to AOldReg in an operand to ANewReg }
  2315. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2316. var
  2317. OldSupReg, NewSupReg: TSuperRegister;
  2318. OldSubReg, NewSubReg: TSubRegister;
  2319. OldRegType: TRegisterType;
  2320. ThisOper: POper;
  2321. begin
  2322. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2323. Result := False;
  2324. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2325. InternalError(2020011801);
  2326. OldSupReg := getsupreg(AOldReg);
  2327. OldSubReg := getsubreg(AOldReg);
  2328. OldRegType := getregtype(AOldReg);
  2329. NewSupReg := getsupreg(ANewReg);
  2330. NewSubReg := getsubreg(ANewReg);
  2331. if OldRegType <> getregtype(ANewReg) then
  2332. InternalError(2020011802);
  2333. if OldSubReg <> NewSubReg then
  2334. InternalError(2020011803);
  2335. case ThisOper^.typ of
  2336. top_reg:
  2337. if (
  2338. (ThisOper^.reg = AOldReg) or
  2339. (
  2340. (OldRegType = R_INTREGISTER) and
  2341. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2342. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2343. (
  2344. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2345. {$ifndef x86_64}
  2346. and (
  2347. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2348. don't have an 8-bit representation }
  2349. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2350. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2351. )
  2352. {$endif x86_64}
  2353. )
  2354. )
  2355. ) then
  2356. begin
  2357. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2358. Result := True;
  2359. end;
  2360. top_ref:
  2361. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2362. Result := True;
  2363. else
  2364. ;
  2365. end;
  2366. end;
  2367. { Replaces all references to AOldReg in an instruction to ANewReg }
  2368. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2369. const
  2370. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2371. var
  2372. OperIdx: Integer;
  2373. begin
  2374. Result := False;
  2375. for OperIdx := 0 to p.ops - 1 do
  2376. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2377. begin
  2378. { The shift and rotate instructions can only use CL }
  2379. if not (
  2380. (OperIdx = 0) and
  2381. { This second condition just helps to avoid unnecessarily
  2382. calling MatchInstruction for 10 different opcodes }
  2383. (p.oper[0]^.reg = NR_CL) and
  2384. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2385. ) then
  2386. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2387. end
  2388. else if p.oper[OperIdx]^.typ = top_ref then
  2389. { It's okay to replace registers in references that get written to }
  2390. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2391. end;
  2392. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2393. begin
  2394. Result :=
  2395. (ref^.index = NR_NO) and
  2396. (
  2397. {$ifdef x86_64}
  2398. (
  2399. (ref^.base = NR_RIP) and
  2400. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2401. ) or
  2402. {$endif x86_64}
  2403. (ref^.refaddr = addr_full) or
  2404. (ref^.base = NR_STACK_POINTER_REG) or
  2405. (ref^.base = current_procinfo.framepointer)
  2406. );
  2407. end;
  2408. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2409. var
  2410. l: asizeint;
  2411. begin
  2412. Result := False;
  2413. { Should have been checked previously }
  2414. if p.opcode <> A_LEA then
  2415. InternalError(2020072501);
  2416. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2417. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2418. not(cs_opt_size in current_settings.optimizerswitches) then
  2419. exit;
  2420. with p.oper[0]^.ref^ do
  2421. begin
  2422. if (base <> p.oper[1]^.reg) or
  2423. (index <> NR_NO) or
  2424. assigned(symbol) then
  2425. exit;
  2426. l:=offset;
  2427. if (l=1) and UseIncDec then
  2428. begin
  2429. p.opcode:=A_INC;
  2430. p.loadreg(0,p.oper[1]^.reg);
  2431. p.ops:=1;
  2432. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2433. end
  2434. else if (l=-1) and UseIncDec then
  2435. begin
  2436. p.opcode:=A_DEC;
  2437. p.loadreg(0,p.oper[1]^.reg);
  2438. p.ops:=1;
  2439. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2440. end
  2441. else
  2442. begin
  2443. if (l<0) and (l<>-2147483648) then
  2444. begin
  2445. p.opcode:=A_SUB;
  2446. p.loadConst(0,-l);
  2447. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2448. end
  2449. else
  2450. begin
  2451. p.opcode:=A_ADD;
  2452. p.loadConst(0,l);
  2453. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2454. end;
  2455. end;
  2456. end;
  2457. Result := True;
  2458. end;
  2459. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2460. var
  2461. CurrentReg, ReplaceReg: TRegister;
  2462. begin
  2463. Result := False;
  2464. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2465. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2466. case hp.opcode of
  2467. A_FSTSW, A_FNSTSW,
  2468. A_IN, A_INS, A_OUT, A_OUTS,
  2469. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2470. { These routines have explicit operands, but they are restricted in
  2471. what they can be (e.g. IN and OUT can only read from AL, AX or
  2472. EAX. }
  2473. Exit;
  2474. A_IMUL:
  2475. begin
  2476. { The 1-operand version writes to implicit registers
  2477. The 2-operand version reads from the first operator, and reads
  2478. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2479. the 3-operand version reads from a register that it doesn't write to
  2480. }
  2481. case hp.ops of
  2482. 1:
  2483. if (
  2484. (
  2485. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2486. ) or
  2487. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2488. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2489. begin
  2490. Result := True;
  2491. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2492. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2493. end;
  2494. 2:
  2495. { Only modify the first parameter }
  2496. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2497. begin
  2498. Result := True;
  2499. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2500. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2501. end;
  2502. 3:
  2503. { Only modify the second parameter }
  2504. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. else
  2511. InternalError(2020012901);
  2512. end;
  2513. end;
  2514. else
  2515. if (hp.ops > 0) and
  2516. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2517. begin
  2518. Result := True;
  2519. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2520. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2521. end;
  2522. end;
  2523. end;
  2524. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2525. var
  2526. hp2: tai;
  2527. p_SourceReg, p_TargetReg: TRegister;
  2528. begin
  2529. Result := False;
  2530. { Backward optimisation. If we have:
  2531. func. %reg1,%reg2
  2532. mov %reg2,%reg3
  2533. (dealloc %reg2)
  2534. Change to:
  2535. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2536. Perform similar optimisations with 1, 3 and 4-operand instructions
  2537. that only have one output.
  2538. }
  2539. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2540. begin
  2541. p_SourceReg := taicpu(p).oper[0]^.reg;
  2542. p_TargetReg := taicpu(p).oper[1]^.reg;
  2543. TransferUsedRegs(TmpUsedRegs);
  2544. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2545. GetLastInstruction(p, hp2) and
  2546. (hp2.typ = ait_instruction) and
  2547. { Have to make sure it's an instruction that only reads from
  2548. the first operands and only writes (not reads or modifies) to
  2549. the last one; in essence, a pure function such as BSR, POPCNT
  2550. or ANDN }
  2551. (
  2552. (
  2553. (taicpu(hp2).ops = 1) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2555. ) or
  2556. (
  2557. (taicpu(hp2).ops = 2) and
  2558. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2559. ) or
  2560. (
  2561. (taicpu(hp2).ops = 3) and
  2562. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2563. ) or
  2564. (
  2565. (taicpu(hp2).ops = 4) and
  2566. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2567. )
  2568. ) and
  2569. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2570. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2571. begin
  2572. case taicpu(hp2).opcode of
  2573. A_FSTSW, A_FNSTSW,
  2574. A_IN, A_INS, A_OUT, A_OUTS,
  2575. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2576. { These routines have explicit operands, but they are restricted in
  2577. what they can be (e.g. IN and OUT can only read from AL, AX or
  2578. EAX. }
  2579. ;
  2580. else
  2581. begin
  2582. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2583. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2584. if not RegInInstruction(p_TargetReg, hp2) then
  2585. begin
  2586. { Since we're allocating from an earlier point, we
  2587. need to remove the register from the tracking }
  2588. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2589. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2590. end;
  2591. RemoveCurrentp(p, hp1);
  2592. { If the Func was another MOV instruction, we might get
  2593. "mov %reg,%reg" that doesn't get removed in Pass 2
  2594. otherwise, so deal with it here (also do something
  2595. similar with lea (%reg),%reg}
  2596. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2597. begin
  2598. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2599. if p = hp2 then
  2600. RemoveCurrentp(p)
  2601. else
  2602. RemoveInstruction(hp2);
  2603. end;
  2604. Result := True;
  2605. Exit;
  2606. end;
  2607. end;
  2608. end;
  2609. end;
  2610. end;
  2611. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2612. begin
  2613. Result := False;
  2614. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2615. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2616. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2617. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2618. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2619. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2620. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2621. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2622. begin
  2623. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2624. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2625. Result := True;
  2626. end;
  2627. end;
  2628. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2629. var
  2630. hp1, hp2, hp3, hp4: tai;
  2631. DoOptimisation, TempBool: Boolean;
  2632. {$ifdef x86_64}
  2633. NewConst: TCGInt;
  2634. {$endif x86_64}
  2635. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2636. begin
  2637. if taicpu(hp1).opcode = signed_movop then
  2638. begin
  2639. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2640. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2641. end
  2642. else
  2643. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2644. end;
  2645. function TryConstMerge(var p1, p2: tai): Boolean;
  2646. var
  2647. ThisRef: TReference;
  2648. begin
  2649. Result := False;
  2650. ThisRef := taicpu(p2).oper[1]^.ref^;
  2651. { Only permit writes to the stack, since we can guarantee alignment with that }
  2652. if (ThisRef.index = NR_NO) and
  2653. (
  2654. (ThisRef.base = NR_STACK_POINTER_REG) or
  2655. (ThisRef.base = current_procinfo.framepointer)
  2656. ) then
  2657. begin
  2658. case taicpu(p).opsize of
  2659. S_B:
  2660. begin
  2661. { Word writes must be on a 2-byte boundary }
  2662. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2663. begin
  2664. { Reduce offset of second reference to see if it is sequential with the first }
  2665. Dec(ThisRef.offset, 1);
  2666. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2667. begin
  2668. { Make sure the constants aren't represented as a
  2669. negative number, as these won't merge properly }
  2670. taicpu(p1).opsize := S_W;
  2671. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2672. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2673. RemoveInstruction(p2);
  2674. Result := True;
  2675. end;
  2676. end;
  2677. end;
  2678. S_W:
  2679. begin
  2680. { Longword writes must be on a 4-byte boundary }
  2681. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2682. begin
  2683. { Reduce offset of second reference to see if it is sequential with the first }
  2684. Dec(ThisRef.offset, 2);
  2685. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2686. begin
  2687. { Make sure the constants aren't represented as a
  2688. negative number, as these won't merge properly }
  2689. taicpu(p1).opsize := S_L;
  2690. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2691. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2692. RemoveInstruction(p2);
  2693. Result := True;
  2694. end;
  2695. end;
  2696. end;
  2697. {$ifdef x86_64}
  2698. S_L:
  2699. begin
  2700. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2701. see if the constants can be encoded this way. }
  2702. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2703. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2704. { Quadword writes must be on an 8-byte boundary }
  2705. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2706. begin
  2707. { Reduce offset of second reference to see if it is sequential with the first }
  2708. Dec(ThisRef.offset, 4);
  2709. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2710. begin
  2711. { Make sure the constants aren't represented as a
  2712. negative number, as these won't merge properly }
  2713. taicpu(p1).opsize := S_Q;
  2714. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2715. taicpu(p1).oper[0]^.val := NewConst;
  2716. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2717. RemoveInstruction(p2);
  2718. Result := True;
  2719. end;
  2720. end;
  2721. end;
  2722. {$endif x86_64}
  2723. else
  2724. ;
  2725. end;
  2726. end;
  2727. end;
  2728. var
  2729. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2730. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2731. NewSize: topsize; NewOffset: asizeint;
  2732. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2733. SourceRef, TargetRef: TReference;
  2734. MovAligned, MovUnaligned: TAsmOp;
  2735. ThisRef: TReference;
  2736. JumpTracking: TLinkedList;
  2737. begin
  2738. Result:=false;
  2739. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2740. { remove mov reg1,reg1? }
  2741. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2742. then
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2745. { take care of the register (de)allocs following p }
  2746. RemoveCurrentP(p, hp1);
  2747. Result:=true;
  2748. exit;
  2749. end;
  2750. { All the next optimisations require a next instruction }
  2751. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2752. Exit;
  2753. { Prevent compiler warnings }
  2754. p_TargetReg := NR_NO;
  2755. if taicpu(p).oper[1]^.typ = top_reg then
  2756. begin
  2757. { Saves on a large number of dereferences }
  2758. p_TargetReg := taicpu(p).oper[1]^.reg;
  2759. { Look for:
  2760. mov %reg1,%reg2
  2761. ??? %reg2,r/m
  2762. Change to:
  2763. mov %reg1,%reg2
  2764. ??? %reg1,r/m
  2765. }
  2766. if taicpu(p).oper[0]^.typ = top_reg then
  2767. begin
  2768. if RegReadByInstruction(p_TargetReg, hp1) and
  2769. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2770. begin
  2771. { A change has occurred, just not in p }
  2772. Result := True;
  2773. TransferUsedRegs(TmpUsedRegs);
  2774. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2775. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2776. { Just in case something didn't get modified (e.g. an
  2777. implicit register) }
  2778. not RegReadByInstruction(p_TargetReg, hp1) then
  2779. begin
  2780. { We can remove the original MOV }
  2781. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2782. RemoveCurrentp(p, hp1);
  2783. { UsedRegs got updated by RemoveCurrentp }
  2784. Result := True;
  2785. Exit;
  2786. end;
  2787. { If we know a MOV instruction has become a null operation, we might as well
  2788. get rid of it now to save time. }
  2789. if (taicpu(hp1).opcode = A_MOV) and
  2790. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2791. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2792. { Just being a register is enough to confirm it's a null operation }
  2793. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2794. begin
  2795. Result := True;
  2796. { Speed-up to reduce a pipeline stall... if we had something like...
  2797. movl %eax,%edx
  2798. movw %dx,%ax
  2799. ... the second instruction would change to movw %ax,%ax, but
  2800. given that it is now %ax that's active rather than %eax,
  2801. penalties might occur due to a partial register write, so instead,
  2802. change it to a MOVZX instruction when optimising for speed.
  2803. }
  2804. if not (cs_opt_size in current_settings.optimizerswitches) and
  2805. IsMOVZXAcceptable and
  2806. (taicpu(hp1).opsize < taicpu(p).opsize)
  2807. {$ifdef x86_64}
  2808. { operations already implicitly set the upper 64 bits to zero }
  2809. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2810. {$endif x86_64}
  2811. then
  2812. begin
  2813. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2814. case taicpu(p).opsize of
  2815. S_W:
  2816. if taicpu(hp1).opsize = S_B then
  2817. taicpu(hp1).opsize := S_BL
  2818. else
  2819. InternalError(2020012911);
  2820. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2821. case taicpu(hp1).opsize of
  2822. S_B:
  2823. taicpu(hp1).opsize := S_BL;
  2824. S_W:
  2825. taicpu(hp1).opsize := S_WL;
  2826. else
  2827. InternalError(2020012912);
  2828. end;
  2829. else
  2830. InternalError(2020012910);
  2831. end;
  2832. taicpu(hp1).opcode := A_MOVZX;
  2833. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2834. end
  2835. else
  2836. begin
  2837. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2838. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2839. RemoveInstruction(hp1);
  2840. { The instruction after what was hp1 is now the immediate next instruction,
  2841. so we can continue to make optimisations if it's present }
  2842. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2843. Exit;
  2844. hp1 := hp2;
  2845. end;
  2846. end;
  2847. end;
  2848. end;
  2849. end;
  2850. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2851. overwrites the original destination register. e.g.
  2852. movl ###,%reg2d
  2853. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2854. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2855. }
  2856. if (taicpu(p).oper[1]^.typ = top_reg) and
  2857. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2858. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2859. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2860. begin
  2861. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2862. begin
  2863. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2864. case taicpu(p).oper[0]^.typ of
  2865. top_const:
  2866. { We have something like:
  2867. movb $x, %regb
  2868. movzbl %regb,%regd
  2869. Change to:
  2870. movl $x, %regd
  2871. }
  2872. begin
  2873. case taicpu(hp1).opsize of
  2874. S_BW:
  2875. begin
  2876. convert_mov_value(A_MOVSX, $FF);
  2877. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2878. taicpu(p).opsize := S_W;
  2879. end;
  2880. S_BL:
  2881. begin
  2882. convert_mov_value(A_MOVSX, $FF);
  2883. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2884. taicpu(p).opsize := S_L;
  2885. end;
  2886. S_WL:
  2887. begin
  2888. convert_mov_value(A_MOVSX, $FFFF);
  2889. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2890. taicpu(p).opsize := S_L;
  2891. end;
  2892. {$ifdef x86_64}
  2893. S_BQ:
  2894. begin
  2895. convert_mov_value(A_MOVSX, $FF);
  2896. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2897. taicpu(p).opsize := S_Q;
  2898. end;
  2899. S_WQ:
  2900. begin
  2901. convert_mov_value(A_MOVSX, $FFFF);
  2902. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2903. taicpu(p).opsize := S_Q;
  2904. end;
  2905. S_LQ:
  2906. begin
  2907. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2908. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2909. taicpu(p).opsize := S_Q;
  2910. end;
  2911. {$endif x86_64}
  2912. else
  2913. { If hp1 was a MOV instruction, it should have been
  2914. optimised already }
  2915. InternalError(2020021001);
  2916. end;
  2917. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2918. RemoveInstruction(hp1);
  2919. Result := True;
  2920. Exit;
  2921. end;
  2922. top_ref:
  2923. begin
  2924. { We have something like:
  2925. movb mem, %regb
  2926. movzbl %regb,%regd
  2927. Change to:
  2928. movzbl mem, %regd
  2929. }
  2930. ThisRef := taicpu(p).oper[0]^.ref^;
  2931. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2932. begin
  2933. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2934. taicpu(hp1).loadref(0, ThisRef);
  2935. { Make sure any registers in the references are properly tracked }
  2936. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2937. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2938. if (ThisRef.index <> NR_NO) then
  2939. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2940. RemoveCurrentP(p, hp1);
  2941. Result := True;
  2942. Exit;
  2943. end;
  2944. end;
  2945. else
  2946. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2947. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2948. Exit;
  2949. end;
  2950. end
  2951. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2952. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2953. optimised }
  2954. else
  2955. begin
  2956. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2957. RemoveCurrentP(p, hp1);
  2958. Result := True;
  2959. Exit;
  2960. end;
  2961. end;
  2962. if (taicpu(hp1).opcode = A_AND) and
  2963. (taicpu(p).oper[1]^.typ = top_reg) and
  2964. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2965. begin
  2966. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2967. begin
  2968. case taicpu(p).opsize of
  2969. S_L:
  2970. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2971. begin
  2972. { Optimize out:
  2973. mov x, %reg
  2974. and ffffffffh, %reg
  2975. }
  2976. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2977. RemoveInstruction(hp1);
  2978. Result:=true;
  2979. exit;
  2980. end;
  2981. S_Q: { TODO: Confirm if this is even possible }
  2982. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2983. begin
  2984. { Optimize out:
  2985. mov x, %reg
  2986. and ffffffffffffffffh, %reg
  2987. }
  2988. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2989. RemoveInstruction(hp1);
  2990. Result:=true;
  2991. exit;
  2992. end;
  2993. else
  2994. ;
  2995. end;
  2996. if (
  2997. (taicpu(p).oper[0]^.typ=top_reg) or
  2998. (
  2999. (taicpu(p).oper[0]^.typ=top_ref) and
  3000. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3001. )
  3002. ) and
  3003. GetNextInstruction(hp1,hp2) and
  3004. MatchInstruction(hp2,A_TEST,[]) and
  3005. (
  3006. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3007. (
  3008. { If the register being tested is smaller than the one
  3009. that received a bitwise AND, permit it if the constant
  3010. fits into the smaller size }
  3011. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3012. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3013. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3014. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3015. (
  3016. (
  3017. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3018. (taicpu(hp1).oper[0]^.val <= $FF)
  3019. ) or
  3020. (
  3021. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3022. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3023. {$ifdef x86_64}
  3024. ) or
  3025. (
  3026. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3027. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3028. {$endif x86_64}
  3029. )
  3030. )
  3031. )
  3032. ) and
  3033. (
  3034. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3035. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3036. ) and
  3037. GetNextInstruction(hp2,hp3) and
  3038. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3039. (taicpu(hp3).condition in [C_E,C_NE]) then
  3040. begin
  3041. TransferUsedRegs(TmpUsedRegs);
  3042. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3043. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3044. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3045. begin
  3046. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3047. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3048. taicpu(hp1).opcode:=A_TEST;
  3049. { Shrink the TEST instruction down to the smallest possible size }
  3050. case taicpu(hp1).oper[0]^.val of
  3051. 0..255:
  3052. if (taicpu(hp1).opsize <> S_B)
  3053. {$ifndef x86_64}
  3054. and (
  3055. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3056. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3057. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3058. )
  3059. {$endif x86_64}
  3060. then
  3061. begin
  3062. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3063. { Only print debug message if the TEST instruction
  3064. is a different size before and after }
  3065. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3066. taicpu(hp1).opsize := S_B;
  3067. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3068. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3069. end;
  3070. 256..65535:
  3071. if (taicpu(hp1).opsize <> S_W) then
  3072. begin
  3073. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3074. { Only print debug message if the TEST instruction
  3075. is a different size before and after }
  3076. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3077. taicpu(hp1).opsize := S_W;
  3078. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3079. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3080. end;
  3081. {$ifdef x86_64}
  3082. 65536..$7FFFFFFF:
  3083. if (taicpu(hp1).opsize <> S_L) then
  3084. begin
  3085. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3086. { Only print debug message if the TEST instruction
  3087. is a different size before and after }
  3088. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3089. taicpu(hp1).opsize := S_L;
  3090. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3091. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3092. end;
  3093. {$endif x86_64}
  3094. else
  3095. ;
  3096. end;
  3097. RemoveInstruction(hp2);
  3098. RemoveCurrentP(p, hp1);
  3099. Result:=true;
  3100. exit;
  3101. end;
  3102. end;
  3103. end
  3104. else if IsMOVZXAcceptable and
  3105. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3106. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3107. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3108. then
  3109. begin
  3110. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3111. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3112. case taicpu(p).opsize of
  3113. S_B:
  3114. if (taicpu(hp1).oper[0]^.val = $ff) then
  3115. begin
  3116. { Convert:
  3117. movb x, %regl movb x, %regl
  3118. andw ffh, %regw andl ffh, %regd
  3119. To:
  3120. movzbw x, %regd movzbl x, %regd
  3121. (Identical registers, just different sizes)
  3122. }
  3123. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3124. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3125. case taicpu(hp1).opsize of
  3126. S_W: NewSize := S_BW;
  3127. S_L: NewSize := S_BL;
  3128. {$ifdef x86_64}
  3129. S_Q: NewSize := S_BQ;
  3130. {$endif x86_64}
  3131. else
  3132. InternalError(2018011510);
  3133. end;
  3134. end
  3135. else
  3136. NewSize := S_NO;
  3137. S_W:
  3138. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3139. begin
  3140. { Convert:
  3141. movw x, %regw
  3142. andl ffffh, %regd
  3143. To:
  3144. movzwl x, %regd
  3145. (Identical registers, just different sizes)
  3146. }
  3147. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3148. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3149. case taicpu(hp1).opsize of
  3150. S_L: NewSize := S_WL;
  3151. {$ifdef x86_64}
  3152. S_Q: NewSize := S_WQ;
  3153. {$endif x86_64}
  3154. else
  3155. InternalError(2018011511);
  3156. end;
  3157. end
  3158. else
  3159. NewSize := S_NO;
  3160. else
  3161. NewSize := S_NO;
  3162. end;
  3163. if NewSize <> S_NO then
  3164. begin
  3165. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3166. { The actual optimization }
  3167. taicpu(p).opcode := A_MOVZX;
  3168. taicpu(p).changeopsize(NewSize);
  3169. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3170. { Safeguard if "and" is followed by a conditional command }
  3171. TransferUsedRegs(TmpUsedRegs);
  3172. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3173. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3174. begin
  3175. { At this point, the "and" command is effectively equivalent to
  3176. "test %reg,%reg". This will be handled separately by the
  3177. Peephole Optimizer. [Kit] }
  3178. DebugMsg(SPeepholeOptimization + PreMessage +
  3179. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3180. end
  3181. else
  3182. begin
  3183. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3184. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3185. RemoveInstruction(hp1);
  3186. end;
  3187. Result := True;
  3188. Exit;
  3189. end;
  3190. end;
  3191. end;
  3192. if (taicpu(hp1).opcode = A_OR) and
  3193. (taicpu(p).oper[1]^.typ = top_reg) and
  3194. MatchOperand(taicpu(p).oper[0]^, 0) and
  3195. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3196. begin
  3197. { mov 0, %reg
  3198. or ###,%reg
  3199. Change to (only if the flags are not used):
  3200. mov ###,%reg
  3201. }
  3202. TransferUsedRegs(TmpUsedRegs);
  3203. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3204. DoOptimisation := True;
  3205. { Even if the flags are used, we might be able to do the optimisation
  3206. if the conditions are predictable }
  3207. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3208. begin
  3209. { Only perform if ### = %reg (the same register) or equal to 0,
  3210. so %reg is guaranteed to still have a value of zero }
  3211. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3212. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3213. begin
  3214. hp2 := hp1;
  3215. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3216. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3217. GetNextInstruction(hp2, hp3) do
  3218. begin
  3219. { Don't continue modifying if the flags state is getting changed }
  3220. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3221. Break;
  3222. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3223. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3224. begin
  3225. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3226. begin
  3227. { Condition is always true }
  3228. case taicpu(hp3).opcode of
  3229. A_Jcc:
  3230. begin
  3231. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3232. { Check for jump shortcuts before we destroy the condition }
  3233. DoJumpOptimizations(hp3, TempBool);
  3234. MakeUnconditional(taicpu(hp3));
  3235. Result := True;
  3236. end;
  3237. A_CMOVcc:
  3238. begin
  3239. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3240. taicpu(hp3).opcode := A_MOV;
  3241. taicpu(hp3).condition := C_None;
  3242. Result := True;
  3243. end;
  3244. A_SETcc:
  3245. begin
  3246. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3247. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3248. taicpu(hp3).opcode := A_MOV;
  3249. taicpu(hp3).ops := 2;
  3250. taicpu(hp3).condition := C_None;
  3251. taicpu(hp3).opsize := S_B;
  3252. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3253. taicpu(hp3).loadconst(0, 1);
  3254. Result := True;
  3255. end;
  3256. else
  3257. InternalError(2021090701);
  3258. end;
  3259. end
  3260. 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
  3261. begin
  3262. { Condition is always false }
  3263. case taicpu(hp3).opcode of
  3264. A_Jcc:
  3265. begin
  3266. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3267. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3268. RemoveInstruction(hp3);
  3269. Result := True;
  3270. { Since hp3 was deleted, hp2 must not be updated }
  3271. Continue;
  3272. end;
  3273. A_CMOVcc:
  3274. begin
  3275. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3276. RemoveInstruction(hp3);
  3277. Result := True;
  3278. { Since hp3 was deleted, hp2 must not be updated }
  3279. Continue;
  3280. end;
  3281. A_SETcc:
  3282. begin
  3283. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3284. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3285. taicpu(hp3).opcode := A_MOV;
  3286. taicpu(hp3).ops := 2;
  3287. taicpu(hp3).condition := C_None;
  3288. taicpu(hp3).opsize := S_B;
  3289. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3290. taicpu(hp3).loadconst(0, 0);
  3291. Result := True;
  3292. end;
  3293. else
  3294. InternalError(2021090702);
  3295. end;
  3296. end
  3297. else
  3298. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3299. DoOptimisation := False;
  3300. end;
  3301. hp2 := hp3;
  3302. end;
  3303. { Flags are still in use - don't optimise }
  3304. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3305. DoOptimisation := False;
  3306. end
  3307. else
  3308. DoOptimisation := False;
  3309. end;
  3310. if DoOptimisation then
  3311. begin
  3312. {$ifdef x86_64}
  3313. { OR only supports 32-bit sign-extended constants for 64-bit
  3314. instructions, so compensate for this if the constant is
  3315. encoded as a value greater than or equal to 2^31 }
  3316. if (taicpu(hp1).opsize = S_Q) and
  3317. (taicpu(hp1).oper[0]^.typ = top_const) and
  3318. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3319. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3320. {$endif x86_64}
  3321. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3322. taicpu(hp1).opcode := A_MOV;
  3323. RemoveCurrentP(p, hp1);
  3324. Result := True;
  3325. Exit;
  3326. end;
  3327. end;
  3328. { Next instruction is also a MOV ? }
  3329. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3330. begin
  3331. if MatchOpType(taicpu(p), top_const, top_ref) and
  3332. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3333. TryConstMerge(p, hp1) then
  3334. begin
  3335. Result := True;
  3336. { In case we have four byte writes in a row, check for 2 more
  3337. right now so we don't have to wait for another iteration of
  3338. pass 1
  3339. }
  3340. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3341. case taicpu(p).opsize of
  3342. S_W:
  3343. begin
  3344. if GetNextInstruction(p, hp1) and
  3345. MatchInstruction(hp1, A_MOV, [S_B]) and
  3346. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3347. GetNextInstruction(hp1, hp2) and
  3348. MatchInstruction(hp2, A_MOV, [S_B]) and
  3349. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3350. { Try to merge the two bytes }
  3351. TryConstMerge(hp1, hp2) then
  3352. { Now try to merge the two words (hp2 will get deleted) }
  3353. TryConstMerge(p, hp1);
  3354. end;
  3355. S_L:
  3356. begin
  3357. { Though this only really benefits x86_64 and not i386, it
  3358. gets a potential optimisation done faster and hence
  3359. reduces the number of times OptPass1MOV is entered }
  3360. if GetNextInstruction(p, hp1) and
  3361. MatchInstruction(hp1, A_MOV, [S_W]) and
  3362. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3363. GetNextInstruction(hp1, hp2) and
  3364. MatchInstruction(hp2, A_MOV, [S_W]) and
  3365. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3366. { Try to merge the two words }
  3367. TryConstMerge(hp1, hp2) then
  3368. { This will always fail on i386, so don't bother
  3369. calling it unless we're doing x86_64 }
  3370. {$ifdef x86_64}
  3371. { Now try to merge the two longwords (hp2 will get deleted) }
  3372. TryConstMerge(p, hp1)
  3373. {$endif x86_64}
  3374. ;
  3375. end;
  3376. else
  3377. ;
  3378. end;
  3379. Exit;
  3380. end;
  3381. if (taicpu(p).oper[1]^.typ = top_reg) and
  3382. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3383. begin
  3384. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3385. TransferUsedRegs(TmpUsedRegs);
  3386. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3387. { we have
  3388. mov x, %treg
  3389. mov %treg, y
  3390. }
  3391. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3392. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3393. { we've got
  3394. mov x, %treg
  3395. mov %treg, y
  3396. with %treg is not used after }
  3397. case taicpu(p).oper[0]^.typ Of
  3398. { top_reg is covered by DeepMOVOpt }
  3399. top_const:
  3400. begin
  3401. { change
  3402. mov const, %treg
  3403. mov %treg, y
  3404. to
  3405. mov const, y
  3406. }
  3407. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3408. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3409. begin
  3410. if taicpu(hp1).oper[1]^.typ=top_reg then
  3411. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3412. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3413. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3414. RemoveInstruction(hp1);
  3415. Result:=true;
  3416. Exit;
  3417. end;
  3418. end;
  3419. top_ref:
  3420. case taicpu(hp1).oper[1]^.typ of
  3421. top_reg:
  3422. begin
  3423. { change
  3424. mov mem, %treg
  3425. mov %treg, %reg
  3426. to
  3427. mov mem, %reg"
  3428. }
  3429. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3430. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3431. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3432. RemoveInstruction(hp1);
  3433. Result:=true;
  3434. Exit;
  3435. end;
  3436. top_ref:
  3437. begin
  3438. {$ifdef x86_64}
  3439. { Look for the following to simplify:
  3440. mov x(mem1), %reg
  3441. mov %reg, y(mem2)
  3442. mov x+8(mem1), %reg
  3443. mov %reg, y+8(mem2)
  3444. Change to:
  3445. movdqu x(mem1), %xmmreg
  3446. movdqu %xmmreg, y(mem2)
  3447. ...but only as long as the memory blocks don't overlap
  3448. }
  3449. SourceRef := taicpu(p).oper[0]^.ref^;
  3450. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3451. if (taicpu(p).opsize = S_Q) and
  3452. GetNextInstruction(hp1, hp2) and
  3453. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3454. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3455. begin
  3456. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3457. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3458. Inc(SourceRef.offset, 8);
  3459. if UseAVX then
  3460. begin
  3461. MovAligned := A_VMOVDQA;
  3462. MovUnaligned := A_VMOVDQU;
  3463. end
  3464. else
  3465. begin
  3466. MovAligned := A_MOVDQA;
  3467. MovUnaligned := A_MOVDQU;
  3468. end;
  3469. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3470. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3471. begin
  3472. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3473. Inc(TargetRef.offset, 8);
  3474. if GetNextInstruction(hp2, hp3) and
  3475. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3476. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3477. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3478. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3479. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3480. begin
  3481. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3482. if NewMMReg <> NR_NO then
  3483. begin
  3484. { Remember that the offsets are 8 ahead }
  3485. if ((SourceRef.offset mod 16) = 8) and
  3486. (
  3487. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3488. (SourceRef.base = current_procinfo.framepointer) or
  3489. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3490. ) then
  3491. taicpu(p).opcode := MovAligned
  3492. else
  3493. taicpu(p).opcode := MovUnaligned;
  3494. taicpu(p).opsize := S_XMM;
  3495. taicpu(p).oper[1]^.reg := NewMMReg;
  3496. if ((TargetRef.offset mod 16) = 8) and
  3497. (
  3498. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3499. (TargetRef.base = current_procinfo.framepointer) or
  3500. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3501. ) then
  3502. taicpu(hp1).opcode := MovAligned
  3503. else
  3504. taicpu(hp1).opcode := MovUnaligned;
  3505. taicpu(hp1).opsize := S_XMM;
  3506. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3507. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3508. RemoveInstruction(hp2);
  3509. RemoveInstruction(hp3);
  3510. Result := True;
  3511. Exit;
  3512. end;
  3513. end;
  3514. end
  3515. else
  3516. begin
  3517. { See if the next references are 8 less rather than 8 greater }
  3518. Dec(SourceRef.offset, 16); { -8 the other way }
  3519. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3520. begin
  3521. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3522. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3523. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3524. GetNextInstruction(hp2, hp3) and
  3525. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3526. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3527. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3528. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3529. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3530. begin
  3531. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3532. if NewMMReg <> NR_NO then
  3533. begin
  3534. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3535. if ((SourceRef.offset mod 16) = 0) and
  3536. (
  3537. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3538. (SourceRef.base = current_procinfo.framepointer) or
  3539. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3540. ) then
  3541. taicpu(hp2).opcode := MovAligned
  3542. else
  3543. taicpu(hp2).opcode := MovUnaligned;
  3544. taicpu(hp2).opsize := S_XMM;
  3545. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3546. if ((TargetRef.offset mod 16) = 0) and
  3547. (
  3548. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3549. (TargetRef.base = current_procinfo.framepointer) or
  3550. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3551. ) then
  3552. taicpu(hp3).opcode := MovAligned
  3553. else
  3554. taicpu(hp3).opcode := MovUnaligned;
  3555. taicpu(hp3).opsize := S_XMM;
  3556. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3557. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3558. RemoveInstruction(hp1);
  3559. RemoveCurrentP(p, hp2);
  3560. Result := True;
  3561. Exit;
  3562. end;
  3563. end;
  3564. end;
  3565. end;
  3566. end;
  3567. {$endif x86_64}
  3568. end;
  3569. else
  3570. { The write target should be a reg or a ref }
  3571. InternalError(2021091601);
  3572. end;
  3573. else
  3574. ;
  3575. end
  3576. else
  3577. { %treg is used afterwards, but all eventualities
  3578. other than the first MOV instruction being a constant
  3579. are covered by DeepMOVOpt, so only check for that }
  3580. if (taicpu(p).oper[0]^.typ = top_const) and
  3581. (
  3582. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3583. not (cs_opt_size in current_settings.optimizerswitches) or
  3584. (taicpu(hp1).opsize = S_B)
  3585. ) and
  3586. (
  3587. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3588. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3589. ) then
  3590. begin
  3591. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3592. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3593. end;
  3594. end;
  3595. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3596. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3597. { mov reg1, mem1 or mov mem1, reg1
  3598. mov mem2, reg2 mov reg2, mem2}
  3599. begin
  3600. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3601. { mov reg1, mem1 or mov mem1, reg1
  3602. mov mem2, reg1 mov reg2, mem1}
  3603. begin
  3604. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3605. { Removes the second statement from
  3606. mov reg1, mem1/reg2
  3607. mov mem1/reg2, reg1 }
  3608. begin
  3609. if taicpu(p).oper[0]^.typ=top_reg then
  3610. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3611. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3612. RemoveInstruction(hp1);
  3613. Result:=true;
  3614. exit;
  3615. end
  3616. else
  3617. begin
  3618. TransferUsedRegs(TmpUsedRegs);
  3619. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3620. if (taicpu(p).oper[1]^.typ = top_ref) and
  3621. { mov reg1, mem1
  3622. mov mem2, reg1 }
  3623. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3624. GetNextInstruction(hp1, hp2) and
  3625. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3626. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3627. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3628. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3629. { change to
  3630. mov reg1, mem1 mov reg1, mem1
  3631. mov mem2, reg1 cmp reg1, mem2
  3632. cmp mem1, reg1
  3633. }
  3634. begin
  3635. RemoveInstruction(hp2);
  3636. taicpu(hp1).opcode := A_CMP;
  3637. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3638. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3639. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3640. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3641. end;
  3642. end;
  3643. end
  3644. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3645. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3646. begin
  3647. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3648. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3649. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3650. end
  3651. else
  3652. begin
  3653. TransferUsedRegs(TmpUsedRegs);
  3654. if GetNextInstruction(hp1, hp2) and
  3655. MatchOpType(taicpu(p),top_ref,top_reg) and
  3656. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3657. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3658. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3659. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3660. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3661. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3662. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3663. { mov mem1, %reg1
  3664. mov %reg1, mem2
  3665. mov mem2, reg2
  3666. to:
  3667. mov mem1, reg2
  3668. mov reg2, mem2}
  3669. begin
  3670. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3671. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3672. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3673. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3674. RemoveInstruction(hp2);
  3675. Result := True;
  3676. end
  3677. {$ifdef i386}
  3678. { this is enabled for i386 only, as the rules to create the reg sets below
  3679. are too complicated for x86-64, so this makes this code too error prone
  3680. on x86-64
  3681. }
  3682. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3683. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3684. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3685. { mov mem1, reg1 mov mem1, reg1
  3686. mov reg1, mem2 mov reg1, mem2
  3687. mov mem2, reg2 mov mem2, reg1
  3688. to: to:
  3689. mov mem1, reg1 mov mem1, reg1
  3690. mov mem1, reg2 mov reg1, mem2
  3691. mov reg1, mem2
  3692. or (if mem1 depends on reg1
  3693. and/or if mem2 depends on reg2)
  3694. to:
  3695. mov mem1, reg1
  3696. mov reg1, mem2
  3697. mov reg1, reg2
  3698. }
  3699. begin
  3700. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3701. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3702. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3703. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3704. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3705. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3706. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3707. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3708. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3709. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3710. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3711. end
  3712. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3713. begin
  3714. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3715. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3716. end
  3717. else
  3718. begin
  3719. RemoveInstruction(hp2);
  3720. end
  3721. {$endif i386}
  3722. ;
  3723. end;
  3724. end
  3725. { movl [mem1],reg1
  3726. movl [mem1],reg2
  3727. to
  3728. movl [mem1],reg1
  3729. movl reg1,reg2
  3730. }
  3731. else if not CheckMovMov2MovMov2(p, hp1) and
  3732. { movl const1,[mem1]
  3733. movl [mem1],reg1
  3734. to
  3735. movl const1,reg1
  3736. movl reg1,[mem1]
  3737. }
  3738. MatchOpType(Taicpu(p),top_const,top_ref) and
  3739. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3740. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3741. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3742. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3743. begin
  3744. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3745. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3746. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3747. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3748. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3749. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3750. Result:=true;
  3751. exit;
  3752. end;
  3753. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3754. { Change:
  3755. movl %reg1,%reg2
  3756. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3757. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3758. To:
  3759. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3760. movl x(%reg1),%reg1
  3761. movl %reg1,%regX
  3762. }
  3763. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3764. begin
  3765. p_SourceReg := taicpu(p).oper[0]^.reg;
  3766. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3767. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3768. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3769. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3770. GetNextInstruction(hp1, hp2) and
  3771. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3772. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3773. begin
  3774. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3775. if RegInRef(p_TargetReg, SourceRef) and
  3776. { If %reg1 also appears in the second reference, then it will
  3777. not refer to the same memory block as the first reference }
  3778. not RegInRef(p_SourceReg, SourceRef) then
  3779. begin
  3780. { Check to see if the references match if %reg2 is changed to %reg1 }
  3781. if SourceRef.base = p_TargetReg then
  3782. SourceRef.base := p_SourceReg;
  3783. if SourceRef.index = p_TargetReg then
  3784. SourceRef.index := p_SourceReg;
  3785. { RefsEqual also checks to ensure both references are non-volatile }
  3786. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3787. begin
  3788. taicpu(hp2).loadreg(0, p_SourceReg);
  3789. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3790. Result := True;
  3791. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3792. begin
  3793. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3794. RemoveCurrentP(p, hp1);
  3795. Exit;
  3796. end
  3797. else
  3798. begin
  3799. { Check to see if %reg2 is no longer in use }
  3800. TransferUsedRegs(TmpUsedRegs);
  3801. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3802. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3803. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3804. begin
  3805. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3806. RemoveCurrentP(p, hp1);
  3807. Exit;
  3808. end;
  3809. end;
  3810. { If we reach this point, p and hp1 weren't actually modified,
  3811. so we can do a bit more work on this pass }
  3812. end;
  3813. end;
  3814. end;
  3815. end;
  3816. end;
  3817. {$ifdef x86_64}
  3818. { Change:
  3819. movl %reg1l,%reg2l
  3820. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3821. To:
  3822. movl %reg1l,%reg2l
  3823. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3824. If %reg1 = %reg3, convert to:
  3825. movl %reg1l,%reg2l
  3826. andl %reg1l,%reg1l
  3827. }
  3828. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3829. MatchOpType(taicpu(p), top_reg, top_reg) and
  3830. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3831. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3832. begin
  3833. TransferUsedRegs(TmpUsedRegs);
  3834. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3835. taicpu(hp1).opsize := S_L;
  3836. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3837. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3838. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3839. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3840. begin
  3841. { %reg1 = %reg3 }
  3842. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3843. taicpu(hp1).opcode := A_AND;
  3844. end
  3845. else
  3846. begin
  3847. { %reg1 <> %reg3 }
  3848. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3849. end;
  3850. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3851. begin
  3852. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3853. RemoveCurrentP(p, hp1);
  3854. Result := True;
  3855. Exit;
  3856. end
  3857. else
  3858. begin
  3859. { Initial instruction wasn't actually changed }
  3860. Include(OptsToCheck, aoc_ForceNewIteration);
  3861. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3862. appears below since %reg1 has technically changed }
  3863. if taicpu(hp1).opcode = A_AND then
  3864. Exit;
  3865. end;
  3866. end;
  3867. {$endif x86_64}
  3868. { search further than the next instruction for a mov (as long as it's not a jump) }
  3869. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3870. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3871. (taicpu(p).oper[1]^.typ = top_reg) and
  3872. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3873. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3874. begin
  3875. { we work with hp2 here, so hp1 can be still used later on when
  3876. checking for GetNextInstruction_p }
  3877. hp3 := hp1;
  3878. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3879. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3880. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3881. TransferUsedRegs(TmpUsedRegs);
  3882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3883. if NotFirstIteration then
  3884. JumpTracking := TLinkedList.Create
  3885. else
  3886. JumpTracking := nil;
  3887. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3888. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3889. (hp2.typ=ait_instruction) do
  3890. begin
  3891. case taicpu(hp2).opcode of
  3892. A_POP:
  3893. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3894. begin
  3895. if not CrossJump and
  3896. not RegUsedBetween(p_TargetReg, p, hp2) then
  3897. begin
  3898. { We can remove the original MOV since the register
  3899. wasn't used between it and its popping from the stack }
  3900. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3901. RemoveCurrentp(p, hp1);
  3902. Result := True;
  3903. JumpTracking.Free;
  3904. Exit;
  3905. end;
  3906. { Can't go any further }
  3907. Break;
  3908. end;
  3909. A_MOV:
  3910. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3911. ((taicpu(p).oper[0]^.typ=top_const) or
  3912. ((taicpu(p).oper[0]^.typ=top_reg) and
  3913. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3914. )
  3915. ) then
  3916. begin
  3917. { we have
  3918. mov x, %treg
  3919. mov %treg, y
  3920. }
  3921. { We don't need to call UpdateUsedRegs for every instruction between
  3922. p and hp2 because the register we're concerned about will not
  3923. become deallocated (otherwise GetNextInstructionUsingReg would
  3924. have stopped at an earlier instruction). [Kit] }
  3925. TempRegUsed :=
  3926. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3927. RegReadByInstruction(p_TargetReg, hp3) or
  3928. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3929. case taicpu(p).oper[0]^.typ Of
  3930. top_reg:
  3931. begin
  3932. { change
  3933. mov %reg, %treg
  3934. mov %treg, y
  3935. to
  3936. mov %reg, y
  3937. }
  3938. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3939. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3940. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3941. begin
  3942. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3943. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3944. if TempRegUsed then
  3945. begin
  3946. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3947. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3948. { Set the start of the next GetNextInstructionUsingRegCond search
  3949. to start at the entry right before hp2 (which is about to be removed) }
  3950. hp3 := tai(hp2.Previous);
  3951. RemoveInstruction(hp2);
  3952. Include(OptsToCheck, aoc_ForceNewIteration);
  3953. { See if there's more we can optimise }
  3954. Continue;
  3955. end
  3956. else
  3957. begin
  3958. RemoveInstruction(hp2);
  3959. { We can remove the original MOV too }
  3960. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3961. RemoveCurrentP(p, hp1);
  3962. Result:=true;
  3963. JumpTracking.Free;
  3964. Exit;
  3965. end;
  3966. end
  3967. else
  3968. begin
  3969. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3970. taicpu(hp2).loadReg(0, p_SourceReg);
  3971. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3972. { Check to see if the register also appears in the reference }
  3973. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3974. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3975. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3976. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3977. begin
  3978. { Don't remove the first instruction if the temporary register is in use }
  3979. if not TempRegUsed then
  3980. begin
  3981. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3982. RemoveCurrentP(p, hp1);
  3983. Result:=true;
  3984. JumpTracking.Free;
  3985. Exit;
  3986. end;
  3987. { No need to set Result to True here. If there's another instruction later
  3988. on that can be optimised, it will be detected when the main Pass 1 loop
  3989. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3990. hp3 := hp2;
  3991. Continue;
  3992. end;
  3993. end;
  3994. end;
  3995. top_const:
  3996. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3997. begin
  3998. { change
  3999. mov const, %treg
  4000. mov %treg, y
  4001. to
  4002. mov const, y
  4003. }
  4004. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4005. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4006. begin
  4007. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4008. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4009. if TempRegUsed then
  4010. begin
  4011. { Don't remove the first instruction if the temporary register is in use }
  4012. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4013. { No need to set Result to True. If there's another instruction later on
  4014. that can be optimised, it will be detected when the main Pass 1 loop
  4015. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4016. end
  4017. else
  4018. begin
  4019. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4020. RemoveCurrentP(p, hp1);
  4021. Result:=true;
  4022. Exit;
  4023. end;
  4024. end;
  4025. end;
  4026. else
  4027. Internalerror(2019103001);
  4028. end;
  4029. end
  4030. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4031. begin
  4032. if not CrossJump and
  4033. not RegUsedBetween(p_TargetReg, p, hp2) and
  4034. not RegReadByInstruction(p_TargetReg, hp2) then
  4035. begin
  4036. { Register is not used before it is overwritten }
  4037. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4038. RemoveCurrentp(p, hp1);
  4039. Result := True;
  4040. Exit;
  4041. end;
  4042. if (taicpu(p).oper[0]^.typ = top_const) and
  4043. (taicpu(hp2).oper[0]^.typ = top_const) then
  4044. begin
  4045. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4046. begin
  4047. { Same value - register hasn't changed }
  4048. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4049. RemoveInstruction(hp2);
  4050. Include(OptsToCheck, aoc_ForceNewIteration);
  4051. { See if there's more we can optimise }
  4052. Continue;
  4053. end;
  4054. end;
  4055. {$ifdef x86_64}
  4056. end
  4057. { Change:
  4058. movl %reg1l,%reg2l
  4059. ...
  4060. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4061. To:
  4062. movl %reg1l,%reg2l
  4063. ...
  4064. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4065. If %reg1 = %reg3, convert to:
  4066. movl %reg1l,%reg2l
  4067. ...
  4068. andl %reg1l,%reg1l
  4069. }
  4070. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4071. (taicpu(p).oper[0]^.typ = top_reg) and
  4072. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4073. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4074. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4075. begin
  4076. TempRegUsed :=
  4077. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4078. RegReadByInstruction(p_TargetReg, hp3) or
  4079. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4080. taicpu(hp2).opsize := S_L;
  4081. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4082. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4083. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4084. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4085. begin
  4086. { %reg1 = %reg3 }
  4087. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4088. taicpu(hp2).opcode := A_AND;
  4089. end
  4090. else
  4091. begin
  4092. { %reg1 <> %reg3 }
  4093. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4094. end;
  4095. if not TempRegUsed then
  4096. begin
  4097. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4098. RemoveCurrentP(p, hp1);
  4099. Result := True;
  4100. Exit;
  4101. end
  4102. else
  4103. begin
  4104. { Initial instruction wasn't actually changed }
  4105. Include(OptsToCheck, aoc_ForceNewIteration);
  4106. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4107. appears below since %reg1 has technically changed }
  4108. if taicpu(hp2).opcode = A_AND then
  4109. Break;
  4110. end;
  4111. {$endif x86_64}
  4112. end
  4113. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4114. GetNextInstruction(hp2, hp4) and
  4115. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4116. { Optimise the following first:
  4117. movl [mem1],reg1
  4118. movl [mem1],reg2
  4119. to
  4120. movl [mem1],reg1
  4121. movl reg1,reg2
  4122. If [mem1] contains the target register and reg1 is the
  4123. the source register, this optimisation will get missed
  4124. and produce less efficient code later on.
  4125. }
  4126. if CheckMovMov2MovMov2(hp2, hp4) then
  4127. { Initial instruction wasn't actually changed }
  4128. Include(OptsToCheck, aoc_ForceNewIteration);
  4129. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4130. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4131. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4132. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4133. begin
  4134. {
  4135. Change from:
  4136. mov ###, %reg
  4137. ...
  4138. movs/z %reg,%reg (Same register, just different sizes)
  4139. To:
  4140. movs/z ###, %reg (Longer version)
  4141. ...
  4142. (remove)
  4143. }
  4144. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4145. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4146. { Keep the first instruction as mov if ### is a constant }
  4147. if taicpu(p).oper[0]^.typ = top_const then
  4148. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4149. else
  4150. begin
  4151. taicpu(p).opcode := taicpu(hp2).opcode;
  4152. taicpu(p).opsize := taicpu(hp2).opsize;
  4153. end;
  4154. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4155. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4156. RemoveInstruction(hp2);
  4157. Result := True;
  4158. JumpTracking.Free;
  4159. Exit;
  4160. end;
  4161. else
  4162. { Move down to the if-block below };
  4163. end;
  4164. { Also catches MOV/S/Z instructions that aren't modified }
  4165. if taicpu(p).oper[0]^.typ = top_reg then
  4166. begin
  4167. p_SourceReg := taicpu(p).oper[0]^.reg;
  4168. if
  4169. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4170. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4171. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4172. begin
  4173. Result := True;
  4174. { Just in case something didn't get modified (e.g. an
  4175. implicit register). Also, if it does read from this
  4176. register, then there's no longer an advantage to
  4177. changing the register on subsequent instructions.}
  4178. if not RegReadByInstruction(p_TargetReg, hp2) then
  4179. begin
  4180. { If a conditional jump was crossed, do not delete
  4181. the original MOV no matter what }
  4182. if not CrossJump and
  4183. { RegEndOfLife returns True if the register is
  4184. deallocated before the next instruction or has
  4185. been loaded with a new value }
  4186. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4187. begin
  4188. { We can remove the original MOV }
  4189. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4190. RemoveCurrentp(p, hp1);
  4191. JumpTracking.Free;
  4192. Result := True;
  4193. Exit;
  4194. end;
  4195. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4196. begin
  4197. { See if there's more we can optimise }
  4198. hp3 := hp2;
  4199. Continue;
  4200. end;
  4201. end;
  4202. end;
  4203. end;
  4204. { Break out of the while loop under normal circumstances }
  4205. Break;
  4206. end;
  4207. JumpTracking.Free;
  4208. end;
  4209. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4210. (taicpu(p).oper[1]^.typ = top_reg) and
  4211. (taicpu(p).opsize = S_L) and
  4212. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4213. (hp2.typ = ait_instruction) and
  4214. (taicpu(hp2).opcode = A_AND) and
  4215. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4216. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4217. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4218. ) then
  4219. begin
  4220. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4221. begin
  4222. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4223. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4224. begin
  4225. { Optimize out:
  4226. mov x, %reg
  4227. and ffffffffh, %reg
  4228. }
  4229. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4230. RemoveInstruction(hp2);
  4231. Result:=true;
  4232. exit;
  4233. end;
  4234. end;
  4235. end;
  4236. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4237. x >= RetOffset) as it doesn't do anything (it writes either to a
  4238. parameter or to the temporary storage room for the function
  4239. result)
  4240. }
  4241. if IsExitCode(hp1) and
  4242. (taicpu(p).oper[1]^.typ = top_ref) and
  4243. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4244. (
  4245. (
  4246. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4247. not (
  4248. assigned(current_procinfo.procdef.funcretsym) and
  4249. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4250. )
  4251. ) or
  4252. { Also discard writes to the stack that are below the base pointer,
  4253. as this is temporary storage rather than a function result on the
  4254. stack, say. }
  4255. (
  4256. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4257. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4258. )
  4259. ) then
  4260. begin
  4261. RemoveCurrentp(p, hp1);
  4262. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4263. RemoveLastDeallocForFuncRes(p);
  4264. Result:=true;
  4265. exit;
  4266. end;
  4267. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4268. begin
  4269. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4270. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4271. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4272. begin
  4273. { change
  4274. mov reg1, mem1
  4275. test/cmp x, mem1
  4276. to
  4277. mov reg1, mem1
  4278. test/cmp x, reg1
  4279. }
  4280. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4281. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4282. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4283. Result := True;
  4284. Exit;
  4285. end;
  4286. if DoMovCmpMemOpt(p, hp1) then
  4287. begin
  4288. Result := True;
  4289. Exit;
  4290. end;
  4291. end;
  4292. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4293. { If the flags register is in use, don't change the instruction to an
  4294. ADD otherwise this will scramble the flags. [Kit] }
  4295. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4296. begin
  4297. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4298. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4299. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4300. ) or
  4301. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4302. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4303. )
  4304. ) then
  4305. { mov reg1,ref
  4306. lea reg2,[reg1,reg2]
  4307. to
  4308. add reg2,ref}
  4309. begin
  4310. TransferUsedRegs(TmpUsedRegs);
  4311. { reg1 may not be used afterwards }
  4312. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4313. begin
  4314. Taicpu(hp1).opcode:=A_ADD;
  4315. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4316. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4317. RemoveCurrentp(p, hp1);
  4318. result:=true;
  4319. exit;
  4320. end;
  4321. end;
  4322. { If the LEA instruction can be converted into an arithmetic instruction,
  4323. it may be possible to then fold it in the next optimisation, otherwise
  4324. there's nothing more that can be optimised here. }
  4325. if not ConvertLEA(taicpu(hp1)) then
  4326. Exit;
  4327. end;
  4328. if (taicpu(p).oper[1]^.typ = top_reg) and
  4329. (hp1.typ = ait_instruction) and
  4330. GetNextInstruction(hp1, hp2) and
  4331. MatchInstruction(hp2,A_MOV,[]) and
  4332. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4333. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4334. (
  4335. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4336. {$ifdef x86_64}
  4337. or
  4338. (
  4339. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4340. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4341. )
  4342. {$endif x86_64}
  4343. ) then
  4344. begin
  4345. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4346. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4347. { change movsX/movzX reg/ref, reg2
  4348. add/sub/or/... reg3/$const, reg2
  4349. mov reg2 reg/ref
  4350. dealloc reg2
  4351. to
  4352. add/sub/or/... reg3/$const, reg/ref }
  4353. begin
  4354. TransferUsedRegs(TmpUsedRegs);
  4355. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4356. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4357. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4358. begin
  4359. { by example:
  4360. movswl %si,%eax movswl %si,%eax p
  4361. decl %eax addl %edx,%eax hp1
  4362. movw %ax,%si movw %ax,%si hp2
  4363. ->
  4364. movswl %si,%eax movswl %si,%eax p
  4365. decw %eax addw %edx,%eax hp1
  4366. movw %ax,%si movw %ax,%si hp2
  4367. }
  4368. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4369. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4370. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4371. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4372. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4373. {
  4374. ->
  4375. movswl %si,%eax movswl %si,%eax p
  4376. decw %si addw %dx,%si hp1
  4377. movw %ax,%si movw %ax,%si hp2
  4378. }
  4379. case taicpu(hp1).ops of
  4380. 1:
  4381. begin
  4382. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4383. if taicpu(hp1).oper[0]^.typ=top_reg then
  4384. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4385. end;
  4386. 2:
  4387. begin
  4388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4389. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4390. (taicpu(hp1).opcode<>A_SHL) and
  4391. (taicpu(hp1).opcode<>A_SHR) and
  4392. (taicpu(hp1).opcode<>A_SAR) then
  4393. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4394. end;
  4395. else
  4396. internalerror(2008042701);
  4397. end;
  4398. {
  4399. ->
  4400. decw %si addw %dx,%si p
  4401. }
  4402. RemoveInstruction(hp2);
  4403. RemoveCurrentP(p, hp1);
  4404. Result:=True;
  4405. Exit;
  4406. end;
  4407. end;
  4408. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4409. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4410. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4411. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4412. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4413. )
  4414. {$ifdef i386}
  4415. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4416. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4417. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4418. {$endif i386}
  4419. then
  4420. { change movsX/movzX reg/ref, reg2
  4421. add/sub/or/... regX/$const, reg2
  4422. mov reg2, reg3
  4423. dealloc reg2
  4424. to
  4425. movsX/movzX reg/ref, reg3
  4426. add/sub/or/... reg3/$const, reg3
  4427. }
  4428. begin
  4429. TransferUsedRegs(TmpUsedRegs);
  4430. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4431. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4432. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4433. begin
  4434. { by example:
  4435. movswl %si,%eax movswl %si,%eax p
  4436. decl %eax addl %edx,%eax hp1
  4437. movw %ax,%si movw %ax,%si hp2
  4438. ->
  4439. movswl %si,%eax movswl %si,%eax p
  4440. decw %eax addw %edx,%eax hp1
  4441. movw %ax,%si movw %ax,%si hp2
  4442. }
  4443. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4444. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4445. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4446. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4447. { limit size of constants as well to avoid assembler errors, but
  4448. check opsize to avoid overflow when left shifting the 1 }
  4449. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4450. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4451. {$ifdef x86_64}
  4452. { Be careful of, for example:
  4453. movl %reg1,%reg2
  4454. addl %reg3,%reg2
  4455. movq %reg2,%reg4
  4456. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4457. }
  4458. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4459. begin
  4460. taicpu(hp2).changeopsize(S_L);
  4461. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4462. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4463. end;
  4464. {$endif x86_64}
  4465. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4466. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4467. if taicpu(p).oper[0]^.typ=top_reg then
  4468. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4469. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4470. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4471. {
  4472. ->
  4473. movswl %si,%eax movswl %si,%eax p
  4474. decw %si addw %dx,%si hp1
  4475. movw %ax,%si movw %ax,%si hp2
  4476. }
  4477. case taicpu(hp1).ops of
  4478. 1:
  4479. begin
  4480. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4481. if taicpu(hp1).oper[0]^.typ=top_reg then
  4482. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4483. end;
  4484. 2:
  4485. begin
  4486. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4487. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4488. (taicpu(hp1).opcode<>A_SHL) and
  4489. (taicpu(hp1).opcode<>A_SHR) and
  4490. (taicpu(hp1).opcode<>A_SAR) then
  4491. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4492. end;
  4493. else
  4494. internalerror(2018111801);
  4495. end;
  4496. {
  4497. ->
  4498. decw %si addw %dx,%si p
  4499. }
  4500. RemoveInstruction(hp2);
  4501. end;
  4502. end;
  4503. end;
  4504. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4505. GetNextInstruction(hp1, hp2) and
  4506. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4507. MatchOperand(Taicpu(p).oper[0]^,0) and
  4508. (Taicpu(p).oper[1]^.typ = top_reg) and
  4509. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4510. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4511. { mov reg1,0
  4512. bts reg1,operand1 --> mov reg1,operand2
  4513. or reg1,operand2 bts reg1,operand1}
  4514. begin
  4515. Taicpu(hp2).opcode:=A_MOV;
  4516. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4517. asml.remove(hp1);
  4518. insertllitem(hp2,hp2.next,hp1);
  4519. RemoveCurrentp(p, hp1);
  4520. Result:=true;
  4521. exit;
  4522. end;
  4523. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4524. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4525. GetNextInstruction(hp1, hp2) and
  4526. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4527. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4528. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4529. { change
  4530. mov reg1,reg2
  4531. sub reg3,reg2
  4532. cmp reg3,reg1
  4533. into
  4534. mov reg1,reg2
  4535. sub reg3,reg2
  4536. }
  4537. begin
  4538. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4539. RemoveInstruction(hp2);
  4540. Result:=true;
  4541. exit;
  4542. end;
  4543. {
  4544. mov ref,reg0
  4545. <op> reg0,reg1
  4546. dealloc reg0
  4547. to
  4548. <op> ref,reg1
  4549. }
  4550. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4551. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4552. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4553. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4554. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4555. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4556. begin
  4557. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4558. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4559. RemoveCurrentp(p, hp1);
  4560. Result:=true;
  4561. exit;
  4562. end;
  4563. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4564. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4565. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4566. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4567. begin
  4568. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4569. {$ifdef x86_64}
  4570. { Convert:
  4571. movq x(ref),%reg64
  4572. shrq y,%reg64
  4573. To:
  4574. movl x+4(ref),%reg32
  4575. shrl y-32,%reg32 (Remove if y = 32)
  4576. }
  4577. if (taicpu(p).opsize = S_Q) and
  4578. (taicpu(hp1).opcode = A_SHR) and
  4579. (taicpu(hp1).oper[0]^.val >= 32) then
  4580. begin
  4581. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4582. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4583. { Convert to 32-bit }
  4584. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4585. taicpu(p).opsize := S_L;
  4586. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4587. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4588. if (taicpu(hp1).oper[0]^.val = 32) then
  4589. begin
  4590. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4591. RemoveInstruction(hp1);
  4592. end
  4593. else
  4594. begin
  4595. { This will potentially open up more arithmetic operations since
  4596. the peephole optimizer now has a big hint that only the lower
  4597. 32 bits are currently in use (and opcodes are smaller in size) }
  4598. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4599. taicpu(hp1).opsize := S_L;
  4600. Dec(taicpu(hp1).oper[0]^.val, 32);
  4601. DebugMsg(SPeepholeOptimization + PreMessage +
  4602. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4603. end;
  4604. Result := True;
  4605. Exit;
  4606. end;
  4607. {$endif x86_64}
  4608. { Convert:
  4609. movl x(ref),%reg
  4610. shrl $24,%reg
  4611. To:
  4612. movzbl x+3(ref),%reg
  4613. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4614. Also accept sar instead of shr, but convert to movsx instead of movzx
  4615. }
  4616. if taicpu(hp1).opcode = A_SHR then
  4617. MovUnaligned := A_MOVZX
  4618. else
  4619. MovUnaligned := A_MOVSX;
  4620. NewSize := S_NO;
  4621. NewOffset := 0;
  4622. case taicpu(p).opsize of
  4623. S_B:
  4624. { No valid combinations };
  4625. S_W:
  4626. if (taicpu(hp1).oper[0]^.val = 8) then
  4627. begin
  4628. NewSize := S_BW;
  4629. NewOffset := 1;
  4630. end;
  4631. S_L:
  4632. case taicpu(hp1).oper[0]^.val of
  4633. 16:
  4634. begin
  4635. NewSize := S_WL;
  4636. NewOffset := 2;
  4637. end;
  4638. 24:
  4639. begin
  4640. NewSize := S_BL;
  4641. NewOffset := 3;
  4642. end;
  4643. else
  4644. ;
  4645. end;
  4646. {$ifdef x86_64}
  4647. S_Q:
  4648. case taicpu(hp1).oper[0]^.val of
  4649. 32:
  4650. begin
  4651. if taicpu(hp1).opcode = A_SAR then
  4652. begin
  4653. { 32-bit to 64-bit is a distinct instruction }
  4654. MovUnaligned := A_MOVSXD;
  4655. NewSize := S_LQ;
  4656. NewOffset := 4;
  4657. end
  4658. else
  4659. { Should have been handled by MovShr2Mov above }
  4660. InternalError(2022081811);
  4661. end;
  4662. 48:
  4663. begin
  4664. NewSize := S_WQ;
  4665. NewOffset := 6;
  4666. end;
  4667. 56:
  4668. begin
  4669. NewSize := S_BQ;
  4670. NewOffset := 7;
  4671. end;
  4672. else
  4673. ;
  4674. end;
  4675. {$endif x86_64}
  4676. else
  4677. InternalError(2022081810);
  4678. end;
  4679. if (NewSize <> S_NO) and
  4680. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4681. begin
  4682. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4683. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4684. debug_op2str(MovUnaligned);
  4685. {$ifdef x86_64}
  4686. if MovUnaligned <> A_MOVSXD then
  4687. { Don't add size suffix for MOVSXD }
  4688. {$endif x86_64}
  4689. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4690. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4691. taicpu(p).opcode := MovUnaligned;
  4692. taicpu(p).opsize := NewSize;
  4693. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4694. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4695. RemoveInstruction(hp1);
  4696. Result := True;
  4697. Exit;
  4698. end;
  4699. end;
  4700. { Backward optimisation shared with OptPass2MOV }
  4701. if FuncMov2Func(p, hp1) then
  4702. begin
  4703. Result := True;
  4704. Exit;
  4705. end;
  4706. end;
  4707. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4708. var
  4709. hp1 : tai;
  4710. begin
  4711. Result:=false;
  4712. if taicpu(p).ops <> 2 then
  4713. exit;
  4714. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4715. GetNextInstruction(p,hp1) then
  4716. begin
  4717. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4718. (taicpu(hp1).ops = 2) then
  4719. begin
  4720. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4721. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4722. { movXX reg1, mem1 or movXX mem1, reg1
  4723. movXX mem2, reg2 movXX reg2, mem2}
  4724. begin
  4725. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4726. { movXX reg1, mem1 or movXX mem1, reg1
  4727. movXX mem2, reg1 movXX reg2, mem1}
  4728. begin
  4729. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4730. begin
  4731. { Removes the second statement from
  4732. movXX reg1, mem1/reg2
  4733. movXX mem1/reg2, reg1
  4734. }
  4735. if taicpu(p).oper[0]^.typ=top_reg then
  4736. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4737. { Removes the second statement from
  4738. movXX mem1/reg1, reg2
  4739. movXX reg2, mem1/reg1
  4740. }
  4741. if (taicpu(p).oper[1]^.typ=top_reg) and
  4742. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4743. begin
  4744. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4745. RemoveInstruction(hp1);
  4746. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4747. Result:=true;
  4748. exit;
  4749. end
  4750. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4751. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4752. begin
  4753. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4754. RemoveInstruction(hp1);
  4755. Result:=true;
  4756. exit;
  4757. end;
  4758. end
  4759. end;
  4760. end;
  4761. end;
  4762. end;
  4763. end;
  4764. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4765. var
  4766. hp1 : tai;
  4767. begin
  4768. result:=false;
  4769. { replace
  4770. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4771. MovX %mreg2,%mreg1
  4772. dealloc %mreg2
  4773. by
  4774. <Op>X %mreg2,%mreg1
  4775. ?
  4776. }
  4777. if GetNextInstruction(p,hp1) and
  4778. { we mix single and double opperations here because we assume that the compiler
  4779. generates vmovapd only after double operations and vmovaps only after single operations }
  4780. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4781. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4782. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4783. (taicpu(p).oper[0]^.typ=top_reg) then
  4784. begin
  4785. TransferUsedRegs(TmpUsedRegs);
  4786. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4787. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4788. begin
  4789. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4790. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4791. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4792. RemoveInstruction(hp1);
  4793. result:=true;
  4794. end;
  4795. end;
  4796. end;
  4797. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4798. var
  4799. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4800. JumpLabel, JumpLabel_dist: TAsmLabel;
  4801. FirstValue, SecondValue: TCGInt;
  4802. function OptimizeJump(var InputP: tai): Boolean;
  4803. var
  4804. TempBool: Boolean;
  4805. begin
  4806. Result := False;
  4807. TempBool := True;
  4808. if DoJumpOptimizations(InputP, TempBool) or
  4809. not TempBool then
  4810. begin
  4811. Result := True;
  4812. if Assigned(InputP) then
  4813. begin
  4814. { CollapseZeroDistJump will be set to the label or an align
  4815. before it after the jump if it optimises, whether or not
  4816. the label is live or dead }
  4817. if (InputP.typ = ait_align) or
  4818. (
  4819. (InputP.typ = ait_label) and
  4820. not (tai_label(InputP).labsym.is_used)
  4821. ) then
  4822. GetNextInstruction(InputP, InputP);
  4823. end;
  4824. Exit;
  4825. end;
  4826. end;
  4827. begin
  4828. Result := False;
  4829. if (taicpu(p).oper[0]^.typ = top_const) and
  4830. (taicpu(p).oper[0]^.val <> -1) then
  4831. begin
  4832. { Convert unsigned maximum constants to -1 to aid optimisation }
  4833. case taicpu(p).opsize of
  4834. S_B:
  4835. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4836. begin
  4837. taicpu(p).oper[0]^.val := -1;
  4838. Result := True;
  4839. Exit;
  4840. end;
  4841. S_W:
  4842. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4843. begin
  4844. taicpu(p).oper[0]^.val := -1;
  4845. Result := True;
  4846. Exit;
  4847. end;
  4848. S_L:
  4849. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4850. begin
  4851. taicpu(p).oper[0]^.val := -1;
  4852. Result := True;
  4853. Exit;
  4854. end;
  4855. {$ifdef x86_64}
  4856. S_Q:
  4857. { Storing anything greater than $7FFFFFFF is not possible so do
  4858. nothing };
  4859. {$endif x86_64}
  4860. else
  4861. InternalError(2021121001);
  4862. end;
  4863. end;
  4864. if GetNextInstruction(p, hp1) and
  4865. TrySwapMovCmp(p, hp1) then
  4866. begin
  4867. Result := True;
  4868. Exit;
  4869. end;
  4870. p_label := nil;
  4871. JumpLabel := nil;
  4872. if MatchInstruction(hp1, A_Jcc, []) then
  4873. begin
  4874. if OptimizeJump(hp1) then
  4875. begin
  4876. Result := True;
  4877. if Assigned(hp1) then
  4878. begin
  4879. { CollapseZeroDistJump will be set to the label or an align
  4880. before it after the jump if it optimises, whether or not
  4881. the label is live or dead }
  4882. if (hp1.typ = ait_align) or
  4883. (
  4884. (hp1.typ = ait_label) and
  4885. not (tai_label(hp1).labsym.is_used)
  4886. ) then
  4887. GetNextInstruction(hp1, hp1);
  4888. end;
  4889. TransferUsedRegs(TmpUsedRegs);
  4890. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4891. if not Assigned(hp1) or
  4892. (
  4893. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4894. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4895. ) then
  4896. begin
  4897. { No more conditional jumps; conditional statement is no longer required }
  4898. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4899. RemoveCurrentP(p);
  4900. end;
  4901. Exit;
  4902. end;
  4903. if IsJumpToLabel(taicpu(hp1)) then
  4904. begin
  4905. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4906. if Assigned(JumpLabel) then
  4907. p_label := getlabelwithsym(JumpLabel);
  4908. end;
  4909. end;
  4910. { Search for:
  4911. test $x,(reg/ref)
  4912. jne @lbl1
  4913. test $y,(reg/ref) (same register or reference)
  4914. jne @lbl1
  4915. Change to:
  4916. test $(x or y),(reg/ref)
  4917. jne @lbl1
  4918. (Note, this doesn't work with je instead of jne)
  4919. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4920. Also search for:
  4921. test $x,(reg/ref)
  4922. je @lbl1
  4923. ...
  4924. test $y,(reg/ref)
  4925. je/jne @lbl2
  4926. If (x or y) = x, then the second jump is deterministic
  4927. }
  4928. if (
  4929. (
  4930. (taicpu(p).oper[0]^.typ = top_const) or
  4931. (
  4932. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4933. (taicpu(p).oper[0]^.typ = top_reg) and
  4934. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4935. )
  4936. ) and
  4937. MatchInstruction(hp1, A_JCC, [])
  4938. ) then
  4939. begin
  4940. if (taicpu(p).oper[0]^.typ = top_reg) and
  4941. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4942. FirstValue := -1
  4943. else
  4944. FirstValue := taicpu(p).oper[0]^.val;
  4945. { If we have several test/jne's in a row, it might be the case that
  4946. the second label doesn't go to the same location, but the one
  4947. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4948. so accommodate for this with a while loop.
  4949. }
  4950. hp1_last := hp1;
  4951. while (
  4952. (
  4953. (taicpu(p).oper[1]^.typ = top_reg) and
  4954. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4955. ) or GetNextInstruction(hp1_last, p_dist)
  4956. ) and (p_dist.typ = ait_instruction) do
  4957. begin
  4958. if (
  4959. (
  4960. (taicpu(p_dist).opcode = A_TEST) and
  4961. (
  4962. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4963. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4964. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4965. )
  4966. ) or
  4967. (
  4968. { cmp 0,%reg = test %reg,%reg }
  4969. (taicpu(p_dist).opcode = A_CMP) and
  4970. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4971. )
  4972. ) and
  4973. { Make sure the destination operands are actually the same }
  4974. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4975. GetNextInstruction(p_dist, hp1_dist) and
  4976. MatchInstruction(hp1_dist, A_JCC, []) then
  4977. begin
  4978. if OptimizeJump(hp1_dist) then
  4979. begin
  4980. Result := True;
  4981. Exit;
  4982. end;
  4983. if
  4984. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4985. (
  4986. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4987. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4988. ) then
  4989. SecondValue := -1
  4990. else
  4991. SecondValue := taicpu(p_dist).oper[0]^.val;
  4992. { If both of the TEST constants are identical, delete the
  4993. second TEST that is unnecessary (be careful though, just
  4994. in case the flags are modified in between) }
  4995. if (FirstValue = SecondValue) then
  4996. begin
  4997. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4998. begin
  4999. { Since the second jump's condition is a subset of the first, we
  5000. know it will never branch because the first jump dominates it.
  5001. Get it out of the way now rather than wait for the jump
  5002. optimisations for a speed boost. }
  5003. if IsJumpToLabel(taicpu(hp1_dist)) then
  5004. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5005. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5006. RemoveInstruction(hp1_dist);
  5007. Result := True;
  5008. end
  5009. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5010. begin
  5011. { If the inverse of the first condition is a subset of the second,
  5012. the second one will definitely branch if the first one doesn't }
  5013. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5014. { We can remove the TEST instruction too }
  5015. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5016. RemoveInstruction(p_dist);
  5017. MakeUnconditional(taicpu(hp1_dist));
  5018. RemoveDeadCodeAfterJump(hp1_dist);
  5019. { Since the jump is now unconditional, we can't
  5020. continue any further with this particular
  5021. optimisation. The original TEST is still intact
  5022. though, so there might be something else we can
  5023. do }
  5024. Include(OptsToCheck, aoc_ForceNewIteration);
  5025. Break;
  5026. end;
  5027. if Result or
  5028. { If a jump wasn't removed or made unconditional, only
  5029. remove the identical TEST instruction if the flags
  5030. weren't modified }
  5031. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5032. begin
  5033. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5034. RemoveInstruction(p_dist);
  5035. { If the jump was removed or made unconditional, we
  5036. don't need to allocate NR_DEFAULTFLAGS over the
  5037. entire range }
  5038. if not Result then
  5039. begin
  5040. { Mark the flags as 'in use' over the entire range }
  5041. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5042. { Speed gain - continue search from the Jcc instruction }
  5043. hp1_last := hp1_dist;
  5044. { Only the TEST instruction was removed, and the
  5045. original was unchanged, so we can safely do
  5046. another iteration of the while loop }
  5047. Include(OptsToCheck, aoc_ForceNewIteration);
  5048. Continue;
  5049. end;
  5050. Exit;
  5051. end;
  5052. end;
  5053. hp1_last := nil;
  5054. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5055. (
  5056. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5057. { Always adjacent under -O2 and under }
  5058. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5059. (
  5060. GetNextInstruction(hp1, hp1_last) and
  5061. (hp1_last = p_dist)
  5062. )
  5063. ) and
  5064. (
  5065. (
  5066. { Test the following variant:
  5067. test $x,(reg/ref)
  5068. jne @lbl1
  5069. test $y,(reg/ref)
  5070. je @lbl2
  5071. @lbl1:
  5072. Becomes:
  5073. test $(x or y),(reg/ref)
  5074. je @lbl2
  5075. @lbl1: (may become a dead label)
  5076. }
  5077. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5078. GetNextInstruction(hp1_dist, hp1_last) and
  5079. (hp1_last = p_label)
  5080. ) or
  5081. (
  5082. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5083. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5084. then the second jump will never branch, so it can also be
  5085. removed regardless of where it goes }
  5086. (
  5087. (FirstValue = -1) or
  5088. (SecondValue = -1) or
  5089. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5090. )
  5091. )
  5092. ) then
  5093. begin
  5094. { Same jump location... can be a register since nothing's changed }
  5095. { If any of the entries are equivalent to test %reg,%reg, then the
  5096. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5097. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5098. if (hp1_last = p_label) then
  5099. begin
  5100. { Variant }
  5101. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5102. RemoveInstruction(p_dist);
  5103. if Assigned(JumpLabel) then
  5104. JumpLabel.decrefs;
  5105. RemoveInstruction(hp1);
  5106. end
  5107. else
  5108. begin
  5109. { Only remove the second test if no jumps or other conditional instructions follow }
  5110. TransferUsedRegs(TmpUsedRegs);
  5111. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5113. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5114. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5115. begin
  5116. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5117. RemoveInstruction(p_dist);
  5118. { Remove the first jump, not the second, to keep
  5119. any register deallocations between the second
  5120. TEST/JNE pair in the same place. Aids future
  5121. optimisation. }
  5122. if Assigned(JumpLabel) then
  5123. JumpLabel.decrefs;
  5124. RemoveInstruction(hp1);
  5125. end
  5126. else
  5127. begin
  5128. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5129. if IsJumpToLabel(taicpu(hp1_dist)) then
  5130. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5131. { Remove second jump in this instance }
  5132. RemoveInstruction(hp1_dist);
  5133. end;
  5134. end;
  5135. Result := True;
  5136. Exit;
  5137. end;
  5138. end;
  5139. if { If -O2 and under, it may stop on any old instruction }
  5140. (cs_opt_level3 in current_settings.optimizerswitches) and
  5141. (taicpu(p).oper[1]^.typ = top_reg) and
  5142. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5143. begin
  5144. hp1_last := p_dist;
  5145. Continue;
  5146. end;
  5147. Break;
  5148. end;
  5149. end;
  5150. { Search for:
  5151. test %reg,%reg
  5152. j(c1) @lbl1
  5153. ...
  5154. @lbl:
  5155. test %reg,%reg (same register)
  5156. j(c2) @lbl2
  5157. If c2 is a subset of c1, change to:
  5158. test %reg,%reg
  5159. j(c1) @lbl2
  5160. (@lbl1 may become a dead label as a result)
  5161. }
  5162. if (taicpu(p).oper[1]^.typ = top_reg) and
  5163. (taicpu(p).oper[0]^.typ = top_reg) and
  5164. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5165. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5166. Assigned(p_label) and
  5167. GetNextInstruction(p_label, p_dist) and
  5168. MatchInstruction(p_dist, A_TEST, []) and
  5169. { It's fine if the second test uses smaller sub-registers }
  5170. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5171. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5172. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5173. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5174. GetNextInstruction(p_dist, hp1_dist) and
  5175. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5176. begin
  5177. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5178. if JumpLabel = JumpLabel_dist then
  5179. { This is an infinite loop }
  5180. Exit;
  5181. { Best optimisation when the first condition is a subset (or equal) of the second }
  5182. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5183. begin
  5184. { Any registers used here will already be allocated }
  5185. if Assigned(JumpLabel) then
  5186. JumpLabel.DecRefs;
  5187. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5188. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5189. Result := True;
  5190. Exit;
  5191. end;
  5192. end;
  5193. end;
  5194. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5195. var
  5196. hp1, hp2: tai;
  5197. ActiveReg: TRegister;
  5198. OldOffset: asizeint;
  5199. ThisConst: TCGInt;
  5200. function RegDeallocated: Boolean;
  5201. begin
  5202. TransferUsedRegs(TmpUsedRegs);
  5203. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5204. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5205. end;
  5206. begin
  5207. result:=false;
  5208. hp1 := nil;
  5209. { replace
  5210. addX const,%reg1
  5211. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5212. dealloc %reg1
  5213. by
  5214. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5215. }
  5216. if MatchOpType(taicpu(p),top_const,top_reg) then
  5217. begin
  5218. ActiveReg := taicpu(p).oper[1]^.reg;
  5219. { Ensures the entire register was updated }
  5220. if (taicpu(p).opsize >= S_L) and
  5221. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5222. MatchInstruction(hp1,A_LEA,[]) and
  5223. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5224. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5225. (
  5226. { Cover the case where the register in the reference is also the destination register }
  5227. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5228. (
  5229. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5230. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5231. RegDeallocated
  5232. )
  5233. ) then
  5234. begin
  5235. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5236. {$push}
  5237. {$R-}{$Q-}
  5238. { Explicitly disable overflow checking for these offset calculation
  5239. as those do not matter for the final result }
  5240. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5241. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5242. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5243. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5244. {$pop}
  5245. {$ifdef x86_64}
  5246. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5247. begin
  5248. { Overflow; abort }
  5249. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5250. end
  5251. else
  5252. {$endif x86_64}
  5253. begin
  5254. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5255. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5256. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5257. RemoveCurrentP(p, hp1)
  5258. else
  5259. RemoveCurrentP(p);
  5260. result:=true;
  5261. Exit;
  5262. end;
  5263. end;
  5264. if (
  5265. { Save calling GetNextInstructionUsingReg again }
  5266. Assigned(hp1) or
  5267. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5268. ) and
  5269. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5270. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5271. begin
  5272. if taicpu(hp1).oper[0]^.typ = top_const then
  5273. begin
  5274. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5275. if taicpu(hp1).opcode = A_ADD then
  5276. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5277. else
  5278. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5279. Result := True;
  5280. { Handle any overflows }
  5281. case taicpu(p).opsize of
  5282. S_B:
  5283. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5284. S_W:
  5285. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5286. S_L:
  5287. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5288. {$ifdef x86_64}
  5289. S_Q:
  5290. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5291. { Overflow; abort }
  5292. Result := False
  5293. else
  5294. taicpu(p).oper[0]^.val := ThisConst;
  5295. {$endif x86_64}
  5296. else
  5297. InternalError(2021102610);
  5298. end;
  5299. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5300. if Result then
  5301. begin
  5302. if (taicpu(p).oper[0]^.val < 0) and
  5303. (
  5304. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5305. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5306. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5307. ) then
  5308. begin
  5309. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5310. taicpu(p).opcode := A_SUB;
  5311. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5312. end
  5313. else
  5314. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5315. RemoveInstruction(hp1);
  5316. end;
  5317. end
  5318. else
  5319. begin
  5320. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5321. TransferUsedRegs(TmpUsedRegs);
  5322. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5323. hp2 := p;
  5324. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5325. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5326. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5327. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5328. begin
  5329. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5330. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5331. Asml.Remove(p);
  5332. Asml.InsertAfter(p, hp1);
  5333. p := hp1;
  5334. Result := True;
  5335. Exit;
  5336. end;
  5337. end;
  5338. end;
  5339. if DoArithCombineOpt(p) then
  5340. Result:=true;
  5341. end;
  5342. end;
  5343. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5344. var
  5345. hp1, hp2: tai;
  5346. ref: Integer;
  5347. saveref: treference;
  5348. offsetcalc: Int64;
  5349. TempReg: TRegister;
  5350. Multiple: TCGInt;
  5351. Adjacent, IntermediateRegDiscarded: Boolean;
  5352. begin
  5353. Result:=false;
  5354. { play save and throw an error if LEA uses a seg register prefix,
  5355. this is most likely an error somewhere else }
  5356. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5357. internalerror(2022022001);
  5358. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5359. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5360. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5361. (
  5362. { do not mess with leas accessing the stack pointer
  5363. unless it's a null operation }
  5364. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5365. (
  5366. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5367. (taicpu(p).oper[0]^.ref^.offset = 0)
  5368. )
  5369. ) and
  5370. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5371. begin
  5372. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5373. begin
  5374. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5375. begin
  5376. taicpu(p).opcode := A_MOV;
  5377. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5378. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5379. end
  5380. else
  5381. begin
  5382. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5383. RemoveCurrentP(p);
  5384. end;
  5385. Result:=true;
  5386. exit;
  5387. end
  5388. else if (
  5389. { continue to use lea to adjust the stack pointer,
  5390. it is the recommended way, but only if not optimizing for size }
  5391. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5392. (cs_opt_size in current_settings.optimizerswitches)
  5393. ) and
  5394. { If the flags register is in use, don't change the instruction
  5395. to an ADD otherwise this will scramble the flags. [Kit] }
  5396. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5397. ConvertLEA(taicpu(p)) then
  5398. begin
  5399. Result:=true;
  5400. exit;
  5401. end;
  5402. end;
  5403. { Don't optimise if the stack or frame pointer is the destination register }
  5404. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5405. Exit;
  5406. if GetNextInstruction(p,hp1) and
  5407. (hp1.typ=ait_instruction) then
  5408. begin
  5409. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5410. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5411. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5412. begin
  5413. TransferUsedRegs(TmpUsedRegs);
  5414. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5415. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5416. begin
  5417. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5418. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5419. RemoveInstruction(hp1);
  5420. result:=true;
  5421. exit;
  5422. end;
  5423. end;
  5424. { changes
  5425. lea <ref1>, reg1
  5426. <op> ...,<ref. with reg1>,...
  5427. to
  5428. <op> ...,<ref1>,... }
  5429. { find a reference which uses reg1 }
  5430. 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
  5431. ref:=0
  5432. 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
  5433. ref:=1
  5434. else
  5435. ref:=-1;
  5436. if (ref<>-1) and
  5437. { reg1 must be either the base or the index }
  5438. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5439. begin
  5440. { reg1 can be removed from the reference }
  5441. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5442. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5443. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5444. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5445. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5446. else
  5447. Internalerror(2019111201);
  5448. { check if the can insert all data of the lea into the second instruction }
  5449. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5450. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5451. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5452. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5453. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5454. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5455. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5456. {$ifdef x86_64}
  5457. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5458. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5459. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5460. )
  5461. {$endif x86_64}
  5462. then
  5463. begin
  5464. { reg1 might not used by the second instruction after it is remove from the reference }
  5465. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5466. begin
  5467. TransferUsedRegs(TmpUsedRegs);
  5468. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5469. { reg1 is not updated so it might not be used afterwards }
  5470. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5471. begin
  5472. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5473. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5474. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5475. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5476. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5477. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5478. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5479. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5480. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5481. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5482. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5483. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5484. RemoveCurrentP(p, hp1);
  5485. result:=true;
  5486. exit;
  5487. end
  5488. end;
  5489. end;
  5490. { recover }
  5491. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5492. end;
  5493. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5494. if Adjacent or
  5495. { Check further ahead (up to 2 instructions ahead for -O2) }
  5496. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5497. begin
  5498. { Check common LEA/LEA conditions }
  5499. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5500. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5501. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5502. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5503. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5504. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5505. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5506. (
  5507. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5508. calling it (since it calls GetNextInstruction) }
  5509. Adjacent or
  5510. (
  5511. (
  5512. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5513. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5514. ) and (
  5515. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5516. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5517. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5518. )
  5519. )
  5520. ) then
  5521. begin
  5522. TransferUsedRegs(TmpUsedRegs);
  5523. hp2 := p;
  5524. repeat
  5525. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5526. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5527. IntermediateRegDiscarded :=
  5528. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5529. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5530. { changes
  5531. lea offset1(regX,scale), reg1
  5532. lea offset2(reg1,reg1), reg2
  5533. to
  5534. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5535. and
  5536. lea offset1(regX,scale1), reg1
  5537. lea offset2(reg1,scale2), reg2
  5538. to
  5539. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5540. and
  5541. lea offset1(regX,scale1), reg1
  5542. lea offset2(reg3,reg1,scale2), reg2
  5543. to
  5544. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5545. ... so long as the final scale does not exceed 8
  5546. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5547. }
  5548. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5549. (
  5550. { Don't optimise if size is a concern and the intermediate register remains in use }
  5551. IntermediateRegDiscarded or
  5552. not (cs_opt_size in current_settings.optimizerswitches)
  5553. ) and
  5554. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5555. (
  5556. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5557. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5558. ) and (
  5559. (
  5560. { lea (reg1,scale2), reg2 variant }
  5561. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5562. (
  5563. Adjacent or
  5564. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5565. ) and
  5566. (
  5567. (
  5568. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5569. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5570. ) or (
  5571. { lea (regX,regX), reg1 variant }
  5572. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5573. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5574. )
  5575. )
  5576. ) or (
  5577. { lea (reg1,reg1), reg1 variant }
  5578. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5579. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5580. )
  5581. ) then
  5582. begin
  5583. { Make everything homogeneous to make calculations easier }
  5584. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5585. begin
  5586. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5587. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5588. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5589. else
  5590. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5591. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5592. end;
  5593. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5594. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5595. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5596. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5597. begin
  5598. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5599. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5600. begin
  5601. { Put the register to change in the index register }
  5602. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5603. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5604. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5605. end;
  5606. { Change lea (reg,reg) to lea(,reg,2) }
  5607. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5608. begin
  5609. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5610. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5611. end;
  5612. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5613. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5614. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5615. { Just to prevent miscalculations }
  5616. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5617. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5618. else
  5619. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5620. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5621. if IntermediateRegDiscarded then
  5622. begin
  5623. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5624. RemoveCurrentP(p);
  5625. end
  5626. else
  5627. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5628. result:=true;
  5629. exit;
  5630. end;
  5631. end;
  5632. { changes
  5633. lea offset1(regX), reg1
  5634. lea offset2(reg1), reg2
  5635. to
  5636. lea offset1+offset2(regX), reg2 }
  5637. if (
  5638. { Don't optimise if size is a concern and the intermediate register remains in use }
  5639. IntermediateRegDiscarded or
  5640. not (cs_opt_size in current_settings.optimizerswitches)
  5641. ) and
  5642. (
  5643. (
  5644. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5645. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5646. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5647. ) or (
  5648. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5649. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5650. (
  5651. (
  5652. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5653. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5654. ) or (
  5655. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5656. (
  5657. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5658. (
  5659. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5660. (
  5661. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5662. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5663. )
  5664. )
  5665. )
  5666. )
  5667. )
  5668. )
  5669. ) then
  5670. begin
  5671. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5672. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5673. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5674. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5675. begin
  5676. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5677. begin
  5678. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5679. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5680. { if the register is used as index and base, we have to increase for base as well
  5681. and adapt base }
  5682. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5683. begin
  5684. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5685. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5686. end;
  5687. end
  5688. else
  5689. begin
  5690. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5691. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5692. end;
  5693. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5694. begin
  5695. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5696. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5697. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5698. end;
  5699. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5700. if IntermediateRegDiscarded then
  5701. begin
  5702. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5703. RemoveCurrentP(p);
  5704. end
  5705. else
  5706. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5707. result:=true;
  5708. exit;
  5709. end;
  5710. end;
  5711. end;
  5712. { Change:
  5713. leal/q $x(%reg1),%reg2
  5714. ...
  5715. shll/q $y,%reg2
  5716. To:
  5717. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5718. }
  5719. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5720. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5721. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5722. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5723. (taicpu(hp1).oper[0]^.val <= 3) then
  5724. begin
  5725. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5726. TransferUsedRegs(TmpUsedRegs);
  5727. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5728. if
  5729. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5730. (this works even if scalefactor is zero) }
  5731. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5732. { Ensure offset doesn't go out of bounds }
  5733. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5734. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5735. (
  5736. (
  5737. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5738. (
  5739. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5740. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5741. (
  5742. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5743. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5744. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5745. )
  5746. )
  5747. ) or (
  5748. (
  5749. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5750. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5751. ) and
  5752. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5753. )
  5754. ) then
  5755. begin
  5756. repeat
  5757. with taicpu(p).oper[0]^.ref^ do
  5758. begin
  5759. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5760. if index = base then
  5761. begin
  5762. if Multiple > 4 then
  5763. { Optimisation will no longer work because resultant
  5764. scale factor will exceed 8 }
  5765. Break;
  5766. base := NR_NO;
  5767. scalefactor := 2;
  5768. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5769. end
  5770. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5771. begin
  5772. { Scale factor only works on the index register }
  5773. index := base;
  5774. base := NR_NO;
  5775. end;
  5776. { For safety }
  5777. if scalefactor <= 1 then
  5778. begin
  5779. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5780. scalefactor := Multiple;
  5781. end
  5782. else
  5783. begin
  5784. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5785. scalefactor := scalefactor * Multiple;
  5786. end;
  5787. offset := offset * Multiple;
  5788. end;
  5789. RemoveInstruction(hp1);
  5790. Result := True;
  5791. Exit;
  5792. { This repeat..until loop exists for the benefit of Break }
  5793. until True;
  5794. end;
  5795. end;
  5796. end;
  5797. end;
  5798. end;
  5799. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5800. var
  5801. hp1 : tai;
  5802. SubInstr: Boolean;
  5803. ThisConst: TCGInt;
  5804. const
  5805. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5806. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5807. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5808. begin
  5809. Result := False;
  5810. if taicpu(p).oper[0]^.typ <> top_const then
  5811. { Should have been confirmed before calling }
  5812. InternalError(2021102601);
  5813. SubInstr := (taicpu(p).opcode = A_SUB);
  5814. if GetLastInstruction(p, hp1) and
  5815. (hp1.typ = ait_instruction) and
  5816. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5817. begin
  5818. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5819. { Bad size }
  5820. InternalError(2022042001);
  5821. case taicpu(hp1).opcode Of
  5822. A_INC:
  5823. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5824. begin
  5825. if SubInstr then
  5826. ThisConst := taicpu(p).oper[0]^.val - 1
  5827. else
  5828. ThisConst := taicpu(p).oper[0]^.val + 1;
  5829. end
  5830. else
  5831. Exit;
  5832. A_DEC:
  5833. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5834. begin
  5835. if SubInstr then
  5836. ThisConst := taicpu(p).oper[0]^.val + 1
  5837. else
  5838. ThisConst := taicpu(p).oper[0]^.val - 1;
  5839. end
  5840. else
  5841. Exit;
  5842. A_SUB:
  5843. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5844. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5845. begin
  5846. if SubInstr then
  5847. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5848. else
  5849. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5850. end
  5851. else
  5852. Exit;
  5853. A_ADD:
  5854. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5855. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5856. begin
  5857. if SubInstr then
  5858. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5859. else
  5860. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5861. end
  5862. else
  5863. Exit;
  5864. else
  5865. Exit;
  5866. end;
  5867. { Check that the values are in range }
  5868. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5869. { Overflow; abort }
  5870. Exit;
  5871. if (ThisConst = 0) then
  5872. begin
  5873. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5874. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5875. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5876. RemoveInstruction(hp1);
  5877. hp1 := tai(p.next);
  5878. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5879. if not GetLastInstruction(hp1, p) then
  5880. p := hp1;
  5881. end
  5882. else
  5883. begin
  5884. if taicpu(hp1).opercnt=1 then
  5885. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5886. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5887. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5888. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5889. else
  5890. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5891. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5892. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5893. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5894. RemoveInstruction(hp1);
  5895. taicpu(p).loadconst(0, ThisConst);
  5896. end;
  5897. Result := True;
  5898. end;
  5899. end;
  5900. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5901. begin
  5902. Result := False;
  5903. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5904. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5905. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5906. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5907. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5908. (
  5909. (
  5910. (taicpu(hp1).opcode = A_TEST)
  5911. ) or (
  5912. (taicpu(hp1).opcode = A_CMP) and
  5913. { A sanity check more than anything }
  5914. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5915. )
  5916. ) then
  5917. begin
  5918. { change
  5919. mov mem, %reg
  5920. ...
  5921. cmp/test x, %reg / test %reg,%reg
  5922. (reg deallocated)
  5923. to
  5924. cmp/test x, mem / cmp 0, mem
  5925. }
  5926. TransferUsedRegs(TmpUsedRegs);
  5927. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5928. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5929. begin
  5930. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5931. if (taicpu(hp1).opcode = A_TEST) and
  5932. (
  5933. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5934. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5935. ) then
  5936. begin
  5937. taicpu(hp1).opcode := A_CMP;
  5938. taicpu(hp1).loadconst(0, 0);
  5939. end;
  5940. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5941. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5942. RemoveCurrentP(p);
  5943. if (p <> hp1) then
  5944. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5945. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5946. { Make sure the flags are allocated across the CMP instruction }
  5947. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5948. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5949. Result := True;
  5950. Exit;
  5951. end;
  5952. end;
  5953. end;
  5954. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5955. var
  5956. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5957. ThisReg, SecondReg: TRegister;
  5958. JumpLoc: TAsmLabel;
  5959. NewSize: TOpSize;
  5960. begin
  5961. Result := False;
  5962. {
  5963. Convert:
  5964. j<c> .L1
  5965. .L2:
  5966. mov 1,reg
  5967. jmp .L3 (or ret, although it might not be a RET yet)
  5968. .L1:
  5969. mov 0,reg
  5970. jmp .L3 (or ret)
  5971. ( As long as .L3 <> .L1 or .L2)
  5972. To:
  5973. mov 0,reg
  5974. set<not(c)> reg
  5975. jmp .L3 (or ret)
  5976. .L2:
  5977. mov 1,reg
  5978. jmp .L3 (or ret)
  5979. .L1:
  5980. mov 0,reg
  5981. jmp .L3 (or ret)
  5982. }
  5983. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5984. Exit;
  5985. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5986. if GetNextInstruction(hp_label, hp2) and
  5987. MatchInstruction(hp2,A_MOV,[]) and
  5988. (taicpu(hp2).oper[0]^.typ = top_const) and
  5989. (
  5990. (
  5991. (taicpu(hp2).oper[1]^.typ = top_reg)
  5992. {$ifdef i386}
  5993. { Under i386, ESI, EDI, EBP and ESP
  5994. don't have an 8-bit representation }
  5995. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5996. {$endif i386}
  5997. ) or (
  5998. {$ifdef i386}
  5999. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6000. {$endif i386}
  6001. (taicpu(hp2).opsize = S_B)
  6002. )
  6003. ) and
  6004. GetNextInstruction(hp2, hp3) and
  6005. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6006. (
  6007. (taicpu(hp3).opcode=A_RET) or
  6008. (
  6009. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6010. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6011. )
  6012. ) and
  6013. GetNextInstruction(hp3, hp4) and
  6014. (hp4.typ=ait_label) and
  6015. (tai_label(hp4).labsym=JumpLoc) and
  6016. (
  6017. not (cs_opt_size in current_settings.optimizerswitches) or
  6018. { If the initial jump is the label's only reference, then it will
  6019. become a dead label if the other conditions are met and hence
  6020. remove at least 2 instructions, including a jump }
  6021. (JumpLoc.getrefs = 1)
  6022. ) and
  6023. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6024. that will be optimised out }
  6025. GetNextInstruction(hp4, hp5) and
  6026. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6027. (taicpu(hp5).oper[0]^.typ = top_const) and
  6028. (
  6029. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6030. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6031. ) and
  6032. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6033. GetNextInstruction(hp5,hp6) and
  6034. (
  6035. (hp6.typ<>ait_label) or
  6036. SkipLabels(hp6, hp6)
  6037. ) and
  6038. (hp6.typ=ait_instruction) then
  6039. begin
  6040. { First, let's look at the two jumps that are hp3 and hp6 }
  6041. if not
  6042. (
  6043. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6044. (
  6045. (taicpu(hp6).opcode=A_RET) or
  6046. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6047. )
  6048. ) then
  6049. { If condition is False, then the JMP/RET instructions matched conventionally }
  6050. begin
  6051. { See if one of the jumps can be instantly converted into a RET }
  6052. if (taicpu(hp3).opcode=A_JMP) then
  6053. begin
  6054. { Reuse hp5 }
  6055. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6056. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6057. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6058. Exit;
  6059. if MatchInstruction(hp5, A_RET, []) then
  6060. begin
  6061. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6062. ConvertJumpToRET(hp3, hp5);
  6063. Result := True;
  6064. end
  6065. else
  6066. Exit;
  6067. end;
  6068. if (taicpu(hp6).opcode=A_JMP) then
  6069. begin
  6070. { Reuse hp5 }
  6071. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6072. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6073. Exit;
  6074. if MatchInstruction(hp5, A_RET, []) then
  6075. begin
  6076. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6077. ConvertJumpToRET(hp6, hp5);
  6078. Result := True;
  6079. end
  6080. else
  6081. Exit;
  6082. end;
  6083. if not
  6084. (
  6085. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6086. (
  6087. (taicpu(hp6).opcode=A_RET) or
  6088. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6089. )
  6090. ) then
  6091. { Still doesn't match }
  6092. Exit;
  6093. end;
  6094. if (taicpu(hp2).oper[0]^.val = 1) then
  6095. begin
  6096. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6097. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6098. end
  6099. else
  6100. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6101. if taicpu(hp2).opsize=S_B then
  6102. begin
  6103. if taicpu(hp2).oper[1]^.typ = top_reg then
  6104. begin
  6105. SecondReg := taicpu(hp2).oper[1]^.reg;
  6106. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6107. end
  6108. else
  6109. begin
  6110. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6111. SecondReg := NR_NO;
  6112. end;
  6113. hp_pos := p;
  6114. hp_allocstart := hp4;
  6115. end
  6116. else
  6117. begin
  6118. { Will be a register because the size can't be S_B otherwise }
  6119. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6120. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6121. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6122. if (cs_opt_size in current_settings.optimizerswitches) then
  6123. begin
  6124. { Favour using MOVZX when optimising for size }
  6125. case taicpu(hp2).opsize of
  6126. S_W:
  6127. NewSize := S_BW;
  6128. S_L:
  6129. NewSize := S_BL;
  6130. {$ifdef x86_64}
  6131. S_Q:
  6132. begin
  6133. NewSize := S_BL;
  6134. { Will implicitly zero-extend to 64-bit }
  6135. setsubreg(SecondReg, R_SUBD);
  6136. end;
  6137. {$endif x86_64}
  6138. else
  6139. InternalError(2022101301);
  6140. end;
  6141. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6142. { Inserting it right before p will guarantee that the flags are also tracked }
  6143. Asml.InsertBefore(hp5, p);
  6144. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6145. hp_pos := hp5;
  6146. hp_allocstart := hp4;
  6147. end
  6148. else
  6149. begin
  6150. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6151. { Inserting it right before p will guarantee that the flags are also tracked }
  6152. Asml.InsertBefore(hp5, p);
  6153. hp_pos := p;
  6154. hp_allocstart := hp5;
  6155. end;
  6156. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6157. end;
  6158. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6159. taicpu(hp4).condition := taicpu(p).condition;
  6160. asml.InsertBefore(hp4, hp_pos);
  6161. if taicpu(hp3).is_jmp then
  6162. begin
  6163. JumpLoc.decrefs;
  6164. MakeUnconditional(taicpu(p));
  6165. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6166. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6167. end
  6168. else
  6169. ConvertJumpToRET(p, hp3);
  6170. if SecondReg <> NR_NO then
  6171. { Ensure the destination register is allocated over this region }
  6172. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6173. if (JumpLoc.getrefs = 0) then
  6174. RemoveDeadCodeAfterJump(hp3);
  6175. Result:=true;
  6176. exit;
  6177. end;
  6178. end;
  6179. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6180. var
  6181. hp1, hp2: tai;
  6182. ActiveReg: TRegister;
  6183. OldOffset: asizeint;
  6184. ThisConst: TCGInt;
  6185. function RegDeallocated: Boolean;
  6186. begin
  6187. TransferUsedRegs(TmpUsedRegs);
  6188. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6189. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6190. end;
  6191. begin
  6192. Result:=false;
  6193. hp1 := nil;
  6194. { replace
  6195. subX const,%reg1
  6196. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6197. dealloc %reg1
  6198. by
  6199. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6200. }
  6201. if MatchOpType(taicpu(p),top_const,top_reg) then
  6202. begin
  6203. ActiveReg := taicpu(p).oper[1]^.reg;
  6204. { Ensures the entire register was updated }
  6205. if (taicpu(p).opsize >= S_L) and
  6206. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6207. MatchInstruction(hp1,A_LEA,[]) and
  6208. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6209. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6210. (
  6211. { Cover the case where the register in the reference is also the destination register }
  6212. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6213. (
  6214. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6215. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6216. RegDeallocated
  6217. )
  6218. ) then
  6219. begin
  6220. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6221. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6222. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6223. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6224. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6225. {$ifdef x86_64}
  6226. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6227. begin
  6228. { Overflow; abort }
  6229. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6230. end
  6231. else
  6232. {$endif x86_64}
  6233. begin
  6234. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6235. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6236. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6237. RemoveCurrentP(p, hp1)
  6238. else
  6239. RemoveCurrentP(p);
  6240. result:=true;
  6241. Exit;
  6242. end;
  6243. end;
  6244. if (
  6245. { Save calling GetNextInstructionUsingReg again }
  6246. Assigned(hp1) or
  6247. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6248. ) and
  6249. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6250. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6251. begin
  6252. if taicpu(hp1).oper[0]^.typ = top_const then
  6253. begin
  6254. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6255. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6256. Result := True;
  6257. { Handle any overflows }
  6258. case taicpu(p).opsize of
  6259. S_B:
  6260. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6261. S_W:
  6262. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6263. S_L:
  6264. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6265. {$ifdef x86_64}
  6266. S_Q:
  6267. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6268. { Overflow; abort }
  6269. Result := False
  6270. else
  6271. taicpu(p).oper[0]^.val := ThisConst;
  6272. {$endif x86_64}
  6273. else
  6274. InternalError(2021102611);
  6275. end;
  6276. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6277. if Result then
  6278. begin
  6279. if (taicpu(p).oper[0]^.val < 0) and
  6280. (
  6281. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6282. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6283. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6284. ) then
  6285. begin
  6286. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6287. taicpu(p).opcode := A_SUB;
  6288. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6289. end
  6290. else
  6291. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6292. RemoveInstruction(hp1);
  6293. end;
  6294. end
  6295. else
  6296. begin
  6297. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6298. TransferUsedRegs(TmpUsedRegs);
  6299. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6300. hp2 := p;
  6301. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6302. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6303. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6304. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6305. begin
  6306. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6307. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6308. Asml.Remove(p);
  6309. Asml.InsertAfter(p, hp1);
  6310. p := hp1;
  6311. Result := True;
  6312. Exit;
  6313. end;
  6314. end;
  6315. end;
  6316. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6317. { * change "sub/add const1, reg" or "dec reg" followed by
  6318. "sub const2, reg" to one "sub ..., reg" }
  6319. {$ifdef i386}
  6320. if (taicpu(p).oper[0]^.val = 2) and
  6321. (ActiveReg = NR_ESP) and
  6322. { Don't do the sub/push optimization if the sub }
  6323. { comes from setting up the stack frame (JM) }
  6324. (not(GetLastInstruction(p,hp1)) or
  6325. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6326. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6327. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6328. begin
  6329. hp1 := tai(p.next);
  6330. while Assigned(hp1) and
  6331. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6332. not RegReadByInstruction(NR_ESP,hp1) and
  6333. not RegModifiedByInstruction(NR_ESP,hp1) do
  6334. hp1 := tai(hp1.next);
  6335. if Assigned(hp1) and
  6336. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6337. begin
  6338. taicpu(hp1).changeopsize(S_L);
  6339. if taicpu(hp1).oper[0]^.typ=top_reg then
  6340. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6341. hp1 := tai(p.next);
  6342. RemoveCurrentp(p, hp1);
  6343. Result:=true;
  6344. exit;
  6345. end;
  6346. end;
  6347. {$endif i386}
  6348. if DoArithCombineOpt(p) then
  6349. Result:=true;
  6350. end;
  6351. end;
  6352. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6353. var
  6354. TmpBool1,TmpBool2 : Boolean;
  6355. tmpref : treference;
  6356. hp1,hp2: tai;
  6357. mask, shiftval: tcgint;
  6358. begin
  6359. Result:=false;
  6360. { All these optimisations work on "shl/sal const,%reg" }
  6361. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6362. Exit;
  6363. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6364. (taicpu(p).oper[0]^.val <= 3) then
  6365. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6366. begin
  6367. { should we check the next instruction? }
  6368. TmpBool1 := True;
  6369. { have we found an add/sub which could be
  6370. integrated in the lea? }
  6371. TmpBool2 := False;
  6372. reference_reset(tmpref,2,[]);
  6373. TmpRef.index := taicpu(p).oper[1]^.reg;
  6374. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6375. while TmpBool1 and
  6376. GetNextInstruction(p, hp1) and
  6377. (tai(hp1).typ = ait_instruction) and
  6378. ((((taicpu(hp1).opcode = A_ADD) or
  6379. (taicpu(hp1).opcode = A_SUB)) and
  6380. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6381. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6382. (((taicpu(hp1).opcode = A_INC) or
  6383. (taicpu(hp1).opcode = A_DEC)) and
  6384. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6385. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6386. ((taicpu(hp1).opcode = A_LEA) and
  6387. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6388. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6389. (not GetNextInstruction(hp1,hp2) or
  6390. not instrReadsFlags(hp2)) Do
  6391. begin
  6392. TmpBool1 := False;
  6393. if taicpu(hp1).opcode=A_LEA then
  6394. begin
  6395. if (TmpRef.base = NR_NO) and
  6396. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6397. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6398. { Segment register isn't a concern here }
  6399. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6400. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6401. begin
  6402. TmpBool1 := True;
  6403. TmpBool2 := True;
  6404. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6405. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6406. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6407. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6408. RemoveInstruction(hp1);
  6409. end
  6410. end
  6411. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6412. begin
  6413. TmpBool1 := True;
  6414. TmpBool2 := True;
  6415. case taicpu(hp1).opcode of
  6416. A_ADD:
  6417. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6418. A_SUB:
  6419. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6420. else
  6421. internalerror(2019050536);
  6422. end;
  6423. RemoveInstruction(hp1);
  6424. end
  6425. else
  6426. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6427. (((taicpu(hp1).opcode = A_ADD) and
  6428. (TmpRef.base = NR_NO)) or
  6429. (taicpu(hp1).opcode = A_INC) or
  6430. (taicpu(hp1).opcode = A_DEC)) then
  6431. begin
  6432. TmpBool1 := True;
  6433. TmpBool2 := True;
  6434. case taicpu(hp1).opcode of
  6435. A_ADD:
  6436. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6437. A_INC:
  6438. inc(TmpRef.offset);
  6439. A_DEC:
  6440. dec(TmpRef.offset);
  6441. else
  6442. internalerror(2019050535);
  6443. end;
  6444. RemoveInstruction(hp1);
  6445. end;
  6446. end;
  6447. if TmpBool2
  6448. {$ifndef x86_64}
  6449. or
  6450. ((current_settings.optimizecputype < cpu_Pentium2) and
  6451. (taicpu(p).oper[0]^.val <= 3) and
  6452. not(cs_opt_size in current_settings.optimizerswitches))
  6453. {$endif x86_64}
  6454. then
  6455. begin
  6456. if not(TmpBool2) and
  6457. (taicpu(p).oper[0]^.val=1) then
  6458. begin
  6459. taicpu(p).opcode := A_ADD;
  6460. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6461. end
  6462. else
  6463. begin
  6464. taicpu(p).opcode := A_LEA;
  6465. taicpu(p).loadref(0, TmpRef);
  6466. end;
  6467. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6468. Result := True;
  6469. end;
  6470. end
  6471. {$ifndef x86_64}
  6472. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6473. begin
  6474. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6475. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6476. (unlike shl, which is only Tairable in the U pipe) }
  6477. if taicpu(p).oper[0]^.val=1 then
  6478. begin
  6479. taicpu(p).opcode := A_ADD;
  6480. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6481. Result := True;
  6482. end
  6483. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6484. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6485. else if (taicpu(p).opsize = S_L) and
  6486. (taicpu(p).oper[0]^.val<= 3) then
  6487. begin
  6488. reference_reset(tmpref,2,[]);
  6489. TmpRef.index := taicpu(p).oper[1]^.reg;
  6490. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6491. taicpu(p).opcode := A_LEA;
  6492. taicpu(p).loadref(0, TmpRef);
  6493. Result := True;
  6494. end;
  6495. end
  6496. {$endif x86_64}
  6497. else if
  6498. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6499. (
  6500. (
  6501. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6502. SetAndTest(hp1, hp2)
  6503. {$ifdef x86_64}
  6504. ) or
  6505. (
  6506. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6507. GetNextInstruction(hp1, hp2) and
  6508. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6509. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6510. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6511. {$endif x86_64}
  6512. )
  6513. ) and
  6514. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6515. begin
  6516. { Change:
  6517. shl x, %reg1
  6518. mov -(1<<x), %reg2
  6519. and %reg2, %reg1
  6520. Or:
  6521. shl x, %reg1
  6522. and -(1<<x), %reg1
  6523. To just:
  6524. shl x, %reg1
  6525. Since the and operation only zeroes bits that are already zero from the shl operation
  6526. }
  6527. case taicpu(p).oper[0]^.val of
  6528. 8:
  6529. mask:=$FFFFFFFFFFFFFF00;
  6530. 16:
  6531. mask:=$FFFFFFFFFFFF0000;
  6532. 32:
  6533. mask:=$FFFFFFFF00000000;
  6534. 63:
  6535. { Constant pre-calculated to prevent overflow errors with Int64 }
  6536. mask:=$8000000000000000;
  6537. else
  6538. begin
  6539. if taicpu(p).oper[0]^.val >= 64 then
  6540. { Shouldn't happen realistically, since the register
  6541. is guaranteed to be set to zero at this point }
  6542. mask := 0
  6543. else
  6544. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6545. end;
  6546. end;
  6547. if taicpu(hp1).oper[0]^.val = mask then
  6548. begin
  6549. { Everything checks out, perform the optimisation, as long as
  6550. the FLAGS register isn't being used}
  6551. TransferUsedRegs(TmpUsedRegs);
  6552. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6553. {$ifdef x86_64}
  6554. if (hp1 <> hp2) then
  6555. begin
  6556. { "shl/mov/and" version }
  6557. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6558. { Don't do the optimisation if the FLAGS register is in use }
  6559. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6560. begin
  6561. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6562. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6563. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6564. begin
  6565. RemoveInstruction(hp1);
  6566. Result := True;
  6567. end;
  6568. { Only set Result to True if the 'mov' instruction was removed }
  6569. RemoveInstruction(hp2);
  6570. end;
  6571. end
  6572. else
  6573. {$endif x86_64}
  6574. begin
  6575. { "shl/and" version }
  6576. { Don't do the optimisation if the FLAGS register is in use }
  6577. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6578. begin
  6579. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6580. RemoveInstruction(hp1);
  6581. Result := True;
  6582. end;
  6583. end;
  6584. Exit;
  6585. end
  6586. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6587. begin
  6588. { Even if the mask doesn't allow for its removal, we might be
  6589. able to optimise the mask for the "shl/and" version, which
  6590. may permit other peephole optimisations }
  6591. {$ifdef DEBUG_AOPTCPU}
  6592. mask := taicpu(hp1).oper[0]^.val and mask;
  6593. if taicpu(hp1).oper[0]^.val <> mask then
  6594. begin
  6595. DebugMsg(
  6596. SPeepholeOptimization +
  6597. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6598. ' to $' + debug_tostr(mask) +
  6599. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6600. taicpu(hp1).oper[0]^.val := mask;
  6601. end;
  6602. {$else DEBUG_AOPTCPU}
  6603. { If debugging is off, just set the operand even if it's the same }
  6604. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6605. {$endif DEBUG_AOPTCPU}
  6606. end;
  6607. end;
  6608. {
  6609. change
  6610. shl/sal const,reg
  6611. <op> ...(...,reg,1),...
  6612. into
  6613. <op> ...(...,reg,1 shl const),...
  6614. if const in 1..3
  6615. }
  6616. if MatchOpType(taicpu(p), top_const, top_reg) and
  6617. (taicpu(p).oper[0]^.val in [1..3]) and
  6618. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6619. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6620. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6621. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6622. MatchOpType(taicpu(hp1),top_ref))
  6623. ) and
  6624. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6625. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6626. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6627. begin
  6628. TransferUsedRegs(TmpUsedRegs);
  6629. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6630. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6631. begin
  6632. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6633. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6634. RemoveCurrentP(p);
  6635. Result:=true;
  6636. exit;
  6637. end;
  6638. end;
  6639. if MatchOpType(taicpu(p), top_const, top_reg) and
  6640. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6641. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6642. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6643. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6644. begin
  6645. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6646. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6647. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6648. {$ifdef x86_64}
  6649. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6650. {$endif x86_64}
  6651. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6652. begin
  6653. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6654. taicpu(hp1).opcode:=A_MOV;
  6655. taicpu(hp1).oper[0]^.val:=0;
  6656. end
  6657. else
  6658. begin
  6659. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6660. taicpu(hp1).oper[0]^.val:=shiftval;
  6661. end;
  6662. RemoveCurrentP(p);
  6663. Result:=true;
  6664. exit;
  6665. end;
  6666. end;
  6667. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6668. begin
  6669. case shr_size of
  6670. S_B:
  6671. { No valid combinations }
  6672. Result := False;
  6673. S_W:
  6674. Result := (Shift >= 8) and (movz_size = S_BW);
  6675. S_L:
  6676. Result :=
  6677. (Shift >= 24) { Any opsize is valid for this shift } or
  6678. ((Shift >= 16) and (movz_size = S_WL));
  6679. {$ifdef x86_64}
  6680. S_Q:
  6681. Result :=
  6682. (Shift >= 56) { Any opsize is valid for this shift } or
  6683. ((Shift >= 48) and (movz_size = S_WL));
  6684. {$endif x86_64}
  6685. else
  6686. InternalError(2022081510);
  6687. end;
  6688. end;
  6689. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6690. var
  6691. hp1, hp2: tai;
  6692. Shift: TCGInt;
  6693. LimitSize: Topsize;
  6694. DoNotMerge: Boolean;
  6695. begin
  6696. Result := False;
  6697. { All these optimisations work on "shr const,%reg" }
  6698. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6699. Exit;
  6700. DoNotMerge := False;
  6701. Shift := taicpu(p).oper[0]^.val;
  6702. LimitSize := taicpu(p).opsize;
  6703. hp1 := p;
  6704. repeat
  6705. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6706. Exit;
  6707. case taicpu(hp1).opcode of
  6708. A_TEST, A_CMP, A_Jcc:
  6709. { Skip over conditional jumps and relevant comparisons }
  6710. Continue;
  6711. A_MOVZX:
  6712. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6713. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6714. begin
  6715. { Since the original register is being read as is, subsequent
  6716. SHRs must not be merged at this point }
  6717. DoNotMerge := True;
  6718. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6719. begin
  6720. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6721. begin
  6722. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6723. taicpu(hp1).opcode := A_MOV;
  6724. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6725. case taicpu(hp1).opsize of
  6726. S_BW:
  6727. taicpu(hp1).opsize := S_W;
  6728. S_BL, S_WL:
  6729. taicpu(hp1).opsize := S_L;
  6730. else
  6731. InternalError(2022081503);
  6732. end;
  6733. { p itself hasn't changed, so no need to set Result to True }
  6734. Include(OptsToCheck, aoc_ForceNewIteration);
  6735. { See if there's anything afterwards that can be
  6736. optimised, since the input register hasn't changed }
  6737. Continue;
  6738. end;
  6739. { NOTE: If the MOVZX instruction reads and writes the same
  6740. register, defer this to the post-peephole optimisation stage }
  6741. Exit;
  6742. end;
  6743. end;
  6744. A_SHL, A_SAL, A_SHR:
  6745. if (taicpu(hp1).opsize <= LimitSize) and
  6746. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6747. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6748. begin
  6749. { Make sure the sizes don't exceed the register size limit
  6750. (measured by the shift value falling below the limit) }
  6751. if taicpu(hp1).opsize < LimitSize then
  6752. LimitSize := taicpu(hp1).opsize;
  6753. if taicpu(hp1).opcode = A_SHR then
  6754. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6755. else
  6756. begin
  6757. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6758. DoNotMerge := True;
  6759. end;
  6760. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6761. Exit;
  6762. { Since we've established that the combined shift is within
  6763. limits, we can actually combine the adjacent SHR
  6764. instructions even if they're different sizes }
  6765. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6766. begin
  6767. hp2 := tai(hp1.Previous);
  6768. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6769. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6770. RemoveInstruction(hp1);
  6771. hp1 := hp2;
  6772. { Though p has changed, only the constant has, and its
  6773. effects can still be detected on the next iteration of
  6774. the repeat..until loop }
  6775. Include(OptsToCheck, aoc_ForceNewIteration);
  6776. end;
  6777. { Move onto the next instruction }
  6778. Continue;
  6779. end;
  6780. else
  6781. ;
  6782. end;
  6783. Break;
  6784. until False;
  6785. end;
  6786. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6787. var
  6788. CurrentRef: TReference;
  6789. FullReg: TRegister;
  6790. hp1, hp2: tai;
  6791. begin
  6792. Result := False;
  6793. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6794. Exit;
  6795. { We assume you've checked if the operand is actually a reference by
  6796. this point. If it isn't, you'll most likely get an access violation }
  6797. CurrentRef := first_mov.oper[1]^.ref^;
  6798. { Memory must be aligned }
  6799. if (CurrentRef.offset mod 4) <> 0 then
  6800. Exit;
  6801. Inc(CurrentRef.offset);
  6802. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6803. if MatchOperand(second_mov.oper[0]^, 0) and
  6804. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6805. GetNextInstruction(second_mov, hp1) and
  6806. (hp1.typ = ait_instruction) and
  6807. (taicpu(hp1).opcode = A_MOV) and
  6808. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6809. (taicpu(hp1).oper[0]^.val = 0) then
  6810. begin
  6811. Inc(CurrentRef.offset);
  6812. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6813. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6814. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6815. begin
  6816. case taicpu(hp1).opsize of
  6817. S_B:
  6818. if GetNextInstruction(hp1, hp2) and
  6819. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6820. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6821. (taicpu(hp2).oper[0]^.val = 0) then
  6822. begin
  6823. Inc(CurrentRef.offset);
  6824. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6825. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6826. (taicpu(hp2).opsize = S_B) then
  6827. begin
  6828. RemoveInstruction(hp1);
  6829. RemoveInstruction(hp2);
  6830. first_mov.opsize := S_L;
  6831. if first_mov.oper[0]^.typ = top_reg then
  6832. begin
  6833. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6834. { Reuse second_mov as a MOVZX instruction }
  6835. second_mov.opcode := A_MOVZX;
  6836. second_mov.opsize := S_BL;
  6837. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6838. second_mov.loadreg(1, FullReg);
  6839. first_mov.oper[0]^.reg := FullReg;
  6840. asml.Remove(second_mov);
  6841. asml.InsertBefore(second_mov, first_mov);
  6842. end
  6843. else
  6844. { It's a value }
  6845. begin
  6846. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6847. RemoveInstruction(second_mov);
  6848. end;
  6849. Result := True;
  6850. Exit;
  6851. end;
  6852. end;
  6853. S_W:
  6854. begin
  6855. RemoveInstruction(hp1);
  6856. first_mov.opsize := S_L;
  6857. if first_mov.oper[0]^.typ = top_reg then
  6858. begin
  6859. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6860. { Reuse second_mov as a MOVZX instruction }
  6861. second_mov.opcode := A_MOVZX;
  6862. second_mov.opsize := S_BL;
  6863. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6864. second_mov.loadreg(1, FullReg);
  6865. first_mov.oper[0]^.reg := FullReg;
  6866. asml.Remove(second_mov);
  6867. asml.InsertBefore(second_mov, first_mov);
  6868. end
  6869. else
  6870. { It's a value }
  6871. begin
  6872. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6873. RemoveInstruction(second_mov);
  6874. end;
  6875. Result := True;
  6876. Exit;
  6877. end;
  6878. else
  6879. ;
  6880. end;
  6881. end;
  6882. end;
  6883. end;
  6884. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6885. { returns true if a "continue" should be done after this optimization }
  6886. var
  6887. hp1, hp2, hp3: tai;
  6888. begin
  6889. Result := false;
  6890. hp3 := nil;
  6891. if MatchOpType(taicpu(p),top_ref) and
  6892. GetNextInstruction(p, hp1) and
  6893. (hp1.typ = ait_instruction) and
  6894. (((taicpu(hp1).opcode = A_FLD) and
  6895. (taicpu(p).opcode = A_FSTP)) or
  6896. ((taicpu(p).opcode = A_FISTP) and
  6897. (taicpu(hp1).opcode = A_FILD))) and
  6898. MatchOpType(taicpu(hp1),top_ref) and
  6899. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6900. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6901. begin
  6902. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6903. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6904. GetNextInstruction(hp1, hp2) and
  6905. (((hp2.typ = ait_instruction) and
  6906. IsExitCode(hp2) and
  6907. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6908. not(assigned(current_procinfo.procdef.funcretsym) and
  6909. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6910. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6911. { fstp <temp>
  6912. fld <temp>
  6913. <dealloc> <temp>
  6914. }
  6915. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6916. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6917. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6918. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6919. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6920. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6921. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6922. )
  6923. )
  6924. ) then
  6925. begin
  6926. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6927. RemoveInstruction(hp1);
  6928. RemoveCurrentP(p, hp2);
  6929. { first case: exit code }
  6930. if hp2.typ = ait_instruction then
  6931. RemoveLastDeallocForFuncRes(p);
  6932. Result := true;
  6933. end
  6934. else
  6935. { we can do this only in fast math mode as fstp is rounding ...
  6936. ... still disabled as it breaks the compiler and/or rtl }
  6937. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6938. { ... or if another fstp equal to the first one follows }
  6939. GetNextInstruction(hp1,hp2) and
  6940. (hp2.typ = ait_instruction) and
  6941. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6942. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6943. begin
  6944. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6945. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6946. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6947. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6948. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6949. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6950. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6951. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6952. ) then
  6953. begin
  6954. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6955. RemoveCurrentP(p,hp2);
  6956. RemoveInstruction(hp1);
  6957. Result := true;
  6958. end
  6959. else if { fst can't store an extended/comp value }
  6960. (taicpu(p).opsize <> S_FX) and
  6961. (taicpu(p).opsize <> S_IQ) then
  6962. begin
  6963. if (taicpu(p).opcode = A_FSTP) then
  6964. taicpu(p).opcode := A_FST
  6965. else
  6966. taicpu(p).opcode := A_FIST;
  6967. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6968. RemoveInstruction(hp1);
  6969. Result := true;
  6970. end;
  6971. end;
  6972. end;
  6973. end;
  6974. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6975. var
  6976. hp1, hp2, hp3: tai;
  6977. begin
  6978. result:=false;
  6979. if MatchOpType(taicpu(p),top_reg) and
  6980. GetNextInstruction(p, hp1) and
  6981. (hp1.typ = Ait_Instruction) and
  6982. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6983. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6984. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6985. { change to
  6986. fld reg fxxx reg,st
  6987. fxxxp st, st1 (hp1)
  6988. Remark: non commutative operations must be reversed!
  6989. }
  6990. begin
  6991. case taicpu(hp1).opcode Of
  6992. A_FMULP,A_FADDP,
  6993. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6994. begin
  6995. case taicpu(hp1).opcode Of
  6996. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6997. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6998. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6999. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7000. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7001. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7002. else
  7003. internalerror(2019050534);
  7004. end;
  7005. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7006. taicpu(hp1).oper[1]^.reg := NR_ST;
  7007. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7008. RemoveCurrentP(p, hp1);
  7009. Result:=true;
  7010. exit;
  7011. end;
  7012. else
  7013. ;
  7014. end;
  7015. end
  7016. else
  7017. if MatchOpType(taicpu(p),top_ref) and
  7018. GetNextInstruction(p, hp2) and
  7019. (hp2.typ = Ait_Instruction) and
  7020. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7021. (taicpu(p).opsize in [S_FS, S_FL]) and
  7022. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7023. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7024. if GetLastInstruction(p, hp1) and
  7025. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7026. MatchOpType(taicpu(hp1),top_ref) and
  7027. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7028. if ((taicpu(hp2).opcode = A_FMULP) or
  7029. (taicpu(hp2).opcode = A_FADDP)) then
  7030. { change to
  7031. fld/fst mem1 (hp1) fld/fst mem1
  7032. fld mem1 (p) fadd/
  7033. faddp/ fmul st, st
  7034. fmulp st, st1 (hp2) }
  7035. begin
  7036. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7037. RemoveCurrentP(p, hp1);
  7038. if (taicpu(hp2).opcode = A_FADDP) then
  7039. taicpu(hp2).opcode := A_FADD
  7040. else
  7041. taicpu(hp2).opcode := A_FMUL;
  7042. taicpu(hp2).oper[1]^.reg := NR_ST;
  7043. end
  7044. else
  7045. { change to
  7046. fld/fst mem1 (hp1) fld/fst mem1
  7047. fld mem1 (p) fld st
  7048. }
  7049. begin
  7050. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7051. taicpu(p).changeopsize(S_FL);
  7052. taicpu(p).loadreg(0,NR_ST);
  7053. end
  7054. else
  7055. begin
  7056. case taicpu(hp2).opcode Of
  7057. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7058. { change to
  7059. fld/fst mem1 (hp1) fld/fst mem1
  7060. fld mem2 (p) fxxx mem2
  7061. fxxxp st, st1 (hp2) }
  7062. begin
  7063. case taicpu(hp2).opcode Of
  7064. A_FADDP: taicpu(p).opcode := A_FADD;
  7065. A_FMULP: taicpu(p).opcode := A_FMUL;
  7066. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7067. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7068. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7069. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7070. else
  7071. internalerror(2019050533);
  7072. end;
  7073. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7074. RemoveInstruction(hp2);
  7075. end
  7076. else
  7077. ;
  7078. end
  7079. end
  7080. end;
  7081. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7082. begin
  7083. Result := condition_in(cond1, cond2) or
  7084. { Not strictly subsets due to the actual flags checked, but because we're
  7085. comparing integers, E is a subset of AE and GE and their aliases }
  7086. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7087. end;
  7088. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7089. var
  7090. v: TCGInt;
  7091. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7092. FirstMatch, TempBool: Boolean;
  7093. NewReg: TRegister;
  7094. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7095. begin
  7096. Result:=false;
  7097. { All these optimisations need a next instruction }
  7098. if not GetNextInstruction(p, hp1) then
  7099. Exit;
  7100. { Search for:
  7101. cmp ###,###
  7102. j(c1) @lbl1
  7103. ...
  7104. @lbl:
  7105. cmp ###,### (same comparison as above)
  7106. j(c2) @lbl2
  7107. If c1 is a subset of c2, change to:
  7108. cmp ###,###
  7109. j(c1) @lbl2
  7110. (@lbl1 may become a dead label as a result)
  7111. }
  7112. { Also handle cases where there are multiple jumps in a row }
  7113. p_jump := hp1;
  7114. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7115. begin
  7116. if IsJumpToLabel(taicpu(p_jump)) then
  7117. begin
  7118. { Do jump optimisations first in case the condition becomes
  7119. unnecessary }
  7120. TempBool := True;
  7121. if DoJumpOptimizations(p_jump, TempBool) or
  7122. not TempBool then
  7123. begin
  7124. if Assigned(p_jump) then
  7125. begin
  7126. { CollapseZeroDistJump will be set to the label or an align
  7127. before it after the jump if it optimises, whether or not
  7128. the label is live or dead }
  7129. if (p_jump.typ = ait_align) or
  7130. (
  7131. (p_jump.typ = ait_label) and
  7132. not (tai_label(p_jump).labsym.is_used)
  7133. ) then
  7134. GetNextInstruction(p_jump, p_jump);
  7135. end;
  7136. TransferUsedRegs(TmpUsedRegs);
  7137. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7138. if not Assigned(p_jump) or
  7139. (
  7140. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7141. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7142. ) then
  7143. begin
  7144. { No more conditional jumps; conditional statement is no longer required }
  7145. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7146. RemoveCurrentP(p);
  7147. Result := True;
  7148. Exit;
  7149. end;
  7150. hp1 := p_jump;
  7151. Include(OptsToCheck, aoc_ForceNewIteration);
  7152. Continue;
  7153. end;
  7154. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7155. if GetNextInstruction(p_jump, hp2) and
  7156. (
  7157. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7158. not TempBool
  7159. ) then
  7160. begin
  7161. hp1 := p_jump;
  7162. Include(OptsToCheck, aoc_ForceNewIteration);
  7163. Continue;
  7164. end;
  7165. p_label := nil;
  7166. if Assigned(JumpLabel) then
  7167. p_label := getlabelwithsym(JumpLabel);
  7168. if Assigned(p_label) and
  7169. GetNextInstruction(p_label, p_dist) and
  7170. MatchInstruction(p_dist, A_CMP, []) and
  7171. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7172. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7173. GetNextInstruction(p_dist, hp1_dist) and
  7174. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7175. begin
  7176. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7177. if JumpLabel = JumpLabel_dist then
  7178. { This is an infinite loop }
  7179. Exit;
  7180. { Best optimisation when the first condition is a subset (or equal) of the second }
  7181. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7182. begin
  7183. { Any registers used here will already be allocated }
  7184. if Assigned(JumpLabel) then
  7185. JumpLabel.DecRefs;
  7186. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7187. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7188. Result := True;
  7189. { Don't exit yet. Since p and p_jump haven't actually been
  7190. removed, we can check for more on this iteration }
  7191. end
  7192. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7193. GetNextInstruction(hp1_dist, hp1_label) and
  7194. (hp1_label.typ = ait_label) then
  7195. begin
  7196. JumpLabel_far := tai_label(hp1_label).labsym;
  7197. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7198. { This is an infinite loop }
  7199. Exit;
  7200. if Assigned(JumpLabel_far) then
  7201. begin
  7202. { In this situation, if the first jump branches, the second one will never,
  7203. branch so change the destination label to after the second jump }
  7204. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7205. if Assigned(JumpLabel) then
  7206. JumpLabel.DecRefs;
  7207. JumpLabel_far.IncRefs;
  7208. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7209. Result := True;
  7210. { Don't exit yet. Since p and p_jump haven't actually been
  7211. removed, we can check for more on this iteration }
  7212. Continue;
  7213. end;
  7214. end;
  7215. end;
  7216. end;
  7217. { Search for:
  7218. cmp ###,###
  7219. j(c1) @lbl1
  7220. cmp ###,### (same as first)
  7221. Remove second cmp
  7222. }
  7223. if GetNextInstruction(p_jump, hp2) and
  7224. (
  7225. (
  7226. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7227. (
  7228. (
  7229. MatchOpType(taicpu(p), top_const, top_reg) and
  7230. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7231. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7232. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7233. ) or (
  7234. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7235. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7236. )
  7237. )
  7238. ) or (
  7239. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7240. MatchOperand(taicpu(p).oper[0]^, 0) and
  7241. (taicpu(p).oper[1]^.typ = top_reg) and
  7242. MatchInstruction(hp2, A_TEST, []) and
  7243. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7244. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7245. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7246. )
  7247. ) then
  7248. begin
  7249. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7250. RemoveInstruction(hp2);
  7251. Result := True;
  7252. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7253. end;
  7254. GetNextInstruction(p_jump, p_jump);
  7255. end;
  7256. if (
  7257. { Don't call GetNextInstruction again if we already have it }
  7258. (hp1 = p_jump) or
  7259. GetNextInstruction(p, hp1)
  7260. ) and
  7261. MatchInstruction(hp1, A_Jcc, []) and
  7262. IsJumpToLabel(taicpu(hp1)) and
  7263. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7264. GetNextInstruction(hp1, hp2) then
  7265. begin
  7266. {
  7267. cmp x, y (or "cmp y, x")
  7268. je @lbl
  7269. mov x, y
  7270. @lbl:
  7271. (x and y can be constants, registers or references)
  7272. Change to:
  7273. mov x, y (x and y will always be equal in the end)
  7274. @lbl: (may beceome a dead label)
  7275. Also:
  7276. cmp x, y (or "cmp y, x")
  7277. jne @lbl
  7278. mov x, y
  7279. @lbl:
  7280. (x and y can be constants, registers or references)
  7281. Change to:
  7282. Absolutely nothing! (Except @lbl if it's still live)
  7283. }
  7284. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7285. (
  7286. (
  7287. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7288. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7289. ) or (
  7290. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7291. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7292. )
  7293. ) and
  7294. GetNextInstruction(hp2, hp1_label) and
  7295. (hp1_label.typ = ait_label) and
  7296. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7297. begin
  7298. tai_label(hp1_label).labsym.DecRefs;
  7299. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7300. begin
  7301. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7302. RemoveInstruction(hp2);
  7303. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7304. end
  7305. else
  7306. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7307. RemoveInstruction(hp1);
  7308. RemoveCurrentp(p, hp2);
  7309. Result := True;
  7310. Exit;
  7311. end;
  7312. {
  7313. Try to optimise the following:
  7314. cmp $x,### ($x and $y can be registers or constants)
  7315. je @lbl1 (only reference)
  7316. cmp $y,### (### are identical)
  7317. @Lbl:
  7318. sete %reg1
  7319. Change to:
  7320. cmp $x,###
  7321. sete %reg2 (allocate new %reg2)
  7322. cmp $y,###
  7323. sete %reg1
  7324. orb %reg2,%reg1
  7325. (dealloc %reg2)
  7326. This adds an instruction (so don't perform under -Os), but it removes
  7327. a conditional branch.
  7328. }
  7329. if not (cs_opt_size in current_settings.optimizerswitches) and
  7330. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7331. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7332. { The first operand of CMP instructions can only be a register or
  7333. immediate anyway, so no need to check }
  7334. GetNextInstruction(hp2, p_label) and
  7335. (p_label.typ = ait_label) and
  7336. (tai_label(p_label).labsym.getrefs = 1) and
  7337. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7338. GetNextInstruction(p_label, p_dist) and
  7339. MatchInstruction(p_dist, A_SETcc, []) and
  7340. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7341. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7342. begin
  7343. TransferUsedRegs(TmpUsedRegs);
  7344. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7345. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7346. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7347. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7348. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7349. { Get the instruction after the SETcc instruction so we can
  7350. allocate a new register over the entire range }
  7351. GetNextInstruction(p_dist, hp1_dist) then
  7352. begin
  7353. { Register can appear in p if it's not used afterwards, so only
  7354. allocate between hp1 and hp1_dist }
  7355. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7356. if NewReg <> NR_NO then
  7357. begin
  7358. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7359. { Change the jump instruction into a SETcc instruction }
  7360. taicpu(hp1).opcode := A_SETcc;
  7361. taicpu(hp1).opsize := S_B;
  7362. taicpu(hp1).loadreg(0, NewReg);
  7363. { This is now a dead label }
  7364. tai_label(p_label).labsym.decrefs;
  7365. { Prefer adding before the next instruction so the FLAGS
  7366. register is deallicated first }
  7367. AsmL.InsertBefore(
  7368. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7369. hp1_dist
  7370. );
  7371. Result := True;
  7372. { Don't exit yet, as p wasn't changed and hp1, while
  7373. modified, is still intact and might be optimised by the
  7374. SETcc optimisation below }
  7375. end;
  7376. end;
  7377. end;
  7378. end;
  7379. if taicpu(p).oper[0]^.typ = top_const then
  7380. begin
  7381. if (taicpu(p).oper[0]^.val = 0) and
  7382. (taicpu(p).oper[1]^.typ = top_reg) and
  7383. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7384. begin
  7385. hp2 := p;
  7386. FirstMatch := True;
  7387. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7388. anything meaningful once it's converted to "test %reg,%reg";
  7389. additionally, some jumps will always (or never) branch, so
  7390. evaluate every jump immediately following the
  7391. comparison, optimising the conditions if possible.
  7392. Similarly with SETcc... those that are always set to 0 or 1
  7393. are changed to MOV instructions }
  7394. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7395. (
  7396. GetNextInstruction(hp2, hp1) and
  7397. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7398. ) do
  7399. begin
  7400. FirstMatch := False;
  7401. case taicpu(hp1).condition of
  7402. C_B, C_C, C_NAE, C_O:
  7403. { For B/NAE:
  7404. Will never branch since an unsigned integer can never be below zero
  7405. For C/O:
  7406. Result cannot overflow because 0 is being subtracted
  7407. }
  7408. begin
  7409. if taicpu(hp1).opcode = A_Jcc then
  7410. begin
  7411. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7412. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7413. RemoveInstruction(hp1);
  7414. { Since hp1 was deleted, hp2 must not be updated }
  7415. Continue;
  7416. end
  7417. else
  7418. begin
  7419. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7420. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7421. taicpu(hp1).opcode := A_MOV;
  7422. taicpu(hp1).ops := 2;
  7423. taicpu(hp1).condition := C_None;
  7424. taicpu(hp1).opsize := S_B;
  7425. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7426. taicpu(hp1).loadconst(0, 0);
  7427. end;
  7428. end;
  7429. C_BE, C_NA:
  7430. begin
  7431. { Will only branch if equal to zero }
  7432. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7433. taicpu(hp1).condition := C_E;
  7434. end;
  7435. C_A, C_NBE:
  7436. begin
  7437. { Will only branch if not equal to zero }
  7438. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7439. taicpu(hp1).condition := C_NE;
  7440. end;
  7441. C_AE, C_NB, C_NC, C_NO:
  7442. begin
  7443. { Will always branch }
  7444. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7445. if taicpu(hp1).opcode = A_Jcc then
  7446. begin
  7447. MakeUnconditional(taicpu(hp1));
  7448. { Any jumps/set that follow will now be dead code }
  7449. RemoveDeadCodeAfterJump(taicpu(hp1));
  7450. Break;
  7451. end
  7452. else
  7453. begin
  7454. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7455. taicpu(hp1).opcode := A_MOV;
  7456. taicpu(hp1).ops := 2;
  7457. taicpu(hp1).condition := C_None;
  7458. taicpu(hp1).opsize := S_B;
  7459. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7460. taicpu(hp1).loadconst(0, 1);
  7461. end;
  7462. end;
  7463. C_None:
  7464. InternalError(2020012201);
  7465. C_P, C_PE, C_NP, C_PO:
  7466. { We can't handle parity checks and they should never be generated
  7467. after a general-purpose CMP (it's used in some floating-point
  7468. comparisons that don't use CMP) }
  7469. InternalError(2020012202);
  7470. else
  7471. { Zero/Equality, Sign, their complements and all of the
  7472. signed comparisons do not need to be converted };
  7473. end;
  7474. hp2 := hp1;
  7475. end;
  7476. { Convert the instruction to a TEST }
  7477. taicpu(p).opcode := A_TEST;
  7478. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7479. Result := True;
  7480. Exit;
  7481. end
  7482. else if (taicpu(p).oper[0]^.val = 1) and
  7483. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7484. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7485. begin
  7486. { Convert; To:
  7487. cmp $1,r/m cmp $0,r/m
  7488. jl @lbl jle @lbl
  7489. (Also do inverted conditions)
  7490. }
  7491. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7492. taicpu(p).oper[0]^.val := 0;
  7493. if taicpu(hp1).condition in [C_L, C_NGE] then
  7494. taicpu(hp1).condition := C_LE
  7495. else
  7496. taicpu(hp1).condition := C_NLE;
  7497. { If the instruction is now "cmp $0,%reg", convert it to a
  7498. TEST (and effectively do the work of the "cmp $0,%reg" in
  7499. the block above)
  7500. }
  7501. if (taicpu(p).oper[1]^.typ = top_reg) then
  7502. begin
  7503. taicpu(p).opcode := A_TEST;
  7504. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7505. end;
  7506. Result := True;
  7507. Exit;
  7508. end
  7509. else if (taicpu(p).oper[1]^.typ = top_reg)
  7510. {$ifdef x86_64}
  7511. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7512. {$endif x86_64}
  7513. then
  7514. begin
  7515. { cmp register,$8000 neg register
  7516. je target --> jo target
  7517. .... only if register is deallocated before jump.}
  7518. case Taicpu(p).opsize of
  7519. S_B: v:=$80;
  7520. S_W: v:=$8000;
  7521. S_L: v:=qword($80000000);
  7522. else
  7523. internalerror(2013112905);
  7524. end;
  7525. if (taicpu(p).oper[0]^.val=v) and
  7526. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7527. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7528. begin
  7529. TransferUsedRegs(TmpUsedRegs);
  7530. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7531. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7532. begin
  7533. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7534. Taicpu(p).opcode:=A_NEG;
  7535. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7536. Taicpu(p).clearop(1);
  7537. Taicpu(p).ops:=1;
  7538. if Taicpu(hp1).condition=C_E then
  7539. Taicpu(hp1).condition:=C_O
  7540. else
  7541. Taicpu(hp1).condition:=C_NO;
  7542. Result:=true;
  7543. exit;
  7544. end;
  7545. end;
  7546. end;
  7547. end;
  7548. if TrySwapMovCmp(p, hp1) then
  7549. begin
  7550. Result := True;
  7551. Exit;
  7552. end;
  7553. end;
  7554. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7555. var
  7556. hp1: tai;
  7557. begin
  7558. {
  7559. remove the second (v)pxor from
  7560. pxor reg,reg
  7561. ...
  7562. pxor reg,reg
  7563. }
  7564. Result:=false;
  7565. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7566. MatchOpType(taicpu(p),top_reg,top_reg) and
  7567. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7568. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7569. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7570. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7571. begin
  7572. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7573. RemoveInstruction(hp1);
  7574. Result:=true;
  7575. Exit;
  7576. end
  7577. {
  7578. replace
  7579. pxor reg1,reg1
  7580. movapd/s reg1,reg2
  7581. dealloc reg1
  7582. by
  7583. pxor reg2,reg2
  7584. }
  7585. else if GetNextInstruction(p,hp1) and
  7586. { we mix single and double opperations here because we assume that the compiler
  7587. generates vmovapd only after double operations and vmovaps only after single operations }
  7588. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7589. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7590. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7591. (taicpu(p).oper[0]^.typ=top_reg) then
  7592. begin
  7593. TransferUsedRegs(TmpUsedRegs);
  7594. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7595. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7596. begin
  7597. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7598. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7599. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7600. RemoveInstruction(hp1);
  7601. result:=true;
  7602. end;
  7603. end;
  7604. end;
  7605. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7606. var
  7607. hp1: tai;
  7608. begin
  7609. {
  7610. remove the second (v)pxor from
  7611. (v)pxor reg,reg
  7612. ...
  7613. (v)pxor reg,reg
  7614. }
  7615. Result:=false;
  7616. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7617. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7618. begin
  7619. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7620. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7621. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7622. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7623. begin
  7624. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7625. RemoveInstruction(hp1);
  7626. Result:=true;
  7627. Exit;
  7628. end;
  7629. {$ifdef x86_64}
  7630. {
  7631. replace
  7632. vpxor reg1,reg1,reg1
  7633. vmov reg,mem
  7634. by
  7635. movq $0,mem
  7636. }
  7637. if GetNextInstruction(p,hp1) and
  7638. MatchInstruction(hp1,A_VMOVSD,[]) and
  7639. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7640. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7641. begin
  7642. TransferUsedRegs(TmpUsedRegs);
  7643. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7644. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7645. begin
  7646. taicpu(hp1).loadconst(0,0);
  7647. taicpu(hp1).opcode:=A_MOV;
  7648. taicpu(hp1).opsize:=S_Q;
  7649. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7650. RemoveCurrentP(p);
  7651. result:=true;
  7652. Exit;
  7653. end;
  7654. end;
  7655. {$endif x86_64}
  7656. end
  7657. {
  7658. replace
  7659. vpxor reg1,reg1,reg2
  7660. by
  7661. vpxor reg2,reg2,reg2
  7662. to avoid unncessary data dependencies
  7663. }
  7664. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7665. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7666. begin
  7667. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7668. { avoid unncessary data dependency }
  7669. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7670. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7671. result:=true;
  7672. exit;
  7673. end;
  7674. Result:=OptPass1VOP(p);
  7675. end;
  7676. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7677. var
  7678. hp1 : tai;
  7679. begin
  7680. result:=false;
  7681. { replace
  7682. IMul const,%mreg1,%mreg2
  7683. Mov %reg2,%mreg3
  7684. dealloc %mreg3
  7685. by
  7686. Imul const,%mreg1,%mreg23
  7687. }
  7688. if (taicpu(p).ops=3) and
  7689. GetNextInstruction(p,hp1) and
  7690. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7691. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7692. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7693. begin
  7694. TransferUsedRegs(TmpUsedRegs);
  7695. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7696. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7697. begin
  7698. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7699. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7700. RemoveInstruction(hp1);
  7701. result:=true;
  7702. end;
  7703. end;
  7704. end;
  7705. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7706. var
  7707. hp1 : tai;
  7708. begin
  7709. result:=false;
  7710. { replace
  7711. IMul %reg0,%reg1,%reg2
  7712. Mov %reg2,%reg3
  7713. dealloc %reg2
  7714. by
  7715. Imul %reg0,%reg1,%reg3
  7716. }
  7717. if GetNextInstruction(p,hp1) and
  7718. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7719. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7720. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7721. begin
  7722. TransferUsedRegs(TmpUsedRegs);
  7723. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7724. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7725. begin
  7726. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7727. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7728. RemoveInstruction(hp1);
  7729. result:=true;
  7730. end;
  7731. end;
  7732. end;
  7733. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7734. var
  7735. hp1: tai;
  7736. begin
  7737. Result:=false;
  7738. { get rid of
  7739. (v)cvtss2sd reg0,<reg1,>reg2
  7740. (v)cvtss2sd reg2,<reg2,>reg0
  7741. }
  7742. if GetNextInstruction(p,hp1) and
  7743. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7744. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7745. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7746. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7747. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7748. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7749. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7750. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7751. )
  7752. ) then
  7753. begin
  7754. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7755. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7756. begin
  7757. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7758. RemoveCurrentP(p);
  7759. RemoveInstruction(hp1);
  7760. end
  7761. else
  7762. begin
  7763. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7764. if taicpu(hp1).opcode=A_CVTSD2SS then
  7765. begin
  7766. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7767. taicpu(p).opcode:=A_MOVAPS;
  7768. end
  7769. else
  7770. begin
  7771. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7772. taicpu(p).opcode:=A_VMOVAPS;
  7773. end;
  7774. taicpu(p).ops:=2;
  7775. RemoveInstruction(hp1);
  7776. end;
  7777. Result:=true;
  7778. Exit;
  7779. end;
  7780. end;
  7781. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7782. var
  7783. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7784. ThisReg: TRegister;
  7785. begin
  7786. Result := False;
  7787. if not GetNextInstruction(p,hp1) then
  7788. Exit;
  7789. {
  7790. convert
  7791. j<c> .L1
  7792. mov 1,reg
  7793. jmp .L2
  7794. .L1
  7795. mov 0,reg
  7796. .L2
  7797. into
  7798. mov 0,reg
  7799. set<not(c)> reg
  7800. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7801. would destroy the flag contents
  7802. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7803. executed at the same time as a previous comparison.
  7804. set<not(c)> reg
  7805. movzx reg, reg
  7806. }
  7807. if MatchInstruction(hp1,A_MOV,[]) and
  7808. (taicpu(hp1).oper[0]^.typ = top_const) and
  7809. (
  7810. (
  7811. (taicpu(hp1).oper[1]^.typ = top_reg)
  7812. {$ifdef i386}
  7813. { Under i386, ESI, EDI, EBP and ESP
  7814. don't have an 8-bit representation }
  7815. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7816. {$endif i386}
  7817. ) or (
  7818. {$ifdef i386}
  7819. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7820. {$endif i386}
  7821. (taicpu(hp1).opsize = S_B)
  7822. )
  7823. ) and
  7824. GetNextInstruction(hp1,hp2) and
  7825. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7826. GetNextInstruction(hp2,hp3) and
  7827. (hp3.typ=ait_label) and
  7828. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7829. GetNextInstruction(hp3,hp4) and
  7830. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7831. (taicpu(hp4).oper[0]^.typ = top_const) and
  7832. (
  7833. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7834. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7835. ) and
  7836. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7837. GetNextInstruction(hp4,hp5) and
  7838. (hp5.typ=ait_label) and
  7839. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7840. begin
  7841. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7842. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7843. tai_label(hp3).labsym.DecRefs;
  7844. { If this isn't the only reference to the middle label, we can
  7845. still make a saving - only that the first jump and everything
  7846. that follows will remain. }
  7847. if (tai_label(hp3).labsym.getrefs = 0) then
  7848. begin
  7849. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7850. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7851. else
  7852. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7853. { remove jump, first label and second MOV (also catching any aligns) }
  7854. repeat
  7855. if not GetNextInstruction(hp2, hp3) then
  7856. InternalError(2021040810);
  7857. RemoveInstruction(hp2);
  7858. hp2 := hp3;
  7859. until hp2 = hp5;
  7860. { Don't decrement reference count before the removal loop
  7861. above, otherwise GetNextInstruction won't stop on the
  7862. the label }
  7863. tai_label(hp5).labsym.DecRefs;
  7864. end
  7865. else
  7866. begin
  7867. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7868. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7869. else
  7870. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7871. end;
  7872. taicpu(p).opcode:=A_SETcc;
  7873. taicpu(p).opsize:=S_B;
  7874. taicpu(p).is_jmp:=False;
  7875. if taicpu(hp1).opsize=S_B then
  7876. begin
  7877. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7878. if taicpu(hp1).oper[1]^.typ = top_reg then
  7879. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7880. RemoveInstruction(hp1);
  7881. end
  7882. else
  7883. begin
  7884. { Will be a register because the size can't be S_B otherwise }
  7885. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7886. taicpu(p).loadreg(0, ThisReg);
  7887. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7888. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7889. begin
  7890. case taicpu(hp1).opsize of
  7891. S_W:
  7892. taicpu(hp1).opsize := S_BW;
  7893. S_L:
  7894. taicpu(hp1).opsize := S_BL;
  7895. {$ifdef x86_64}
  7896. S_Q:
  7897. begin
  7898. taicpu(hp1).opsize := S_BL;
  7899. { Change the destination register to 32-bit }
  7900. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7901. end;
  7902. {$endif x86_64}
  7903. else
  7904. InternalError(2021040820);
  7905. end;
  7906. taicpu(hp1).opcode := A_MOVZX;
  7907. taicpu(hp1).loadreg(0, ThisReg);
  7908. end
  7909. else
  7910. begin
  7911. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7912. { hp1 is already a MOV instruction with the correct register }
  7913. taicpu(hp1).loadconst(0, 0);
  7914. { Inserting it right before p will guarantee that the flags are also tracked }
  7915. asml.Remove(hp1);
  7916. asml.InsertBefore(hp1, p);
  7917. end;
  7918. end;
  7919. Result:=true;
  7920. exit;
  7921. end
  7922. else if (hp1.typ = ait_label) then
  7923. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7924. end;
  7925. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7926. var
  7927. hp1, hp2, hp3: tai;
  7928. SourceRef, TargetRef: TReference;
  7929. CurrentReg: TRegister;
  7930. begin
  7931. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7932. if not UseAVX then
  7933. InternalError(2021100501);
  7934. Result := False;
  7935. { Look for the following to simplify:
  7936. vmovdqa/u x(mem1), %xmmreg
  7937. vmovdqa/u %xmmreg, y(mem2)
  7938. vmovdqa/u x+16(mem1), %xmmreg
  7939. vmovdqa/u %xmmreg, y+16(mem2)
  7940. Change to:
  7941. vmovdqa/u x(mem1), %ymmreg
  7942. vmovdqa/u %ymmreg, y(mem2)
  7943. vpxor %ymmreg, %ymmreg, %ymmreg
  7944. ( The VPXOR instruction is to zero the upper half, thus removing the
  7945. need to call the potentially expensive VZEROUPPER instruction. Other
  7946. peephole optimisations can remove VPXOR if it's unnecessary )
  7947. }
  7948. TransferUsedRegs(TmpUsedRegs);
  7949. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7950. { NOTE: In the optimisations below, if the references dictate that an
  7951. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7952. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7953. if (taicpu(p).opsize = S_XMM) and
  7954. MatchOpType(taicpu(p), top_ref, top_reg) and
  7955. GetNextInstruction(p, hp1) and
  7956. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7957. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7958. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7959. begin
  7960. SourceRef := taicpu(p).oper[0]^.ref^;
  7961. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7962. if GetNextInstruction(hp1, hp2) and
  7963. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7964. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7965. begin
  7966. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7967. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7968. Inc(SourceRef.offset, 16);
  7969. { Reuse the register in the first block move }
  7970. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7971. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7972. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7973. begin
  7974. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7975. Inc(TargetRef.offset, 16);
  7976. if GetNextInstruction(hp2, hp3) and
  7977. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7978. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7979. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7980. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7981. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7982. begin
  7983. { Update the register tracking to the new size }
  7984. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7985. { Remember that the offsets are 16 ahead }
  7986. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7987. if not (
  7988. ((SourceRef.offset mod 32) = 16) and
  7989. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7990. ) then
  7991. taicpu(p).opcode := A_VMOVDQU;
  7992. taicpu(p).opsize := S_YMM;
  7993. taicpu(p).oper[1]^.reg := CurrentReg;
  7994. if not (
  7995. ((TargetRef.offset mod 32) = 16) and
  7996. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7997. ) then
  7998. taicpu(hp1).opcode := A_VMOVDQU;
  7999. taicpu(hp1).opsize := S_YMM;
  8000. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8001. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8002. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8003. if (pi_uses_ymm in current_procinfo.flags) then
  8004. RemoveInstruction(hp2)
  8005. else
  8006. begin
  8007. taicpu(hp2).opcode := A_VPXOR;
  8008. taicpu(hp2).opsize := S_YMM;
  8009. taicpu(hp2).loadreg(0, CurrentReg);
  8010. taicpu(hp2).loadreg(1, CurrentReg);
  8011. taicpu(hp2).loadreg(2, CurrentReg);
  8012. taicpu(hp2).ops := 3;
  8013. end;
  8014. RemoveInstruction(hp3);
  8015. Result := True;
  8016. Exit;
  8017. end;
  8018. end
  8019. else
  8020. begin
  8021. { See if the next references are 16 less rather than 16 greater }
  8022. Dec(SourceRef.offset, 32); { -16 the other way }
  8023. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8024. begin
  8025. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8026. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8027. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8028. GetNextInstruction(hp2, hp3) and
  8029. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8030. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8031. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8032. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8033. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8034. begin
  8035. { Update the register tracking to the new size }
  8036. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8037. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8038. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8039. if not(
  8040. ((SourceRef.offset mod 32) = 0) and
  8041. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8042. ) then
  8043. taicpu(hp2).opcode := A_VMOVDQU;
  8044. taicpu(hp2).opsize := S_YMM;
  8045. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8046. if not (
  8047. ((TargetRef.offset mod 32) = 0) and
  8048. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8049. ) then
  8050. taicpu(hp3).opcode := A_VMOVDQU;
  8051. taicpu(hp3).opsize := S_YMM;
  8052. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8053. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8054. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8055. if (pi_uses_ymm in current_procinfo.flags) then
  8056. RemoveInstruction(hp1)
  8057. else
  8058. begin
  8059. taicpu(hp1).opcode := A_VPXOR;
  8060. taicpu(hp1).opsize := S_YMM;
  8061. taicpu(hp1).loadreg(0, CurrentReg);
  8062. taicpu(hp1).loadreg(1, CurrentReg);
  8063. taicpu(hp1).loadreg(2, CurrentReg);
  8064. taicpu(hp1).ops := 3;
  8065. Asml.Remove(hp1);
  8066. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8067. end;
  8068. RemoveCurrentP(p, hp2);
  8069. Result := True;
  8070. Exit;
  8071. end;
  8072. end;
  8073. end;
  8074. end;
  8075. end;
  8076. end;
  8077. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8078. var
  8079. hp2, hp3, first_assignment: tai;
  8080. IncCount, OperIdx: Integer;
  8081. OrigLabel: TAsmLabel;
  8082. begin
  8083. Count := 0;
  8084. Result := False;
  8085. first_assignment := nil;
  8086. if (LoopCount >= 20) then
  8087. begin
  8088. { Guard against infinite loops }
  8089. Exit;
  8090. end;
  8091. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8092. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8093. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8094. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8095. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8096. Exit;
  8097. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8098. {
  8099. change
  8100. jmp .L1
  8101. ...
  8102. .L1:
  8103. mov ##, ## ( multiple movs possible )
  8104. jmp/ret
  8105. into
  8106. mov ##, ##
  8107. jmp/ret
  8108. }
  8109. if not Assigned(hp1) then
  8110. begin
  8111. hp1 := GetLabelWithSym(OrigLabel);
  8112. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8113. Exit;
  8114. end;
  8115. hp2 := hp1;
  8116. while Assigned(hp2) do
  8117. begin
  8118. if Assigned(hp2) and (hp2.typ = ait_label) then
  8119. SkipLabels(hp2,hp2);
  8120. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8121. Break;
  8122. case taicpu(hp2).opcode of
  8123. A_MOVSD:
  8124. begin
  8125. if taicpu(hp2).ops = 0 then
  8126. { Wrong MOVSD }
  8127. Break;
  8128. Inc(Count);
  8129. if Count >= 5 then
  8130. { Too many to be worthwhile }
  8131. Break;
  8132. GetNextInstruction(hp2, hp2);
  8133. Continue;
  8134. end;
  8135. A_MOV,
  8136. A_MOVD,
  8137. A_MOVQ,
  8138. A_MOVSX,
  8139. {$ifdef x86_64}
  8140. A_MOVSXD,
  8141. {$endif x86_64}
  8142. A_MOVZX,
  8143. A_MOVAPS,
  8144. A_MOVUPS,
  8145. A_MOVSS,
  8146. A_MOVAPD,
  8147. A_MOVUPD,
  8148. A_MOVDQA,
  8149. A_MOVDQU,
  8150. A_VMOVSS,
  8151. A_VMOVAPS,
  8152. A_VMOVUPS,
  8153. A_VMOVSD,
  8154. A_VMOVAPD,
  8155. A_VMOVUPD,
  8156. A_VMOVDQA,
  8157. A_VMOVDQU:
  8158. begin
  8159. Inc(Count);
  8160. if Count >= 5 then
  8161. { Too many to be worthwhile }
  8162. Break;
  8163. GetNextInstruction(hp2, hp2);
  8164. Continue;
  8165. end;
  8166. A_JMP:
  8167. begin
  8168. { Guard against infinite loops }
  8169. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8170. Exit;
  8171. { Analyse this jump first in case it also duplicates assignments }
  8172. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8173. begin
  8174. { Something did change! }
  8175. Result := True;
  8176. Inc(Count, IncCount);
  8177. if Count >= 5 then
  8178. begin
  8179. { Too many to be worthwhile }
  8180. Exit;
  8181. end;
  8182. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8183. Break;
  8184. end;
  8185. Result := True;
  8186. Break;
  8187. end;
  8188. A_RET:
  8189. begin
  8190. Result := True;
  8191. Break;
  8192. end;
  8193. else
  8194. Break;
  8195. end;
  8196. end;
  8197. if Result then
  8198. begin
  8199. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8200. if Count = 0 then
  8201. begin
  8202. Result := False;
  8203. Exit;
  8204. end;
  8205. hp3 := p;
  8206. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8207. while True do
  8208. begin
  8209. if Assigned(hp1) and (hp1.typ = ait_label) then
  8210. SkipLabels(hp1,hp1);
  8211. if (hp1.typ <> ait_instruction) then
  8212. InternalError(2021040720);
  8213. case taicpu(hp1).opcode of
  8214. A_JMP:
  8215. begin
  8216. { Change the original jump to the new destination }
  8217. OrigLabel.decrefs;
  8218. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8219. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8220. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8221. if not Assigned(first_assignment) then
  8222. InternalError(2021040810)
  8223. else
  8224. p := first_assignment;
  8225. Exit;
  8226. end;
  8227. A_RET:
  8228. begin
  8229. { Now change the jump into a RET instruction }
  8230. ConvertJumpToRET(p, hp1);
  8231. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8232. if not Assigned(first_assignment) then
  8233. InternalError(2021040811)
  8234. else
  8235. p := first_assignment;
  8236. Exit;
  8237. end;
  8238. else
  8239. begin
  8240. { Duplicate the MOV instruction }
  8241. hp3:=tai(hp1.getcopy);
  8242. if first_assignment = nil then
  8243. first_assignment := hp3;
  8244. asml.InsertBefore(hp3, p);
  8245. { Make sure the compiler knows about any final registers written here }
  8246. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8247. with taicpu(hp3).oper[OperIdx]^ do
  8248. begin
  8249. case typ of
  8250. top_ref:
  8251. begin
  8252. if (ref^.base <> NR_NO) and
  8253. (getsupreg(ref^.base) <> RS_ESP) and
  8254. (getsupreg(ref^.base) <> RS_EBP)
  8255. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8256. then
  8257. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8258. if (ref^.index <> NR_NO) and
  8259. (getsupreg(ref^.index) <> RS_ESP) and
  8260. (getsupreg(ref^.index) <> RS_EBP)
  8261. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8262. (ref^.index <> ref^.base) then
  8263. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8264. end;
  8265. top_reg:
  8266. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8267. else
  8268. ;
  8269. end;
  8270. end;
  8271. end;
  8272. end;
  8273. if not GetNextInstruction(hp1, hp1) then
  8274. { Should have dropped out earlier }
  8275. InternalError(2021040710);
  8276. end;
  8277. end;
  8278. end;
  8279. const
  8280. WriteOp: array[0..3] of set of TInsChange = (
  8281. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8282. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8283. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8284. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8285. RegWriteFlags: array[0..7] of set of TInsChange = (
  8286. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8287. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8288. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8289. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8290. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8291. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8292. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8293. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8294. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8295. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8296. var
  8297. hp2: tai;
  8298. X: Integer;
  8299. begin
  8300. { If we have something like:
  8301. op ###,###
  8302. mov ###,###
  8303. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8304. interfere in regards to what they write to.
  8305. NOTE: p must be a 2-operand instruction
  8306. }
  8307. Result := False;
  8308. if (hp1.typ <> ait_instruction) or
  8309. taicpu(hp1).is_jmp or
  8310. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8311. Exit;
  8312. { NOP is a pipeline fence, likely marking the beginning of the function
  8313. epilogue, so drop out. Similarly, drop out if POP or RET are
  8314. encountered }
  8315. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8316. Exit;
  8317. if (taicpu(hp1).opcode = A_MOVSD) and
  8318. (taicpu(hp1).ops = 0) then
  8319. { Wrong MOVSD }
  8320. Exit;
  8321. { Check for writes to specific registers first }
  8322. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8323. for X := 0 to 7 do
  8324. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8325. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8326. Exit;
  8327. for X := 0 to taicpu(hp1).ops - 1 do
  8328. begin
  8329. { Check to see if this operand writes to something }
  8330. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8331. { And matches something in the CMP/TEST instruction }
  8332. (
  8333. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8334. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8335. (
  8336. { If it's a register, make sure the register written to doesn't
  8337. appear in the cmp instruction as part of a reference }
  8338. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8339. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8340. )
  8341. ) then
  8342. Exit;
  8343. end;
  8344. { Check p to make sure it doesn't write to something that affects hp1 }
  8345. { Check for writes to specific registers first }
  8346. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8347. for X := 0 to 7 do
  8348. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8349. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8350. Exit;
  8351. for X := 0 to taicpu(p).ops - 1 do
  8352. begin
  8353. { Check to see if this operand writes to something }
  8354. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8355. { And matches something in hp1 }
  8356. (taicpu(p).oper[X]^.typ = top_reg) and
  8357. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8358. Exit;
  8359. end;
  8360. { The instruction can be safely moved }
  8361. asml.Remove(hp1);
  8362. { Try to insert after the last instructions where the FLAGS register is not
  8363. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8364. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8365. asml.InsertBefore(hp1, hp2)
  8366. { Failing that, try to insert after the last instructions where the
  8367. FLAGS register is not yet in use }
  8368. else if GetLastInstruction(p, hp2) and
  8369. (
  8370. (hp2.typ <> ait_instruction) or
  8371. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8372. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8373. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8374. ) then
  8375. asml.InsertAfter(hp1, hp2)
  8376. else
  8377. { Note, if p.Previous is nil (even if it should logically never be the
  8378. case), FindRegAllocBackward immediately exits with False and so we
  8379. safely land here (we can't just pass p because FindRegAllocBackward
  8380. immediately exits on an instruction). [Kit] }
  8381. asml.InsertBefore(hp1, p);
  8382. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8383. { We can't trust UsedRegs because we're looking backwards, although we
  8384. know the registers are allocated after p at the very least, so manually
  8385. create tai_regalloc objects if needed }
  8386. for X := 0 to taicpu(hp1).ops - 1 do
  8387. case taicpu(hp1).oper[X]^.typ of
  8388. top_reg:
  8389. begin
  8390. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8391. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8392. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8393. end;
  8394. top_ref:
  8395. begin
  8396. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8397. begin
  8398. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8399. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8400. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8401. end;
  8402. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8403. begin
  8404. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8405. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8406. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8407. end;
  8408. end;
  8409. else
  8410. ;
  8411. end;
  8412. Result := True;
  8413. end;
  8414. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8415. var
  8416. hp2: tai;
  8417. X: Integer;
  8418. begin
  8419. { If we have something like:
  8420. cmp ###,%reg1
  8421. mov 0,%reg2
  8422. And no modified registers are shared, move the instruction to before
  8423. the comparison as this means it can be optimised without worrying
  8424. about the FLAGS register. (CMP/MOV is generated by
  8425. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8426. As long as the second instruction doesn't use the flags or one of the
  8427. registers used by CMP or TEST (also check any references that use the
  8428. registers), then it can be moved prior to the comparison.
  8429. }
  8430. Result := False;
  8431. if not TrySwapMovOp(p, hp1) then
  8432. Exit;
  8433. if taicpu(hp1).opcode = A_LEA then
  8434. { The flags will be overwritten by the CMP/TEST instruction }
  8435. ConvertLEA(taicpu(hp1));
  8436. Result := True;
  8437. { Can we move it one further back? }
  8438. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8439. { Check to see if CMP/TEST is a comparison against zero }
  8440. (
  8441. (
  8442. (taicpu(p).opcode = A_CMP) and
  8443. MatchOperand(taicpu(p).oper[0]^, 0)
  8444. ) or
  8445. (
  8446. (taicpu(p).opcode = A_TEST) and
  8447. (
  8448. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8449. MatchOperand(taicpu(p).oper[0]^, -1)
  8450. )
  8451. )
  8452. ) and
  8453. { These instructions set the zero flag if the result is zero }
  8454. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8455. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8456. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8457. TrySwapMovOp(hp2, hp1);
  8458. end;
  8459. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8460. function IsXCHGAcceptable: Boolean; inline;
  8461. begin
  8462. { Always accept if optimising for size }
  8463. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8464. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8465. than 3, so it becomes a saving compared to three MOVs with two of
  8466. them able to execute simultaneously. [Kit] }
  8467. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8468. end;
  8469. var
  8470. NewRef: TReference;
  8471. hp1, hp2, hp3, hp4: Tai;
  8472. {$ifndef x86_64}
  8473. OperIdx: Integer;
  8474. {$endif x86_64}
  8475. NewInstr : Taicpu;
  8476. NewAligh : Tai_align;
  8477. DestLabel: TAsmLabel;
  8478. TempTracking: TAllUsedRegs;
  8479. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8480. var
  8481. NextInstr: tai;
  8482. begin
  8483. Result := False;
  8484. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8485. if not GetNextInstruction(InputInstr, NextInstr) or
  8486. (
  8487. { The FLAGS register isn't always tracked properly, so do not
  8488. perform this optimisation if a conditional statement follows }
  8489. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8490. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8491. ) then
  8492. begin
  8493. reference_reset(NewRef, 1, []);
  8494. NewRef.base := taicpu(p).oper[0]^.reg;
  8495. NewRef.scalefactor := 1;
  8496. if taicpu(InputInstr).opcode = A_ADD then
  8497. begin
  8498. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8499. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8500. end
  8501. else
  8502. begin
  8503. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8504. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8505. end;
  8506. taicpu(p).opcode := A_LEA;
  8507. taicpu(p).loadref(0, NewRef);
  8508. RemoveInstruction(InputInstr);
  8509. Result := True;
  8510. end;
  8511. end;
  8512. begin
  8513. Result:=false;
  8514. { This optimisation adds an instruction, so only do it for speed }
  8515. if not (cs_opt_size in current_settings.optimizerswitches) and
  8516. MatchOpType(taicpu(p), top_const, top_reg) and
  8517. (taicpu(p).oper[0]^.val = 0) then
  8518. begin
  8519. { To avoid compiler warning }
  8520. DestLabel := nil;
  8521. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8522. InternalError(2021040750);
  8523. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8524. Exit;
  8525. case hp1.typ of
  8526. ait_label:
  8527. begin
  8528. { Change:
  8529. mov $0,%reg mov $0,%reg
  8530. @Lbl1: @Lbl1:
  8531. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8532. je @Lbl2 jne @Lbl2
  8533. To: To:
  8534. mov $0,%reg mov $0,%reg
  8535. jmp @Lbl2 jmp @Lbl3
  8536. (align) (align)
  8537. @Lbl1: @Lbl1:
  8538. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8539. je @Lbl2 je @Lbl2
  8540. @Lbl3: <-- Only if label exists
  8541. (Not if it's optimised for size)
  8542. }
  8543. if not GetNextInstruction(hp1, hp2) then
  8544. Exit;
  8545. if (hp2.typ = ait_instruction) and
  8546. (
  8547. { Register sizes must exactly match }
  8548. (
  8549. (taicpu(hp2).opcode = A_CMP) and
  8550. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8551. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8552. ) or (
  8553. (taicpu(hp2).opcode = A_TEST) and
  8554. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8555. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8556. )
  8557. ) and GetNextInstruction(hp2, hp3) and
  8558. (hp3.typ = ait_instruction) and
  8559. (taicpu(hp3).opcode = A_JCC) and
  8560. (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
  8561. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8562. begin
  8563. { Check condition of jump }
  8564. { Always true? }
  8565. if condition_in(C_E, taicpu(hp3).condition) then
  8566. begin
  8567. { Copy label symbol and obtain matching label entry for the
  8568. conditional jump, as this will be our destination}
  8569. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8570. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8571. Result := True;
  8572. end
  8573. { Always false? }
  8574. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8575. begin
  8576. { This is only worth it if there's a jump to take }
  8577. case hp2.typ of
  8578. ait_instruction:
  8579. begin
  8580. if taicpu(hp2).opcode = A_JMP then
  8581. begin
  8582. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8583. { An unconditional jump follows the conditional jump which will always be false,
  8584. so use this jump's destination for the new jump }
  8585. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8586. Result := True;
  8587. end
  8588. else if taicpu(hp2).opcode = A_JCC then
  8589. begin
  8590. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8591. if condition_in(C_E, taicpu(hp2).condition) then
  8592. begin
  8593. { A second conditional jump follows the conditional jump which will always be false,
  8594. while the second jump is always True, so use this jump's destination for the new jump }
  8595. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8596. Result := True;
  8597. end;
  8598. { Don't risk it if the jump isn't always true (Result remains False) }
  8599. end;
  8600. end;
  8601. else
  8602. { If anything else don't optimise };
  8603. end;
  8604. end;
  8605. if Result then
  8606. begin
  8607. { Just so we have something to insert as a paremeter}
  8608. reference_reset(NewRef, 1, []);
  8609. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8610. { Now actually load the correct parameter (this also
  8611. increases the reference count) }
  8612. NewInstr.loadsymbol(0, DestLabel, 0);
  8613. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8614. begin
  8615. { Get instruction before original label (may not be p under -O3) }
  8616. if not GetLastInstruction(hp1, hp2) then
  8617. { Shouldn't fail here }
  8618. InternalError(2021040701);
  8619. end
  8620. else
  8621. hp2 := p;
  8622. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8623. AsmL.InsertAfter(NewInstr, hp2);
  8624. { Add new alignment field }
  8625. (* AsmL.InsertAfter(
  8626. cai_align.create_max(
  8627. current_settings.alignment.jumpalign,
  8628. current_settings.alignment.jumpalignskipmax
  8629. ),
  8630. NewInstr
  8631. ); *)
  8632. end;
  8633. Exit;
  8634. end;
  8635. end;
  8636. else
  8637. ;
  8638. end;
  8639. end;
  8640. if not GetNextInstruction(p, hp1) then
  8641. Exit;
  8642. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8643. and DoMovCmpMemOpt(p, hp1) then
  8644. begin
  8645. Result := True;
  8646. Exit;
  8647. end
  8648. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8649. begin
  8650. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8651. further, but we can't just put this jump optimisation in pass 1
  8652. because it tends to perform worse when conditional jumps are
  8653. nearby (e.g. when converting CMOV instructions). [Kit] }
  8654. CopyUsedRegs(TempTracking);
  8655. UpdateUsedRegs(tai(p.Next));
  8656. if OptPass2JMP(hp1) then
  8657. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8658. Result := OptPass1MOV(p);
  8659. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8660. returned True and the instruction is still a MOV, thus checking
  8661. the optimisations below }
  8662. { If OptPass2JMP returned False, no optimisations were done to
  8663. the jump and there are no further optimisations that can be done
  8664. to the MOV instruction on this pass }
  8665. { Restore register state }
  8666. RestoreUsedRegs(TempTracking);
  8667. ReleaseUsedRegs(TempTracking);
  8668. end
  8669. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8670. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8671. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8672. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8673. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8674. begin
  8675. { Change:
  8676. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8677. addl/q $x,%reg2 subl/q $x,%reg2
  8678. To:
  8679. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8680. }
  8681. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8682. { be lazy, checking separately for sub would be slightly better }
  8683. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8684. begin
  8685. TransferUsedRegs(TmpUsedRegs);
  8686. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8687. if TryMovArith2Lea(hp1) then
  8688. begin
  8689. Result := True;
  8690. Exit;
  8691. end
  8692. end
  8693. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8694. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8695. { Same as above, but also adds or subtracts to %reg2 in between.
  8696. It's still valid as long as the flags aren't in use }
  8697. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8698. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8699. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8700. { be lazy, checking separately for sub would be slightly better }
  8701. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8702. begin
  8703. TransferUsedRegs(TmpUsedRegs);
  8704. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8705. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8706. if TryMovArith2Lea(hp2) then
  8707. begin
  8708. Result := True;
  8709. Exit;
  8710. end;
  8711. end;
  8712. end
  8713. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8714. {$ifdef x86_64}
  8715. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8716. {$else x86_64}
  8717. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8718. {$endif x86_64}
  8719. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8720. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8721. { mov reg1, reg2 mov reg1, reg2
  8722. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8723. begin
  8724. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8725. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8726. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8727. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8728. TransferUsedRegs(TmpUsedRegs);
  8729. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8730. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8731. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8732. then
  8733. begin
  8734. RemoveCurrentP(p, hp1);
  8735. Result:=true;
  8736. end;
  8737. exit;
  8738. end
  8739. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8740. IsXCHGAcceptable and
  8741. { XCHG doesn't support 8-byte registers }
  8742. (taicpu(p).opsize <> S_B) and
  8743. MatchInstruction(hp1, A_MOV, []) and
  8744. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8745. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8746. GetNextInstruction(hp1, hp2) and
  8747. MatchInstruction(hp2, A_MOV, []) and
  8748. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8749. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8750. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8751. begin
  8752. { mov %reg1,%reg2
  8753. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8754. mov %reg2,%reg3
  8755. (%reg2 not used afterwards)
  8756. Note that xchg takes 3 cycles to execute, and generally mov's take
  8757. only one cycle apiece, but the first two mov's can be executed in
  8758. parallel, only taking 2 cycles overall. Older processors should
  8759. therefore only optimise for size. [Kit]
  8760. }
  8761. TransferUsedRegs(TmpUsedRegs);
  8762. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8763. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8764. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8765. begin
  8766. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8767. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8768. taicpu(hp1).opcode := A_XCHG;
  8769. RemoveCurrentP(p, hp1);
  8770. RemoveInstruction(hp2);
  8771. Result := True;
  8772. Exit;
  8773. end;
  8774. end
  8775. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8776. MatchInstruction(hp1, A_SAR, []) then
  8777. begin
  8778. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8779. begin
  8780. { the use of %edx also covers the opsize being S_L }
  8781. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8782. begin
  8783. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8784. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8785. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8786. begin
  8787. { Change:
  8788. movl %eax,%edx
  8789. sarl $31,%edx
  8790. To:
  8791. cltd
  8792. }
  8793. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8794. RemoveInstruction(hp1);
  8795. taicpu(p).opcode := A_CDQ;
  8796. taicpu(p).opsize := S_NO;
  8797. taicpu(p).clearop(1);
  8798. taicpu(p).clearop(0);
  8799. taicpu(p).ops:=0;
  8800. Result := True;
  8801. end
  8802. else if (cs_opt_size in current_settings.optimizerswitches) and
  8803. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8804. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8805. begin
  8806. { Change:
  8807. movl %edx,%eax
  8808. sarl $31,%edx
  8809. To:
  8810. movl %edx,%eax
  8811. cltd
  8812. Note that this creates a dependency between the two instructions,
  8813. so only perform if optimising for size.
  8814. }
  8815. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8816. taicpu(hp1).opcode := A_CDQ;
  8817. taicpu(hp1).opsize := S_NO;
  8818. taicpu(hp1).clearop(1);
  8819. taicpu(hp1).clearop(0);
  8820. taicpu(hp1).ops:=0;
  8821. end;
  8822. {$ifndef x86_64}
  8823. end
  8824. { Don't bother if CMOV is supported, because a more optimal
  8825. sequence would have been generated for the Abs() intrinsic }
  8826. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8827. { the use of %eax also covers the opsize being S_L }
  8828. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8829. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8830. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8831. GetNextInstruction(hp1, hp2) and
  8832. MatchInstruction(hp2, A_XOR, [S_L]) and
  8833. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8834. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8835. GetNextInstruction(hp2, hp3) and
  8836. MatchInstruction(hp3, A_SUB, [S_L]) and
  8837. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8838. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8839. begin
  8840. { Change:
  8841. movl %eax,%edx
  8842. sarl $31,%eax
  8843. xorl %eax,%edx
  8844. subl %eax,%edx
  8845. (Instruction that uses %edx)
  8846. (%eax deallocated)
  8847. (%edx deallocated)
  8848. To:
  8849. cltd
  8850. xorl %edx,%eax <-- Note the registers have swapped
  8851. subl %edx,%eax
  8852. (Instruction that uses %eax) <-- %eax rather than %edx
  8853. }
  8854. TransferUsedRegs(TmpUsedRegs);
  8855. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8856. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8857. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8858. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8859. begin
  8860. if GetNextInstruction(hp3, hp4) and
  8861. not RegModifiedByInstruction(NR_EDX, hp4) and
  8862. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8863. begin
  8864. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8865. taicpu(p).opcode := A_CDQ;
  8866. taicpu(p).clearop(1);
  8867. taicpu(p).clearop(0);
  8868. taicpu(p).ops:=0;
  8869. RemoveInstruction(hp1);
  8870. taicpu(hp2).loadreg(0, NR_EDX);
  8871. taicpu(hp2).loadreg(1, NR_EAX);
  8872. taicpu(hp3).loadreg(0, NR_EDX);
  8873. taicpu(hp3).loadreg(1, NR_EAX);
  8874. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8875. { Convert references in the following instruction (hp4) from %edx to %eax }
  8876. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8877. with taicpu(hp4).oper[OperIdx]^ do
  8878. case typ of
  8879. top_reg:
  8880. if getsupreg(reg) = RS_EDX then
  8881. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8882. top_ref:
  8883. begin
  8884. if getsupreg(reg) = RS_EDX then
  8885. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8886. if getsupreg(reg) = RS_EDX then
  8887. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8888. end;
  8889. else
  8890. ;
  8891. end;
  8892. end;
  8893. end;
  8894. {$else x86_64}
  8895. end;
  8896. end
  8897. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8898. { the use of %rdx also covers the opsize being S_Q }
  8899. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8900. begin
  8901. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8902. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8903. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8904. begin
  8905. { Change:
  8906. movq %rax,%rdx
  8907. sarq $63,%rdx
  8908. To:
  8909. cqto
  8910. }
  8911. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8912. RemoveInstruction(hp1);
  8913. taicpu(p).opcode := A_CQO;
  8914. taicpu(p).opsize := S_NO;
  8915. taicpu(p).clearop(1);
  8916. taicpu(p).clearop(0);
  8917. taicpu(p).ops:=0;
  8918. Result := True;
  8919. end
  8920. else if (cs_opt_size in current_settings.optimizerswitches) and
  8921. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8922. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8923. begin
  8924. { Change:
  8925. movq %rdx,%rax
  8926. sarq $63,%rdx
  8927. To:
  8928. movq %rdx,%rax
  8929. cqto
  8930. Note that this creates a dependency between the two instructions,
  8931. so only perform if optimising for size.
  8932. }
  8933. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8934. taicpu(hp1).opcode := A_CQO;
  8935. taicpu(hp1).opsize := S_NO;
  8936. taicpu(hp1).clearop(1);
  8937. taicpu(hp1).clearop(0);
  8938. taicpu(hp1).ops:=0;
  8939. {$endif x86_64}
  8940. end;
  8941. end;
  8942. end
  8943. else if MatchInstruction(hp1, A_MOV, []) and
  8944. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8945. { Though "GetNextInstruction" could be factored out, along with
  8946. the instructions that depend on hp2, it is an expensive call that
  8947. should be delayed for as long as possible, hence we do cheaper
  8948. checks first that are likely to be False. [Kit] }
  8949. begin
  8950. if (
  8951. (
  8952. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8953. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8954. (
  8955. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8956. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8957. )
  8958. ) or
  8959. (
  8960. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8961. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8962. (
  8963. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8964. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8965. )
  8966. )
  8967. ) and
  8968. GetNextInstruction(hp1, hp2) and
  8969. MatchInstruction(hp2, A_SAR, []) and
  8970. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8971. begin
  8972. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8973. begin
  8974. { Change:
  8975. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8976. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8977. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8978. To:
  8979. movl r/m,%eax <- Note the change in register
  8980. cltd
  8981. }
  8982. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8983. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8984. taicpu(p).loadreg(1, NR_EAX);
  8985. taicpu(hp1).opcode := A_CDQ;
  8986. taicpu(hp1).clearop(1);
  8987. taicpu(hp1).clearop(0);
  8988. taicpu(hp1).ops:=0;
  8989. RemoveInstruction(hp2);
  8990. (*
  8991. {$ifdef x86_64}
  8992. end
  8993. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8994. { This code sequence does not get generated - however it might become useful
  8995. if and when 128-bit signed integer types make an appearance, so the code
  8996. is kept here for when it is eventually needed. [Kit] }
  8997. (
  8998. (
  8999. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9000. (
  9001. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9002. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9003. )
  9004. ) or
  9005. (
  9006. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9007. (
  9008. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9009. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9010. )
  9011. )
  9012. ) and
  9013. GetNextInstruction(hp1, hp2) and
  9014. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9015. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9016. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9017. begin
  9018. { Change:
  9019. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9020. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9021. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9022. To:
  9023. movq r/m,%rax <- Note the change in register
  9024. cqto
  9025. }
  9026. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9027. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9028. taicpu(p).loadreg(1, NR_RAX);
  9029. taicpu(hp1).opcode := A_CQO;
  9030. taicpu(hp1).clearop(1);
  9031. taicpu(hp1).clearop(0);
  9032. taicpu(hp1).ops:=0;
  9033. RemoveInstruction(hp2);
  9034. {$endif x86_64}
  9035. *)
  9036. end;
  9037. end;
  9038. {$ifdef x86_64}
  9039. end
  9040. else if (taicpu(p).opsize = S_L) and
  9041. (taicpu(p).oper[1]^.typ = top_reg) and
  9042. (
  9043. MatchInstruction(hp1, A_MOV,[]) and
  9044. (taicpu(hp1).opsize = S_L) and
  9045. (taicpu(hp1).oper[1]^.typ = top_reg)
  9046. ) and (
  9047. GetNextInstruction(hp1, hp2) and
  9048. (tai(hp2).typ=ait_instruction) and
  9049. (taicpu(hp2).opsize = S_Q) and
  9050. (
  9051. (
  9052. MatchInstruction(hp2, A_ADD,[]) and
  9053. (taicpu(hp2).opsize = S_Q) and
  9054. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9055. (
  9056. (
  9057. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9058. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9059. ) or (
  9060. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9061. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9062. )
  9063. )
  9064. ) or (
  9065. MatchInstruction(hp2, A_LEA,[]) and
  9066. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9067. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9068. (
  9069. (
  9070. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9071. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9072. ) or (
  9073. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9074. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9075. )
  9076. ) and (
  9077. (
  9078. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9079. ) or (
  9080. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9081. )
  9082. )
  9083. )
  9084. )
  9085. ) and (
  9086. GetNextInstruction(hp2, hp3) and
  9087. MatchInstruction(hp3, A_SHR,[]) and
  9088. (taicpu(hp3).opsize = S_Q) and
  9089. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9090. (taicpu(hp3).oper[0]^.val = 1) and
  9091. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9092. ) then
  9093. begin
  9094. { Change movl x, reg1d movl x, reg1d
  9095. movl y, reg2d movl y, reg2d
  9096. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9097. shrq $1, reg1q shrq $1, reg1q
  9098. ( reg1d and reg2d can be switched around in the first two instructions )
  9099. To movl x, reg1d
  9100. addl y, reg1d
  9101. rcrl $1, reg1d
  9102. This corresponds to the common expression (x + y) shr 1, where
  9103. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9104. smaller code, but won't account for x + y causing an overflow). [Kit]
  9105. }
  9106. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9107. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9108. { Change first MOV command to have the same register as the final output }
  9109. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9110. else
  9111. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9112. { Change second MOV command to an ADD command. This is easier than
  9113. converting the existing command because it means we don't have to
  9114. touch 'y', which might be a complicated reference, and also the
  9115. fact that the third command might either be ADD or LEA. [Kit] }
  9116. taicpu(hp1).opcode := A_ADD;
  9117. { Delete old ADD/LEA instruction }
  9118. RemoveInstruction(hp2);
  9119. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9120. taicpu(hp3).opcode := A_RCR;
  9121. taicpu(hp3).changeopsize(S_L);
  9122. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9123. {$endif x86_64}
  9124. end;
  9125. if FuncMov2Func(p, hp1) then
  9126. begin
  9127. Result := True;
  9128. Exit;
  9129. end;
  9130. end;
  9131. {$push}
  9132. {$q-}{$r-}
  9133. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9134. var
  9135. ThisReg: TRegister;
  9136. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9137. TargetSubReg: TSubRegister;
  9138. hp1, hp2: tai;
  9139. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9140. { Store list of found instructions so we don't have to call
  9141. GetNextInstructionUsingReg multiple times }
  9142. InstrList: array of taicpu;
  9143. InstrMax, Index: Integer;
  9144. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9145. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9146. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9147. WorkingValue: TCgInt;
  9148. PreMessage: string;
  9149. { Data flow analysis }
  9150. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9151. BitwiseOnly, OrXorUsed,
  9152. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9153. function CheckOverflowConditions: Boolean;
  9154. begin
  9155. Result := True;
  9156. if (TestValSignedMax > SignedUpperLimit) then
  9157. UpperSignedOverflow := True;
  9158. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9159. LowerSignedOverflow := True;
  9160. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9161. LowerUnsignedOverflow := True;
  9162. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9163. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9164. begin
  9165. { Absolute overflow }
  9166. Result := False;
  9167. Exit;
  9168. end;
  9169. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9170. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9171. ShiftDownOverflow := True;
  9172. if (TestValMin < 0) or (TestValMax < 0) then
  9173. begin
  9174. LowerUnsignedOverflow := True;
  9175. UpperUnsignedOverflow := True;
  9176. end;
  9177. end;
  9178. function AdjustInitialLoadAndSize: Boolean;
  9179. begin
  9180. Result := False;
  9181. if not p_removed then
  9182. begin
  9183. if TargetSize = MinSize then
  9184. begin
  9185. { Convert the input MOVZX to a MOV }
  9186. if (taicpu(p).oper[0]^.typ = top_reg) and
  9187. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9188. begin
  9189. { Or remove it completely! }
  9190. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9191. RemoveCurrentP(p);
  9192. p_removed := True;
  9193. end
  9194. else
  9195. begin
  9196. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9197. taicpu(p).opcode := A_MOV;
  9198. taicpu(p).oper[1]^.reg := ThisReg;
  9199. taicpu(p).opsize := TargetSize;
  9200. end;
  9201. Result := True;
  9202. end
  9203. else if TargetSize <> MaxSize then
  9204. begin
  9205. case MaxSize of
  9206. S_L:
  9207. if TargetSize = S_W then
  9208. begin
  9209. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9210. taicpu(p).opsize := S_BW;
  9211. taicpu(p).oper[1]^.reg := ThisReg;
  9212. Result := True;
  9213. end
  9214. else
  9215. InternalError(2020112341);
  9216. S_W:
  9217. if TargetSize = S_L then
  9218. begin
  9219. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9220. taicpu(p).opsize := S_BL;
  9221. taicpu(p).oper[1]^.reg := ThisReg;
  9222. Result := True;
  9223. end
  9224. else
  9225. InternalError(2020112342);
  9226. else
  9227. ;
  9228. end;
  9229. end
  9230. else if not hp1_removed and not RegInUse then
  9231. begin
  9232. { If we have something like:
  9233. movzbl (oper),%regd
  9234. add x, %regd
  9235. movzbl %regb, %regd
  9236. We can reduce the register size to the input of the final
  9237. movzbl instruction. Overflows won't have any effect.
  9238. }
  9239. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9240. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9241. begin
  9242. TargetSize := S_B;
  9243. setsubreg(ThisReg, R_SUBL);
  9244. Result := True;
  9245. end
  9246. else if (taicpu(p).opsize = S_WL) and
  9247. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9248. begin
  9249. TargetSize := S_W;
  9250. setsubreg(ThisReg, R_SUBW);
  9251. Result := True;
  9252. end;
  9253. if Result then
  9254. begin
  9255. { Convert the input MOVZX to a MOV }
  9256. if (taicpu(p).oper[0]^.typ = top_reg) and
  9257. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9258. begin
  9259. { Or remove it completely! }
  9260. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9261. RemoveCurrentP(p);
  9262. p_removed := True;
  9263. end
  9264. else
  9265. begin
  9266. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9267. taicpu(p).opcode := A_MOV;
  9268. taicpu(p).oper[1]^.reg := ThisReg;
  9269. taicpu(p).opsize := TargetSize;
  9270. end;
  9271. end;
  9272. end;
  9273. end;
  9274. end;
  9275. procedure AdjustFinalLoad;
  9276. begin
  9277. if not LowerUnsignedOverflow then
  9278. begin
  9279. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9280. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9281. begin
  9282. { Convert the output MOVZX to a MOV }
  9283. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9284. begin
  9285. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9286. if (MinSize = S_B) or
  9287. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9288. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9289. begin
  9290. { Remove it completely! }
  9291. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9292. { Be careful; if p = hp1 and p was also removed, p
  9293. will become a dangling pointer }
  9294. if p = hp1 then
  9295. begin
  9296. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9297. p_removed := True;
  9298. end
  9299. else
  9300. RemoveInstruction(hp1);
  9301. hp1_removed := True;
  9302. end;
  9303. end
  9304. else
  9305. begin
  9306. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9307. taicpu(hp1).opcode := A_MOV;
  9308. taicpu(hp1).oper[0]^.reg := ThisReg;
  9309. taicpu(hp1).opsize := TargetSize;
  9310. end;
  9311. end
  9312. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9313. begin
  9314. { Need to change the size of the output }
  9315. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9316. taicpu(hp1).oper[0]^.reg := ThisReg;
  9317. taicpu(hp1).opsize := S_BL;
  9318. end;
  9319. end;
  9320. end;
  9321. function CompressInstructions: Boolean;
  9322. var
  9323. LocalIndex: Integer;
  9324. begin
  9325. Result := False;
  9326. { The objective here is to try to find a combination that
  9327. removes one of the MOV/Z instructions. }
  9328. if (
  9329. (taicpu(p).oper[0]^.typ <> top_reg) or
  9330. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9331. ) and
  9332. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9333. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9334. begin
  9335. { Make a preference to remove the second MOVZX instruction }
  9336. case taicpu(hp1).opsize of
  9337. S_BL, S_WL:
  9338. begin
  9339. TargetSize := S_L;
  9340. TargetSubReg := R_SUBD;
  9341. end;
  9342. S_BW:
  9343. begin
  9344. TargetSize := S_W;
  9345. TargetSubReg := R_SUBW;
  9346. end;
  9347. else
  9348. InternalError(2020112302);
  9349. end;
  9350. end
  9351. else
  9352. begin
  9353. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9354. begin
  9355. { Exceeded lower bound but not upper bound }
  9356. TargetSize := MaxSize;
  9357. end
  9358. else if not LowerUnsignedOverflow then
  9359. begin
  9360. { Size didn't exceed lower bound }
  9361. TargetSize := MinSize;
  9362. end
  9363. else
  9364. Exit;
  9365. end;
  9366. case TargetSize of
  9367. S_B:
  9368. TargetSubReg := R_SUBL;
  9369. S_W:
  9370. TargetSubReg := R_SUBW;
  9371. S_L:
  9372. TargetSubReg := R_SUBD;
  9373. else
  9374. InternalError(2020112350);
  9375. end;
  9376. { Update the register to its new size }
  9377. setsubreg(ThisReg, TargetSubReg);
  9378. RegInUse := False;
  9379. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9380. begin
  9381. { Check to see if the active register is used afterwards;
  9382. if not, we can change it and make a saving. }
  9383. TransferUsedRegs(TmpUsedRegs);
  9384. { The target register may be marked as in use to cross
  9385. a jump to a distant label, so exclude it }
  9386. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9387. hp2 := p;
  9388. repeat
  9389. { Explicitly check for the excluded register (don't include the first
  9390. instruction as it may be reading from here }
  9391. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9392. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9393. begin
  9394. RegInUse := True;
  9395. Break;
  9396. end;
  9397. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9398. if not GetNextInstruction(hp2, hp2) then
  9399. InternalError(2020112340);
  9400. until (hp2 = hp1);
  9401. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9402. { We might still be able to get away with this }
  9403. RegInUse := not
  9404. (
  9405. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9406. (hp2.typ = ait_instruction) and
  9407. (
  9408. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9409. instruction that doesn't actually contain ThisReg }
  9410. (cs_opt_level3 in current_settings.optimizerswitches) or
  9411. RegInInstruction(ThisReg, hp2)
  9412. ) and
  9413. RegLoadedWithNewValue(ThisReg, hp2)
  9414. );
  9415. if not RegInUse then
  9416. begin
  9417. { Force the register size to the same as this instruction so it can be removed}
  9418. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9419. begin
  9420. TargetSize := S_L;
  9421. TargetSubReg := R_SUBD;
  9422. end
  9423. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9424. begin
  9425. TargetSize := S_W;
  9426. TargetSubReg := R_SUBW;
  9427. end;
  9428. ThisReg := taicpu(hp1).oper[1]^.reg;
  9429. setsubreg(ThisReg, TargetSubReg);
  9430. RegChanged := True;
  9431. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9432. TransferUsedRegs(TmpUsedRegs);
  9433. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9434. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9435. if p = hp1 then
  9436. begin
  9437. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9438. p_removed := True;
  9439. end
  9440. else
  9441. RemoveInstruction(hp1);
  9442. hp1_removed := True;
  9443. { Instruction will become "mov %reg,%reg" }
  9444. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9445. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9446. begin
  9447. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9448. RemoveCurrentP(p);
  9449. p_removed := True;
  9450. end
  9451. else
  9452. taicpu(p).oper[1]^.reg := ThisReg;
  9453. Result := True;
  9454. end
  9455. else
  9456. begin
  9457. if TargetSize <> MaxSize then
  9458. begin
  9459. { Since the register is in use, we have to force it to
  9460. MaxSize otherwise part of it may become undefined later on }
  9461. TargetSize := MaxSize;
  9462. case TargetSize of
  9463. S_B:
  9464. TargetSubReg := R_SUBL;
  9465. S_W:
  9466. TargetSubReg := R_SUBW;
  9467. S_L:
  9468. TargetSubReg := R_SUBD;
  9469. else
  9470. InternalError(2020112351);
  9471. end;
  9472. setsubreg(ThisReg, TargetSubReg);
  9473. end;
  9474. AdjustFinalLoad;
  9475. end;
  9476. end
  9477. else
  9478. AdjustFinalLoad;
  9479. Result := AdjustInitialLoadAndSize or Result;
  9480. { Now go through every instruction we found and change the
  9481. size. If TargetSize = MaxSize, then almost no changes are
  9482. needed and Result can remain False if it hasn't been set
  9483. yet.
  9484. If RegChanged is True, then the register requires changing
  9485. and so the point about TargetSize = MaxSize doesn't apply. }
  9486. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9487. begin
  9488. for LocalIndex := 0 to InstrMax do
  9489. begin
  9490. { If p_removed is true, then the original MOV/Z was removed
  9491. and removing the AND instruction may not be safe if it
  9492. appears first }
  9493. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9494. InternalError(2020112310);
  9495. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9496. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9497. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9498. InstrList[LocalIndex].opsize := TargetSize;
  9499. end;
  9500. Result := True;
  9501. end;
  9502. end;
  9503. begin
  9504. Result := False;
  9505. p_removed := False;
  9506. hp1_removed := False;
  9507. ThisReg := taicpu(p).oper[1]^.reg;
  9508. { Check for:
  9509. movs/z ###,%ecx (or %cx or %rcx)
  9510. ...
  9511. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9512. (dealloc %ecx)
  9513. Change to:
  9514. mov ###,%cl (if ### = %cl, then remove completely)
  9515. ...
  9516. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9517. }
  9518. if (getsupreg(ThisReg) = RS_ECX) and
  9519. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9520. (hp1.typ = ait_instruction) and
  9521. (
  9522. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9523. instruction that doesn't actually contain ECX }
  9524. (cs_opt_level3 in current_settings.optimizerswitches) or
  9525. RegInInstruction(NR_ECX, hp1) or
  9526. (
  9527. { It's common for the shift/rotate's read/write register to be
  9528. initialised in between, so under -O2 and under, search ahead
  9529. one more instruction
  9530. }
  9531. GetNextInstruction(hp1, hp1) and
  9532. (hp1.typ = ait_instruction) and
  9533. RegInInstruction(NR_ECX, hp1)
  9534. )
  9535. ) and
  9536. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9537. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9538. begin
  9539. TransferUsedRegs(TmpUsedRegs);
  9540. hp2 := p;
  9541. repeat
  9542. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9543. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9544. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9545. begin
  9546. case taicpu(p).opsize of
  9547. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9548. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9549. begin
  9550. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9551. RemoveCurrentP(p);
  9552. end
  9553. else
  9554. begin
  9555. taicpu(p).opcode := A_MOV;
  9556. taicpu(p).opsize := S_B;
  9557. taicpu(p).oper[1]^.reg := NR_CL;
  9558. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9559. end;
  9560. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9561. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9562. begin
  9563. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9564. RemoveCurrentP(p);
  9565. end
  9566. else
  9567. begin
  9568. taicpu(p).opcode := A_MOV;
  9569. taicpu(p).opsize := S_W;
  9570. taicpu(p).oper[1]^.reg := NR_CX;
  9571. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9572. end;
  9573. {$ifdef x86_64}
  9574. S_LQ:
  9575. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9576. begin
  9577. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9578. RemoveCurrentP(p);
  9579. end
  9580. else
  9581. begin
  9582. taicpu(p).opcode := A_MOV;
  9583. taicpu(p).opsize := S_L;
  9584. taicpu(p).oper[1]^.reg := NR_ECX;
  9585. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9586. end;
  9587. {$endif x86_64}
  9588. else
  9589. InternalError(2021120401);
  9590. end;
  9591. Result := True;
  9592. Exit;
  9593. end;
  9594. end;
  9595. { This is anything but quick! }
  9596. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9597. Exit;
  9598. SetLength(InstrList, 0);
  9599. InstrMax := -1;
  9600. case taicpu(p).opsize of
  9601. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9602. begin
  9603. {$if defined(i386) or defined(i8086)}
  9604. { If the target size is 8-bit, make sure we can actually encode it }
  9605. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9606. Exit;
  9607. {$endif i386 or i8086}
  9608. LowerLimit := $FF;
  9609. SignedLowerLimit := $7F;
  9610. SignedLowerLimitBottom := -128;
  9611. MinSize := S_B;
  9612. if taicpu(p).opsize = S_BW then
  9613. begin
  9614. MaxSize := S_W;
  9615. UpperLimit := $FFFF;
  9616. SignedUpperLimit := $7FFF;
  9617. SignedUpperLimitBottom := -32768;
  9618. end
  9619. else
  9620. begin
  9621. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9622. MaxSize := S_L;
  9623. UpperLimit := $FFFFFFFF;
  9624. SignedUpperLimit := $7FFFFFFF;
  9625. SignedUpperLimitBottom := -2147483648;
  9626. end;
  9627. end;
  9628. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9629. begin
  9630. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9631. LowerLimit := $FFFF;
  9632. SignedLowerLimit := $7FFF;
  9633. SignedLowerLimitBottom := -32768;
  9634. UpperLimit := $FFFFFFFF;
  9635. SignedUpperLimit := $7FFFFFFF;
  9636. SignedUpperLimitBottom := -2147483648;
  9637. MinSize := S_W;
  9638. MaxSize := S_L;
  9639. end;
  9640. {$ifdef x86_64}
  9641. S_LQ:
  9642. begin
  9643. { Both the lower and upper limits are set to 32-bit. If a limit
  9644. is breached, then optimisation is impossible }
  9645. LowerLimit := $FFFFFFFF;
  9646. SignedLowerLimit := $7FFFFFFF;
  9647. SignedLowerLimitBottom := -2147483648;
  9648. UpperLimit := $FFFFFFFF;
  9649. SignedUpperLimit := $7FFFFFFF;
  9650. SignedUpperLimitBottom := -2147483648;
  9651. MinSize := S_L;
  9652. MaxSize := S_L;
  9653. end;
  9654. {$endif x86_64}
  9655. else
  9656. InternalError(2020112301);
  9657. end;
  9658. TestValMin := 0;
  9659. TestValMax := LowerLimit;
  9660. TestValSignedMax := SignedLowerLimit;
  9661. TryShiftDownLimit := LowerLimit;
  9662. TryShiftDown := S_NO;
  9663. ShiftDownOverflow := False;
  9664. RegChanged := False;
  9665. BitwiseOnly := True;
  9666. OrXorUsed := False;
  9667. UpperSignedOverflow := False;
  9668. LowerSignedOverflow := False;
  9669. UpperUnsignedOverflow := False;
  9670. LowerUnsignedOverflow := False;
  9671. hp1 := p;
  9672. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9673. (hp1.typ = ait_instruction) and
  9674. (
  9675. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9676. instruction that doesn't actually contain ThisReg }
  9677. (cs_opt_level3 in current_settings.optimizerswitches) or
  9678. { This allows this Movx optimisation to work through the SETcc instructions
  9679. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9680. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9681. skip over these SETcc instructions). }
  9682. (taicpu(hp1).opcode = A_SETcc) or
  9683. RegInInstruction(ThisReg, hp1)
  9684. ) do
  9685. begin
  9686. case taicpu(hp1).opcode of
  9687. A_INC,A_DEC:
  9688. begin
  9689. { Has to be an exact match on the register }
  9690. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9691. Break;
  9692. if taicpu(hp1).opcode = A_INC then
  9693. begin
  9694. Inc(TestValMin);
  9695. Inc(TestValMax);
  9696. Inc(TestValSignedMax);
  9697. end
  9698. else
  9699. begin
  9700. Dec(TestValMin);
  9701. Dec(TestValMax);
  9702. Dec(TestValSignedMax);
  9703. end;
  9704. end;
  9705. A_TEST, A_CMP:
  9706. begin
  9707. if (
  9708. { Too high a risk of non-linear behaviour that breaks DFA
  9709. here, unless it's cmp $0,%reg, which is equivalent to
  9710. test %reg,%reg }
  9711. OrXorUsed and
  9712. (taicpu(hp1).opcode = A_CMP) and
  9713. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9714. ) or
  9715. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9716. { Has to be an exact match on the register }
  9717. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9718. (
  9719. { Permit "test %reg,%reg" }
  9720. (taicpu(hp1).opcode = A_TEST) and
  9721. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9722. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9723. ) or
  9724. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9725. { Make sure the comparison value is not smaller than the
  9726. smallest allowed signed value for the minimum size (e.g.
  9727. -128 for 8-bit) }
  9728. not (
  9729. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9730. { Is it in the negative range? }
  9731. (
  9732. (taicpu(hp1).oper[0]^.val < 0) and
  9733. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9734. )
  9735. ) then
  9736. Break;
  9737. { Check to see if the active register is used afterwards }
  9738. TransferUsedRegs(TmpUsedRegs);
  9739. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9740. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9741. begin
  9742. { Make sure the comparison or any previous instructions
  9743. hasn't pushed the test values outside of the range of
  9744. MinSize }
  9745. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9746. begin
  9747. { Exceeded lower bound but not upper bound }
  9748. Exit;
  9749. end
  9750. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9751. begin
  9752. { Size didn't exceed lower bound }
  9753. TargetSize := MinSize;
  9754. end
  9755. else
  9756. Break;
  9757. case TargetSize of
  9758. S_B:
  9759. TargetSubReg := R_SUBL;
  9760. S_W:
  9761. TargetSubReg := R_SUBW;
  9762. S_L:
  9763. TargetSubReg := R_SUBD;
  9764. else
  9765. InternalError(2021051002);
  9766. end;
  9767. if TargetSize <> MaxSize then
  9768. begin
  9769. { Update the register to its new size }
  9770. setsubreg(ThisReg, TargetSubReg);
  9771. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9772. taicpu(hp1).oper[1]^.reg := ThisReg;
  9773. taicpu(hp1).opsize := TargetSize;
  9774. { Convert the input MOVZX to a MOV if necessary }
  9775. AdjustInitialLoadAndSize;
  9776. if (InstrMax >= 0) then
  9777. begin
  9778. for Index := 0 to InstrMax do
  9779. begin
  9780. { If p_removed is true, then the original MOV/Z was removed
  9781. and removing the AND instruction may not be safe if it
  9782. appears first }
  9783. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9784. InternalError(2020112311);
  9785. if InstrList[Index].oper[0]^.typ = top_reg then
  9786. InstrList[Index].oper[0]^.reg := ThisReg;
  9787. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9788. InstrList[Index].opsize := MinSize;
  9789. end;
  9790. end;
  9791. Result := True;
  9792. end;
  9793. Exit;
  9794. end;
  9795. end;
  9796. A_SETcc:
  9797. begin
  9798. { This allows this Movx optimisation to work through the SETcc instructions
  9799. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9800. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9801. skip over these SETcc instructions). }
  9802. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9803. { Of course, break out if the current register is used }
  9804. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9805. Break
  9806. else
  9807. { We must use Continue so the instruction doesn't get added
  9808. to InstrList }
  9809. Continue;
  9810. end;
  9811. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9812. begin
  9813. if
  9814. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9815. { Has to be an exact match on the register }
  9816. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9817. (
  9818. (
  9819. (taicpu(hp1).oper[0]^.typ = top_const) and
  9820. (
  9821. (
  9822. (taicpu(hp1).opcode = A_SHL) and
  9823. (
  9824. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9825. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9826. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9827. )
  9828. ) or (
  9829. (taicpu(hp1).opcode <> A_SHL) and
  9830. (
  9831. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9832. { Is it in the negative range? }
  9833. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9834. )
  9835. )
  9836. )
  9837. ) or (
  9838. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9839. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9840. )
  9841. ) then
  9842. Break;
  9843. { Only process OR and XOR if there are only bitwise operations,
  9844. since otherwise they can too easily fool the data flow
  9845. analysis (they can cause non-linear behaviour) }
  9846. case taicpu(hp1).opcode of
  9847. A_ADD:
  9848. begin
  9849. if OrXorUsed then
  9850. { Too high a risk of non-linear behaviour that breaks DFA here }
  9851. Break
  9852. else
  9853. BitwiseOnly := False;
  9854. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9855. begin
  9856. TestValMin := TestValMin * 2;
  9857. TestValMax := TestValMax * 2;
  9858. TestValSignedMax := TestValSignedMax * 2;
  9859. end
  9860. else
  9861. begin
  9862. WorkingValue := taicpu(hp1).oper[0]^.val;
  9863. TestValMin := TestValMin + WorkingValue;
  9864. TestValMax := TestValMax + WorkingValue;
  9865. TestValSignedMax := TestValSignedMax + WorkingValue;
  9866. end;
  9867. end;
  9868. A_SUB:
  9869. begin
  9870. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9871. begin
  9872. TestValMin := 0;
  9873. TestValMax := 0;
  9874. TestValSignedMax := 0;
  9875. end
  9876. else
  9877. begin
  9878. if OrXorUsed then
  9879. { Too high a risk of non-linear behaviour that breaks DFA here }
  9880. Break
  9881. else
  9882. BitwiseOnly := False;
  9883. WorkingValue := taicpu(hp1).oper[0]^.val;
  9884. TestValMin := TestValMin - WorkingValue;
  9885. TestValMax := TestValMax - WorkingValue;
  9886. TestValSignedMax := TestValSignedMax - WorkingValue;
  9887. end;
  9888. end;
  9889. A_AND:
  9890. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9891. begin
  9892. { we might be able to go smaller if AND appears first }
  9893. if InstrMax = -1 then
  9894. case MinSize of
  9895. S_B:
  9896. ;
  9897. S_W:
  9898. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9899. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9900. begin
  9901. TryShiftDown := S_B;
  9902. TryShiftDownLimit := $FF;
  9903. end;
  9904. S_L:
  9905. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9906. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9907. begin
  9908. TryShiftDown := S_B;
  9909. TryShiftDownLimit := $FF;
  9910. end
  9911. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9912. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9913. begin
  9914. TryShiftDown := S_W;
  9915. TryShiftDownLimit := $FFFF;
  9916. end;
  9917. else
  9918. InternalError(2020112320);
  9919. end;
  9920. WorkingValue := taicpu(hp1).oper[0]^.val;
  9921. TestValMin := TestValMin and WorkingValue;
  9922. TestValMax := TestValMax and WorkingValue;
  9923. TestValSignedMax := TestValSignedMax and WorkingValue;
  9924. end;
  9925. A_OR:
  9926. begin
  9927. if not BitwiseOnly then
  9928. Break;
  9929. OrXorUsed := True;
  9930. WorkingValue := taicpu(hp1).oper[0]^.val;
  9931. TestValMin := TestValMin or WorkingValue;
  9932. TestValMax := TestValMax or WorkingValue;
  9933. TestValSignedMax := TestValSignedMax or WorkingValue;
  9934. end;
  9935. A_XOR:
  9936. begin
  9937. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9938. begin
  9939. TestValMin := 0;
  9940. TestValMax := 0;
  9941. TestValSignedMax := 0;
  9942. end
  9943. else
  9944. begin
  9945. if not BitwiseOnly then
  9946. Break;
  9947. OrXorUsed := True;
  9948. WorkingValue := taicpu(hp1).oper[0]^.val;
  9949. TestValMin := TestValMin xor WorkingValue;
  9950. TestValMax := TestValMax xor WorkingValue;
  9951. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9952. end;
  9953. end;
  9954. A_SHL:
  9955. begin
  9956. BitwiseOnly := False;
  9957. WorkingValue := taicpu(hp1).oper[0]^.val;
  9958. TestValMin := TestValMin shl WorkingValue;
  9959. TestValMax := TestValMax shl WorkingValue;
  9960. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9961. end;
  9962. A_SHR,
  9963. { The first instruction was MOVZX, so the value won't be negative }
  9964. A_SAR:
  9965. begin
  9966. if InstrMax <> -1 then
  9967. BitwiseOnly := False
  9968. else
  9969. { we might be able to go smaller if SHR appears first }
  9970. case MinSize of
  9971. S_B:
  9972. ;
  9973. S_W:
  9974. if (taicpu(hp1).oper[0]^.val >= 8) then
  9975. begin
  9976. TryShiftDown := S_B;
  9977. TryShiftDownLimit := $FF;
  9978. TryShiftDownSignedLimit := $7F;
  9979. TryShiftDownSignedLimitLower := -128;
  9980. end;
  9981. S_L:
  9982. if (taicpu(hp1).oper[0]^.val >= 24) then
  9983. begin
  9984. TryShiftDown := S_B;
  9985. TryShiftDownLimit := $FF;
  9986. TryShiftDownSignedLimit := $7F;
  9987. TryShiftDownSignedLimitLower := -128;
  9988. end
  9989. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9990. begin
  9991. TryShiftDown := S_W;
  9992. TryShiftDownLimit := $FFFF;
  9993. TryShiftDownSignedLimit := $7FFF;
  9994. TryShiftDownSignedLimitLower := -32768;
  9995. end;
  9996. else
  9997. InternalError(2020112321);
  9998. end;
  9999. WorkingValue := taicpu(hp1).oper[0]^.val;
  10000. if taicpu(hp1).opcode = A_SAR then
  10001. begin
  10002. TestValMin := SarInt64(TestValMin, WorkingValue);
  10003. TestValMax := SarInt64(TestValMax, WorkingValue);
  10004. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10005. end
  10006. else
  10007. begin
  10008. TestValMin := TestValMin shr WorkingValue;
  10009. TestValMax := TestValMax shr WorkingValue;
  10010. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10011. end;
  10012. end;
  10013. else
  10014. InternalError(2020112303);
  10015. end;
  10016. end;
  10017. (*
  10018. A_IMUL:
  10019. case taicpu(hp1).ops of
  10020. 2:
  10021. begin
  10022. if not MatchOpType(hp1, top_reg, top_reg) or
  10023. { Has to be an exact match on the register }
  10024. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10025. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10026. Break;
  10027. TestValMin := TestValMin * TestValMin;
  10028. TestValMax := TestValMax * TestValMax;
  10029. TestValSignedMax := TestValSignedMax * TestValMax;
  10030. end;
  10031. 3:
  10032. begin
  10033. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10034. { Has to be an exact match on the register }
  10035. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10036. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10037. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10038. { Is it in the negative range? }
  10039. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10040. Break;
  10041. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10042. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10043. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10044. end;
  10045. else
  10046. Break;
  10047. end;
  10048. A_IDIV:
  10049. case taicpu(hp1).ops of
  10050. 3:
  10051. begin
  10052. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10053. { Has to be an exact match on the register }
  10054. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10055. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10056. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10057. { Is it in the negative range? }
  10058. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10059. Break;
  10060. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10061. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10062. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10063. end;
  10064. else
  10065. Break;
  10066. end;
  10067. *)
  10068. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10069. begin
  10070. { If there are no instructions in between, then we might be able to make a saving }
  10071. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10072. Break;
  10073. { We have something like:
  10074. movzbw %dl,%dx
  10075. ...
  10076. movswl %dx,%edx
  10077. Change the latter to a zero-extension then enter the
  10078. A_MOVZX case branch.
  10079. }
  10080. {$ifdef x86_64}
  10081. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10082. begin
  10083. { this becomes a zero extension from 32-bit to 64-bit, but
  10084. the upper 32 bits are already zero, so just delete the
  10085. instruction }
  10086. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10087. RemoveInstruction(hp1);
  10088. Result := True;
  10089. Exit;
  10090. end
  10091. else
  10092. {$endif x86_64}
  10093. begin
  10094. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10095. taicpu(hp1).opcode := A_MOVZX;
  10096. {$ifdef x86_64}
  10097. case taicpu(hp1).opsize of
  10098. S_BQ:
  10099. begin
  10100. taicpu(hp1).opsize := S_BL;
  10101. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10102. end;
  10103. S_WQ:
  10104. begin
  10105. taicpu(hp1).opsize := S_WL;
  10106. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10107. end;
  10108. S_LQ:
  10109. begin
  10110. taicpu(hp1).opcode := A_MOV;
  10111. taicpu(hp1).opsize := S_L;
  10112. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10113. { In this instance, we need to break out because the
  10114. instruction is no longer MOVZX or MOVSXD }
  10115. Result := True;
  10116. Exit;
  10117. end;
  10118. else
  10119. ;
  10120. end;
  10121. {$endif x86_64}
  10122. Result := CompressInstructions;
  10123. Exit;
  10124. end;
  10125. end;
  10126. A_MOVZX:
  10127. begin
  10128. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10129. Break;
  10130. if (InstrMax = -1) then
  10131. begin
  10132. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10133. begin
  10134. { Optimise around i40003 }
  10135. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10136. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10137. {$ifndef x86_64}
  10138. and (
  10139. (taicpu(p).oper[0]^.typ <> top_reg) or
  10140. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10141. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10142. )
  10143. {$endif not x86_64}
  10144. then
  10145. begin
  10146. if (taicpu(p).oper[0]^.typ = top_reg) then
  10147. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10148. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10149. taicpu(p).opsize := S_BL;
  10150. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10151. RemoveInstruction(hp1);
  10152. Result := True;
  10153. Exit;
  10154. end;
  10155. end
  10156. else
  10157. begin
  10158. { Will return false if the second parameter isn't ThisReg
  10159. (can happen on -O2 and under) }
  10160. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10161. begin
  10162. { The two MOVZX instructions are adjacent, so remove the first one }
  10163. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10164. RemoveCurrentP(p);
  10165. Result := True;
  10166. Exit;
  10167. end;
  10168. Break;
  10169. end;
  10170. end;
  10171. Result := CompressInstructions;
  10172. Exit;
  10173. end;
  10174. else
  10175. { This includes ADC, SBB and IDIV }
  10176. Break;
  10177. end;
  10178. if not CheckOverflowConditions then
  10179. Break;
  10180. { Contains highest index (so instruction count - 1) }
  10181. Inc(InstrMax);
  10182. if InstrMax > High(InstrList) then
  10183. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10184. InstrList[InstrMax] := taicpu(hp1);
  10185. end;
  10186. end;
  10187. {$pop}
  10188. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10189. var
  10190. hp1 : tai;
  10191. begin
  10192. Result:=false;
  10193. if (taicpu(p).ops >= 2) and
  10194. ((taicpu(p).oper[0]^.typ = top_const) or
  10195. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10196. (taicpu(p).oper[1]^.typ = top_reg) and
  10197. ((taicpu(p).ops = 2) or
  10198. ((taicpu(p).oper[2]^.typ = top_reg) and
  10199. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10200. GetLastInstruction(p,hp1) and
  10201. MatchInstruction(hp1,A_MOV,[]) and
  10202. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10203. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10204. begin
  10205. TransferUsedRegs(TmpUsedRegs);
  10206. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10207. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10208. { change
  10209. mov reg1,reg2
  10210. imul y,reg2 to imul y,reg1,reg2 }
  10211. begin
  10212. taicpu(p).ops := 3;
  10213. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10214. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10215. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10216. RemoveInstruction(hp1);
  10217. result:=true;
  10218. end;
  10219. end;
  10220. end;
  10221. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10222. var
  10223. ThisLabel: TAsmLabel;
  10224. begin
  10225. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10226. ThisLabel.decrefs;
  10227. taicpu(p).condition := C_None;
  10228. taicpu(p).opcode := A_RET;
  10229. taicpu(p).is_jmp := false;
  10230. taicpu(p).ops := taicpu(ret_p).ops;
  10231. case taicpu(ret_p).ops of
  10232. 0:
  10233. taicpu(p).clearop(0);
  10234. 1:
  10235. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10236. else
  10237. internalerror(2016041301);
  10238. end;
  10239. { If the original label is now dead, it might turn out that the label
  10240. immediately follows p. As a result, everything beyond it, which will
  10241. be just some final register configuration and a RET instruction, is
  10242. now dead code. [Kit] }
  10243. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10244. running RemoveDeadCodeAfterJump for each RET instruction, because
  10245. this optimisation rarely happens and most RETs appear at the end of
  10246. routines where there is nothing that can be stripped. [Kit] }
  10247. if not ThisLabel.is_used then
  10248. RemoveDeadCodeAfterJump(p);
  10249. end;
  10250. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10251. var
  10252. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10253. Unconditional, PotentialModified: Boolean;
  10254. OperPtr: POper;
  10255. NewRef: TReference;
  10256. InstrList: array of taicpu;
  10257. InstrMax, Index: Integer;
  10258. const
  10259. {$ifdef DEBUG_AOPTCPU}
  10260. SNoFlags: shortstring = ' so the flags aren''t modified';
  10261. {$else DEBUG_AOPTCPU}
  10262. SNoFlags = '';
  10263. {$endif DEBUG_AOPTCPU}
  10264. begin
  10265. Result:=false;
  10266. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10267. begin
  10268. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10269. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10270. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10271. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10272. GetNextInstruction(hp1, hp2) and
  10273. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10274. { Change from: To:
  10275. set(C) %reg j(~C) label
  10276. test %reg,%reg/cmp $0,%reg
  10277. je label
  10278. set(C) %reg j(C) label
  10279. test %reg,%reg/cmp $0,%reg
  10280. jne label
  10281. (Also do something similar with sete/setne instead of je/jne)
  10282. }
  10283. begin
  10284. { Before we do anything else, we need to check the instructions
  10285. in between SETcc and TEST to make sure they don't modify the
  10286. FLAGS register - if -O2 or under, there won't be any
  10287. instructions between SET and TEST }
  10288. TransferUsedRegs(TmpUsedRegs);
  10289. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10290. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10291. begin
  10292. next := p;
  10293. SetLength(InstrList, 0);
  10294. InstrMax := -1;
  10295. PotentialModified := False;
  10296. { Make a note of every instruction that modifies the FLAGS
  10297. register }
  10298. while GetNextInstruction(next, next) and (next <> hp1) do
  10299. begin
  10300. if next.typ <> ait_instruction then
  10301. { GetNextInstructionUsingReg should have returned False }
  10302. InternalError(2021051701);
  10303. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10304. begin
  10305. case taicpu(next).opcode of
  10306. A_SETcc,
  10307. A_CMOVcc,
  10308. A_Jcc:
  10309. begin
  10310. if PotentialModified then
  10311. { Not safe because the flags were modified earlier }
  10312. Exit
  10313. else
  10314. { Condition is the same as the initial SETcc, so this is safe
  10315. (don't add to instruction list though) }
  10316. Continue;
  10317. end;
  10318. A_ADD:
  10319. begin
  10320. if (taicpu(next).opsize = S_B) or
  10321. { LEA doesn't support 8-bit operands }
  10322. (taicpu(next).oper[1]^.typ <> top_reg) or
  10323. { Must write to a register }
  10324. (taicpu(next).oper[0]^.typ = top_ref) then
  10325. { Require a constant or a register }
  10326. Exit;
  10327. PotentialModified := True;
  10328. end;
  10329. A_SUB:
  10330. begin
  10331. if (taicpu(next).opsize = S_B) or
  10332. { LEA doesn't support 8-bit operands }
  10333. (taicpu(next).oper[1]^.typ <> top_reg) or
  10334. { Must write to a register }
  10335. (taicpu(next).oper[0]^.typ <> top_const) or
  10336. (taicpu(next).oper[0]^.val = $80000000) then
  10337. { Can't subtract a register with LEA - also
  10338. check that the value isn't -2^31, as this
  10339. can't be negated }
  10340. Exit;
  10341. PotentialModified := True;
  10342. end;
  10343. A_SAL,
  10344. A_SHL:
  10345. begin
  10346. if (taicpu(next).opsize = S_B) or
  10347. { LEA doesn't support 8-bit operands }
  10348. (taicpu(next).oper[1]^.typ <> top_reg) or
  10349. { Must write to a register }
  10350. (taicpu(next).oper[0]^.typ <> top_const) or
  10351. (taicpu(next).oper[0]^.val < 0) or
  10352. (taicpu(next).oper[0]^.val > 3) then
  10353. Exit;
  10354. PotentialModified := True;
  10355. end;
  10356. A_IMUL:
  10357. begin
  10358. if (taicpu(next).ops <> 3) or
  10359. (taicpu(next).oper[1]^.typ <> top_reg) or
  10360. { Must write to a register }
  10361. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10362. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10363. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10364. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10365. Exit
  10366. else
  10367. PotentialModified := True;
  10368. end;
  10369. else
  10370. { Don't know how to change this, so abort }
  10371. Exit;
  10372. end;
  10373. { Contains highest index (so instruction count - 1) }
  10374. Inc(InstrMax);
  10375. if InstrMax > High(InstrList) then
  10376. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10377. InstrList[InstrMax] := taicpu(next);
  10378. end;
  10379. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10380. end;
  10381. if not Assigned(next) or (next <> hp1) then
  10382. { It should be equal to hp1 }
  10383. InternalError(2021051702);
  10384. { Cycle through each instruction and check to see if we can
  10385. change them to versions that don't modify the flags }
  10386. if (InstrMax >= 0) then
  10387. begin
  10388. for Index := 0 to InstrMax do
  10389. case InstrList[Index].opcode of
  10390. A_ADD:
  10391. begin
  10392. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10393. InstrList[Index].opcode := A_LEA;
  10394. reference_reset(NewRef, 1, []);
  10395. NewRef.base := InstrList[Index].oper[1]^.reg;
  10396. if InstrList[Index].oper[0]^.typ = top_reg then
  10397. begin
  10398. NewRef.index := InstrList[Index].oper[0]^.reg;
  10399. NewRef.scalefactor := 1;
  10400. end
  10401. else
  10402. NewRef.offset := InstrList[Index].oper[0]^.val;
  10403. InstrList[Index].loadref(0, NewRef);
  10404. end;
  10405. A_SUB:
  10406. begin
  10407. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10408. InstrList[Index].opcode := A_LEA;
  10409. reference_reset(NewRef, 1, []);
  10410. NewRef.base := InstrList[Index].oper[1]^.reg;
  10411. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10412. InstrList[Index].loadref(0, NewRef);
  10413. end;
  10414. A_SHL,
  10415. A_SAL:
  10416. begin
  10417. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10418. InstrList[Index].opcode := A_LEA;
  10419. reference_reset(NewRef, 1, []);
  10420. NewRef.index := InstrList[Index].oper[1]^.reg;
  10421. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10422. InstrList[Index].loadref(0, NewRef);
  10423. end;
  10424. A_IMUL:
  10425. begin
  10426. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10427. InstrList[Index].opcode := A_LEA;
  10428. reference_reset(NewRef, 1, []);
  10429. NewRef.index := InstrList[Index].oper[1]^.reg;
  10430. case InstrList[Index].oper[0]^.val of
  10431. 2, 4, 8:
  10432. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10433. else {3, 5 and 9}
  10434. begin
  10435. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10436. NewRef.base := InstrList[Index].oper[1]^.reg;
  10437. end;
  10438. end;
  10439. InstrList[Index].loadref(0, NewRef);
  10440. end;
  10441. else
  10442. InternalError(2021051710);
  10443. end;
  10444. end;
  10445. { Mark the FLAGS register as used across this whole block }
  10446. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10447. end;
  10448. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10449. JumpC := taicpu(hp2).condition;
  10450. Unconditional := False;
  10451. if conditions_equal(JumpC, C_E) then
  10452. SetC := inverse_cond(taicpu(p).condition)
  10453. else if conditions_equal(JumpC, C_NE) then
  10454. SetC := taicpu(p).condition
  10455. else
  10456. { We've got something weird here (and inefficent) }
  10457. begin
  10458. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10459. SetC := C_NONE;
  10460. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10461. if condition_in(C_AE, JumpC) then
  10462. Unconditional := True
  10463. else
  10464. { Not sure what to do with this jump - drop out }
  10465. Exit;
  10466. end;
  10467. RemoveInstruction(hp1);
  10468. if Unconditional then
  10469. MakeUnconditional(taicpu(hp2))
  10470. else
  10471. begin
  10472. if SetC = C_NONE then
  10473. InternalError(2018061402);
  10474. taicpu(hp2).SetCondition(SetC);
  10475. end;
  10476. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10477. TmpUsedRegs }
  10478. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10479. begin
  10480. RemoveCurrentp(p, hp2);
  10481. if taicpu(hp2).opcode = A_SETcc then
  10482. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10483. else
  10484. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10485. end
  10486. else
  10487. if taicpu(hp2).opcode = A_SETcc then
  10488. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10489. else
  10490. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10491. Result := True;
  10492. end
  10493. else if
  10494. { Make sure the instructions are adjacent }
  10495. (
  10496. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10497. GetNextInstruction(p, hp1)
  10498. ) and
  10499. MatchInstruction(hp1, A_MOV, [S_B]) and
  10500. { Writing to memory is allowed }
  10501. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10502. begin
  10503. {
  10504. Watch out for sequences such as:
  10505. set(c)b %regb
  10506. movb %regb,(ref)
  10507. movb $0,1(ref)
  10508. movb $0,2(ref)
  10509. movb $0,3(ref)
  10510. Much more efficient to turn it into:
  10511. movl $0,%regl
  10512. set(c)b %regb
  10513. movl %regl,(ref)
  10514. Or:
  10515. set(c)b %regb
  10516. movzbl %regb,%regl
  10517. movl %regl,(ref)
  10518. }
  10519. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10520. GetNextInstruction(hp1, hp2) and
  10521. MatchInstruction(hp2, A_MOV, [S_B]) and
  10522. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10523. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10524. begin
  10525. { Don't do anything else except set Result to True }
  10526. end
  10527. else
  10528. begin
  10529. if taicpu(p).oper[0]^.typ = top_reg then
  10530. begin
  10531. TransferUsedRegs(TmpUsedRegs);
  10532. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10533. end;
  10534. { If it's not a register, it's a memory address }
  10535. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10536. begin
  10537. { Even if the register is still in use, we can minimise the
  10538. pipeline stall by changing the MOV into another SETcc. }
  10539. taicpu(hp1).opcode := A_SETcc;
  10540. taicpu(hp1).condition := taicpu(p).condition;
  10541. if taicpu(hp1).oper[1]^.typ = top_ref then
  10542. begin
  10543. { Swapping the operand pointers like this is probably a
  10544. bit naughty, but it is far faster than using loadoper
  10545. to transfer the reference from oper[1] to oper[0] if
  10546. you take into account the extra procedure calls and
  10547. the memory allocation and deallocation required }
  10548. OperPtr := taicpu(hp1).oper[1];
  10549. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10550. taicpu(hp1).oper[0] := OperPtr;
  10551. end
  10552. else
  10553. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10554. taicpu(hp1).clearop(1);
  10555. taicpu(hp1).ops := 1;
  10556. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10557. end
  10558. else
  10559. begin
  10560. if taicpu(hp1).oper[1]^.typ = top_reg then
  10561. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10562. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10563. RemoveInstruction(hp1);
  10564. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10565. end
  10566. end;
  10567. Result := True;
  10568. end;
  10569. end;
  10570. end;
  10571. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10572. var
  10573. hp1: tai;
  10574. Count: Integer;
  10575. OrigLabel: TAsmLabel;
  10576. begin
  10577. result := False;
  10578. { Sometimes, the optimisations below can permit this }
  10579. RemoveDeadCodeAfterJump(p);
  10580. 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
  10581. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10582. begin
  10583. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10584. { Also a side-effect of optimisations }
  10585. if CollapseZeroDistJump(p, OrigLabel) then
  10586. begin
  10587. Result := True;
  10588. Exit;
  10589. end;
  10590. hp1 := GetLabelWithSym(OrigLabel);
  10591. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10592. begin
  10593. if taicpu(hp1).opcode = A_RET then
  10594. begin
  10595. {
  10596. change
  10597. jmp .L1
  10598. ...
  10599. .L1:
  10600. ret
  10601. into
  10602. ret
  10603. }
  10604. begin
  10605. ConvertJumpToRET(p, hp1);
  10606. result:=true;
  10607. end;
  10608. end
  10609. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10610. not (cs_opt_size in current_settings.optimizerswitches) and
  10611. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10612. begin
  10613. Result := True;
  10614. Exit;
  10615. end;
  10616. end;
  10617. end;
  10618. end;
  10619. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10620. begin
  10621. Result := assigned(p) and
  10622. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10623. (taicpu(p).oper[1]^.typ = top_reg) and
  10624. (
  10625. (taicpu(p).oper[0]^.typ = top_reg) or
  10626. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10627. it is not expected that this can cause a seg. violation }
  10628. (
  10629. (taicpu(p).oper[0]^.typ = top_ref) and
  10630. { TODO: Can we detect which references become constants at this
  10631. stage so we don't have to do a blanket ban? }
  10632. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10633. (
  10634. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10635. (
  10636. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10637. not RefModified and
  10638. { If the reference also appears in the condition, then we know it's safe, otherwise
  10639. any kind of access violation would have occurred already }
  10640. Assigned(cond_p) and
  10641. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10642. (cond_p.typ = ait_instruction) and
  10643. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10644. { Just consider 2-operand comparison instructions for now to be safe }
  10645. (taicpu(cond_p).ops = 2) and
  10646. (
  10647. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10648. (
  10649. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10650. { Don't risk identical registers but different offsets, as we may have constructs
  10651. such as buffer streams with things like length fields that indicate whether
  10652. any more data follows. And there are probably some contrived examples where
  10653. writing to offsets behind the one being read also lead to access violations }
  10654. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10655. (
  10656. { Check that we're not modifying a register that appears in the reference }
  10657. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10658. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10659. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10660. )
  10661. )
  10662. )
  10663. )
  10664. )
  10665. )
  10666. );
  10667. end;
  10668. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10669. begin
  10670. { Update integer registers, ignoring deallocations }
  10671. repeat
  10672. while assigned(p) and
  10673. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10674. (p.typ = ait_label) or
  10675. ((p.typ = ait_marker) and
  10676. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10677. p := tai(p.next);
  10678. while assigned(p) and
  10679. (p.typ=ait_RegAlloc) Do
  10680. begin
  10681. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10682. begin
  10683. case tai_regalloc(p).ratype of
  10684. ra_alloc :
  10685. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10686. else
  10687. ;
  10688. end;
  10689. end;
  10690. p := tai(p.next);
  10691. end;
  10692. until not(assigned(p)) or
  10693. (not(p.typ in SkipInstr) and
  10694. not((p.typ = ait_label) and
  10695. labelCanBeSkipped(tai_label(p))));
  10696. end;
  10697. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10698. var
  10699. hp1,hp2: tai;
  10700. carryadd_opcode : TAsmOp;
  10701. symbol: TAsmSymbol;
  10702. increg, tmpreg: TRegister;
  10703. RefModified: Boolean;
  10704. {$ifndef i8086}
  10705. { Code and variables specific to CMOV optimisations }
  10706. hp3,hp4,hp5,
  10707. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10708. l, c, w, x : Longint;
  10709. condition, second_condition : TAsmCond;
  10710. FoundMatchingJump, RegMatch: Boolean;
  10711. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10712. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10713. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10714. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10715. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10716. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10717. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10718. new register to store the constant }
  10719. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10720. var
  10721. RegSize: TSubRegister;
  10722. CurrentVal: TCGInt;
  10723. ANewReg: TRegister;
  10724. X: ShortInt;
  10725. begin
  10726. Result := False;
  10727. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10728. Exit;
  10729. if StoredCount >= MAX_CMOV_REGISTERS then
  10730. { Arrays are full }
  10731. Exit;
  10732. { Remember that CMOV can't encode 8-bit registers }
  10733. case taicpu(p).opsize of
  10734. S_W:
  10735. RegSize := R_SUBW;
  10736. S_L:
  10737. RegSize := R_SUBD;
  10738. {$ifdef x86_64}
  10739. S_Q:
  10740. RegSize := R_SUBQ;
  10741. {$endif x86_64}
  10742. else
  10743. InternalError(2021100401);
  10744. end;
  10745. { See if the value has already been reserved for another CMOV instruction }
  10746. CurrentVal := taicpu(p).oper[0]^.val;
  10747. for X := 0 to StoredCount - 1 do
  10748. if ConstVals[X] = CurrentVal then
  10749. begin
  10750. ConstRegs[StoredCount] := ConstRegs[X];
  10751. ConstSizes[StoredCount] := RegSize;
  10752. ConstVals[StoredCount] := CurrentVal;
  10753. Result := True;
  10754. Inc(StoredCount);
  10755. { Don't increase CMOVCount this time, since we're re-using a register }
  10756. Exit;
  10757. end;
  10758. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10759. if ANewReg = NR_NO then
  10760. { No free registers }
  10761. Exit;
  10762. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10763. up vying for the same register }
  10764. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10765. ConstRegs[StoredCount] := ANewReg;
  10766. ConstSizes[StoredCount] := RegSize;
  10767. ConstVals[StoredCount] := CurrentVal;
  10768. Inc(StoredCount);
  10769. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10770. MOV required adds complexity and will cause diminishing returns
  10771. sooner than normal. This is more of an approximate weighting than
  10772. anything else. }
  10773. Inc(CMOVCount);
  10774. Result := True;
  10775. end;
  10776. {$endif i8086}
  10777. begin
  10778. result:=false;
  10779. if GetNextInstruction(p,hp1) then
  10780. begin
  10781. if (hp1.typ=ait_label) then
  10782. begin
  10783. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10784. Exit;
  10785. end
  10786. else if (hp1.typ<>ait_instruction) then
  10787. Exit;
  10788. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10789. if (
  10790. (
  10791. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10792. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10793. (Taicpu(hp1).oper[0]^.val=1)
  10794. ) or
  10795. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10796. ) and
  10797. GetNextInstruction(hp1,hp2) and
  10798. (hp2.typ = ait_label) and
  10799. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10800. { jb @@1 cmc
  10801. inc/dec operand --> adc/sbb operand,0
  10802. @@1:
  10803. ... and ...
  10804. jnb @@1
  10805. inc/dec operand --> adc/sbb operand,0
  10806. @@1: }
  10807. begin
  10808. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10809. begin
  10810. case taicpu(hp1).opcode of
  10811. A_INC,
  10812. A_ADD:
  10813. carryadd_opcode:=A_ADC;
  10814. A_DEC,
  10815. A_SUB:
  10816. carryadd_opcode:=A_SBB;
  10817. else
  10818. InternalError(2021011001);
  10819. end;
  10820. Taicpu(p).clearop(0);
  10821. Taicpu(p).ops:=0;
  10822. Taicpu(p).is_jmp:=false;
  10823. Taicpu(p).opcode:=A_CMC;
  10824. Taicpu(p).condition:=C_NONE;
  10825. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10826. Taicpu(hp1).ops:=2;
  10827. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10828. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10829. else
  10830. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10831. Taicpu(hp1).loadconst(0,0);
  10832. Taicpu(hp1).opcode:=carryadd_opcode;
  10833. result:=true;
  10834. exit;
  10835. end
  10836. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10837. begin
  10838. case taicpu(hp1).opcode of
  10839. A_INC,
  10840. A_ADD:
  10841. carryadd_opcode:=A_ADC;
  10842. A_DEC,
  10843. A_SUB:
  10844. carryadd_opcode:=A_SBB;
  10845. else
  10846. InternalError(2021011002);
  10847. end;
  10848. Taicpu(hp1).ops:=2;
  10849. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10850. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10851. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10852. else
  10853. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10854. Taicpu(hp1).loadconst(0,0);
  10855. Taicpu(hp1).opcode:=carryadd_opcode;
  10856. RemoveCurrentP(p, hp1);
  10857. result:=true;
  10858. exit;
  10859. end
  10860. {
  10861. jcc @@1 setcc tmpreg
  10862. inc/dec/add/sub operand -> (movzx tmpreg)
  10863. @@1: add/sub tmpreg,operand
  10864. While this increases code size slightly, it makes the code much faster if the
  10865. jump is unpredictable
  10866. }
  10867. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10868. begin
  10869. { search for an available register which is volatile }
  10870. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10871. if increg <> NR_NO then
  10872. begin
  10873. { We don't need to check if tmpreg is in hp1 or not, because
  10874. it will be marked as in use at p (if not, this is
  10875. indictive of a compiler bug). }
  10876. TAsmLabel(symbol).decrefs;
  10877. Taicpu(p).clearop(0);
  10878. Taicpu(p).ops:=1;
  10879. Taicpu(p).is_jmp:=false;
  10880. Taicpu(p).opcode:=A_SETcc;
  10881. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10882. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10883. Taicpu(p).loadreg(0,increg);
  10884. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10885. begin
  10886. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10887. R_SUBW:
  10888. begin
  10889. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10890. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10891. end;
  10892. R_SUBD:
  10893. begin
  10894. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10895. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10896. end;
  10897. {$ifdef x86_64}
  10898. R_SUBQ:
  10899. begin
  10900. { MOVZX doesn't have a 64-bit variant, because
  10901. the 32-bit version implicitly zeroes the
  10902. upper 32-bits of the destination register }
  10903. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10904. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10905. setsubreg(tmpreg, R_SUBQ);
  10906. end;
  10907. {$endif x86_64}
  10908. else
  10909. Internalerror(2020030601);
  10910. end;
  10911. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10912. asml.InsertAfter(hp2,p);
  10913. end
  10914. else
  10915. tmpreg := increg;
  10916. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10917. begin
  10918. Taicpu(hp1).ops:=2;
  10919. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10920. end;
  10921. Taicpu(hp1).loadreg(0,tmpreg);
  10922. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10923. Result := True;
  10924. { p is no longer a Jcc instruction, so exit }
  10925. Exit;
  10926. end;
  10927. end;
  10928. end;
  10929. { Detect the following:
  10930. jmp<cond> @Lbl1
  10931. jmp @Lbl2
  10932. ...
  10933. @Lbl1:
  10934. ret
  10935. Change to:
  10936. jmp<inv_cond> @Lbl2
  10937. ret
  10938. }
  10939. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10940. begin
  10941. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10942. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10943. MatchInstruction(hp2,A_RET,[S_NO]) then
  10944. begin
  10945. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10946. { Change label address to that of the unconditional jump }
  10947. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10948. TAsmLabel(symbol).DecRefs;
  10949. taicpu(hp1).opcode := A_RET;
  10950. taicpu(hp1).is_jmp := false;
  10951. taicpu(hp1).ops := taicpu(hp2).ops;
  10952. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10953. case taicpu(hp2).ops of
  10954. 0:
  10955. taicpu(hp1).clearop(0);
  10956. 1:
  10957. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10958. else
  10959. internalerror(2016041302);
  10960. end;
  10961. end;
  10962. {$ifndef i8086}
  10963. end
  10964. {
  10965. convert
  10966. j<c> .L1
  10967. mov 1,reg
  10968. jmp .L2
  10969. .L1
  10970. mov 0,reg
  10971. .L2
  10972. into
  10973. mov 0,reg
  10974. set<not(c)> reg
  10975. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10976. would destroy the flag contents
  10977. }
  10978. else if MatchInstruction(hp1,A_MOV,[]) and
  10979. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10980. {$ifdef i386}
  10981. (
  10982. { Under i386, ESI, EDI, EBP and ESP
  10983. don't have an 8-bit representation }
  10984. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10985. ) and
  10986. {$endif i386}
  10987. (taicpu(hp1).oper[0]^.val=1) and
  10988. GetNextInstruction(hp1,hp2) and
  10989. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10990. GetNextInstruction(hp2,hp3) and
  10991. (hp3.typ=ait_label) and
  10992. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10993. (tai_label(hp3).labsym.getrefs=1) and
  10994. GetNextInstruction(hp3,hp4) and
  10995. MatchInstruction(hp4,A_MOV,[]) and
  10996. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10997. (taicpu(hp4).oper[0]^.val=0) and
  10998. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10999. GetNextInstruction(hp4,hp5) and
  11000. (hp5.typ=ait_label) and
  11001. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  11002. (tai_label(hp5).labsym.getrefs=1) then
  11003. begin
  11004. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  11005. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  11006. { remove last label }
  11007. RemoveInstruction(hp5);
  11008. { remove second label }
  11009. RemoveInstruction(hp3);
  11010. { remove jmp }
  11011. RemoveInstruction(hp2);
  11012. if taicpu(hp1).opsize=S_B then
  11013. RemoveInstruction(hp1)
  11014. else
  11015. taicpu(hp1).loadconst(0,0);
  11016. taicpu(hp4).opcode:=A_SETcc;
  11017. taicpu(hp4).opsize:=S_B;
  11018. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  11019. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  11020. taicpu(hp4).opercnt:=1;
  11021. taicpu(hp4).ops:=1;
  11022. taicpu(hp4).freeop(1);
  11023. RemoveCurrentP(p);
  11024. Result:=true;
  11025. exit;
  11026. end
  11027. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  11028. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  11029. begin
  11030. { check for
  11031. jCC xxx
  11032. <several movs>
  11033. xxx:
  11034. Also spot:
  11035. Jcc xxx
  11036. <several movs>
  11037. jmp xxx
  11038. Change to:
  11039. <several cmovs with inverted condition>
  11040. jmp xxx (only for the 2nd case)
  11041. }
  11042. hp2 := p;
  11043. hp_lblxxx := hp1;
  11044. hp_flagalloc := nil;
  11045. hp_stop := nil;
  11046. FoundMatchingJump := False;
  11047. { Remember the first instruction in the first block of MOVs }
  11048. hpmov1 := hp1;
  11049. TransferUsedRegs(TmpUsedRegs);
  11050. while assigned(hp_lblxxx) and
  11051. { stop on labels }
  11052. (hp_lblxxx.typ <> ait_label) do
  11053. begin
  11054. { Keep track of all integer registers that are used }
  11055. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11056. if hp_lblxxx.typ = ait_instruction then
  11057. begin
  11058. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  11059. IsJumpToLabel(taicpu(hp_lblxxx)) then
  11060. begin
  11061. hp_stop := hp_lblxxx;
  11062. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  11063. begin
  11064. { We found Jcc xxx; <several movs>; Jmp xxx }
  11065. FoundMatchingJump := True;
  11066. Break;
  11067. end;
  11068. { If it's not the jump we're looking for, it's
  11069. possibly the "if..else" variant }
  11070. end
  11071. { Check to see if we have a valid MOV instruction instead }
  11072. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11073. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11074. Break
  11075. else
  11076. { This will be a valid MOV }
  11077. hp_stop := hp_lblxxx;
  11078. end;
  11079. hp2 := hp_lblxxx;
  11080. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11081. end;
  11082. { Just make sure the last MOV is included if there's no jump }
  11083. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11084. hp_stop := hp_lblxxx;
  11085. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11086. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11087. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11088. jmp yyy; xxx:; movs; yyy:" variation }
  11089. if assigned(hp_lblxxx) and
  11090. (
  11091. { If we found JMP xxx, we don't actually need a label
  11092. (hp_lblxxx is the JMP instruction instead) }
  11093. FoundMatchingJump or
  11094. { Make sure we actually have the right label }
  11095. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11096. ) then
  11097. begin
  11098. { Use TmpUsedRegs to track registers that we reserve }
  11099. { When allocating temporary registers, try to look one
  11100. instruction back, as defining them before a CMP or TEST
  11101. instruction will be faster, and also avoid picking a
  11102. register that was only just deallocated }
  11103. if GetLastInstruction(p, hp_prev) and
  11104. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11105. begin
  11106. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11107. for l := 0 to 1 do
  11108. with taicpu(hp_prev).oper[l]^ do
  11109. case typ of
  11110. top_reg:
  11111. if getregtype(reg) = R_INTREGISTER then
  11112. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11113. top_ref:
  11114. begin
  11115. if
  11116. {$ifdef x86_64}
  11117. (ref^.base <> NR_RIP) and
  11118. {$endif x86_64}
  11119. (ref^.base <> NR_NO) then
  11120. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11121. if (ref^.index <> NR_NO) then
  11122. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11123. end
  11124. else
  11125. ;
  11126. end;
  11127. { When inserting instructions before hp_prev, try to insert
  11128. them before the allocation of the FLAGS register }
  11129. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11130. { If not found, set it equal to hp_prev so it's something sensible }
  11131. hp_flagalloc := hp_prev;
  11132. hp_prev2 := nil;
  11133. { When dealing with a comparison against zero, take
  11134. note of the instruction before it to see if we can
  11135. move instructions further back in order to benefit
  11136. PostPeepholeOptTestOr.
  11137. }
  11138. if (
  11139. (
  11140. (taicpu(hp_prev).opcode = A_CMP) and
  11141. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11142. ) or
  11143. (
  11144. (taicpu(hp_prev).opcode = A_TEST) and
  11145. (
  11146. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11147. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11148. )
  11149. )
  11150. ) and
  11151. GetLastInstruction(hp_prev, hp_prev2) then
  11152. begin
  11153. if (hp_prev2.typ = ait_instruction) and
  11154. { These instructions set the zero flag if the result is zero }
  11155. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11156. begin
  11157. { Also mark all the registers in this previous instruction
  11158. as 'in use', even if they've just been deallocated }
  11159. for l := 0 to 1 do
  11160. with taicpu(hp_prev2).oper[l]^ do
  11161. case typ of
  11162. top_reg:
  11163. if getregtype(reg) = R_INTREGISTER then
  11164. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11165. top_ref:
  11166. begin
  11167. if
  11168. {$ifdef x86_64}
  11169. (ref^.base <> NR_RIP) and
  11170. {$endif x86_64}
  11171. (ref^.base <> NR_NO) then
  11172. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11173. if (ref^.index <> NR_NO) then
  11174. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11175. end
  11176. else
  11177. ;
  11178. end;
  11179. end
  11180. else
  11181. { Unsuitable instruction }
  11182. hp_prev2 := nil;
  11183. end;
  11184. end
  11185. else
  11186. begin
  11187. hp_prev := p;
  11188. { When inserting instructions before hp_prev, try to insert
  11189. them before the allocation of the FLAGS register }
  11190. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11191. { If not found, set it equal to p so it's something sensible }
  11192. hp_flagalloc := p;
  11193. hp_prev2 := nil;
  11194. end;
  11195. l := 0;
  11196. c := 0;
  11197. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11198. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11199. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11200. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11201. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11202. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11203. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11204. RefModified := False;
  11205. while assigned(hp1) and
  11206. { Stop on the label we found }
  11207. (hp1 <> hp_lblxxx) do
  11208. begin
  11209. case hp1.typ of
  11210. ait_instruction:
  11211. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11212. begin
  11213. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11214. begin
  11215. Inc(l);
  11216. { MOV instruction will be writing to a register }
  11217. if Assigned(hp_prev) and
  11218. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11219. (hp_prev.typ = ait_instruction) and
  11220. (taicpu(hp_prev).ops = 2) and
  11221. (
  11222. (
  11223. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11224. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11225. ) or
  11226. (
  11227. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11228. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11229. )
  11230. ) then
  11231. { It is no longer safe to use the reference in the condition.
  11232. this prevents problems such as:
  11233. mov (%reg),%reg
  11234. mov (%reg),...
  11235. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11236. (fixes #40165)
  11237. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11238. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11239. }
  11240. RefModified := True;
  11241. end
  11242. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11243. { CMOV with constants grows the code size }
  11244. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11245. begin
  11246. { Register was reserved by TryCMOVConst and
  11247. stored on ConstRegs[c] }
  11248. end
  11249. else
  11250. Break;
  11251. end
  11252. else
  11253. Break;
  11254. else
  11255. ;
  11256. end;
  11257. GetNextInstruction(hp1,hp1);
  11258. end;
  11259. if (hp1 = hp_lblxxx) then
  11260. begin
  11261. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11262. begin
  11263. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11264. TmpUsedRegs[R_INTREGISTER].Clear;
  11265. x := 0;
  11266. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11267. condition := inverse_cond(taicpu(p).condition);
  11268. UpdateUsedRegs(tai(p.next));
  11269. hp1 := hpmov1;
  11270. repeat
  11271. if not Assigned(hp1) then
  11272. InternalError(2018062900);
  11273. if (hp1.typ = ait_instruction) then
  11274. begin
  11275. { Extra safeguard }
  11276. if (taicpu(hp1).opcode <> A_MOV) then
  11277. InternalError(2018062901);
  11278. if taicpu(hp1).oper[0]^.typ = top_const then
  11279. begin
  11280. if x >= MAX_CMOV_REGISTERS then
  11281. InternalError(2021100410);
  11282. { If it's in TmpUsedRegs, then this register
  11283. is being used more than once and hence has
  11284. already had its value defined (it gets
  11285. added to UsedRegs through AllocRegBetween
  11286. below) }
  11287. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11288. begin
  11289. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11290. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11291. asml.InsertBefore(hp_new, hp_flagalloc);
  11292. if Assigned(hp_prev2) then
  11293. TrySwapMovOp(hp_prev2, hp_new);
  11294. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11295. ConstMovs[X] := hp_new;
  11296. end
  11297. else
  11298. { We just need an instruction between hp_prev and hp1
  11299. where we know the register is marked as in use }
  11300. hp_new := hpmov1;
  11301. { Keep track of largest write for this register so it can be optimised later }
  11302. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11303. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11304. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11305. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11306. Inc(x);
  11307. end;
  11308. taicpu(hp1).opcode := A_CMOVcc;
  11309. taicpu(hp1).condition := condition;
  11310. end;
  11311. UpdateUsedRegs(tai(hp1.next));
  11312. GetNextInstruction(hp1, hp1);
  11313. until (hp1 = hp_lblxxx);
  11314. { Update initialisation MOVs to the smallest possible size }
  11315. for c := 0 to x - 1 do
  11316. if Assigned(ConstMovs[c]) then
  11317. begin
  11318. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11319. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11320. end;
  11321. hp2 := hp_lblxxx;
  11322. repeat
  11323. if not Assigned(hp2) then
  11324. InternalError(2018062910);
  11325. case hp2.typ of
  11326. ait_label:
  11327. { What we expected - break out of the loop (it won't be a dead label at the top of
  11328. a cluster because that was optimised at an earlier stage) }
  11329. Break;
  11330. ait_instruction:
  11331. begin
  11332. if taicpu(hp2).opcode<>A_JMP then
  11333. InternalError(2018062912);
  11334. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11335. Break;
  11336. end
  11337. else
  11338. begin
  11339. { Might be a comment or temporary allocation entry }
  11340. if not (hp2.typ in SkipInstr) then
  11341. InternalError(2018062911);
  11342. hp2 := tai(hp2.Next);
  11343. Continue;
  11344. end;
  11345. end;
  11346. until False;
  11347. { Now we can safely decrement the reference count }
  11348. tasmlabel(symbol).decrefs;
  11349. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11350. { Remove the original jump }
  11351. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11352. if hp2.typ=ait_instruction then
  11353. begin
  11354. p := hp2;
  11355. Result := True;
  11356. end
  11357. else
  11358. begin
  11359. UpdateUsedRegs(tai(hp2.next));
  11360. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11361. { Remove the label if this is its final reference }
  11362. if (tasmlabel(symbol).getrefs=0) then
  11363. begin
  11364. { Make sure the aligns get stripped too }
  11365. hp1 := tai(hp_lblxxx.Previous);
  11366. while Assigned(hp1) and (hp1.typ = ait_align) do
  11367. begin
  11368. hp_lblxxx := hp1;
  11369. hp1 := tai(hp_lblxxx.Previous);
  11370. end;
  11371. StripLabelFast(hp_lblxxx);
  11372. end;
  11373. end;
  11374. Exit;
  11375. end;
  11376. end
  11377. else if assigned(hp_lblxxx) and
  11378. { check further for
  11379. jCC xxx
  11380. <several movs 1>
  11381. jmp yyy
  11382. xxx:
  11383. <several movs 2>
  11384. yyy:
  11385. }
  11386. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11387. { hp1 should be pointing to jmp yyy }
  11388. MatchInstruction(hp1, A_JMP, []) and
  11389. { real label and jump, no further references to the
  11390. label are allowed }
  11391. (TAsmLabel(symbol).getrefs=1) and
  11392. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11393. begin
  11394. hp_jump := hp1;
  11395. { Don't set c to zero }
  11396. l := 0;
  11397. w := 0;
  11398. GetNextInstruction(hp_lblxxx, hpmov2);
  11399. hp2 := hp_lblxxx;
  11400. hp_lblyyy := hpmov2;
  11401. while assigned(hp_lblyyy) and
  11402. { stop on labels }
  11403. (hp_lblyyy.typ <> ait_label) do
  11404. begin
  11405. { Keep track of all integer registers that are used }
  11406. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11407. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11408. Break;
  11409. hp2 := hp_lblyyy;
  11410. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11411. end;
  11412. { Analyse the second batch of MOVs to see if the setup is valid }
  11413. RefModified := False;
  11414. hp1 := hpmov2;
  11415. while assigned(hp1) and
  11416. (hp1 <> hp_lblyyy) do
  11417. begin
  11418. case hp1.typ of
  11419. ait_instruction:
  11420. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11421. begin
  11422. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11423. begin
  11424. Inc(l);
  11425. { MOV instruction will be writing to a register }
  11426. if Assigned(hp_prev) and
  11427. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11428. (hp_prev.typ = ait_instruction) and
  11429. (taicpu(hp_prev).ops = 2) and
  11430. (
  11431. (
  11432. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11433. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11434. ) or
  11435. (
  11436. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11437. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11438. )
  11439. ) then
  11440. { It is no longer safe to use the reference in the condition.
  11441. this prevents problems such as:
  11442. mov (%reg),%reg
  11443. mov (%reg),...
  11444. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11445. (fixes #40165)
  11446. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11447. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11448. }
  11449. RefModified := True;
  11450. end
  11451. else if not (cs_opt_size in current_settings.optimizerswitches)
  11452. { CMOV with constants grows the code size }
  11453. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11454. begin
  11455. { Register was reserved by TryCMOVConst and
  11456. stored on ConstRegs[c] }
  11457. end
  11458. else
  11459. Break;
  11460. end
  11461. else
  11462. Break;
  11463. else
  11464. ;
  11465. end;
  11466. GetNextInstruction(hp1,hp1);
  11467. end;
  11468. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11469. TmpUsedRegs[R_INTREGISTER].Clear;
  11470. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11471. (hp1 = hp_lblyyy) and
  11472. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11473. begin
  11474. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11475. second_condition := taicpu(p).condition;
  11476. condition := inverse_cond(taicpu(p).condition);
  11477. UpdateUsedRegs(tai(p.next));
  11478. { Scan through the first set of MOVs to update UsedRegs,
  11479. but don't process them yet }
  11480. hp1 := hpmov1;
  11481. repeat
  11482. if not Assigned(hp1) then
  11483. InternalError(2018062901);
  11484. UpdateUsedRegs(tai(hp1.next));
  11485. GetNextInstruction(hp1, hp1);
  11486. until (hp1 = hp_lblxxx);
  11487. UpdateUsedRegs(tai(hp_lblxxx.next));
  11488. { Process the second set of MOVs first,
  11489. because if a destination register is
  11490. shared between the first and second MOV
  11491. sets, it is more efficient to turn the
  11492. first one into a MOV instruction and place
  11493. it before the CMP if possible, but we
  11494. won't know which registers are shared
  11495. until we've processed at least one list,
  11496. so we might as well make it the second
  11497. one since that won't be modified again. }
  11498. hp1 := hpmov2;
  11499. repeat
  11500. if not Assigned(hp1) then
  11501. InternalError(2018062902);
  11502. if (hp1.typ = ait_instruction) then
  11503. begin
  11504. { Extra safeguard }
  11505. if (taicpu(hp1).opcode <> A_MOV) then
  11506. InternalError(2018062903);
  11507. if taicpu(hp1).oper[0]^.typ = top_const then
  11508. begin
  11509. RegMatch := False;
  11510. for x := 0 to c - 1 do
  11511. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11512. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11513. begin
  11514. RegMatch := True;
  11515. { If it's in TmpUsedRegs, then this register
  11516. is being used more than once and hence has
  11517. already had its value defined (it gets
  11518. added to UsedRegs through AllocRegBetween
  11519. below) }
  11520. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11521. begin
  11522. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11523. asml.InsertBefore(hp_new, hp_flagalloc);
  11524. if Assigned(hp_prev2) then
  11525. TrySwapMovOp(hp_prev2, hp_new);
  11526. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11527. ConstMovs[X] := hp_new;
  11528. end
  11529. else
  11530. { We just need an instruction between hp_prev and hp1
  11531. where we know the register is marked as in use }
  11532. hp_new := hpmov2;
  11533. { Keep track of largest write for this register so it can be optimised later }
  11534. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11535. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11536. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11537. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11538. Break;
  11539. end;
  11540. if not RegMatch then
  11541. InternalError(2021100411);
  11542. end;
  11543. taicpu(hp1).opcode := A_CMOVcc;
  11544. taicpu(hp1).condition := second_condition;
  11545. { Store these writes to search for
  11546. duplicates later on }
  11547. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11548. Inc(w);
  11549. end;
  11550. UpdateUsedRegs(tai(hp1.next));
  11551. GetNextInstruction(hp1, hp1);
  11552. until (hp1 = hp_lblyyy);
  11553. { Now do the first set of MOVs }
  11554. hp1 := hpmov1;
  11555. repeat
  11556. if not Assigned(hp1) then
  11557. InternalError(2018062904);
  11558. if (hp1.typ = ait_instruction) then
  11559. begin
  11560. RegMatch := False;
  11561. { Extra safeguard }
  11562. if (taicpu(hp1).opcode <> A_MOV) then
  11563. InternalError(2018062905);
  11564. { Search through the RegWrites list to see
  11565. if there are any opposing CMOV pairs that
  11566. write to the same register }
  11567. for x := 0 to w - 1 do
  11568. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11569. begin
  11570. { We have a match. Keep this as a MOV }
  11571. { Move ahead in preparation }
  11572. GetNextInstruction(hp1, hp1);
  11573. RegMatch := True;
  11574. Break;
  11575. end;
  11576. if RegMatch then
  11577. Continue;
  11578. if taicpu(hp1).oper[0]^.typ = top_const then
  11579. begin
  11580. RegMatch := False;
  11581. for x := 0 to c - 1 do
  11582. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11583. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11584. begin
  11585. RegMatch := True;
  11586. { If it's in TmpUsedRegs, then this register
  11587. is being used more than once and hence has
  11588. already had its value defined (it gets
  11589. added to UsedRegs through AllocRegBetween
  11590. below) }
  11591. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11592. begin
  11593. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11594. asml.InsertBefore(hp_new, hp_flagalloc);
  11595. if Assigned(hp_prev2) then
  11596. TrySwapMovOp(hp_prev2, hp_new);
  11597. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11598. ConstMovs[X] := hp_new;
  11599. end
  11600. else
  11601. { We just need an instruction between hp_prev and hp1
  11602. where we know the register is marked as in use }
  11603. hp_new := hpmov1;
  11604. { Keep track of largest write for this register so it can be optimised later }
  11605. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11606. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11607. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11608. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11609. Break;
  11610. end;
  11611. if not RegMatch then
  11612. InternalError(2021100412);
  11613. end;
  11614. taicpu(hp1).opcode := A_CMOVcc;
  11615. taicpu(hp1).condition := condition;
  11616. end;
  11617. GetNextInstruction(hp1, hp1);
  11618. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11619. { Update initialisation MOVs to the smallest possible size }
  11620. for x := 0 to c - 1 do
  11621. if Assigned(ConstMovs[x]) then
  11622. begin
  11623. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11624. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11625. end;
  11626. UpdateUsedRegs(tai(hp_jump.next));
  11627. UpdateUsedRegs(tai(hp_lblyyy.next));
  11628. { Get first instruction after label }
  11629. hp1 := p;
  11630. GetNextInstruction(hp_lblyyy, p);
  11631. { Don't dereference yet, as doing so will cause
  11632. GetNextInstruction to skip the label and
  11633. optional align marker. [Kit] }
  11634. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11635. { remove Jcc }
  11636. RemoveInstruction(hp1);
  11637. { Now we can safely decrement it }
  11638. tasmlabel(symbol).decrefs;
  11639. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11640. { Make sure the aligns get stripped too }
  11641. hp1 := tai(hp_lblxxx.Previous);
  11642. while Assigned(hp1) and (hp1.typ = ait_align) do
  11643. begin
  11644. hp_lblxxx := hp1;
  11645. hp1 := tai(hp_lblxxx.Previous);
  11646. end;
  11647. StripLabelFast(hp_lblxxx);
  11648. { remove jmp }
  11649. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11650. RemoveInstruction(hp_jump);
  11651. { As before, now we can safely decrement it }
  11652. TAsmLabel(symbol).decrefs;
  11653. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11654. if TAsmLabel(symbol).getrefs = 0 then
  11655. begin
  11656. { Make sure the aligns get stripped too }
  11657. hp1 := tai(hp_lblyyy.Previous);
  11658. while Assigned(hp1) and (hp1.typ = ait_align) do
  11659. begin
  11660. hp_lblyyy := hp1;
  11661. hp1 := tai(hp_lblyyy.Previous);
  11662. end;
  11663. StripLabelFast(hp_lblyyy);
  11664. end;
  11665. if Assigned(p) then
  11666. result := True;
  11667. exit;
  11668. end;
  11669. end;
  11670. end;
  11671. {$endif i8086}
  11672. end;
  11673. end;
  11674. end;
  11675. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11676. var
  11677. hp1,hp2,hp3: tai;
  11678. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11679. NewSize: TOpSize;
  11680. NewRegSize: TSubRegister;
  11681. Limit: TCgInt;
  11682. SwapOper: POper;
  11683. begin
  11684. result:=false;
  11685. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11686. GetNextInstruction(p,hp1) and
  11687. (hp1.typ = ait_instruction);
  11688. if reg_and_hp1_is_instr and
  11689. (
  11690. (taicpu(hp1).opcode <> A_LEA) or
  11691. { If the LEA instruction can be converted into an arithmetic instruction,
  11692. it may be possible to then fold it. }
  11693. (
  11694. { If the flags register is in use, don't change the instruction
  11695. to an ADD otherwise this will scramble the flags. [Kit] }
  11696. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11697. ConvertLEA(taicpu(hp1))
  11698. )
  11699. ) and
  11700. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11701. GetNextInstruction(hp1,hp2) and
  11702. MatchInstruction(hp2,A_MOV,[]) and
  11703. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11704. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11705. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11706. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11707. {$ifdef i386}
  11708. { not all registers have byte size sub registers on i386 }
  11709. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11710. {$endif i386}
  11711. (((taicpu(hp1).ops=2) and
  11712. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11713. ((taicpu(hp1).ops=1) and
  11714. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11715. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11716. begin
  11717. { change movsX/movzX reg/ref, reg2
  11718. add/sub/or/... reg3/$const, reg2
  11719. mov reg2 reg/ref
  11720. to add/sub/or/... reg3/$const, reg/ref }
  11721. { by example:
  11722. movswl %si,%eax movswl %si,%eax p
  11723. decl %eax addl %edx,%eax hp1
  11724. movw %ax,%si movw %ax,%si hp2
  11725. ->
  11726. movswl %si,%eax movswl %si,%eax p
  11727. decw %eax addw %edx,%eax hp1
  11728. movw %ax,%si movw %ax,%si hp2
  11729. }
  11730. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11731. {
  11732. ->
  11733. movswl %si,%eax movswl %si,%eax p
  11734. decw %si addw %dx,%si hp1
  11735. movw %ax,%si movw %ax,%si hp2
  11736. }
  11737. case taicpu(hp1).ops of
  11738. 1:
  11739. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11740. 2:
  11741. begin
  11742. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11743. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11744. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11745. end;
  11746. else
  11747. internalerror(2008042702);
  11748. end;
  11749. {
  11750. ->
  11751. decw %si addw %dx,%si p
  11752. }
  11753. DebugMsg(SPeepholeOptimization + 'var3',p);
  11754. RemoveCurrentP(p, hp1);
  11755. RemoveInstruction(hp2);
  11756. Result := True;
  11757. Exit;
  11758. end;
  11759. if reg_and_hp1_is_instr and
  11760. (taicpu(hp1).opcode = A_MOV) and
  11761. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11762. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11763. {$ifdef x86_64}
  11764. { check for implicit extension to 64 bit }
  11765. or
  11766. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11767. (taicpu(hp1).opsize=S_Q) and
  11768. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11769. )
  11770. {$endif x86_64}
  11771. )
  11772. then
  11773. begin
  11774. { change
  11775. movx %reg1,%reg2
  11776. mov %reg2,%reg3
  11777. dealloc %reg2
  11778. into
  11779. movx %reg,%reg3
  11780. }
  11781. TransferUsedRegs(TmpUsedRegs);
  11782. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11783. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11784. begin
  11785. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11786. {$ifdef x86_64}
  11787. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11788. (taicpu(hp1).opsize=S_Q) then
  11789. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11790. else
  11791. {$endif x86_64}
  11792. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11793. RemoveInstruction(hp1);
  11794. Result := True;
  11795. Exit;
  11796. end;
  11797. end;
  11798. if reg_and_hp1_is_instr and
  11799. ((taicpu(hp1).opcode=A_MOV) or
  11800. (taicpu(hp1).opcode=A_ADD) or
  11801. (taicpu(hp1).opcode=A_SUB) or
  11802. (taicpu(hp1).opcode=A_CMP) or
  11803. (taicpu(hp1).opcode=A_OR) or
  11804. (taicpu(hp1).opcode=A_XOR) or
  11805. (taicpu(hp1).opcode=A_AND)
  11806. ) and
  11807. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11808. begin
  11809. AndTest := (taicpu(hp1).opcode=A_AND) and
  11810. GetNextInstruction(hp1, hp2) and
  11811. (hp2.typ = ait_instruction) and
  11812. (
  11813. (
  11814. (taicpu(hp2).opcode=A_TEST) and
  11815. (
  11816. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11817. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11818. (
  11819. { If the AND and TEST instructions share a constant, this is also valid }
  11820. (taicpu(hp1).oper[0]^.typ = top_const) and
  11821. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11822. )
  11823. ) and
  11824. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11825. ) or
  11826. (
  11827. (taicpu(hp2).opcode=A_CMP) and
  11828. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11829. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11830. )
  11831. );
  11832. { change
  11833. movx (oper),%reg2
  11834. and $x,%reg2
  11835. test %reg2,%reg2
  11836. dealloc %reg2
  11837. into
  11838. op %reg1,%reg3
  11839. if the second op accesses only the bits stored in reg1
  11840. }
  11841. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11842. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11843. (taicpu(hp1).oper[0]^.typ = top_const) and
  11844. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11845. AndTest then
  11846. begin
  11847. { Check if the AND constant is in range }
  11848. case taicpu(p).opsize of
  11849. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11850. begin
  11851. NewSize := S_B;
  11852. Limit := $FF;
  11853. end;
  11854. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11855. begin
  11856. NewSize := S_W;
  11857. Limit := $FFFF;
  11858. end;
  11859. {$ifdef x86_64}
  11860. S_LQ:
  11861. begin
  11862. NewSize := S_L;
  11863. Limit := $FFFFFFFF;
  11864. end;
  11865. {$endif x86_64}
  11866. else
  11867. InternalError(2021120303);
  11868. end;
  11869. if (
  11870. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11871. { Check for negative operands }
  11872. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11873. ) and
  11874. GetNextInstruction(hp2,hp3) and
  11875. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11876. (taicpu(hp3).condition in [C_E,C_NE]) then
  11877. begin
  11878. TransferUsedRegs(TmpUsedRegs);
  11879. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11880. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11881. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11882. begin
  11883. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11884. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11885. taicpu(hp1).opcode := A_TEST;
  11886. taicpu(hp1).opsize := NewSize;
  11887. RemoveInstruction(hp2);
  11888. RemoveCurrentP(p, hp1);
  11889. Result:=true;
  11890. exit;
  11891. end;
  11892. end;
  11893. end;
  11894. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11895. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11896. (taicpu(hp1).opsize=S_B)) or
  11897. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11898. (taicpu(hp1).opsize=S_W))
  11899. {$ifdef x86_64}
  11900. or ((taicpu(p).opsize=S_LQ) and
  11901. (taicpu(hp1).opsize=S_L))
  11902. {$endif x86_64}
  11903. ) and
  11904. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11905. begin
  11906. { change
  11907. movx %reg1,%reg2
  11908. op %reg2,%reg3
  11909. dealloc %reg2
  11910. into
  11911. op %reg1,%reg3
  11912. if the second op accesses only the bits stored in reg1
  11913. }
  11914. TransferUsedRegs(TmpUsedRegs);
  11915. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11916. if AndTest then
  11917. begin
  11918. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11919. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11920. end
  11921. else
  11922. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11923. if not RegUsed then
  11924. begin
  11925. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11926. if taicpu(p).oper[0]^.typ=top_reg then
  11927. begin
  11928. case taicpu(hp1).opsize of
  11929. S_B:
  11930. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11931. S_W:
  11932. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11933. S_L:
  11934. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11935. else
  11936. Internalerror(2020102301);
  11937. end;
  11938. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11939. end
  11940. else
  11941. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11942. RemoveCurrentP(p);
  11943. if AndTest then
  11944. RemoveInstruction(hp2);
  11945. result:=true;
  11946. exit;
  11947. end;
  11948. end
  11949. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11950. (
  11951. { Bitwise operations only }
  11952. (taicpu(hp1).opcode=A_AND) or
  11953. (taicpu(hp1).opcode=A_TEST) or
  11954. (
  11955. (taicpu(hp1).oper[0]^.typ = top_const) and
  11956. (
  11957. (taicpu(hp1).opcode=A_OR) or
  11958. (taicpu(hp1).opcode=A_XOR)
  11959. )
  11960. )
  11961. ) and
  11962. (
  11963. (taicpu(hp1).oper[0]^.typ = top_const) or
  11964. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11965. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11966. ) then
  11967. begin
  11968. { change
  11969. movx %reg2,%reg2
  11970. op const,%reg2
  11971. into
  11972. op const,%reg2 (smaller version)
  11973. movx %reg2,%reg2
  11974. also change
  11975. movx %reg1,%reg2
  11976. and/test (oper),%reg2
  11977. dealloc %reg2
  11978. into
  11979. and/test (oper),%reg1
  11980. }
  11981. case taicpu(p).opsize of
  11982. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11983. begin
  11984. NewSize := S_B;
  11985. NewRegSize := R_SUBL;
  11986. Limit := $FF;
  11987. end;
  11988. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11989. begin
  11990. NewSize := S_W;
  11991. NewRegSize := R_SUBW;
  11992. Limit := $FFFF;
  11993. end;
  11994. {$ifdef x86_64}
  11995. S_LQ:
  11996. begin
  11997. NewSize := S_L;
  11998. NewRegSize := R_SUBD;
  11999. Limit := $FFFFFFFF;
  12000. end;
  12001. {$endif x86_64}
  12002. else
  12003. Internalerror(2021120302);
  12004. end;
  12005. TransferUsedRegs(TmpUsedRegs);
  12006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12007. if AndTest then
  12008. begin
  12009. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12010. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12011. end
  12012. else
  12013. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12014. if
  12015. (
  12016. (taicpu(p).opcode = A_MOVZX) and
  12017. (
  12018. (taicpu(hp1).opcode=A_AND) or
  12019. (taicpu(hp1).opcode=A_TEST)
  12020. ) and
  12021. not (
  12022. { If both are references, then the final instruction will have
  12023. both operands as references, which is not allowed }
  12024. (taicpu(p).oper[0]^.typ = top_ref) and
  12025. (taicpu(hp1).oper[0]^.typ = top_ref)
  12026. ) and
  12027. not RegUsed
  12028. ) or
  12029. (
  12030. (
  12031. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12032. not RegUsed
  12033. ) and
  12034. (taicpu(p).oper[0]^.typ = top_reg) and
  12035. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12036. (taicpu(hp1).oper[0]^.typ = top_const) and
  12037. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12038. ) then
  12039. begin
  12040. {$if defined(i386) or defined(i8086)}
  12041. { If the target size is 8-bit, make sure we can actually encode it }
  12042. 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
  12043. Exit;
  12044. {$endif i386 or i8086}
  12045. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12046. taicpu(hp1).opsize := NewSize;
  12047. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12048. if AndTest then
  12049. begin
  12050. RemoveInstruction(hp2);
  12051. if not RegUsed then
  12052. begin
  12053. taicpu(hp1).opcode := A_TEST;
  12054. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12055. begin
  12056. { Make sure the reference is the second operand }
  12057. SwapOper := taicpu(hp1).oper[0];
  12058. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12059. taicpu(hp1).oper[1] := SwapOper;
  12060. end;
  12061. end;
  12062. end;
  12063. case taicpu(hp1).oper[0]^.typ of
  12064. top_reg:
  12065. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12066. top_const:
  12067. { For the AND/TEST case }
  12068. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12069. else
  12070. ;
  12071. end;
  12072. if RegUsed then
  12073. begin
  12074. AsmL.Remove(p);
  12075. AsmL.InsertAfter(p, hp1);
  12076. p := hp1;
  12077. end
  12078. else
  12079. RemoveCurrentP(p, hp1);
  12080. result:=true;
  12081. exit;
  12082. end;
  12083. end;
  12084. end;
  12085. if reg_and_hp1_is_instr and
  12086. (taicpu(p).oper[0]^.typ = top_reg) and
  12087. (
  12088. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12089. ) and
  12090. (taicpu(hp1).oper[0]^.typ = top_const) and
  12091. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12092. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12093. { Minimum shift value allowed is the bit difference between the sizes }
  12094. (taicpu(hp1).oper[0]^.val >=
  12095. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12096. 8 * (
  12097. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12098. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12099. )
  12100. ) then
  12101. begin
  12102. { For:
  12103. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12104. shl/sal ##, %reg1
  12105. Remove the movsx/movzx instruction if the shift overwrites the
  12106. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12107. }
  12108. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12109. RemoveCurrentP(p, hp1);
  12110. Result := True;
  12111. Exit;
  12112. end
  12113. else if reg_and_hp1_is_instr and
  12114. (taicpu(p).oper[0]^.typ = top_reg) and
  12115. (
  12116. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12117. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12118. ) and
  12119. (taicpu(hp1).oper[0]^.typ = top_const) and
  12120. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12121. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12122. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12123. (taicpu(hp1).oper[0]^.val <
  12124. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12125. 8 * (
  12126. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12127. )
  12128. ) then
  12129. begin
  12130. { For:
  12131. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12132. sar ##, %reg1 shr ##, %reg1
  12133. Move the shift to before the movx instruction if the shift value
  12134. is not too large.
  12135. }
  12136. asml.Remove(hp1);
  12137. asml.InsertBefore(hp1, p);
  12138. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12139. case taicpu(p).opsize of
  12140. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12141. taicpu(hp1).opsize := S_B;
  12142. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12143. taicpu(hp1).opsize := S_W;
  12144. {$ifdef x86_64}
  12145. S_LQ:
  12146. taicpu(hp1).opsize := S_L;
  12147. {$endif}
  12148. else
  12149. InternalError(2020112401);
  12150. end;
  12151. if (taicpu(hp1).opcode = A_SHR) then
  12152. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12153. else
  12154. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12155. Result := True;
  12156. end;
  12157. if reg_and_hp1_is_instr and
  12158. (taicpu(p).oper[0]^.typ = top_reg) and
  12159. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12160. (
  12161. (taicpu(hp1).opcode = taicpu(p).opcode)
  12162. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12163. {$ifdef x86_64}
  12164. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12165. {$endif x86_64}
  12166. ) then
  12167. begin
  12168. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12169. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12170. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12171. begin
  12172. {
  12173. For example:
  12174. movzbw %al,%ax
  12175. movzwl %ax,%eax
  12176. Compress into:
  12177. movzbl %al,%eax
  12178. }
  12179. RegUsed := False;
  12180. case taicpu(p).opsize of
  12181. S_BW:
  12182. case taicpu(hp1).opsize of
  12183. S_WL:
  12184. begin
  12185. taicpu(p).opsize := S_BL;
  12186. RegUsed := True;
  12187. end;
  12188. {$ifdef x86_64}
  12189. S_WQ:
  12190. begin
  12191. if taicpu(p).opcode = A_MOVZX then
  12192. begin
  12193. taicpu(p).opsize := S_BL;
  12194. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12195. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12196. end
  12197. else
  12198. taicpu(p).opsize := S_BQ;
  12199. RegUsed := True;
  12200. end;
  12201. {$endif x86_64}
  12202. else
  12203. ;
  12204. end;
  12205. {$ifdef x86_64}
  12206. S_BL:
  12207. case taicpu(hp1).opsize of
  12208. S_LQ:
  12209. begin
  12210. if taicpu(p).opcode = A_MOVZX then
  12211. begin
  12212. taicpu(p).opsize := S_BL;
  12213. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12214. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12215. end
  12216. else
  12217. taicpu(p).opsize := S_BQ;
  12218. RegUsed := True;
  12219. end;
  12220. else
  12221. ;
  12222. end;
  12223. S_WL:
  12224. case taicpu(hp1).opsize of
  12225. S_LQ:
  12226. begin
  12227. if taicpu(p).opcode = A_MOVZX then
  12228. begin
  12229. taicpu(p).opsize := S_WL;
  12230. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12231. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12232. end
  12233. else
  12234. taicpu(p).opsize := S_WQ;
  12235. RegUsed := True;
  12236. end;
  12237. else
  12238. ;
  12239. end;
  12240. {$endif x86_64}
  12241. else
  12242. ;
  12243. end;
  12244. if RegUsed then
  12245. begin
  12246. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12247. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12248. RemoveInstruction(hp1);
  12249. Result := True;
  12250. Exit;
  12251. end;
  12252. end;
  12253. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12254. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12255. GetNextInstruction(hp1, hp2) and
  12256. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12257. (
  12258. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12259. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12260. {$ifdef x86_64}
  12261. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12262. {$endif x86_64}
  12263. ) and
  12264. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12265. (
  12266. (
  12267. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12268. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12269. ) or
  12270. (
  12271. { Only allow the operands in reverse order for TEST instructions }
  12272. (taicpu(hp2).opcode = A_TEST) and
  12273. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12274. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12275. )
  12276. ) then
  12277. begin
  12278. {
  12279. For example:
  12280. movzbl %al,%eax
  12281. movzbl (ref),%edx
  12282. andl %edx,%eax
  12283. (%edx deallocated)
  12284. Change to:
  12285. andb (ref),%al
  12286. movzbl %al,%eax
  12287. Rules are:
  12288. - First two instructions have the same opcode and opsize
  12289. - First instruction's operands are the same super-register
  12290. - Second instruction operates on a different register
  12291. - Third instruction is AND, OR, XOR or TEST
  12292. - Third instruction's operands are the destination registers of the first two instructions
  12293. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12294. - Second instruction's destination register is deallocated afterwards
  12295. }
  12296. TransferUsedRegs(TmpUsedRegs);
  12297. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12298. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12299. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12300. begin
  12301. case taicpu(p).opsize of
  12302. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12303. NewSize := S_B;
  12304. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12305. NewSize := S_W;
  12306. {$ifdef x86_64}
  12307. S_LQ:
  12308. NewSize := S_L;
  12309. {$endif x86_64}
  12310. else
  12311. InternalError(2021120301);
  12312. end;
  12313. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12314. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12315. taicpu(hp2).opsize := NewSize;
  12316. RemoveInstruction(hp1);
  12317. { With TEST, it's best to keep the MOVX instruction at the top }
  12318. if (taicpu(hp2).opcode <> A_TEST) then
  12319. begin
  12320. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12321. asml.Remove(p);
  12322. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12323. asml.InsertAfter(p, hp2);
  12324. p := hp2;
  12325. end
  12326. else
  12327. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12328. Result := True;
  12329. Exit;
  12330. end;
  12331. end;
  12332. end;
  12333. if taicpu(p).opcode=A_MOVZX then
  12334. begin
  12335. { removes superfluous And's after movzx's }
  12336. if reg_and_hp1_is_instr and
  12337. (taicpu(hp1).opcode = A_AND) and
  12338. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12339. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12340. {$ifdef x86_64}
  12341. { check for implicit extension to 64 bit }
  12342. or
  12343. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12344. (taicpu(hp1).opsize=S_Q) and
  12345. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12346. )
  12347. {$endif x86_64}
  12348. )
  12349. then
  12350. begin
  12351. case taicpu(p).opsize Of
  12352. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12353. if (taicpu(hp1).oper[0]^.val = $ff) then
  12354. begin
  12355. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12356. RemoveInstruction(hp1);
  12357. Result:=true;
  12358. exit;
  12359. end;
  12360. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12361. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12362. begin
  12363. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12364. RemoveInstruction(hp1);
  12365. Result:=true;
  12366. exit;
  12367. end;
  12368. {$ifdef x86_64}
  12369. S_LQ:
  12370. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12371. begin
  12372. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12373. RemoveInstruction(hp1);
  12374. Result:=true;
  12375. exit;
  12376. end;
  12377. {$endif x86_64}
  12378. else
  12379. ;
  12380. end;
  12381. { we cannot get rid of the and, but can we get rid of the movz ?}
  12382. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12383. begin
  12384. case taicpu(p).opsize Of
  12385. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12386. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12387. begin
  12388. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12389. RemoveCurrentP(p,hp1);
  12390. Result:=true;
  12391. exit;
  12392. end;
  12393. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12394. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12395. begin
  12396. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12397. RemoveCurrentP(p,hp1);
  12398. Result:=true;
  12399. exit;
  12400. end;
  12401. {$ifdef x86_64}
  12402. S_LQ:
  12403. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12404. begin
  12405. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12406. RemoveCurrentP(p,hp1);
  12407. Result:=true;
  12408. exit;
  12409. end;
  12410. {$endif x86_64}
  12411. else
  12412. ;
  12413. end;
  12414. end;
  12415. end;
  12416. { changes some movzx constructs to faster synonyms (all examples
  12417. are given with eax/ax, but are also valid for other registers)}
  12418. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12419. begin
  12420. case taicpu(p).opsize of
  12421. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12422. (the machine code is equivalent to movzbl %al,%eax), but the
  12423. code generator still generates that assembler instruction and
  12424. it is silently converted. This should probably be checked.
  12425. [Kit] }
  12426. S_BW:
  12427. begin
  12428. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12429. (
  12430. not IsMOVZXAcceptable
  12431. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12432. or (
  12433. (cs_opt_size in current_settings.optimizerswitches) and
  12434. (taicpu(p).oper[1]^.reg = NR_AX)
  12435. )
  12436. ) then
  12437. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12438. begin
  12439. DebugMsg(SPeepholeOptimization + 'var7',p);
  12440. taicpu(p).opcode := A_AND;
  12441. taicpu(p).changeopsize(S_W);
  12442. taicpu(p).loadConst(0,$ff);
  12443. Result := True;
  12444. end
  12445. else if not IsMOVZXAcceptable and
  12446. GetNextInstruction(p, hp1) and
  12447. (tai(hp1).typ = ait_instruction) and
  12448. (taicpu(hp1).opcode = A_AND) and
  12449. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12450. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12451. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12452. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12453. begin
  12454. DebugMsg(SPeepholeOptimization + 'var8',p);
  12455. taicpu(p).opcode := A_MOV;
  12456. taicpu(p).changeopsize(S_W);
  12457. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12458. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12459. Result := True;
  12460. end;
  12461. end;
  12462. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12463. S_BL:
  12464. if not IsMOVZXAcceptable then
  12465. begin
  12466. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12467. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12468. begin
  12469. DebugMsg(SPeepholeOptimization + 'var9',p);
  12470. taicpu(p).opcode := A_AND;
  12471. taicpu(p).changeopsize(S_L);
  12472. taicpu(p).loadConst(0,$ff);
  12473. Result := True;
  12474. end
  12475. else if GetNextInstruction(p, hp1) and
  12476. (tai(hp1).typ = ait_instruction) and
  12477. (taicpu(hp1).opcode = A_AND) and
  12478. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12479. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12480. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12481. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12482. begin
  12483. DebugMsg(SPeepholeOptimization + 'var10',p);
  12484. taicpu(p).opcode := A_MOV;
  12485. taicpu(p).changeopsize(S_L);
  12486. { do not use R_SUBWHOLE
  12487. as movl %rdx,%eax
  12488. is invalid in assembler PM }
  12489. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12490. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12491. Result := True;
  12492. end;
  12493. end;
  12494. {$endif i8086}
  12495. S_WL:
  12496. if not IsMOVZXAcceptable then
  12497. begin
  12498. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12499. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12500. begin
  12501. DebugMsg(SPeepholeOptimization + 'var11',p);
  12502. taicpu(p).opcode := A_AND;
  12503. taicpu(p).changeopsize(S_L);
  12504. taicpu(p).loadConst(0,$ffff);
  12505. Result := True;
  12506. end
  12507. else if GetNextInstruction(p, hp1) and
  12508. (tai(hp1).typ = ait_instruction) and
  12509. (taicpu(hp1).opcode = A_AND) and
  12510. (taicpu(hp1).oper[0]^.typ = top_const) and
  12511. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12512. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12513. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12514. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12515. begin
  12516. DebugMsg(SPeepholeOptimization + 'var12',p);
  12517. taicpu(p).opcode := A_MOV;
  12518. taicpu(p).changeopsize(S_L);
  12519. { do not use R_SUBWHOLE
  12520. as movl %rdx,%eax
  12521. is invalid in assembler PM }
  12522. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12523. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12524. Result := True;
  12525. end;
  12526. end;
  12527. else
  12528. InternalError(2017050705);
  12529. end;
  12530. end
  12531. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12532. begin
  12533. if GetNextInstruction(p, hp1) and
  12534. (tai(hp1).typ = ait_instruction) and
  12535. (taicpu(hp1).opcode = A_AND) and
  12536. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12537. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12538. begin
  12539. //taicpu(p).opcode := A_MOV;
  12540. case taicpu(p).opsize Of
  12541. S_BL:
  12542. begin
  12543. DebugMsg(SPeepholeOptimization + 'var13',p);
  12544. taicpu(hp1).changeopsize(S_L);
  12545. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12546. end;
  12547. S_WL:
  12548. begin
  12549. DebugMsg(SPeepholeOptimization + 'var14',p);
  12550. taicpu(hp1).changeopsize(S_L);
  12551. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12552. end;
  12553. S_BW:
  12554. begin
  12555. DebugMsg(SPeepholeOptimization + 'var15',p);
  12556. taicpu(hp1).changeopsize(S_W);
  12557. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12558. end;
  12559. else
  12560. Internalerror(2017050704)
  12561. end;
  12562. Result := True;
  12563. end;
  12564. end;
  12565. end;
  12566. end;
  12567. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12568. var
  12569. hp1, hp2 : tai;
  12570. MaskLength : Cardinal;
  12571. MaskedBits : TCgInt;
  12572. ActiveReg : TRegister;
  12573. begin
  12574. Result:=false;
  12575. { There are no optimisations for reference targets }
  12576. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12577. Exit;
  12578. while GetNextInstruction(p, hp1) and
  12579. (hp1.typ = ait_instruction) do
  12580. begin
  12581. if (taicpu(p).oper[0]^.typ = top_const) then
  12582. begin
  12583. case taicpu(hp1).opcode of
  12584. A_AND:
  12585. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12586. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12587. { the second register must contain the first one, so compare their subreg types }
  12588. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12589. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12590. { change
  12591. and const1, reg
  12592. and const2, reg
  12593. to
  12594. and (const1 and const2), reg
  12595. }
  12596. begin
  12597. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12598. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12599. RemoveCurrentP(p, hp1);
  12600. Result:=true;
  12601. exit;
  12602. end;
  12603. A_CMP:
  12604. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12605. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12606. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12607. { Just check that the condition on the next instruction is compatible }
  12608. GetNextInstruction(hp1, hp2) and
  12609. (hp2.typ = ait_instruction) and
  12610. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12611. then
  12612. { change
  12613. and 2^n, reg
  12614. cmp 2^n, reg
  12615. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12616. to
  12617. and 2^n, reg
  12618. test reg, reg
  12619. j(~c) / set(~c) / cmov(~c)
  12620. }
  12621. begin
  12622. { Keep TEST instruction in, rather than remove it, because
  12623. it may trigger other optimisations such as MovAndTest2Test }
  12624. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12625. taicpu(hp1).opcode := A_TEST;
  12626. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12627. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12628. Result := True;
  12629. Exit;
  12630. end
  12631. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12632. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12633. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12634. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12635. { change
  12636. and $ff/$ff/$ffff, reg
  12637. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12638. dealloc reg
  12639. to
  12640. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12641. }
  12642. begin
  12643. TransferUsedRegs(TmpUsedRegs);
  12644. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12645. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12646. begin
  12647. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12648. case taicpu(p).oper[0]^.val of
  12649. $ff:
  12650. begin
  12651. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12652. taicpu(hp1).opsize:=S_B;
  12653. end;
  12654. $ffff:
  12655. begin
  12656. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12657. taicpu(hp1).opsize:=S_W;
  12658. end;
  12659. $ffffffff:
  12660. begin
  12661. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12662. taicpu(hp1).opsize:=S_L;
  12663. end;
  12664. else
  12665. Internalerror(2023030401);
  12666. end;
  12667. RemoveCurrentP(p);
  12668. Result := True;
  12669. Exit;
  12670. end;
  12671. end;
  12672. A_MOVZX:
  12673. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12674. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12675. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12676. (
  12677. (
  12678. (taicpu(p).opsize=S_W) and
  12679. (taicpu(hp1).opsize=S_BW)
  12680. ) or
  12681. (
  12682. (taicpu(p).opsize=S_L) and
  12683. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12684. )
  12685. {$ifdef x86_64}
  12686. or
  12687. (
  12688. (taicpu(p).opsize=S_Q) and
  12689. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12690. )
  12691. {$endif x86_64}
  12692. ) then
  12693. begin
  12694. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12695. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12696. ) or
  12697. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12698. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12699. then
  12700. begin
  12701. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12702. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12703. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12704. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12705. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12706. }
  12707. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12708. RemoveInstruction(hp1);
  12709. { See if there are other optimisations possible }
  12710. Continue;
  12711. end;
  12712. end;
  12713. A_SHL:
  12714. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12715. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12716. begin
  12717. {$ifopt R+}
  12718. {$define RANGE_WAS_ON}
  12719. {$R-}
  12720. {$endif}
  12721. { get length of potential and mask }
  12722. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12723. { really a mask? }
  12724. {$ifdef RANGE_WAS_ON}
  12725. {$R+}
  12726. {$endif}
  12727. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12728. { unmasked part shifted out? }
  12729. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12730. begin
  12731. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12732. RemoveCurrentP(p, hp1);
  12733. Result:=true;
  12734. exit;
  12735. end;
  12736. end;
  12737. A_SHR:
  12738. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12739. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12740. (taicpu(hp1).oper[0]^.val <= 63) then
  12741. begin
  12742. { Does SHR combined with the AND cover all the bits?
  12743. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12744. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12745. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12746. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12747. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12748. begin
  12749. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12750. RemoveCurrentP(p, hp1);
  12751. Result := True;
  12752. Exit;
  12753. end;
  12754. end;
  12755. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12756. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12757. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12758. begin
  12759. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12760. (
  12761. (
  12762. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12763. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12764. ) or (
  12765. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12766. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12767. {$ifdef x86_64}
  12768. ) or (
  12769. (taicpu(hp1).opsize = S_LQ) and
  12770. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12771. {$endif x86_64}
  12772. )
  12773. ) then
  12774. begin
  12775. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12776. begin
  12777. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12778. RemoveInstruction(hp1);
  12779. { See if there are other optimisations possible }
  12780. Continue;
  12781. end;
  12782. { The super-registers are the same though.
  12783. Note that this change by itself doesn't improve
  12784. code speed, but it opens up other optimisations. }
  12785. {$ifdef x86_64}
  12786. { Convert 64-bit register to 32-bit }
  12787. case taicpu(hp1).opsize of
  12788. S_BQ:
  12789. begin
  12790. taicpu(hp1).opsize := S_BL;
  12791. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12792. end;
  12793. S_WQ:
  12794. begin
  12795. taicpu(hp1).opsize := S_WL;
  12796. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12797. end
  12798. else
  12799. ;
  12800. end;
  12801. {$endif x86_64}
  12802. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12803. taicpu(hp1).opcode := A_MOVZX;
  12804. { See if there are other optimisations possible }
  12805. Continue;
  12806. end;
  12807. end;
  12808. else
  12809. ;
  12810. end;
  12811. end
  12812. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12813. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12814. begin
  12815. {$ifdef x86_64}
  12816. if (taicpu(p).opsize = S_Q) then
  12817. begin
  12818. { Never necessary }
  12819. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12820. RemoveCurrentP(p, hp1);
  12821. Result := True;
  12822. Exit;
  12823. end;
  12824. {$endif x86_64}
  12825. { Forward check to determine necessity of and %reg,%reg }
  12826. TransferUsedRegs(TmpUsedRegs);
  12827. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12828. { Saves on a bunch of dereferences }
  12829. ActiveReg := taicpu(p).oper[1]^.reg;
  12830. case taicpu(hp1).opcode of
  12831. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12832. if (
  12833. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12834. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12835. ) and
  12836. (
  12837. (taicpu(hp1).opcode <> A_MOV) or
  12838. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12839. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12840. ) and
  12841. not (
  12842. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12843. (taicpu(hp1).opcode = A_MOV) and
  12844. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12845. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12846. ) and
  12847. (
  12848. (
  12849. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12850. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12851. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12852. ) or
  12853. (
  12854. {$ifdef x86_64}
  12855. (
  12856. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12857. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12858. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12859. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12860. ) and
  12861. {$endif x86_64}
  12862. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12863. )
  12864. ) then
  12865. begin
  12866. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12867. RemoveCurrentP(p, hp1);
  12868. Result := True;
  12869. Exit;
  12870. end;
  12871. A_ADD,
  12872. A_AND,
  12873. A_BSF,
  12874. A_BSR,
  12875. A_BTC,
  12876. A_BTR,
  12877. A_BTS,
  12878. A_OR,
  12879. A_SUB,
  12880. A_XOR:
  12881. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12882. if (
  12883. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12884. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12885. ) and
  12886. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12887. begin
  12888. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12889. RemoveCurrentP(p, hp1);
  12890. Result := True;
  12891. Exit;
  12892. end;
  12893. A_CMP,
  12894. A_TEST:
  12895. if (
  12896. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12897. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12898. ) and
  12899. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12900. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12901. begin
  12902. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12903. RemoveCurrentP(p, hp1);
  12904. Result := True;
  12905. Exit;
  12906. end;
  12907. A_BSWAP,
  12908. A_NEG,
  12909. A_NOT:
  12910. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12911. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12912. begin
  12913. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12914. RemoveCurrentP(p, hp1);
  12915. Result := True;
  12916. Exit;
  12917. end;
  12918. else
  12919. ;
  12920. end;
  12921. end;
  12922. if (taicpu(hp1).is_jmp) and
  12923. (taicpu(hp1).opcode<>A_JMP) and
  12924. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12925. begin
  12926. { change
  12927. and x, reg
  12928. jxx
  12929. to
  12930. test x, reg
  12931. jxx
  12932. if reg is deallocated before the
  12933. jump, but only if it's a conditional jump (PFV)
  12934. }
  12935. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12936. taicpu(p).opcode := A_TEST;
  12937. Exit;
  12938. end;
  12939. Break;
  12940. end;
  12941. { Lone AND tests }
  12942. if (taicpu(p).oper[0]^.typ = top_const) then
  12943. begin
  12944. {
  12945. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12946. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12947. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12948. }
  12949. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12950. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12951. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12952. begin
  12953. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12954. if taicpu(p).opsize = S_L then
  12955. begin
  12956. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12957. Result := True;
  12958. end;
  12959. end;
  12960. end;
  12961. { Backward check to determine necessity of and %reg,%reg }
  12962. if (taicpu(p).oper[0]^.typ = top_reg) and
  12963. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12964. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12965. GetLastInstruction(p, hp2) and
  12966. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12967. { Check size of adjacent instruction to determine if the AND is
  12968. effectively a null operation }
  12969. (
  12970. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12971. { Note: Don't include S_Q }
  12972. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12973. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12974. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12975. ) then
  12976. begin
  12977. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12978. { If GetNextInstruction returned False, hp1 will be nil }
  12979. RemoveCurrentP(p, hp1);
  12980. Result := True;
  12981. Exit;
  12982. end;
  12983. end;
  12984. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12985. var
  12986. hp1, hp2: tai;
  12987. NewRef: TReference;
  12988. Distance: Cardinal;
  12989. TempTracking: TAllUsedRegs;
  12990. { This entire nested function is used in an if-statement below, but we
  12991. want to avoid all the used reg transfers and GetNextInstruction calls
  12992. until we really have to check }
  12993. function MemRegisterNotUsedLater: Boolean; inline;
  12994. var
  12995. hp2: tai;
  12996. begin
  12997. TransferUsedRegs(TmpUsedRegs);
  12998. hp2 := p;
  12999. repeat
  13000. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13001. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13002. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13003. end;
  13004. begin
  13005. Result := False;
  13006. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13007. (taicpu(p).oper[1]^.typ = top_reg) then
  13008. begin
  13009. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13010. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13011. (hp1.typ <> ait_instruction) or
  13012. not
  13013. (
  13014. (cs_opt_level3 in current_settings.optimizerswitches) or
  13015. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13016. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13017. ) then
  13018. Exit;
  13019. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13020. addq $x, %rax
  13021. movq %rax, %rdx
  13022. sarq $63, %rdx
  13023. (%rax still in use)
  13024. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13025. leaq $x(%rax),%rdx
  13026. addq $x, %rax
  13027. sarq $63, %rdx
  13028. ...which is okay since it breaks the dependency chain between
  13029. addq and movq, but if OptPass2MOV is called first:
  13030. addq $x, %rax
  13031. cqto
  13032. ...which is better in all ways, taking only 2 cycles to execute
  13033. and much smaller in code size.
  13034. }
  13035. { The extra register tracking is quite strenuous }
  13036. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13037. MatchInstruction(hp1, A_MOV, []) then
  13038. begin
  13039. { Update the register tracking to the MOV instruction }
  13040. CopyUsedRegs(TempTracking);
  13041. hp2 := p;
  13042. repeat
  13043. UpdateUsedRegs(tai(hp2.Next));
  13044. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13045. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13046. OptPass2ADD get called again }
  13047. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13048. begin
  13049. { Reset the tracking to the current instruction }
  13050. RestoreUsedRegs(TempTracking);
  13051. ReleaseUsedRegs(TempTracking);
  13052. Result := True;
  13053. Exit;
  13054. end;
  13055. { Reset the tracking to the current instruction }
  13056. RestoreUsedRegs(TempTracking);
  13057. ReleaseUsedRegs(TempTracking);
  13058. { If OptPass2MOV returned True, we don't need to set Result to
  13059. True if hp1 didn't change because the ADD instruction didn't
  13060. get modified and we'll be evaluating hp1 again when the
  13061. peephole optimizer reaches it }
  13062. end;
  13063. { Change:
  13064. add %reg2,%reg1
  13065. (%reg2 not modified in between)
  13066. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13067. To:
  13068. mov/s/z #(%reg1,%reg2),%reg1
  13069. }
  13070. if (taicpu(p).oper[0]^.typ = top_reg) and
  13071. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13072. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13073. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13074. (
  13075. (
  13076. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13077. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13078. { r/esp cannot be an index }
  13079. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13080. ) or (
  13081. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13082. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13083. )
  13084. ) and (
  13085. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13086. (
  13087. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13088. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13089. MemRegisterNotUsedLater
  13090. )
  13091. ) then
  13092. begin
  13093. if (
  13094. { Instructions are guaranteed to be adjacent on -O2 and under }
  13095. (cs_opt_level3 in current_settings.optimizerswitches) and
  13096. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13097. ) then
  13098. begin
  13099. { If the other register is used in between, move the MOV
  13100. instruction to right after the ADD instruction so a
  13101. saving can still be made }
  13102. Asml.Remove(hp1);
  13103. Asml.InsertAfter(hp1, p);
  13104. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13105. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13106. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13107. RemoveCurrentp(p, hp1);
  13108. end
  13109. else
  13110. begin
  13111. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13112. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13113. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13114. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13115. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13116. { hp1 may not be the immediate next instruction under -O3 }
  13117. RemoveCurrentp(p)
  13118. else
  13119. RemoveCurrentp(p, hp1);
  13120. end;
  13121. Result := True;
  13122. Exit;
  13123. end;
  13124. { Change:
  13125. addl/q $x,%reg1
  13126. movl/q %reg1,%reg2
  13127. To:
  13128. leal/q $x(%reg1),%reg2
  13129. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13130. Breaks the dependency chain.
  13131. }
  13132. if (taicpu(p).oper[0]^.typ = top_const) and
  13133. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13134. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13135. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13136. (
  13137. { Instructions are guaranteed to be adjacent on -O2 and under }
  13138. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13139. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13140. ) then
  13141. begin
  13142. TransferUsedRegs(TmpUsedRegs);
  13143. hp2 := p;
  13144. repeat
  13145. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13146. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13147. if (
  13148. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13149. not (cs_opt_size in current_settings.optimizerswitches) or
  13150. (
  13151. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13152. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13153. )
  13154. ) then
  13155. begin
  13156. { Change the MOV instruction to a LEA instruction, and update the
  13157. first operand }
  13158. reference_reset(NewRef, 1, []);
  13159. NewRef.base := taicpu(p).oper[1]^.reg;
  13160. NewRef.scalefactor := 1;
  13161. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13162. taicpu(hp1).opcode := A_LEA;
  13163. taicpu(hp1).loadref(0, NewRef);
  13164. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13165. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13166. begin
  13167. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13168. { Move what is now the LEA instruction to before the ADD instruction }
  13169. Asml.Remove(hp1);
  13170. Asml.InsertBefore(hp1, p);
  13171. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13172. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13173. p := hp1;
  13174. end
  13175. else
  13176. begin
  13177. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13178. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13179. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13180. { hp1 may not be the immediate next instruction under -O3 }
  13181. RemoveCurrentp(p)
  13182. else
  13183. RemoveCurrentp(p, hp1);
  13184. end;
  13185. Result := True;
  13186. end;
  13187. end;
  13188. end;
  13189. end;
  13190. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13191. var
  13192. SubReg: TSubRegister;
  13193. begin
  13194. Result:=false;
  13195. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13196. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13197. with taicpu(p).oper[0]^.ref^ do
  13198. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13199. begin
  13200. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13201. begin
  13202. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13203. taicpu(p).opcode := A_ADD;
  13204. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13205. Result := True;
  13206. end
  13207. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13208. begin
  13209. if (base <> NR_NO) then
  13210. begin
  13211. if (scalefactor <= 1) then
  13212. begin
  13213. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13214. taicpu(p).opcode := A_ADD;
  13215. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13216. Result := True;
  13217. end;
  13218. end
  13219. else
  13220. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13221. if (scalefactor in [2, 4, 8]) then
  13222. begin
  13223. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13224. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13225. taicpu(p).opcode := A_SHL;
  13226. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13227. Result := True;
  13228. end;
  13229. end;
  13230. end;
  13231. end;
  13232. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13233. var
  13234. hp1, hp2: tai;
  13235. NewRef: TReference;
  13236. Distance: Cardinal;
  13237. TempTracking: TAllUsedRegs;
  13238. begin
  13239. Result := False;
  13240. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13241. MatchOpType(taicpu(p),top_const,top_reg) then
  13242. begin
  13243. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13244. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13245. (hp1.typ <> ait_instruction) or
  13246. not
  13247. (
  13248. (cs_opt_level3 in current_settings.optimizerswitches) or
  13249. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13250. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13251. ) then
  13252. Exit;
  13253. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13254. subq $x, %rax
  13255. movq %rax, %rdx
  13256. sarq $63, %rdx
  13257. (%rax still in use)
  13258. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13259. leaq $-x(%rax),%rdx
  13260. movq $x, %rax
  13261. sarq $63, %rdx
  13262. ...which is okay since it breaks the dependency chain between
  13263. subq and movq, but if OptPass2MOV is called first:
  13264. subq $x, %rax
  13265. cqto
  13266. ...which is better in all ways, taking only 2 cycles to execute
  13267. and much smaller in code size.
  13268. }
  13269. { The extra register tracking is quite strenuous }
  13270. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13271. MatchInstruction(hp1, A_MOV, []) then
  13272. begin
  13273. { Update the register tracking to the MOV instruction }
  13274. CopyUsedRegs(TempTracking);
  13275. hp2 := p;
  13276. repeat
  13277. UpdateUsedRegs(tai(hp2.Next));
  13278. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13279. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13280. OptPass2SUB get called again }
  13281. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13282. begin
  13283. { Reset the tracking to the current instruction }
  13284. RestoreUsedRegs(TempTracking);
  13285. ReleaseUsedRegs(TempTracking);
  13286. Result := True;
  13287. Exit;
  13288. end;
  13289. { Reset the tracking to the current instruction }
  13290. RestoreUsedRegs(TempTracking);
  13291. ReleaseUsedRegs(TempTracking);
  13292. { If OptPass2MOV returned True, we don't need to set Result to
  13293. True if hp1 didn't change because the SUB instruction didn't
  13294. get modified and we'll be evaluating hp1 again when the
  13295. peephole optimizer reaches it }
  13296. end;
  13297. { Change:
  13298. subl/q $x,%reg1
  13299. movl/q %reg1,%reg2
  13300. To:
  13301. leal/q $-x(%reg1),%reg2
  13302. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13303. Breaks the dependency chain and potentially permits the removal of
  13304. a CMP instruction if one follows.
  13305. }
  13306. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13307. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13308. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13309. (
  13310. { Instructions are guaranteed to be adjacent on -O2 and under }
  13311. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13312. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13313. ) then
  13314. begin
  13315. TransferUsedRegs(TmpUsedRegs);
  13316. hp2 := p;
  13317. repeat
  13318. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13319. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13320. if (
  13321. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13322. not (cs_opt_size in current_settings.optimizerswitches) or
  13323. (
  13324. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13325. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13326. )
  13327. ) then
  13328. begin
  13329. { Change the MOV instruction to a LEA instruction, and update the
  13330. first operand }
  13331. reference_reset(NewRef, 1, []);
  13332. NewRef.base := taicpu(p).oper[1]^.reg;
  13333. NewRef.scalefactor := 1;
  13334. NewRef.offset := -taicpu(p).oper[0]^.val;
  13335. taicpu(hp1).opcode := A_LEA;
  13336. taicpu(hp1).loadref(0, NewRef);
  13337. TransferUsedRegs(TmpUsedRegs);
  13338. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13339. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13340. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13341. begin
  13342. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13343. { Move what is now the LEA instruction to before the SUB instruction }
  13344. Asml.Remove(hp1);
  13345. Asml.InsertBefore(hp1, p);
  13346. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13347. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13348. p := hp1;
  13349. end
  13350. else
  13351. begin
  13352. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13353. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13354. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13355. { hp1 may not be the immediate next instruction under -O3 }
  13356. RemoveCurrentp(p)
  13357. else
  13358. RemoveCurrentp(p, hp1);
  13359. end;
  13360. Result := True;
  13361. end;
  13362. end;
  13363. end;
  13364. end;
  13365. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13366. begin
  13367. { we can skip all instructions not messing with the stack pointer }
  13368. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13369. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13370. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13371. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13372. ({(taicpu(hp1).ops=0) or }
  13373. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13374. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13375. ) and }
  13376. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13377. )
  13378. ) do
  13379. GetNextInstruction(hp1,hp1);
  13380. Result:=assigned(hp1);
  13381. end;
  13382. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13383. var
  13384. hp1, hp2, hp3, hp4, hp5: tai;
  13385. begin
  13386. Result:=false;
  13387. hp5:=nil;
  13388. { replace
  13389. leal(q) x(<stackpointer>),<stackpointer>
  13390. call procname
  13391. leal(q) -x(<stackpointer>),<stackpointer>
  13392. ret
  13393. by
  13394. jmp procname
  13395. but do it only on level 4 because it destroys stack back traces
  13396. }
  13397. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13398. MatchOpType(taicpu(p),top_ref,top_reg) and
  13399. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13400. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13401. { the -8 or -24 are not required, but bail out early if possible,
  13402. higher values are unlikely }
  13403. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13404. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13405. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13406. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13407. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13408. GetNextInstruction(p, hp1) and
  13409. { Take a copy of hp1 }
  13410. SetAndTest(hp1, hp4) and
  13411. { trick to skip label }
  13412. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13413. SkipSimpleInstructions(hp1) and
  13414. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13415. GetNextInstruction(hp1, hp2) and
  13416. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13417. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13418. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13419. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13420. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13421. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13422. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13423. { Segment register will be NR_NO }
  13424. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13425. GetNextInstruction(hp2, hp3) and
  13426. { trick to skip label }
  13427. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13428. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13429. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13430. SetAndTest(hp3,hp5) and
  13431. GetNextInstruction(hp3,hp3) and
  13432. MatchInstruction(hp3,A_RET,[S_NO])
  13433. )
  13434. ) and
  13435. (taicpu(hp3).ops=0) then
  13436. begin
  13437. taicpu(hp1).opcode := A_JMP;
  13438. taicpu(hp1).is_jmp := true;
  13439. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13440. RemoveCurrentP(p, hp4);
  13441. RemoveInstruction(hp2);
  13442. RemoveInstruction(hp3);
  13443. if Assigned(hp5) then
  13444. begin
  13445. AsmL.Remove(hp5);
  13446. ASmL.InsertBefore(hp5,hp1)
  13447. end;
  13448. Result:=true;
  13449. end;
  13450. end;
  13451. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13452. {$ifdef x86_64}
  13453. var
  13454. hp1, hp2, hp3, hp4, hp5: tai;
  13455. {$endif x86_64}
  13456. begin
  13457. Result:=false;
  13458. {$ifdef x86_64}
  13459. hp5:=nil;
  13460. { replace
  13461. push %rax
  13462. call procname
  13463. pop %rcx
  13464. ret
  13465. by
  13466. jmp procname
  13467. but do it only on level 4 because it destroys stack back traces
  13468. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13469. for all supported calling conventions
  13470. }
  13471. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13472. MatchOpType(taicpu(p),top_reg) and
  13473. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13474. GetNextInstruction(p, hp1) and
  13475. { Take a copy of hp1 }
  13476. SetAndTest(hp1, hp4) and
  13477. { trick to skip label }
  13478. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13479. SkipSimpleInstructions(hp1) and
  13480. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13481. GetNextInstruction(hp1, hp2) and
  13482. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13483. MatchOpType(taicpu(hp2),top_reg) and
  13484. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13485. GetNextInstruction(hp2, hp3) and
  13486. { trick to skip label }
  13487. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13488. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13489. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13490. SetAndTest(hp3,hp5) and
  13491. GetNextInstruction(hp3,hp3) and
  13492. MatchInstruction(hp3,A_RET,[S_NO])
  13493. )
  13494. ) and
  13495. (taicpu(hp3).ops=0) then
  13496. begin
  13497. taicpu(hp1).opcode := A_JMP;
  13498. taicpu(hp1).is_jmp := true;
  13499. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13500. RemoveCurrentP(p, hp4);
  13501. RemoveInstruction(hp2);
  13502. RemoveInstruction(hp3);
  13503. if Assigned(hp5) then
  13504. begin
  13505. AsmL.Remove(hp5);
  13506. ASmL.InsertBefore(hp5,hp1)
  13507. end;
  13508. Result:=true;
  13509. end;
  13510. {$endif x86_64}
  13511. end;
  13512. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13513. var
  13514. Value, RegName: string;
  13515. begin
  13516. Result:=false;
  13517. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13518. begin
  13519. case taicpu(p).oper[0]^.val of
  13520. 0:
  13521. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13522. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13523. begin
  13524. { change "mov $0,%reg" into "xor %reg,%reg" }
  13525. taicpu(p).opcode := A_XOR;
  13526. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13527. Result := True;
  13528. {$ifdef x86_64}
  13529. end
  13530. else if (taicpu(p).opsize = S_Q) then
  13531. begin
  13532. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13533. { The actual optimization }
  13534. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13535. taicpu(p).changeopsize(S_L);
  13536. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13537. Result := True;
  13538. end;
  13539. $1..$FFFFFFFF:
  13540. begin
  13541. { Code size reduction by J. Gareth "Kit" Moreton }
  13542. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13543. case taicpu(p).opsize of
  13544. S_Q:
  13545. begin
  13546. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13547. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13548. { The actual optimization }
  13549. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13550. taicpu(p).changeopsize(S_L);
  13551. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13552. Result := True;
  13553. end;
  13554. else
  13555. { Do nothing };
  13556. end;
  13557. {$endif x86_64}
  13558. end;
  13559. -1:
  13560. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13561. if (cs_opt_size in current_settings.optimizerswitches) and
  13562. (taicpu(p).opsize <> S_B) and
  13563. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13564. begin
  13565. { change "mov $-1,%reg" into "or $-1,%reg" }
  13566. { NOTES:
  13567. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13568. - This operation creates a false dependency on the register, so only do it when optimising for size
  13569. - 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
  13570. }
  13571. taicpu(p).opcode := A_OR;
  13572. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13573. Result := True;
  13574. end;
  13575. else
  13576. { Do nothing };
  13577. end;
  13578. end;
  13579. end;
  13580. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13581. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13582. begin
  13583. Result := False;
  13584. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13585. Exit;
  13586. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13587. so don't bother optimising }
  13588. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13589. Exit;
  13590. if (taicpu(p).oper[0]^.typ <> top_const) or
  13591. { If the value can fit into an 8-bit signed integer, a smaller
  13592. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13593. falls within this range }
  13594. (
  13595. (taicpu(p).oper[0]^.val > -128) and
  13596. (taicpu(p).oper[0]^.val <= 127)
  13597. ) then
  13598. Exit;
  13599. { If we're optimising for size, this is acceptable }
  13600. if (cs_opt_size in current_settings.optimizerswitches) then
  13601. Exit(True);
  13602. if (taicpu(p).oper[1]^.typ = top_reg) and
  13603. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13604. Exit(True);
  13605. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13606. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13607. Exit(True);
  13608. end;
  13609. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13610. var
  13611. hp1: tai;
  13612. Value: TCGInt;
  13613. begin
  13614. Result := False;
  13615. if MatchOpType(taicpu(p), top_const, top_reg) then
  13616. begin
  13617. { Detect:
  13618. andw x, %ax (0 <= x < $8000)
  13619. ...
  13620. movzwl %ax,%eax
  13621. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13622. }
  13623. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13624. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13625. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13626. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13627. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13628. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13629. begin
  13630. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13631. taicpu(hp1).opcode := A_CWDE;
  13632. taicpu(hp1).clearop(0);
  13633. taicpu(hp1).clearop(1);
  13634. taicpu(hp1).ops := 0;
  13635. { A change was made, but not with p, so don't set Result, but
  13636. notify the compiler that a change was made }
  13637. Include(OptsToCheck, aoc_ForceNewIteration);
  13638. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13639. end;
  13640. end;
  13641. { If "not x" is a power of 2 (popcnt = 1), change:
  13642. and $x, %reg/ref
  13643. To:
  13644. btr lb(x), %reg/ref
  13645. }
  13646. if IsBTXAcceptable(p) and
  13647. (
  13648. { Make sure a TEST doesn't follow that plays with the register }
  13649. not GetNextInstruction(p, hp1) or
  13650. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13651. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13652. ) then
  13653. begin
  13654. {$push}{$R-}{$Q-}
  13655. { Value is a sign-extended 32-bit integer - just correct it
  13656. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13657. checks to see if this operand is an immediate. }
  13658. Value := not taicpu(p).oper[0]^.val;
  13659. {$pop}
  13660. {$ifdef x86_64}
  13661. if taicpu(p).opsize = S_L then
  13662. {$endif x86_64}
  13663. Value := Value and $FFFFFFFF;
  13664. if (PopCnt(QWord(Value)) = 1) then
  13665. begin
  13666. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13667. taicpu(p).opcode := A_BTR;
  13668. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13669. Result := True;
  13670. Exit;
  13671. end;
  13672. end;
  13673. end;
  13674. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13675. begin
  13676. Result := False;
  13677. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13678. Exit;
  13679. { Convert:
  13680. movswl %ax,%eax -> cwtl
  13681. movslq %eax,%rax -> cdqe
  13682. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13683. refer to the same opcode and depends only on the assembler's
  13684. current operand-size attribute. [Kit]
  13685. }
  13686. with taicpu(p) do
  13687. case opsize of
  13688. S_WL:
  13689. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13690. begin
  13691. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13692. opcode := A_CWDE;
  13693. clearop(0);
  13694. clearop(1);
  13695. ops := 0;
  13696. Result := True;
  13697. end;
  13698. {$ifdef x86_64}
  13699. S_LQ:
  13700. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13701. begin
  13702. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13703. opcode := A_CDQE;
  13704. clearop(0);
  13705. clearop(1);
  13706. ops := 0;
  13707. Result := True;
  13708. end;
  13709. {$endif x86_64}
  13710. else
  13711. ;
  13712. end;
  13713. end;
  13714. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13715. var
  13716. hp1, hp2: tai;
  13717. IdentityMask, Shift: TCGInt;
  13718. LimitSize: Topsize;
  13719. DoNotMerge: Boolean;
  13720. begin
  13721. Result := False;
  13722. { All these optimisations work on "shr const,%reg" }
  13723. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13724. Exit;
  13725. DoNotMerge := False;
  13726. Shift := taicpu(p).oper[0]^.val;
  13727. LimitSize := taicpu(p).opsize;
  13728. hp1 := p;
  13729. repeat
  13730. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13731. Break;
  13732. { Detect:
  13733. shr x, %reg
  13734. and y, %reg
  13735. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13736. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13737. }
  13738. case taicpu(hp1).opcode of
  13739. A_AND:
  13740. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13741. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13742. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13743. begin
  13744. { Make sure the FLAGS register isn't in use }
  13745. TransferUsedRegs(TmpUsedRegs);
  13746. hp2 := p;
  13747. repeat
  13748. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13749. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13750. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13751. begin
  13752. { Generate the identity mask }
  13753. case taicpu(p).opsize of
  13754. S_B:
  13755. IdentityMask := $FF shr Shift;
  13756. S_W:
  13757. IdentityMask := $FFFF shr Shift;
  13758. S_L:
  13759. IdentityMask := $FFFFFFFF shr Shift;
  13760. {$ifdef x86_64}
  13761. S_Q:
  13762. { We need to force the operands to be unsigned 64-bit
  13763. integers otherwise the wrong value is generated }
  13764. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13765. {$endif x86_64}
  13766. else
  13767. InternalError(2022081501);
  13768. end;
  13769. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13770. begin
  13771. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13772. { All the possible 1 bits are covered, so we can remove the AND }
  13773. hp2 := tai(hp1.Previous);
  13774. RemoveInstruction(hp1);
  13775. { p wasn't actually changed, so don't set Result to True,
  13776. but a change was nonetheless made elsewhere }
  13777. Include(OptsToCheck, aoc_ForceNewIteration);
  13778. { Do another pass in case other AND or MOVZX instructions
  13779. follow }
  13780. hp1 := hp2;
  13781. Continue;
  13782. end;
  13783. end;
  13784. end;
  13785. A_TEST, A_CMP, A_Jcc:
  13786. { Skip over conditional jumps and relevant comparisons }
  13787. Continue;
  13788. A_MOVZX:
  13789. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13790. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13791. begin
  13792. { Since the original register is being read as is, subsequent
  13793. SHRs must not be merged at this point }
  13794. DoNotMerge := True;
  13795. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13796. begin
  13797. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13798. begin
  13799. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13800. { All the possible 1 bits are covered, so we can remove the AND }
  13801. hp2 := tai(hp1.Previous);
  13802. RemoveInstruction(hp1);
  13803. hp1 := hp2;
  13804. end
  13805. else { Different register target }
  13806. begin
  13807. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13808. taicpu(hp1).opcode := A_MOV;
  13809. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13810. case taicpu(hp1).opsize of
  13811. S_BW:
  13812. taicpu(hp1).opsize := S_W;
  13813. S_BL, S_WL:
  13814. taicpu(hp1).opsize := S_L;
  13815. else
  13816. InternalError(2022081503);
  13817. end;
  13818. end;
  13819. end
  13820. else if (Shift > 0) and
  13821. (taicpu(p).opsize = S_W) and
  13822. (taicpu(hp1).opsize = S_WL) and
  13823. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13824. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13825. begin
  13826. { Detect:
  13827. shr x, %ax (x > 0)
  13828. ...
  13829. movzwl %ax,%eax
  13830. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13831. }
  13832. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13833. taicpu(hp1).opcode := A_CWDE;
  13834. taicpu(hp1).clearop(0);
  13835. taicpu(hp1).clearop(1);
  13836. taicpu(hp1).ops := 0;
  13837. end;
  13838. { Move onto the next instruction }
  13839. Continue;
  13840. end;
  13841. A_SHL, A_SAL, A_SHR:
  13842. if (taicpu(hp1).opsize <= LimitSize) and
  13843. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13844. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13845. begin
  13846. { Make sure the sizes don't exceed the register size limit
  13847. (measured by the shift value falling below the limit) }
  13848. if taicpu(hp1).opsize < LimitSize then
  13849. LimitSize := taicpu(hp1).opsize;
  13850. if taicpu(hp1).opcode = A_SHR then
  13851. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13852. else
  13853. begin
  13854. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13855. DoNotMerge := True;
  13856. end;
  13857. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13858. Break;
  13859. { Since we've established that the combined shift is within
  13860. limits, we can actually combine the adjacent SHR
  13861. instructions even if they're different sizes }
  13862. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13863. begin
  13864. hp2 := tai(hp1.Previous);
  13865. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13866. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13867. RemoveInstruction(hp1);
  13868. hp1 := hp2;
  13869. end;
  13870. { Move onto the next instruction }
  13871. Continue;
  13872. end;
  13873. else
  13874. ;
  13875. end;
  13876. Break;
  13877. until False;
  13878. { Detect the following (looking backwards):
  13879. shr %cl,%reg
  13880. shr x, %reg
  13881. Swap the two SHR instructions to minimise a pipeline stall.
  13882. }
  13883. if GetLastInstruction(p, hp1) and
  13884. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13885. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13886. { First operand will be %cl }
  13887. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13888. { Just to be sure }
  13889. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13890. begin
  13891. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13892. { Moving the entries this way ensures the register tracking remains correct }
  13893. Asml.Remove(p);
  13894. Asml.InsertBefore(p, hp1);
  13895. p := hp1;
  13896. { Don't set Result to True because the current instruction is now
  13897. "shr %cl,%reg" and there's nothing more we can do with it }
  13898. end;
  13899. end;
  13900. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13901. var
  13902. hp1, hp2: tai;
  13903. Opposite, SecondOpposite: TAsmOp;
  13904. NewCond: TAsmCond;
  13905. begin
  13906. Result := False;
  13907. { Change:
  13908. add/sub 128,(dest)
  13909. To:
  13910. sub/add -128,(dest)
  13911. This generaally takes fewer bytes to encode because -128 can be stored
  13912. in a signed byte, whereas +128 cannot.
  13913. }
  13914. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13915. begin
  13916. if taicpu(p).opcode = A_ADD then
  13917. Opposite := A_SUB
  13918. else
  13919. Opposite := A_ADD;
  13920. { Be careful if the flags are in use, because the CF flag inverts
  13921. when changing from ADD to SUB and vice versa }
  13922. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13923. GetNextInstruction(p, hp1) then
  13924. begin
  13925. TransferUsedRegs(TmpUsedRegs);
  13926. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13927. hp2 := hp1;
  13928. { Scan ahead to check if everything's safe }
  13929. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13930. begin
  13931. if (hp1.typ <> ait_instruction) then
  13932. { Probably unsafe since the flags are still in use }
  13933. Exit;
  13934. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13935. { Stop searching at an unconditional jump }
  13936. Break;
  13937. if not
  13938. (
  13939. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13940. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13941. ) and
  13942. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13943. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13944. Exit;
  13945. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13946. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13947. { Move to the next instruction }
  13948. GetNextInstruction(hp1, hp1);
  13949. end;
  13950. while Assigned(hp2) and (hp2 <> hp1) do
  13951. begin
  13952. NewCond := C_None;
  13953. case taicpu(hp2).condition of
  13954. C_A, C_NBE:
  13955. NewCond := C_BE;
  13956. C_B, C_C, C_NAE:
  13957. NewCond := C_AE;
  13958. C_AE, C_NB, C_NC:
  13959. NewCond := C_B;
  13960. C_BE, C_NA:
  13961. NewCond := C_A;
  13962. else
  13963. { No change needed };
  13964. end;
  13965. if NewCond <> C_None then
  13966. begin
  13967. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13968. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13969. taicpu(hp2).condition := NewCond;
  13970. end
  13971. else
  13972. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13973. begin
  13974. { Because of the flipping of the carry bit, to ensure
  13975. the operation remains equivalent, ADC becomes SBB
  13976. and vice versa, and the constant is not-inverted.
  13977. If multiple ADCs or SBBs appear in a row, each one
  13978. changed causes the carry bit to invert, so they all
  13979. need to be flipped }
  13980. if taicpu(hp2).opcode = A_ADC then
  13981. SecondOpposite := A_SBB
  13982. else
  13983. SecondOpposite := A_ADC;
  13984. if taicpu(hp2).oper[0]^.typ <> top_const then
  13985. { Should have broken out of this optimisation already }
  13986. InternalError(2021112901);
  13987. 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]^) + ' -> ' +
  13988. 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);
  13989. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13990. taicpu(hp2).opcode := SecondOpposite;
  13991. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13992. end;
  13993. { Move to the next instruction }
  13994. GetNextInstruction(hp2, hp2);
  13995. end;
  13996. if (hp2 <> hp1) then
  13997. InternalError(2021111501);
  13998. end;
  13999. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14000. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14001. taicpu(p).opcode := Opposite;
  14002. taicpu(p).oper[0]^.val := -128;
  14003. { No further optimisations can be made on this instruction, so move
  14004. onto the next one to save time }
  14005. p := tai(p.Next);
  14006. UpdateUsedRegs(p);
  14007. Result := True;
  14008. Exit;
  14009. end;
  14010. { Detect:
  14011. add/sub %reg2,(dest)
  14012. add/sub x, (dest)
  14013. (dest can be a register or a reference)
  14014. Swap the instructions to minimise a pipeline stall. This reverses the
  14015. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14016. optimisations could be made.
  14017. }
  14018. if (taicpu(p).oper[0]^.typ = top_reg) and
  14019. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14020. (
  14021. (
  14022. (taicpu(p).oper[1]^.typ = top_reg) and
  14023. { We can try searching further ahead if we're writing to a register }
  14024. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14025. ) or
  14026. (
  14027. (taicpu(p).oper[1]^.typ = top_ref) and
  14028. GetNextInstruction(p, hp1)
  14029. )
  14030. ) and
  14031. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14032. (taicpu(hp1).oper[0]^.typ = top_const) and
  14033. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14034. begin
  14035. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14036. TransferUsedRegs(TmpUsedRegs);
  14037. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14038. hp2 := p;
  14039. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14040. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14041. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14042. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14043. begin
  14044. asml.remove(hp1);
  14045. asml.InsertBefore(hp1, p);
  14046. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14047. Result := True;
  14048. end;
  14049. end;
  14050. end;
  14051. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14052. var
  14053. hp1: tai;
  14054. begin
  14055. Result:=false;
  14056. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14057. while GetNextInstruction(p, hp1) and
  14058. TrySwapMovCmp(p, hp1) do
  14059. begin
  14060. if MatchInstruction(hp1, A_MOV, []) then
  14061. begin
  14062. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14063. begin
  14064. { A little hacky, but since CMP doesn't read the flags, only
  14065. modify them, it's safe if they get scrambled by MOV -> XOR }
  14066. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14067. Result := PostPeepholeOptMov(hp1);
  14068. {$ifdef x86_64}
  14069. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14070. { Used to shrink instruction size }
  14071. PostPeepholeOptXor(hp1);
  14072. {$endif x86_64}
  14073. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14074. end
  14075. else
  14076. begin
  14077. Result := PostPeepholeOptMov(hp1);
  14078. {$ifdef x86_64}
  14079. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14080. { Used to shrink instruction size }
  14081. PostPeepholeOptXor(hp1);
  14082. {$endif x86_64}
  14083. end;
  14084. end;
  14085. { Enabling this flag is actually a null operation, but it marks
  14086. the code as 'modified' during this pass }
  14087. Include(OptsToCheck, aoc_ForceNewIteration);
  14088. end;
  14089. { change "cmp $0, %reg" to "test %reg, %reg" }
  14090. if MatchOpType(taicpu(p),top_const,top_reg) and
  14091. (taicpu(p).oper[0]^.val = 0) then
  14092. begin
  14093. taicpu(p).opcode := A_TEST;
  14094. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14095. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14096. Result:=true;
  14097. end;
  14098. end;
  14099. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14100. var
  14101. IsTestConstX, IsValid : Boolean;
  14102. hp1,hp2 : tai;
  14103. begin
  14104. Result:=false;
  14105. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14106. if (taicpu(p).opcode = A_TEST) then
  14107. while GetNextInstruction(p, hp1) and
  14108. TrySwapMovCmp(p, hp1) do
  14109. begin
  14110. if MatchInstruction(hp1, A_MOV, []) then
  14111. begin
  14112. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14113. begin
  14114. { A little hacky, but since TEST doesn't read the flags, only
  14115. modify them, it's safe if they get scrambled by MOV -> XOR }
  14116. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14117. Result := PostPeepholeOptMov(hp1);
  14118. {$ifdef x86_64}
  14119. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14120. { Used to shrink instruction size }
  14121. PostPeepholeOptXor(hp1);
  14122. {$endif x86_64}
  14123. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14124. end
  14125. else
  14126. begin
  14127. Result := PostPeepholeOptMov(hp1);
  14128. {$ifdef x86_64}
  14129. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14130. { Used to shrink instruction size }
  14131. PostPeepholeOptXor(hp1);
  14132. {$endif x86_64}
  14133. end;
  14134. end;
  14135. { Enabling this flag is actually a null operation, but it marks
  14136. the code as 'modified' during this pass }
  14137. Include(OptsToCheck, aoc_ForceNewIteration);
  14138. end;
  14139. { If x is a power of 2 (popcnt = 1), change:
  14140. or $x, %reg/ref
  14141. To:
  14142. bts lb(x), %reg/ref
  14143. }
  14144. if (taicpu(p).opcode = A_OR) and
  14145. IsBTXAcceptable(p) and
  14146. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14147. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14148. (
  14149. { Don't optimise if a test instruction follows }
  14150. not GetNextInstruction(p, hp1) or
  14151. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14152. ) then
  14153. begin
  14154. 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);
  14155. taicpu(p).opcode := A_BTS;
  14156. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14157. Result := True;
  14158. Exit;
  14159. end;
  14160. { If x is a power of 2 (popcnt = 1), change:
  14161. test $x, %reg/ref
  14162. je / sete / cmove (or jne / setne)
  14163. To:
  14164. bt lb(x), %reg/ref
  14165. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14166. }
  14167. if (taicpu(p).opcode = A_TEST) and
  14168. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14169. (taicpu(p).oper[0]^.typ = top_const) and
  14170. (
  14171. (cs_opt_size in current_settings.optimizerswitches) or
  14172. (
  14173. (taicpu(p).oper[1]^.typ = top_reg) and
  14174. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14175. ) or
  14176. (
  14177. (taicpu(p).oper[1]^.typ <> top_reg) and
  14178. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14179. )
  14180. ) and
  14181. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14182. { For sizes less than S_L, the byte size is equal or larger with BT,
  14183. so don't bother optimising }
  14184. (taicpu(p).opsize >= S_L) then
  14185. begin
  14186. IsValid := True;
  14187. { Check the next set of instructions, watching the FLAGS register
  14188. and the conditions used }
  14189. TransferUsedRegs(TmpUsedRegs);
  14190. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14191. hp1 := p;
  14192. hp2 := nil;
  14193. while GetNextInstruction(hp1, hp1) do
  14194. begin
  14195. if not Assigned(hp2) then
  14196. { The first instruction after TEST }
  14197. hp2 := hp1;
  14198. if (hp1.typ <> ait_instruction) then
  14199. begin
  14200. { If the flags are no longer in use, everything is fine }
  14201. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14202. IsValid := False;
  14203. Break;
  14204. end;
  14205. case taicpu(hp1).condition of
  14206. C_None:
  14207. begin
  14208. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14209. { Something is not quite normal, so play safe and don't change }
  14210. IsValid := False;
  14211. Break;
  14212. end;
  14213. C_E, C_Z, C_NE, C_NZ:
  14214. { This is fine };
  14215. else
  14216. begin
  14217. { Unsupported condition }
  14218. IsValid := False;
  14219. Break;
  14220. end;
  14221. end;
  14222. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14223. end;
  14224. if IsValid then
  14225. begin
  14226. while hp2 <> hp1 do
  14227. begin
  14228. case taicpu(hp2).condition of
  14229. C_Z, C_E:
  14230. taicpu(hp2).condition := C_NC;
  14231. C_NZ, C_NE:
  14232. taicpu(hp2).condition := C_C;
  14233. else
  14234. { Should not get this by this point }
  14235. InternalError(2022110701);
  14236. end;
  14237. GetNextInstruction(hp2, hp2);
  14238. end;
  14239. 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);
  14240. taicpu(p).opcode := A_BT;
  14241. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14242. Result := True;
  14243. Exit;
  14244. end;
  14245. end;
  14246. { removes the line marked with (x) from the sequence
  14247. and/or/xor/add/sub/... $x, %y
  14248. test/or %y, %y | test $-1, %y (x)
  14249. j(n)z _Label
  14250. as the first instruction already adjusts the ZF
  14251. %y operand may also be a reference }
  14252. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14253. MatchOperand(taicpu(p).oper[0]^,-1);
  14254. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14255. GetLastInstruction(p, hp1) and
  14256. (tai(hp1).typ = ait_instruction) and
  14257. GetNextInstruction(p,hp2) and
  14258. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14259. case taicpu(hp1).opcode Of
  14260. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14261. { These two instructions set the zero flag if the result is zero }
  14262. A_POPCNT, A_LZCNT:
  14263. begin
  14264. if (
  14265. { With POPCNT, an input of zero will set the zero flag
  14266. because the population count of zero is zero }
  14267. (taicpu(hp1).opcode = A_POPCNT) and
  14268. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14269. (
  14270. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14271. { Faster than going through the second half of the 'or'
  14272. condition below }
  14273. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14274. )
  14275. ) or (
  14276. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14277. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14278. { and in case of carry for A(E)/B(E)/C/NC }
  14279. (
  14280. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14281. (
  14282. (taicpu(hp1).opcode <> A_ADD) and
  14283. (taicpu(hp1).opcode <> A_SUB) and
  14284. (taicpu(hp1).opcode <> A_LZCNT)
  14285. )
  14286. )
  14287. ) then
  14288. begin
  14289. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14290. RemoveCurrentP(p, hp2);
  14291. Result:=true;
  14292. Exit;
  14293. end;
  14294. end;
  14295. A_SHL, A_SAL, A_SHR, A_SAR:
  14296. begin
  14297. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14298. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14299. { therefore, it's only safe to do this optimization for }
  14300. { shifts by a (nonzero) constant }
  14301. (taicpu(hp1).oper[0]^.typ = top_const) and
  14302. (taicpu(hp1).oper[0]^.val <> 0) and
  14303. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14304. { and in case of carry for A(E)/B(E)/C/NC }
  14305. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14306. begin
  14307. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14308. RemoveCurrentP(p, hp2);
  14309. Result:=true;
  14310. Exit;
  14311. end;
  14312. end;
  14313. A_DEC, A_INC, A_NEG:
  14314. begin
  14315. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14316. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14317. { and in case of carry for A(E)/B(E)/C/NC }
  14318. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14319. begin
  14320. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14321. RemoveCurrentP(p, hp2);
  14322. Result:=true;
  14323. Exit;
  14324. end;
  14325. end;
  14326. A_ANDN, A_BZHI:
  14327. begin
  14328. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14329. { Only the zero and sign flags are consistent with what the result is }
  14330. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14331. begin
  14332. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14333. RemoveCurrentP(p, hp2);
  14334. Result:=true;
  14335. Exit;
  14336. end;
  14337. end;
  14338. A_BEXTR:
  14339. begin
  14340. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14341. { Only the zero flag is set }
  14342. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14343. begin
  14344. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14345. RemoveCurrentP(p, hp2);
  14346. Result:=true;
  14347. Exit;
  14348. end;
  14349. end;
  14350. else
  14351. ;
  14352. end; { case }
  14353. { change "test $-1,%reg" into "test %reg,%reg" }
  14354. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14355. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14356. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14357. if MatchInstruction(p, A_OR, []) and
  14358. { Can only match if they're both registers }
  14359. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14360. begin
  14361. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14362. taicpu(p).opcode := A_TEST;
  14363. { No need to set Result to True, as we've done all the optimisations we can }
  14364. end;
  14365. end;
  14366. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14367. var
  14368. hp1,hp3 : tai;
  14369. {$ifndef x86_64}
  14370. hp2 : taicpu;
  14371. {$endif x86_64}
  14372. begin
  14373. Result:=false;
  14374. hp3:=nil;
  14375. {$ifndef x86_64}
  14376. { don't do this on modern CPUs, this really hurts them due to
  14377. broken call/ret pairing }
  14378. if (current_settings.optimizecputype < cpu_Pentium2) and
  14379. not(cs_create_pic in current_settings.moduleswitches) and
  14380. GetNextInstruction(p, hp1) and
  14381. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14382. MatchOpType(taicpu(hp1),top_ref) and
  14383. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14384. begin
  14385. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14386. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14387. InsertLLItem(p.previous, p, hp2);
  14388. taicpu(p).opcode := A_JMP;
  14389. taicpu(p).is_jmp := true;
  14390. RemoveInstruction(hp1);
  14391. Result:=true;
  14392. end
  14393. else
  14394. {$endif x86_64}
  14395. { replace
  14396. call procname
  14397. ret
  14398. by
  14399. jmp procname
  14400. but do it only on level 4 because it destroys stack back traces
  14401. else if the subroutine is marked as no return, remove the ret
  14402. }
  14403. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14404. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14405. GetNextInstruction(p, hp1) and
  14406. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14407. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14408. SetAndTest(hp1,hp3) and
  14409. GetNextInstruction(hp1,hp1) and
  14410. MatchInstruction(hp1,A_RET,[S_NO])
  14411. )
  14412. ) and
  14413. (taicpu(hp1).ops=0) then
  14414. begin
  14415. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14416. { we might destroy stack alignment here if we do not do a call }
  14417. (target_info.stackalign<=sizeof(SizeUInt)) then
  14418. begin
  14419. taicpu(p).opcode := A_JMP;
  14420. taicpu(p).is_jmp := true;
  14421. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14422. end
  14423. else
  14424. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14425. RemoveInstruction(hp1);
  14426. if Assigned(hp3) then
  14427. begin
  14428. AsmL.Remove(hp3);
  14429. AsmL.InsertBefore(hp3,p)
  14430. end;
  14431. Result:=true;
  14432. end;
  14433. end;
  14434. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14435. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14436. begin
  14437. case OpSize of
  14438. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14439. Result := (Val <= $FF) and (Val >= -128);
  14440. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14441. Result := (Val <= $FFFF) and (Val >= -32768);
  14442. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14443. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14444. else
  14445. Result := True;
  14446. end;
  14447. end;
  14448. var
  14449. hp1, hp2 : tai;
  14450. SizeChange: Boolean;
  14451. PreMessage: string;
  14452. begin
  14453. Result := False;
  14454. if (taicpu(p).oper[0]^.typ = top_reg) and
  14455. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14456. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14457. begin
  14458. { Change (using movzbl %al,%eax as an example):
  14459. movzbl %al, %eax movzbl %al, %eax
  14460. cmpl x, %eax testl %eax,%eax
  14461. To:
  14462. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14463. movzbl %al, %eax movzbl %al, %eax
  14464. Smaller instruction and minimises pipeline stall as the CPU
  14465. doesn't have to wait for the register to get zero-extended. [Kit]
  14466. Also allow if the smaller of the two registers is being checked,
  14467. as this still removes the false dependency.
  14468. }
  14469. if
  14470. (
  14471. (
  14472. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14473. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14474. ) or (
  14475. { If MatchOperand returns True, they must both be registers }
  14476. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14477. )
  14478. ) and
  14479. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14480. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14481. begin
  14482. 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);
  14483. asml.Remove(hp1);
  14484. asml.InsertBefore(hp1, p);
  14485. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14486. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14487. begin
  14488. taicpu(hp1).opcode := A_TEST;
  14489. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14490. end;
  14491. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14492. case taicpu(p).opsize of
  14493. S_BW, S_BL:
  14494. begin
  14495. SizeChange := taicpu(hp1).opsize <> S_B;
  14496. taicpu(hp1).changeopsize(S_B);
  14497. end;
  14498. S_WL:
  14499. begin
  14500. SizeChange := taicpu(hp1).opsize <> S_W;
  14501. taicpu(hp1).changeopsize(S_W);
  14502. end
  14503. else
  14504. InternalError(2020112701);
  14505. end;
  14506. UpdateUsedRegs(tai(p.Next));
  14507. { Check if the register is used aferwards - if not, we can
  14508. remove the movzx instruction completely }
  14509. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14510. begin
  14511. { Hp1 is a better position than p for debugging purposes }
  14512. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14513. RemoveCurrentp(p, hp1);
  14514. Result := True;
  14515. end;
  14516. if SizeChange then
  14517. DebugMsg(SPeepholeOptimization + PreMessage +
  14518. 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)
  14519. else
  14520. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14521. Exit;
  14522. end;
  14523. { Change (using movzwl %ax,%eax as an example):
  14524. movzwl %ax, %eax
  14525. movb %al, (dest) (Register is smaller than read register in movz)
  14526. To:
  14527. movb %al, (dest) (Move one back to avoid a false dependency)
  14528. movzwl %ax, %eax
  14529. }
  14530. if (taicpu(hp1).opcode = A_MOV) and
  14531. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14532. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14533. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14534. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14535. begin
  14536. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14537. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14538. asml.Remove(hp1);
  14539. asml.InsertBefore(hp1, p);
  14540. if taicpu(hp1).oper[1]^.typ = top_reg then
  14541. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14542. { Check if the register is used aferwards - if not, we can
  14543. remove the movzx instruction completely }
  14544. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14545. begin
  14546. { Hp1 is a better position than p for debugging purposes }
  14547. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14548. RemoveCurrentp(p, hp1);
  14549. Result := True;
  14550. end;
  14551. Exit;
  14552. end;
  14553. end;
  14554. end;
  14555. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14556. var
  14557. hp1: tai;
  14558. {$ifdef x86_64}
  14559. PreMessage, RegName: string;
  14560. {$endif x86_64}
  14561. begin
  14562. Result := False;
  14563. { If x is a power of 2 (popcnt = 1), change:
  14564. xor $x, %reg/ref
  14565. To:
  14566. btc lb(x), %reg/ref
  14567. }
  14568. if IsBTXAcceptable(p) and
  14569. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14570. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14571. (
  14572. { Don't optimise if a test instruction follows }
  14573. not GetNextInstruction(p, hp1) or
  14574. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14575. ) then
  14576. begin
  14577. 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);
  14578. taicpu(p).opcode := A_BTC;
  14579. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14580. Result := True;
  14581. Exit;
  14582. end;
  14583. {$ifdef x86_64}
  14584. { Code size reduction by J. Gareth "Kit" Moreton }
  14585. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14586. as this removes the REX prefix }
  14587. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14588. Exit;
  14589. if taicpu(p).oper[0]^.typ <> top_reg then
  14590. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14591. InternalError(2018011500);
  14592. case taicpu(p).opsize of
  14593. S_Q:
  14594. begin
  14595. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14596. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14597. { The actual optimization }
  14598. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14599. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14600. taicpu(p).changeopsize(S_L);
  14601. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14602. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14603. end;
  14604. else
  14605. ;
  14606. end;
  14607. {$endif x86_64}
  14608. end;
  14609. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14610. var
  14611. XReg: TRegister;
  14612. begin
  14613. Result := False;
  14614. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14615. Smaller encoding and slightly faster on some platforms (also works for
  14616. ZMM-sized registers) }
  14617. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14618. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14619. begin
  14620. XReg := taicpu(p).oper[0]^.reg;
  14621. if (taicpu(p).oper[1]^.reg = XReg) then
  14622. begin
  14623. taicpu(p).changeopsize(S_XMM);
  14624. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14625. if (cs_opt_size in current_settings.optimizerswitches) then
  14626. begin
  14627. { Change input registers to %xmm0 to reduce size. Note that
  14628. there's a risk of a false dependency doing this, so only
  14629. optimise for size here }
  14630. XReg := NR_XMM0;
  14631. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14632. end
  14633. else
  14634. begin
  14635. setsubreg(XReg, R_SUBMMX);
  14636. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14637. end;
  14638. taicpu(p).oper[0]^.reg := XReg;
  14639. taicpu(p).oper[1]^.reg := XReg;
  14640. Result := True;
  14641. end;
  14642. end;
  14643. end;
  14644. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14645. var
  14646. OperIdx: Integer;
  14647. begin
  14648. for OperIdx := 0 to p.ops - 1 do
  14649. if p.oper[OperIdx]^.typ = top_ref then
  14650. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14651. end;
  14652. end.