aoptx86.pas 698 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2037. begin
  2038. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2039. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2040. begin
  2041. { vmova* reg1,reg2
  2042. vmova* reg2,reg3
  2043. dealloc reg2
  2044. =>
  2045. vmova* reg1,reg3 }
  2046. TransferUsedRegs(TmpUsedRegs);
  2047. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2048. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2049. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2050. begin
  2051. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2052. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2053. RemoveInstruction(hp1);
  2054. result:=true;
  2055. exit;
  2056. end;
  2057. { special case:
  2058. vmova* reg1,<op>
  2059. vmova* <op>,reg1
  2060. =>
  2061. vmova* reg1,<op> }
  2062. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2063. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2064. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2065. ) then
  2066. begin
  2067. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2068. RemoveInstruction(hp1);
  2069. result:=true;
  2070. exit;
  2071. end
  2072. end
  2073. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2074. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2075. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2076. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2077. ) and
  2078. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2079. begin
  2080. { vmova* reg1,reg2
  2081. vmovs* reg2,<op>
  2082. dealloc reg2
  2083. =>
  2084. vmovs* reg1,reg3 }
  2085. TransferUsedRegs(TmpUsedRegs);
  2086. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2087. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2088. begin
  2089. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2090. taicpu(p).opcode:=taicpu(hp1).opcode;
  2091. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2092. RemoveInstruction(hp1);
  2093. result:=true;
  2094. exit;
  2095. end
  2096. end;
  2097. end;
  2098. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2099. begin
  2100. if MatchInstruction(hp1,[A_VFMADDPD,
  2101. A_VFMADD132PD,
  2102. A_VFMADD132PS,
  2103. A_VFMADD132SD,
  2104. A_VFMADD132SS,
  2105. A_VFMADD213PD,
  2106. A_VFMADD213PS,
  2107. A_VFMADD213SD,
  2108. A_VFMADD213SS,
  2109. A_VFMADD231PD,
  2110. A_VFMADD231PS,
  2111. A_VFMADD231SD,
  2112. A_VFMADD231SS,
  2113. A_VFMADDSUB132PD,
  2114. A_VFMADDSUB132PS,
  2115. A_VFMADDSUB213PD,
  2116. A_VFMADDSUB213PS,
  2117. A_VFMADDSUB231PD,
  2118. A_VFMADDSUB231PS,
  2119. A_VFMSUB132PD,
  2120. A_VFMSUB132PS,
  2121. A_VFMSUB132SD,
  2122. A_VFMSUB132SS,
  2123. A_VFMSUB213PD,
  2124. A_VFMSUB213PS,
  2125. A_VFMSUB213SD,
  2126. A_VFMSUB213SS,
  2127. A_VFMSUB231PD,
  2128. A_VFMSUB231PS,
  2129. A_VFMSUB231SD,
  2130. A_VFMSUB231SS,
  2131. A_VFMSUBADD132PD,
  2132. A_VFMSUBADD132PS,
  2133. A_VFMSUBADD213PD,
  2134. A_VFMSUBADD213PS,
  2135. A_VFMSUBADD231PD,
  2136. A_VFMSUBADD231PS,
  2137. A_VFNMADD132PD,
  2138. A_VFNMADD132PS,
  2139. A_VFNMADD132SD,
  2140. A_VFNMADD132SS,
  2141. A_VFNMADD213PD,
  2142. A_VFNMADD213PS,
  2143. A_VFNMADD213SD,
  2144. A_VFNMADD213SS,
  2145. A_VFNMADD231PD,
  2146. A_VFNMADD231PS,
  2147. A_VFNMADD231SD,
  2148. A_VFNMADD231SS,
  2149. A_VFNMSUB132PD,
  2150. A_VFNMSUB132PS,
  2151. A_VFNMSUB132SD,
  2152. A_VFNMSUB132SS,
  2153. A_VFNMSUB213PD,
  2154. A_VFNMSUB213PS,
  2155. A_VFNMSUB213SD,
  2156. A_VFNMSUB213SS,
  2157. A_VFNMSUB231PD,
  2158. A_VFNMSUB231PS,
  2159. A_VFNMSUB231SD,
  2160. A_VFNMSUB231SS],[S_NO]) and
  2161. { we mix single and double opperations here because we assume that the compiler
  2162. generates vmovapd only after double operations and vmovaps only after single operations }
  2163. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2164. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2165. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2166. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2170. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2171. begin
  2172. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2173. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2174. RemoveCurrentP(p)
  2175. else
  2176. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2177. RemoveInstruction(hp2);
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_MOVAPS) and
  2182. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2183. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2184. ((taicpu(p).opcode=A_MOVAPD) and
  2185. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2186. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2187. ) and
  2188. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2189. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2190. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2191. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2192. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2193. { change
  2194. movapX reg,reg2
  2195. addsX/subsX/... reg3, reg2
  2196. movapX reg2,reg
  2197. to
  2198. addsX/subsX/... reg3,reg
  2199. }
  2200. begin
  2201. TransferUsedRegs(TmpUsedRegs);
  2202. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2203. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2204. begin
  2205. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2206. debug_op2str(taicpu(p).opcode)+' '+
  2207. debug_op2str(taicpu(hp1).opcode)+' '+
  2208. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2209. { we cannot eliminate the first move if
  2210. the operations uses the same register for source and dest }
  2211. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2212. { Remember that hp1 is not necessarily the immediate
  2213. next instruction }
  2214. RemoveCurrentP(p);
  2215. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2216. RemoveInstruction(hp2);
  2217. result:=true;
  2218. end;
  2219. end
  2220. else if (hp1.typ = ait_instruction) and
  2221. (((taicpu(p).opcode=A_VMOVAPD) and
  2222. (taicpu(hp1).opcode=A_VCOMISD)) or
  2223. ((taicpu(p).opcode=A_VMOVAPS) and
  2224. ((taicpu(hp1).opcode=A_VCOMISS))
  2225. )
  2226. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { change
  2228. movapX reg,reg1
  2229. vcomisX reg1,reg1
  2230. to
  2231. vcomisX reg,reg
  2232. }
  2233. begin
  2234. TransferUsedRegs(TmpUsedRegs);
  2235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2236. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2237. begin
  2238. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2239. debug_op2str(taicpu(p).opcode)+' '+
  2240. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2241. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2242. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2243. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2244. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2245. RemoveCurrentP(p);
  2246. result:=true;
  2247. exit;
  2248. end;
  2249. end
  2250. end;
  2251. end;
  2252. end;
  2253. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2254. var
  2255. hp1 : tai;
  2256. begin
  2257. result:=false;
  2258. { replace
  2259. V<Op>X %mreg1,%mreg2,%mreg3
  2260. VMovX %mreg3,%mreg4
  2261. dealloc %mreg3
  2262. by
  2263. V<Op>X %mreg1,%mreg2,%mreg4
  2264. ?
  2265. }
  2266. if GetNextInstruction(p,hp1) and
  2267. { we mix single and double operations here because we assume that the compiler
  2268. generates vmovapd only after double operations and vmovaps only after single operations }
  2269. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2270. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2271. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2272. begin
  2273. TransferUsedRegs(TmpUsedRegs);
  2274. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2275. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2276. begin
  2277. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2278. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2279. RemoveInstruction(hp1);
  2280. result:=true;
  2281. end;
  2282. end;
  2283. end;
  2284. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2285. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2286. begin
  2287. Result := False;
  2288. { For safety reasons, only check for exact register matches }
  2289. { Check base register }
  2290. if (ref.base = AOldReg) then
  2291. begin
  2292. ref.base := ANewReg;
  2293. Result := True;
  2294. end;
  2295. { Check index register }
  2296. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2297. begin
  2298. ref.index := ANewReg;
  2299. Result := True;
  2300. end;
  2301. end;
  2302. { Replaces all references to AOldReg in an operand to ANewReg }
  2303. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2304. var
  2305. OldSupReg, NewSupReg: TSuperRegister;
  2306. OldSubReg, NewSubReg: TSubRegister;
  2307. OldRegType: TRegisterType;
  2308. ThisOper: POper;
  2309. begin
  2310. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2311. Result := False;
  2312. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2313. InternalError(2020011801);
  2314. OldSupReg := getsupreg(AOldReg);
  2315. OldSubReg := getsubreg(AOldReg);
  2316. OldRegType := getregtype(AOldReg);
  2317. NewSupReg := getsupreg(ANewReg);
  2318. NewSubReg := getsubreg(ANewReg);
  2319. if OldRegType <> getregtype(ANewReg) then
  2320. InternalError(2020011802);
  2321. if OldSubReg <> NewSubReg then
  2322. InternalError(2020011803);
  2323. case ThisOper^.typ of
  2324. top_reg:
  2325. if (
  2326. (ThisOper^.reg = AOldReg) or
  2327. (
  2328. (OldRegType = R_INTREGISTER) and
  2329. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2330. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2331. (
  2332. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2333. {$ifndef x86_64}
  2334. and (
  2335. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2336. don't have an 8-bit representation }
  2337. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2338. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2339. )
  2340. {$endif x86_64}
  2341. )
  2342. )
  2343. ) then
  2344. begin
  2345. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2346. Result := True;
  2347. end;
  2348. top_ref:
  2349. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2350. Result := True;
  2351. else
  2352. ;
  2353. end;
  2354. end;
  2355. { Replaces all references to AOldReg in an instruction to ANewReg }
  2356. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2357. const
  2358. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2359. var
  2360. OperIdx: Integer;
  2361. begin
  2362. Result := False;
  2363. for OperIdx := 0 to p.ops - 1 do
  2364. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2365. begin
  2366. { The shift and rotate instructions can only use CL }
  2367. if not (
  2368. (OperIdx = 0) and
  2369. { This second condition just helps to avoid unnecessarily
  2370. calling MatchInstruction for 10 different opcodes }
  2371. (p.oper[0]^.reg = NR_CL) and
  2372. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2373. ) then
  2374. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2375. end
  2376. else if p.oper[OperIdx]^.typ = top_ref then
  2377. { It's okay to replace registers in references that get written to }
  2378. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2379. end;
  2380. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2381. begin
  2382. Result :=
  2383. (ref^.index = NR_NO) and
  2384. (
  2385. {$ifdef x86_64}
  2386. (
  2387. (ref^.base = NR_RIP) and
  2388. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2389. ) or
  2390. {$endif x86_64}
  2391. (ref^.refaddr = addr_full) or
  2392. (ref^.base = NR_STACK_POINTER_REG) or
  2393. (ref^.base = current_procinfo.framepointer)
  2394. );
  2395. end;
  2396. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2397. var
  2398. l: asizeint;
  2399. begin
  2400. Result := False;
  2401. { Should have been checked previously }
  2402. if p.opcode <> A_LEA then
  2403. InternalError(2020072501);
  2404. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2405. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2406. not(cs_opt_size in current_settings.optimizerswitches) then
  2407. exit;
  2408. with p.oper[0]^.ref^ do
  2409. begin
  2410. if (base <> p.oper[1]^.reg) or
  2411. (index <> NR_NO) or
  2412. assigned(symbol) then
  2413. exit;
  2414. l:=offset;
  2415. if (l=1) and UseIncDec then
  2416. begin
  2417. p.opcode:=A_INC;
  2418. p.loadreg(0,p.oper[1]^.reg);
  2419. p.ops:=1;
  2420. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2421. end
  2422. else if (l=-1) and UseIncDec then
  2423. begin
  2424. p.opcode:=A_DEC;
  2425. p.loadreg(0,p.oper[1]^.reg);
  2426. p.ops:=1;
  2427. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2428. end
  2429. else
  2430. begin
  2431. if (l<0) and (l<>-2147483648) then
  2432. begin
  2433. p.opcode:=A_SUB;
  2434. p.loadConst(0,-l);
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2436. end
  2437. else
  2438. begin
  2439. p.opcode:=A_ADD;
  2440. p.loadConst(0,l);
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2442. end;
  2443. end;
  2444. end;
  2445. Result := True;
  2446. end;
  2447. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2448. var
  2449. CurrentReg, ReplaceReg: TRegister;
  2450. begin
  2451. Result := False;
  2452. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2453. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2454. case hp.opcode of
  2455. A_FSTSW, A_FNSTSW,
  2456. A_IN, A_INS, A_OUT, A_OUTS,
  2457. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2458. { These routines have explicit operands, but they are restricted in
  2459. what they can be (e.g. IN and OUT can only read from AL, AX or
  2460. EAX. }
  2461. Exit;
  2462. A_IMUL:
  2463. begin
  2464. { The 1-operand version writes to implicit registers
  2465. The 2-operand version reads from the first operator, and reads
  2466. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2467. the 3-operand version reads from a register that it doesn't write to
  2468. }
  2469. case hp.ops of
  2470. 1:
  2471. if (
  2472. (
  2473. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2474. ) or
  2475. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2476. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2477. begin
  2478. Result := True;
  2479. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2480. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2481. end;
  2482. 2:
  2483. { Only modify the first parameter }
  2484. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2485. begin
  2486. Result := True;
  2487. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2488. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2489. end;
  2490. 3:
  2491. { Only modify the second parameter }
  2492. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2493. begin
  2494. Result := True;
  2495. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2496. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2497. end;
  2498. else
  2499. InternalError(2020012901);
  2500. end;
  2501. end;
  2502. else
  2503. if (hp.ops > 0) and
  2504. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. end;
  2511. end;
  2512. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2513. var
  2514. hp2: tai;
  2515. p_SourceReg, p_TargetReg: TRegister;
  2516. begin
  2517. Result := False;
  2518. { Backward optimisation. If we have:
  2519. func. %reg1,%reg2
  2520. mov %reg2,%reg3
  2521. (dealloc %reg2)
  2522. Change to:
  2523. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2524. Perform similar optimisations with 1, 3 and 4-operand instructions
  2525. that only have one output.
  2526. }
  2527. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2528. begin
  2529. p_SourceReg := taicpu(p).oper[0]^.reg;
  2530. p_TargetReg := taicpu(p).oper[1]^.reg;
  2531. TransferUsedRegs(TmpUsedRegs);
  2532. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2533. GetLastInstruction(p, hp2) and
  2534. (hp2.typ = ait_instruction) and
  2535. { Have to make sure it's an instruction that only reads from
  2536. the first operands and only writes (not reads or modifies) to
  2537. the last one; in essence, a pure function such as BSR, POPCNT
  2538. or ANDN }
  2539. (
  2540. (
  2541. (taicpu(hp2).ops = 1) and
  2542. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2543. ) or
  2544. (
  2545. (taicpu(hp2).ops = 2) and
  2546. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2547. ) or
  2548. (
  2549. (taicpu(hp2).ops = 3) and
  2550. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2551. ) or
  2552. (
  2553. (taicpu(hp2).ops = 4) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2555. )
  2556. ) and
  2557. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2558. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2559. begin
  2560. case taicpu(hp2).opcode of
  2561. A_FSTSW, A_FNSTSW,
  2562. A_IN, A_INS, A_OUT, A_OUTS,
  2563. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2564. { These routines have explicit operands, but they are restricted in
  2565. what they can be (e.g. IN and OUT can only read from AL, AX or
  2566. EAX. }
  2567. ;
  2568. else
  2569. begin
  2570. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2571. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2572. if not RegInInstruction(p_TargetReg, hp2) then
  2573. begin
  2574. { Since we're allocating from an earlier point, we
  2575. need to remove the register from the tracking }
  2576. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2577. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2578. end;
  2579. RemoveCurrentp(p, hp1);
  2580. { If the Func was another MOV instruction, we might get
  2581. "mov %reg,%reg" that doesn't get removed in Pass 2
  2582. otherwise, so deal with it here (also do something
  2583. similar with lea (%reg),%reg}
  2584. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2585. begin
  2586. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2587. if p = hp2 then
  2588. RemoveCurrentp(p)
  2589. else
  2590. RemoveInstruction(hp2);
  2591. end;
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. end;
  2596. end;
  2597. end;
  2598. end;
  2599. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2600. var
  2601. hp1, hp2, hp3: tai;
  2602. DoOptimisation, TempBool: Boolean;
  2603. {$ifdef x86_64}
  2604. NewConst: TCGInt;
  2605. {$endif x86_64}
  2606. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2607. begin
  2608. if taicpu(hp1).opcode = signed_movop then
  2609. begin
  2610. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2611. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2612. end
  2613. else
  2614. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2615. end;
  2616. function TryConstMerge(var p1, p2: tai): Boolean;
  2617. var
  2618. ThisRef: TReference;
  2619. begin
  2620. Result := False;
  2621. ThisRef := taicpu(p2).oper[1]^.ref^;
  2622. { Only permit writes to the stack, since we can guarantee alignment with that }
  2623. if (ThisRef.index = NR_NO) and
  2624. (
  2625. (ThisRef.base = NR_STACK_POINTER_REG) or
  2626. (ThisRef.base = current_procinfo.framepointer)
  2627. ) then
  2628. begin
  2629. case taicpu(p).opsize of
  2630. S_B:
  2631. begin
  2632. { Word writes must be on a 2-byte boundary }
  2633. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2634. begin
  2635. { Reduce offset of second reference to see if it is sequential with the first }
  2636. Dec(ThisRef.offset, 1);
  2637. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2638. begin
  2639. { Make sure the constants aren't represented as a
  2640. negative number, as these won't merge properly }
  2641. taicpu(p1).opsize := S_W;
  2642. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2643. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2644. RemoveInstruction(p2);
  2645. Result := True;
  2646. end;
  2647. end;
  2648. end;
  2649. S_W:
  2650. begin
  2651. { Longword writes must be on a 4-byte boundary }
  2652. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2653. begin
  2654. { Reduce offset of second reference to see if it is sequential with the first }
  2655. Dec(ThisRef.offset, 2);
  2656. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2657. begin
  2658. { Make sure the constants aren't represented as a
  2659. negative number, as these won't merge properly }
  2660. taicpu(p1).opsize := S_L;
  2661. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2662. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2663. RemoveInstruction(p2);
  2664. Result := True;
  2665. end;
  2666. end;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_L:
  2670. begin
  2671. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2672. see if the constants can be encoded this way. }
  2673. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2674. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2675. { Quadword writes must be on an 8-byte boundary }
  2676. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2677. begin
  2678. { Reduce offset of second reference to see if it is sequential with the first }
  2679. Dec(ThisRef.offset, 4);
  2680. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2681. begin
  2682. { Make sure the constants aren't represented as a
  2683. negative number, as these won't merge properly }
  2684. taicpu(p1).opsize := S_Q;
  2685. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2686. taicpu(p1).oper[0]^.val := NewConst;
  2687. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2688. RemoveInstruction(p2);
  2689. Result := True;
  2690. end;
  2691. end;
  2692. end;
  2693. {$endif x86_64}
  2694. else
  2695. ;
  2696. end;
  2697. end;
  2698. end;
  2699. var
  2700. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2701. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2702. NewSize: topsize; NewOffset: asizeint;
  2703. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2704. SourceRef, TargetRef: TReference;
  2705. MovAligned, MovUnaligned: TAsmOp;
  2706. ThisRef: TReference;
  2707. JumpTracking: TLinkedList;
  2708. begin
  2709. Result:=false;
  2710. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2711. { remove mov reg1,reg1? }
  2712. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2713. then
  2714. begin
  2715. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2716. { take care of the register (de)allocs following p }
  2717. RemoveCurrentP(p, hp1);
  2718. Result:=true;
  2719. exit;
  2720. end;
  2721. { All the next optimisations require a next instruction }
  2722. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2723. Exit;
  2724. { Prevent compiler warnings }
  2725. p_TargetReg := NR_NO;
  2726. if taicpu(p).oper[1]^.typ = top_reg then
  2727. begin
  2728. { Saves on a large number of dereferences }
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. { Look for:
  2731. mov %reg1,%reg2
  2732. ??? %reg2,r/m
  2733. Change to:
  2734. mov %reg1,%reg2
  2735. ??? %reg1,r/m
  2736. }
  2737. if taicpu(p).oper[0]^.typ = top_reg then
  2738. begin
  2739. if RegReadByInstruction(p_TargetReg, hp1) and
  2740. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2741. begin
  2742. { A change has occurred, just not in p }
  2743. Result := True;
  2744. TransferUsedRegs(TmpUsedRegs);
  2745. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2746. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2747. { Just in case something didn't get modified (e.g. an
  2748. implicit register) }
  2749. not RegReadByInstruction(p_TargetReg, hp1) then
  2750. begin
  2751. { We can remove the original MOV }
  2752. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2753. RemoveCurrentp(p, hp1);
  2754. { UsedRegs got updated by RemoveCurrentp }
  2755. Result := True;
  2756. Exit;
  2757. end;
  2758. { If we know a MOV instruction has become a null operation, we might as well
  2759. get rid of it now to save time. }
  2760. if (taicpu(hp1).opcode = A_MOV) and
  2761. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2762. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2763. { Just being a register is enough to confirm it's a null operation }
  2764. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2765. begin
  2766. Result := True;
  2767. { Speed-up to reduce a pipeline stall... if we had something like...
  2768. movl %eax,%edx
  2769. movw %dx,%ax
  2770. ... the second instruction would change to movw %ax,%ax, but
  2771. given that it is now %ax that's active rather than %eax,
  2772. penalties might occur due to a partial register write, so instead,
  2773. change it to a MOVZX instruction when optimising for speed.
  2774. }
  2775. if not (cs_opt_size in current_settings.optimizerswitches) and
  2776. IsMOVZXAcceptable and
  2777. (taicpu(hp1).opsize < taicpu(p).opsize)
  2778. {$ifdef x86_64}
  2779. { operations already implicitly set the upper 64 bits to zero }
  2780. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2781. {$endif x86_64}
  2782. then
  2783. begin
  2784. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2785. case taicpu(p).opsize of
  2786. S_W:
  2787. if taicpu(hp1).opsize = S_B then
  2788. taicpu(hp1).opsize := S_BL
  2789. else
  2790. InternalError(2020012911);
  2791. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2792. case taicpu(hp1).opsize of
  2793. S_B:
  2794. taicpu(hp1).opsize := S_BL;
  2795. S_W:
  2796. taicpu(hp1).opsize := S_WL;
  2797. else
  2798. InternalError(2020012912);
  2799. end;
  2800. else
  2801. InternalError(2020012910);
  2802. end;
  2803. taicpu(hp1).opcode := A_MOVZX;
  2804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2805. end
  2806. else
  2807. begin
  2808. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2809. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2810. RemoveInstruction(hp1);
  2811. { The instruction after what was hp1 is now the immediate next instruction,
  2812. so we can continue to make optimisations if it's present }
  2813. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2814. Exit;
  2815. hp1 := hp2;
  2816. end;
  2817. end;
  2818. end;
  2819. end;
  2820. end;
  2821. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2822. overwrites the original destination register. e.g.
  2823. movl ###,%reg2d
  2824. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2825. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2826. }
  2827. if (taicpu(p).oper[1]^.typ = top_reg) and
  2828. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2829. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2830. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2831. begin
  2832. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2833. begin
  2834. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2835. case taicpu(p).oper[0]^.typ of
  2836. top_const:
  2837. { We have something like:
  2838. movb $x, %regb
  2839. movzbl %regb,%regd
  2840. Change to:
  2841. movl $x, %regd
  2842. }
  2843. begin
  2844. case taicpu(hp1).opsize of
  2845. S_BW:
  2846. begin
  2847. convert_mov_value(A_MOVSX, $FF);
  2848. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2849. taicpu(p).opsize := S_W;
  2850. end;
  2851. S_BL:
  2852. begin
  2853. convert_mov_value(A_MOVSX, $FF);
  2854. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2855. taicpu(p).opsize := S_L;
  2856. end;
  2857. S_WL:
  2858. begin
  2859. convert_mov_value(A_MOVSX, $FFFF);
  2860. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2861. taicpu(p).opsize := S_L;
  2862. end;
  2863. {$ifdef x86_64}
  2864. S_BQ:
  2865. begin
  2866. convert_mov_value(A_MOVSX, $FF);
  2867. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2868. taicpu(p).opsize := S_Q;
  2869. end;
  2870. S_WQ:
  2871. begin
  2872. convert_mov_value(A_MOVSX, $FFFF);
  2873. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2874. taicpu(p).opsize := S_Q;
  2875. end;
  2876. S_LQ:
  2877. begin
  2878. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2879. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2880. taicpu(p).opsize := S_Q;
  2881. end;
  2882. {$endif x86_64}
  2883. else
  2884. { If hp1 was a MOV instruction, it should have been
  2885. optimised already }
  2886. InternalError(2020021001);
  2887. end;
  2888. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2889. RemoveInstruction(hp1);
  2890. Result := True;
  2891. Exit;
  2892. end;
  2893. top_ref:
  2894. begin
  2895. { We have something like:
  2896. movb mem, %regb
  2897. movzbl %regb,%regd
  2898. Change to:
  2899. movzbl mem, %regd
  2900. }
  2901. ThisRef := taicpu(p).oper[0]^.ref^;
  2902. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2903. begin
  2904. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2905. taicpu(hp1).loadref(0, ThisRef);
  2906. { Make sure any registers in the references are properly tracked }
  2907. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2908. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2909. if (ThisRef.index <> NR_NO) then
  2910. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2911. RemoveCurrentP(p, hp1);
  2912. Result := True;
  2913. Exit;
  2914. end;
  2915. end;
  2916. else
  2917. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2918. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2919. Exit;
  2920. end;
  2921. end
  2922. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2923. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2924. optimised }
  2925. else
  2926. begin
  2927. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2928. RemoveCurrentP(p, hp1);
  2929. Result := True;
  2930. Exit;
  2931. end;
  2932. end;
  2933. if (taicpu(hp1).opcode = A_AND) and
  2934. (taicpu(p).oper[1]^.typ = top_reg) and
  2935. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2936. begin
  2937. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2938. begin
  2939. case taicpu(p).opsize of
  2940. S_L:
  2941. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2942. begin
  2943. { Optimize out:
  2944. mov x, %reg
  2945. and ffffffffh, %reg
  2946. }
  2947. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2948. RemoveInstruction(hp1);
  2949. Result:=true;
  2950. exit;
  2951. end;
  2952. S_Q: { TODO: Confirm if this is even possible }
  2953. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2954. begin
  2955. { Optimize out:
  2956. mov x, %reg
  2957. and ffffffffffffffffh, %reg
  2958. }
  2959. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2960. RemoveInstruction(hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. else
  2965. ;
  2966. end;
  2967. if (
  2968. (taicpu(p).oper[0]^.typ=top_reg) or
  2969. (
  2970. (taicpu(p).oper[0]^.typ=top_ref) and
  2971. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2972. )
  2973. ) and
  2974. GetNextInstruction(hp1,hp2) and
  2975. MatchInstruction(hp2,A_TEST,[]) and
  2976. (
  2977. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2978. (
  2979. { If the register being tested is smaller than the one
  2980. that received a bitwise AND, permit it if the constant
  2981. fits into the smaller size }
  2982. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2983. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2984. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2985. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2986. (
  2987. (
  2988. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2989. (taicpu(hp1).oper[0]^.val <= $FF)
  2990. ) or
  2991. (
  2992. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2993. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2994. {$ifdef x86_64}
  2995. ) or
  2996. (
  2997. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2998. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2999. {$endif x86_64}
  3000. )
  3001. )
  3002. )
  3003. ) and
  3004. (
  3005. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3006. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3007. ) and
  3008. GetNextInstruction(hp2,hp3) and
  3009. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3010. (taicpu(hp3).condition in [C_E,C_NE]) then
  3011. begin
  3012. TransferUsedRegs(TmpUsedRegs);
  3013. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3015. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3016. begin
  3017. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3018. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3019. taicpu(hp1).opcode:=A_TEST;
  3020. { Shrink the TEST instruction down to the smallest possible size }
  3021. case taicpu(hp1).oper[0]^.val of
  3022. 0..255:
  3023. if (taicpu(hp1).opsize <> S_B)
  3024. {$ifndef x86_64}
  3025. and (
  3026. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3027. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3028. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3029. )
  3030. {$endif x86_64}
  3031. then
  3032. begin
  3033. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3034. { Only print debug message if the TEST instruction
  3035. is a different size before and after }
  3036. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3037. taicpu(hp1).opsize := S_B;
  3038. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3039. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3040. end;
  3041. 256..65535:
  3042. if (taicpu(hp1).opsize <> S_W) then
  3043. begin
  3044. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3045. { Only print debug message if the TEST instruction
  3046. is a different size before and after }
  3047. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3048. taicpu(hp1).opsize := S_W;
  3049. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3050. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3051. end;
  3052. {$ifdef x86_64}
  3053. 65536..$7FFFFFFF:
  3054. if (taicpu(hp1).opsize <> S_L) then
  3055. begin
  3056. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3057. { Only print debug message if the TEST instruction
  3058. is a different size before and after }
  3059. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3060. taicpu(hp1).opsize := S_L;
  3061. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3062. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3063. end;
  3064. {$endif x86_64}
  3065. else
  3066. ;
  3067. end;
  3068. RemoveInstruction(hp2);
  3069. RemoveCurrentP(p, hp1);
  3070. Result:=true;
  3071. exit;
  3072. end;
  3073. end;
  3074. end
  3075. else if IsMOVZXAcceptable and
  3076. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3077. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3078. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3079. then
  3080. begin
  3081. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3082. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3083. case taicpu(p).opsize of
  3084. S_B:
  3085. if (taicpu(hp1).oper[0]^.val = $ff) then
  3086. begin
  3087. { Convert:
  3088. movb x, %regl movb x, %regl
  3089. andw ffh, %regw andl ffh, %regd
  3090. To:
  3091. movzbw x, %regd movzbl x, %regd
  3092. (Identical registers, just different sizes)
  3093. }
  3094. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3095. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3096. case taicpu(hp1).opsize of
  3097. S_W: NewSize := S_BW;
  3098. S_L: NewSize := S_BL;
  3099. {$ifdef x86_64}
  3100. S_Q: NewSize := S_BQ;
  3101. {$endif x86_64}
  3102. else
  3103. InternalError(2018011510);
  3104. end;
  3105. end
  3106. else
  3107. NewSize := S_NO;
  3108. S_W:
  3109. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3110. begin
  3111. { Convert:
  3112. movw x, %regw
  3113. andl ffffh, %regd
  3114. To:
  3115. movzwl x, %regd
  3116. (Identical registers, just different sizes)
  3117. }
  3118. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3119. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3120. case taicpu(hp1).opsize of
  3121. S_L: NewSize := S_WL;
  3122. {$ifdef x86_64}
  3123. S_Q: NewSize := S_WQ;
  3124. {$endif x86_64}
  3125. else
  3126. InternalError(2018011511);
  3127. end;
  3128. end
  3129. else
  3130. NewSize := S_NO;
  3131. else
  3132. NewSize := S_NO;
  3133. end;
  3134. if NewSize <> S_NO then
  3135. begin
  3136. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3137. { The actual optimization }
  3138. taicpu(p).opcode := A_MOVZX;
  3139. taicpu(p).changeopsize(NewSize);
  3140. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3141. { Safeguard if "and" is followed by a conditional command }
  3142. TransferUsedRegs(TmpUsedRegs);
  3143. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3144. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3145. begin
  3146. { At this point, the "and" command is effectively equivalent to
  3147. "test %reg,%reg". This will be handled separately by the
  3148. Peephole Optimizer. [Kit] }
  3149. DebugMsg(SPeepholeOptimization + PreMessage +
  3150. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3151. end
  3152. else
  3153. begin
  3154. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3155. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3156. RemoveInstruction(hp1);
  3157. end;
  3158. Result := True;
  3159. Exit;
  3160. end;
  3161. end;
  3162. end;
  3163. if (taicpu(hp1).opcode = A_OR) and
  3164. (taicpu(p).oper[1]^.typ = top_reg) and
  3165. MatchOperand(taicpu(p).oper[0]^, 0) and
  3166. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3167. begin
  3168. { mov 0, %reg
  3169. or ###,%reg
  3170. Change to (only if the flags are not used):
  3171. mov ###,%reg
  3172. }
  3173. TransferUsedRegs(TmpUsedRegs);
  3174. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3175. DoOptimisation := True;
  3176. { Even if the flags are used, we might be able to do the optimisation
  3177. if the conditions are predictable }
  3178. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3179. begin
  3180. { Only perform if ### = %reg (the same register) or equal to 0,
  3181. so %reg is guaranteed to still have a value of zero }
  3182. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3183. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3184. begin
  3185. hp2 := hp1;
  3186. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3187. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3188. GetNextInstruction(hp2, hp3) do
  3189. begin
  3190. { Don't continue modifying if the flags state is getting changed }
  3191. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3192. Break;
  3193. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3194. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3195. begin
  3196. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3197. begin
  3198. { Condition is always true }
  3199. case taicpu(hp3).opcode of
  3200. A_Jcc:
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3203. { Check for jump shortcuts before we destroy the condition }
  3204. DoJumpOptimizations(hp3, TempBool);
  3205. MakeUnconditional(taicpu(hp3));
  3206. Result := True;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3211. taicpu(hp3).opcode := A_MOV;
  3212. taicpu(hp3).condition := C_None;
  3213. Result := True;
  3214. end;
  3215. A_SETcc:
  3216. begin
  3217. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3218. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3219. taicpu(hp3).opcode := A_MOV;
  3220. taicpu(hp3).ops := 2;
  3221. taicpu(hp3).condition := C_None;
  3222. taicpu(hp3).opsize := S_B;
  3223. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3224. taicpu(hp3).loadconst(0, 1);
  3225. Result := True;
  3226. end;
  3227. else
  3228. InternalError(2021090701);
  3229. end;
  3230. end
  3231. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3232. begin
  3233. { Condition is always false }
  3234. case taicpu(hp3).opcode of
  3235. A_Jcc:
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3238. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3239. RemoveInstruction(hp3);
  3240. Result := True;
  3241. { Since hp3 was deleted, hp2 must not be updated }
  3242. Continue;
  3243. end;
  3244. A_CMOVcc:
  3245. begin
  3246. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3247. RemoveInstruction(hp3);
  3248. Result := True;
  3249. { Since hp3 was deleted, hp2 must not be updated }
  3250. Continue;
  3251. end;
  3252. A_SETcc:
  3253. begin
  3254. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3256. taicpu(hp3).opcode := A_MOV;
  3257. taicpu(hp3).ops := 2;
  3258. taicpu(hp3).condition := C_None;
  3259. taicpu(hp3).opsize := S_B;
  3260. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3261. taicpu(hp3).loadconst(0, 0);
  3262. Result := True;
  3263. end;
  3264. else
  3265. InternalError(2021090702);
  3266. end;
  3267. end
  3268. else
  3269. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3270. DoOptimisation := False;
  3271. end;
  3272. hp2 := hp3;
  3273. end;
  3274. { Flags are still in use - don't optimise }
  3275. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3276. DoOptimisation := False;
  3277. end
  3278. else
  3279. DoOptimisation := False;
  3280. end;
  3281. if DoOptimisation then
  3282. begin
  3283. {$ifdef x86_64}
  3284. { OR only supports 32-bit sign-extended constants for 64-bit
  3285. instructions, so compensate for this if the constant is
  3286. encoded as a value greater than or equal to 2^31 }
  3287. if (taicpu(hp1).opsize = S_Q) and
  3288. (taicpu(hp1).oper[0]^.typ = top_const) and
  3289. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3290. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3291. {$endif x86_64}
  3292. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3293. taicpu(hp1).opcode := A_MOV;
  3294. RemoveCurrentP(p, hp1);
  3295. Result := True;
  3296. Exit;
  3297. end;
  3298. end;
  3299. { Next instruction is also a MOV ? }
  3300. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3301. begin
  3302. if MatchOpType(taicpu(p), top_const, top_ref) and
  3303. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3304. TryConstMerge(p, hp1) then
  3305. begin
  3306. Result := True;
  3307. { In case we have four byte writes in a row, check for 2 more
  3308. right now so we don't have to wait for another iteration of
  3309. pass 1
  3310. }
  3311. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3312. case taicpu(p).opsize of
  3313. S_W:
  3314. begin
  3315. if GetNextInstruction(p, hp1) and
  3316. MatchInstruction(hp1, A_MOV, [S_B]) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2, A_MOV, [S_B]) and
  3320. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3321. { Try to merge the two bytes }
  3322. TryConstMerge(hp1, hp2) then
  3323. { Now try to merge the two words (hp2 will get deleted) }
  3324. TryConstMerge(p, hp1);
  3325. end;
  3326. S_L:
  3327. begin
  3328. { Though this only really benefits x86_64 and not i386, it
  3329. gets a potential optimisation done faster and hence
  3330. reduces the number of times OptPass1MOV is entered }
  3331. if GetNextInstruction(p, hp1) and
  3332. MatchInstruction(hp1, A_MOV, [S_W]) and
  3333. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3334. GetNextInstruction(hp1, hp2) and
  3335. MatchInstruction(hp2, A_MOV, [S_W]) and
  3336. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3337. { Try to merge the two words }
  3338. TryConstMerge(hp1, hp2) then
  3339. { This will always fail on i386, so don't bother
  3340. calling it unless we're doing x86_64 }
  3341. {$ifdef x86_64}
  3342. { Now try to merge the two longwords (hp2 will get deleted) }
  3343. TryConstMerge(p, hp1)
  3344. {$endif x86_64}
  3345. ;
  3346. end;
  3347. else
  3348. ;
  3349. end;
  3350. Exit;
  3351. end;
  3352. if (taicpu(p).oper[1]^.typ = top_reg) and
  3353. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3354. begin
  3355. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3356. TransferUsedRegs(TmpUsedRegs);
  3357. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3358. { we have
  3359. mov x, %treg
  3360. mov %treg, y
  3361. }
  3362. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3363. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3364. { we've got
  3365. mov x, %treg
  3366. mov %treg, y
  3367. with %treg is not used after }
  3368. case taicpu(p).oper[0]^.typ Of
  3369. { top_reg is covered by DeepMOVOpt }
  3370. top_const:
  3371. begin
  3372. { change
  3373. mov const, %treg
  3374. mov %treg, y
  3375. to
  3376. mov const, y
  3377. }
  3378. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3379. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3380. begin
  3381. if taicpu(hp1).oper[1]^.typ=top_reg then
  3382. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3383. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3385. RemoveInstruction(hp1);
  3386. Result:=true;
  3387. Exit;
  3388. end;
  3389. end;
  3390. top_ref:
  3391. case taicpu(hp1).oper[1]^.typ of
  3392. top_reg:
  3393. begin
  3394. { change
  3395. mov mem, %treg
  3396. mov %treg, %reg
  3397. to
  3398. mov mem, %reg"
  3399. }
  3400. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3401. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3402. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3403. RemoveInstruction(hp1);
  3404. Result:=true;
  3405. Exit;
  3406. end;
  3407. top_ref:
  3408. begin
  3409. {$ifdef x86_64}
  3410. { Look for the following to simplify:
  3411. mov x(mem1), %reg
  3412. mov %reg, y(mem2)
  3413. mov x+8(mem1), %reg
  3414. mov %reg, y+8(mem2)
  3415. Change to:
  3416. movdqu x(mem1), %xmmreg
  3417. movdqu %xmmreg, y(mem2)
  3418. ...but only as long as the memory blocks don't overlap
  3419. }
  3420. SourceRef := taicpu(p).oper[0]^.ref^;
  3421. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3422. if (taicpu(p).opsize = S_Q) and
  3423. GetNextInstruction(hp1, hp2) and
  3424. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3425. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3426. begin
  3427. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3428. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3429. Inc(SourceRef.offset, 8);
  3430. if UseAVX then
  3431. begin
  3432. MovAligned := A_VMOVDQA;
  3433. MovUnaligned := A_VMOVDQU;
  3434. end
  3435. else
  3436. begin
  3437. MovAligned := A_MOVDQA;
  3438. MovUnaligned := A_MOVDQU;
  3439. end;
  3440. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3441. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3442. begin
  3443. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3444. Inc(TargetRef.offset, 8);
  3445. if GetNextInstruction(hp2, hp3) and
  3446. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3447. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3448. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3449. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3450. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3451. begin
  3452. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3453. if NewMMReg <> NR_NO then
  3454. begin
  3455. { Remember that the offsets are 8 ahead }
  3456. if ((SourceRef.offset mod 16) = 8) and
  3457. (
  3458. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3459. (SourceRef.base = current_procinfo.framepointer) or
  3460. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3461. ) then
  3462. taicpu(p).opcode := MovAligned
  3463. else
  3464. taicpu(p).opcode := MovUnaligned;
  3465. taicpu(p).opsize := S_XMM;
  3466. taicpu(p).oper[1]^.reg := NewMMReg;
  3467. if ((TargetRef.offset mod 16) = 8) and
  3468. (
  3469. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3470. (TargetRef.base = current_procinfo.framepointer) or
  3471. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3472. ) then
  3473. taicpu(hp1).opcode := MovAligned
  3474. else
  3475. taicpu(hp1).opcode := MovUnaligned;
  3476. taicpu(hp1).opsize := S_XMM;
  3477. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3478. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3479. RemoveInstruction(hp2);
  3480. RemoveInstruction(hp3);
  3481. Result := True;
  3482. Exit;
  3483. end;
  3484. end;
  3485. end
  3486. else
  3487. begin
  3488. { See if the next references are 8 less rather than 8 greater }
  3489. Dec(SourceRef.offset, 16); { -8 the other way }
  3490. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3491. begin
  3492. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3493. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3494. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3495. GetNextInstruction(hp2, hp3) and
  3496. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3497. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3498. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3499. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3500. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3501. begin
  3502. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3503. if NewMMReg <> NR_NO then
  3504. begin
  3505. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3506. if ((SourceRef.offset mod 16) = 0) and
  3507. (
  3508. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3509. (SourceRef.base = current_procinfo.framepointer) or
  3510. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3511. ) then
  3512. taicpu(hp2).opcode := MovAligned
  3513. else
  3514. taicpu(hp2).opcode := MovUnaligned;
  3515. taicpu(hp2).opsize := S_XMM;
  3516. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3517. if ((TargetRef.offset mod 16) = 0) and
  3518. (
  3519. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3520. (TargetRef.base = current_procinfo.framepointer) or
  3521. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3522. ) then
  3523. taicpu(hp3).opcode := MovAligned
  3524. else
  3525. taicpu(hp3).opcode := MovUnaligned;
  3526. taicpu(hp3).opsize := S_XMM;
  3527. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3528. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3529. RemoveInstruction(hp1);
  3530. RemoveCurrentP(p, hp2);
  3531. Result := True;
  3532. Exit;
  3533. end;
  3534. end;
  3535. end;
  3536. end;
  3537. end;
  3538. {$endif x86_64}
  3539. end;
  3540. else
  3541. { The write target should be a reg or a ref }
  3542. InternalError(2021091601);
  3543. end;
  3544. else
  3545. ;
  3546. end
  3547. else
  3548. { %treg is used afterwards, but all eventualities
  3549. other than the first MOV instruction being a constant
  3550. are covered by DeepMOVOpt, so only check for that }
  3551. if (taicpu(p).oper[0]^.typ = top_const) and
  3552. (
  3553. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3554. not (cs_opt_size in current_settings.optimizerswitches) or
  3555. (taicpu(hp1).opsize = S_B)
  3556. ) and
  3557. (
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3559. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3560. ) then
  3561. begin
  3562. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3563. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3564. end;
  3565. end;
  3566. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3567. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3568. { mov reg1, mem1 or mov mem1, reg1
  3569. mov mem2, reg2 mov reg2, mem2}
  3570. begin
  3571. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3572. { mov reg1, mem1 or mov mem1, reg1
  3573. mov mem2, reg1 mov reg2, mem1}
  3574. begin
  3575. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3576. { Removes the second statement from
  3577. mov reg1, mem1/reg2
  3578. mov mem1/reg2, reg1 }
  3579. begin
  3580. if taicpu(p).oper[0]^.typ=top_reg then
  3581. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3582. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3583. RemoveInstruction(hp1);
  3584. Result:=true;
  3585. exit;
  3586. end
  3587. else
  3588. begin
  3589. TransferUsedRegs(TmpUsedRegs);
  3590. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3591. if (taicpu(p).oper[1]^.typ = top_ref) and
  3592. { mov reg1, mem1
  3593. mov mem2, reg1 }
  3594. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3595. GetNextInstruction(hp1, hp2) and
  3596. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3597. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3598. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3599. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3600. { change to
  3601. mov reg1, mem1 mov reg1, mem1
  3602. mov mem2, reg1 cmp reg1, mem2
  3603. cmp mem1, reg1
  3604. }
  3605. begin
  3606. RemoveInstruction(hp2);
  3607. taicpu(hp1).opcode := A_CMP;
  3608. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3609. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3610. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3611. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3612. end;
  3613. end;
  3614. end
  3615. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3616. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3617. begin
  3618. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3619. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3621. end
  3622. else
  3623. begin
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. if GetNextInstruction(hp1, hp2) and
  3626. MatchOpType(taicpu(p),top_ref,top_reg) and
  3627. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3628. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3629. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3630. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3631. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3632. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3633. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3634. { mov mem1, %reg1
  3635. mov %reg1, mem2
  3636. mov mem2, reg2
  3637. to:
  3638. mov mem1, reg2
  3639. mov reg2, mem2}
  3640. begin
  3641. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3642. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3643. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3644. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3645. RemoveInstruction(hp2);
  3646. Result := True;
  3647. end
  3648. {$ifdef i386}
  3649. { this is enabled for i386 only, as the rules to create the reg sets below
  3650. are too complicated for x86-64, so this makes this code too error prone
  3651. on x86-64
  3652. }
  3653. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3654. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3655. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3656. { mov mem1, reg1 mov mem1, reg1
  3657. mov reg1, mem2 mov reg1, mem2
  3658. mov mem2, reg2 mov mem2, reg1
  3659. to: to:
  3660. mov mem1, reg1 mov mem1, reg1
  3661. mov mem1, reg2 mov reg1, mem2
  3662. mov reg1, mem2
  3663. or (if mem1 depends on reg1
  3664. and/or if mem2 depends on reg2)
  3665. to:
  3666. mov mem1, reg1
  3667. mov reg1, mem2
  3668. mov reg1, reg2
  3669. }
  3670. begin
  3671. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3672. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3673. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3674. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3675. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3676. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3677. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3678. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3679. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3680. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3681. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3682. end
  3683. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3684. begin
  3685. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3686. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3687. end
  3688. else
  3689. begin
  3690. RemoveInstruction(hp2);
  3691. end
  3692. {$endif i386}
  3693. ;
  3694. end;
  3695. end
  3696. { movl [mem1],reg1
  3697. movl [mem1],reg2
  3698. to
  3699. movl [mem1],reg1
  3700. movl reg1,reg2
  3701. }
  3702. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3703. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3704. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3705. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3706. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3707. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3708. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3709. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3710. begin
  3711. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3712. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3713. end;
  3714. { movl const1,[mem1]
  3715. movl [mem1],reg1
  3716. to
  3717. movl const1,reg1
  3718. movl reg1,[mem1]
  3719. }
  3720. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3721. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3722. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3723. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3724. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3725. begin
  3726. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3727. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3728. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3729. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3730. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3731. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3732. Result:=true;
  3733. exit;
  3734. end;
  3735. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3736. { Change:
  3737. movl %reg1,%reg2
  3738. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3739. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3740. To:
  3741. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3742. movl x(%reg1),%reg1
  3743. movl %reg1,%regX
  3744. }
  3745. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3746. begin
  3747. p_SourceReg := taicpu(p).oper[0]^.reg;
  3748. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3749. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3750. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3751. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3752. GetNextInstruction(hp1, hp2) and
  3753. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3754. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3755. begin
  3756. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3757. if RegInRef(p_TargetReg, SourceRef) and
  3758. { If %reg1 also appears in the second reference, then it will
  3759. not refer to the same memory block as the first reference }
  3760. not RegInRef(p_SourceReg, SourceRef) then
  3761. begin
  3762. { Check to see if the references match if %reg2 is changed to %reg1 }
  3763. if SourceRef.base = p_TargetReg then
  3764. SourceRef.base := p_SourceReg;
  3765. if SourceRef.index = p_TargetReg then
  3766. SourceRef.index := p_SourceReg;
  3767. { RefsEqual also checks to ensure both references are non-volatile }
  3768. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3769. begin
  3770. taicpu(hp2).loadreg(0, p_SourceReg);
  3771. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3772. Result := True;
  3773. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3774. begin
  3775. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3776. RemoveCurrentP(p, hp1);
  3777. Exit;
  3778. end
  3779. else
  3780. begin
  3781. { Check to see if %reg2 is no longer in use }
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3785. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3786. begin
  3787. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3788. RemoveCurrentP(p, hp1);
  3789. Exit;
  3790. end;
  3791. end;
  3792. { If we reach this point, p and hp1 weren't actually modified,
  3793. so we can do a bit more work on this pass }
  3794. end;
  3795. end;
  3796. end;
  3797. end;
  3798. end;
  3799. {$ifdef x86_64}
  3800. { Change:
  3801. movl %reg1l,%reg2l
  3802. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3803. To:
  3804. movl %reg1l,%reg2l
  3805. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3806. If %reg1 = %reg3, convert to:
  3807. movl %reg1l,%reg2l
  3808. andl %reg1l,%reg1l
  3809. }
  3810. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3811. MatchOpType(taicpu(p), top_reg, top_reg) and
  3812. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3813. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3814. begin
  3815. TransferUsedRegs(TmpUsedRegs);
  3816. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3817. taicpu(hp1).opsize := S_L;
  3818. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3819. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3820. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3821. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3822. begin
  3823. { %reg1 = %reg3 }
  3824. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3825. taicpu(hp1).opcode := A_AND;
  3826. end
  3827. else
  3828. begin
  3829. { %reg1 <> %reg3 }
  3830. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3831. end;
  3832. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3833. begin
  3834. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3835. RemoveCurrentP(p, hp1);
  3836. Result := True;
  3837. Exit;
  3838. end
  3839. else
  3840. begin
  3841. { Initial instruction wasn't actually changed }
  3842. Include(OptsToCheck, aoc_ForceNewIteration);
  3843. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3844. appears below since %reg1 has technically changed }
  3845. if taicpu(hp1).opcode = A_AND then
  3846. Exit;
  3847. end;
  3848. end;
  3849. {$endif x86_64}
  3850. { search further than the next instruction for a mov (as long as it's not a jump) }
  3851. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3852. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3853. (taicpu(p).oper[1]^.typ = top_reg) and
  3854. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3855. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3856. begin
  3857. { we work with hp2 here, so hp1 can be still used later on when
  3858. checking for GetNextInstruction_p }
  3859. hp3 := hp1;
  3860. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3861. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3862. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3863. TransferUsedRegs(TmpUsedRegs);
  3864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3865. if NotFirstIteration then
  3866. JumpTracking := TLinkedList.Create
  3867. else
  3868. JumpTracking := nil;
  3869. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3870. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3871. (hp2.typ=ait_instruction) do
  3872. begin
  3873. case taicpu(hp2).opcode of
  3874. A_POP:
  3875. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3876. begin
  3877. if not CrossJump and
  3878. not RegUsedBetween(p_TargetReg, p, hp2) then
  3879. begin
  3880. { We can remove the original MOV since the register
  3881. wasn't used between it and its popping from the stack }
  3882. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3883. RemoveCurrentp(p, hp1);
  3884. Result := True;
  3885. JumpTracking.Free;
  3886. Exit;
  3887. end;
  3888. { Can't go any further }
  3889. Break;
  3890. end;
  3891. A_MOV:
  3892. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3893. ((taicpu(p).oper[0]^.typ=top_const) or
  3894. ((taicpu(p).oper[0]^.typ=top_reg) and
  3895. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3896. )
  3897. ) then
  3898. begin
  3899. { we have
  3900. mov x, %treg
  3901. mov %treg, y
  3902. }
  3903. { We don't need to call UpdateUsedRegs for every instruction between
  3904. p and hp2 because the register we're concerned about will not
  3905. become deallocated (otherwise GetNextInstructionUsingReg would
  3906. have stopped at an earlier instruction). [Kit] }
  3907. TempRegUsed :=
  3908. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3909. RegReadByInstruction(p_TargetReg, hp3) or
  3910. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3911. case taicpu(p).oper[0]^.typ Of
  3912. top_reg:
  3913. begin
  3914. { change
  3915. mov %reg, %treg
  3916. mov %treg, y
  3917. to
  3918. mov %reg, y
  3919. }
  3920. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3921. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3922. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3923. begin
  3924. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3925. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3926. if TempRegUsed then
  3927. begin
  3928. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3929. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3930. { Set the start of the next GetNextInstructionUsingRegCond search
  3931. to start at the entry right before hp2 (which is about to be removed) }
  3932. hp3 := tai(hp2.Previous);
  3933. RemoveInstruction(hp2);
  3934. Include(OptsToCheck, aoc_ForceNewIteration);
  3935. { See if there's more we can optimise }
  3936. Continue;
  3937. end
  3938. else
  3939. begin
  3940. RemoveInstruction(hp2);
  3941. { We can remove the original MOV too }
  3942. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3943. RemoveCurrentP(p, hp1);
  3944. Result:=true;
  3945. JumpTracking.Free;
  3946. Exit;
  3947. end;
  3948. end
  3949. else
  3950. begin
  3951. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3952. taicpu(hp2).loadReg(0, p_SourceReg);
  3953. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3954. { Check to see if the register also appears in the reference }
  3955. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3956. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3957. { Don't remove the first instruction if the temporary register is in use }
  3958. if not TempRegUsed and
  3959. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3960. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3961. begin
  3962. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3963. RemoveCurrentP(p, hp1);
  3964. Result:=true;
  3965. JumpTracking.Free;
  3966. Exit;
  3967. end;
  3968. { No need to set Result to True here. If there's another instruction later
  3969. on that can be optimised, it will be detected when the main Pass 1 loop
  3970. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3971. end;
  3972. end;
  3973. top_const:
  3974. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3975. begin
  3976. { change
  3977. mov const, %treg
  3978. mov %treg, y
  3979. to
  3980. mov const, y
  3981. }
  3982. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3983. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3984. begin
  3985. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3986. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3987. if TempRegUsed then
  3988. begin
  3989. { Don't remove the first instruction if the temporary register is in use }
  3990. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3991. { No need to set Result to True. If there's another instruction later on
  3992. that can be optimised, it will be detected when the main Pass 1 loop
  3993. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3994. end
  3995. else
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3998. RemoveCurrentP(p, hp1);
  3999. Result:=true;
  4000. Exit;
  4001. end;
  4002. end;
  4003. end;
  4004. else
  4005. Internalerror(2019103001);
  4006. end;
  4007. end
  4008. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4009. begin
  4010. if not CrossJump and
  4011. not RegUsedBetween(p_TargetReg, p, hp2) and
  4012. not RegReadByInstruction(p_TargetReg, hp2) then
  4013. begin
  4014. { Register is not used before it is overwritten }
  4015. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4016. RemoveCurrentp(p, hp1);
  4017. Result := True;
  4018. Exit;
  4019. end;
  4020. if (taicpu(p).oper[0]^.typ = top_const) and
  4021. (taicpu(hp2).oper[0]^.typ = top_const) then
  4022. begin
  4023. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4024. begin
  4025. { Same value - register hasn't changed }
  4026. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4027. RemoveInstruction(hp2);
  4028. Include(OptsToCheck, aoc_ForceNewIteration);
  4029. { See if there's more we can optimise }
  4030. Continue;
  4031. end;
  4032. end;
  4033. {$ifdef x86_64}
  4034. end
  4035. { Change:
  4036. movl %reg1l,%reg2l
  4037. ...
  4038. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4039. To:
  4040. movl %reg1l,%reg2l
  4041. ...
  4042. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4043. If %reg1 = %reg3, convert to:
  4044. movl %reg1l,%reg2l
  4045. ...
  4046. andl %reg1l,%reg1l
  4047. }
  4048. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4049. (taicpu(p).oper[0]^.typ = top_reg) and
  4050. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4051. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4052. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4053. begin
  4054. TempRegUsed :=
  4055. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4056. RegReadByInstruction(p_TargetReg, hp3) or
  4057. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4058. taicpu(hp2).opsize := S_L;
  4059. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4060. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4062. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4063. begin
  4064. { %reg1 = %reg3 }
  4065. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4066. taicpu(hp2).opcode := A_AND;
  4067. end
  4068. else
  4069. begin
  4070. { %reg1 <> %reg3 }
  4071. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4072. end;
  4073. if not TempRegUsed then
  4074. begin
  4075. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4076. RemoveCurrentP(p, hp1);
  4077. Result := True;
  4078. Exit;
  4079. end
  4080. else
  4081. begin
  4082. { Initial instruction wasn't actually changed }
  4083. Include(OptsToCheck, aoc_ForceNewIteration);
  4084. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4085. appears below since %reg1 has technically changed }
  4086. if taicpu(hp2).opcode = A_AND then
  4087. Break;
  4088. end;
  4089. {$endif x86_64}
  4090. end;
  4091. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4092. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4093. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4094. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4095. begin
  4096. {
  4097. Change from:
  4098. mov ###, %reg
  4099. ...
  4100. movs/z %reg,%reg (Same register, just different sizes)
  4101. To:
  4102. movs/z ###, %reg (Longer version)
  4103. ...
  4104. (remove)
  4105. }
  4106. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4107. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4108. { Keep the first instruction as mov if ### is a constant }
  4109. if taicpu(p).oper[0]^.typ = top_const then
  4110. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4111. else
  4112. begin
  4113. taicpu(p).opcode := taicpu(hp2).opcode;
  4114. taicpu(p).opsize := taicpu(hp2).opsize;
  4115. end;
  4116. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4117. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4118. RemoveInstruction(hp2);
  4119. Result := True;
  4120. JumpTracking.Free;
  4121. Exit;
  4122. end;
  4123. else
  4124. { Move down to the if-block below };
  4125. end;
  4126. { Also catches MOV/S/Z instructions that aren't modified }
  4127. if taicpu(p).oper[0]^.typ = top_reg then
  4128. begin
  4129. p_SourceReg := taicpu(p).oper[0]^.reg;
  4130. if
  4131. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4132. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4133. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4134. begin
  4135. Result := True;
  4136. { Just in case something didn't get modified (e.g. an
  4137. implicit register). Also, if it does read from this
  4138. register, then there's no longer an advantage to
  4139. changing the register on subsequent instructions.}
  4140. if not RegReadByInstruction(p_TargetReg, hp2) then
  4141. begin
  4142. { If a conditional jump was crossed, do not delete
  4143. the original MOV no matter what }
  4144. if not CrossJump and
  4145. { RegEndOfLife returns True if the register is
  4146. deallocated before the next instruction or has
  4147. been loaded with a new value }
  4148. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4149. begin
  4150. { We can remove the original MOV }
  4151. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4152. RemoveCurrentp(p, hp1);
  4153. JumpTracking.Free;
  4154. Result := True;
  4155. Exit;
  4156. end;
  4157. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4158. begin
  4159. { See if there's more we can optimise }
  4160. hp3 := hp2;
  4161. Continue;
  4162. end;
  4163. end;
  4164. end;
  4165. end;
  4166. { Break out of the while loop under normal circumstances }
  4167. Break;
  4168. end;
  4169. JumpTracking.Free;
  4170. end;
  4171. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4172. (taicpu(p).oper[1]^.typ = top_reg) and
  4173. (taicpu(p).opsize = S_L) and
  4174. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4175. (hp2.typ = ait_instruction) and
  4176. (taicpu(hp2).opcode = A_AND) and
  4177. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4178. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4179. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4180. ) then
  4181. begin
  4182. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4183. begin
  4184. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4185. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4186. begin
  4187. { Optimize out:
  4188. mov x, %reg
  4189. and ffffffffh, %reg
  4190. }
  4191. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4192. RemoveInstruction(hp2);
  4193. Result:=true;
  4194. exit;
  4195. end;
  4196. end;
  4197. end;
  4198. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4199. x >= RetOffset) as it doesn't do anything (it writes either to a
  4200. parameter or to the temporary storage room for the function
  4201. result)
  4202. }
  4203. if IsExitCode(hp1) and
  4204. (taicpu(p).oper[1]^.typ = top_ref) and
  4205. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4206. (
  4207. (
  4208. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4209. not (
  4210. assigned(current_procinfo.procdef.funcretsym) and
  4211. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4212. )
  4213. ) or
  4214. { Also discard writes to the stack that are below the base pointer,
  4215. as this is temporary storage rather than a function result on the
  4216. stack, say. }
  4217. (
  4218. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4219. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4220. )
  4221. ) then
  4222. begin
  4223. RemoveCurrentp(p, hp1);
  4224. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4225. RemoveLastDeallocForFuncRes(p);
  4226. Result:=true;
  4227. exit;
  4228. end;
  4229. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4230. begin
  4231. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4232. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4233. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4234. begin
  4235. { change
  4236. mov reg1, mem1
  4237. test/cmp x, mem1
  4238. to
  4239. mov reg1, mem1
  4240. test/cmp x, reg1
  4241. }
  4242. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4243. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if DoMovCmpMemOpt(p, hp1) then
  4249. begin
  4250. Result := True;
  4251. Exit;
  4252. end;
  4253. end;
  4254. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4255. { If the flags register is in use, don't change the instruction to an
  4256. ADD otherwise this will scramble the flags. [Kit] }
  4257. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4258. begin
  4259. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4260. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4261. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4262. ) or
  4263. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4264. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4265. )
  4266. ) then
  4267. { mov reg1,ref
  4268. lea reg2,[reg1,reg2]
  4269. to
  4270. add reg2,ref}
  4271. begin
  4272. TransferUsedRegs(TmpUsedRegs);
  4273. { reg1 may not be used afterwards }
  4274. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4275. begin
  4276. Taicpu(hp1).opcode:=A_ADD;
  4277. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4278. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4279. RemoveCurrentp(p, hp1);
  4280. result:=true;
  4281. exit;
  4282. end;
  4283. end;
  4284. { If the LEA instruction can be converted into an arithmetic instruction,
  4285. it may be possible to then fold it in the next optimisation, otherwise
  4286. there's nothing more that can be optimised here. }
  4287. if not ConvertLEA(taicpu(hp1)) then
  4288. Exit;
  4289. end;
  4290. if (taicpu(p).oper[1]^.typ = top_reg) and
  4291. (hp1.typ = ait_instruction) and
  4292. GetNextInstruction(hp1, hp2) and
  4293. MatchInstruction(hp2,A_MOV,[]) and
  4294. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4295. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4296. (
  4297. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4298. {$ifdef x86_64}
  4299. or
  4300. (
  4301. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4302. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4303. )
  4304. {$endif x86_64}
  4305. ) then
  4306. begin
  4307. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4308. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4309. { change movsX/movzX reg/ref, reg2
  4310. add/sub/or/... reg3/$const, reg2
  4311. mov reg2 reg/ref
  4312. dealloc reg2
  4313. to
  4314. add/sub/or/... reg3/$const, reg/ref }
  4315. begin
  4316. TransferUsedRegs(TmpUsedRegs);
  4317. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4318. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4319. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4320. begin
  4321. { by example:
  4322. movswl %si,%eax movswl %si,%eax p
  4323. decl %eax addl %edx,%eax hp1
  4324. movw %ax,%si movw %ax,%si hp2
  4325. ->
  4326. movswl %si,%eax movswl %si,%eax p
  4327. decw %eax addw %edx,%eax hp1
  4328. movw %ax,%si movw %ax,%si hp2
  4329. }
  4330. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4331. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4332. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4333. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4334. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4335. {
  4336. ->
  4337. movswl %si,%eax movswl %si,%eax p
  4338. decw %si addw %dx,%si hp1
  4339. movw %ax,%si movw %ax,%si hp2
  4340. }
  4341. case taicpu(hp1).ops of
  4342. 1:
  4343. begin
  4344. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4345. if taicpu(hp1).oper[0]^.typ=top_reg then
  4346. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4347. end;
  4348. 2:
  4349. begin
  4350. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4351. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4352. (taicpu(hp1).opcode<>A_SHL) and
  4353. (taicpu(hp1).opcode<>A_SHR) and
  4354. (taicpu(hp1).opcode<>A_SAR) then
  4355. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4356. end;
  4357. else
  4358. internalerror(2008042701);
  4359. end;
  4360. {
  4361. ->
  4362. decw %si addw %dx,%si p
  4363. }
  4364. RemoveInstruction(hp2);
  4365. RemoveCurrentP(p, hp1);
  4366. Result:=True;
  4367. Exit;
  4368. end;
  4369. end;
  4370. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4371. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4372. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4373. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4374. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4375. )
  4376. {$ifdef i386}
  4377. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4378. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4379. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4380. {$endif i386}
  4381. then
  4382. { change movsX/movzX reg/ref, reg2
  4383. add/sub/or/... regX/$const, reg2
  4384. mov reg2, reg3
  4385. dealloc reg2
  4386. to
  4387. movsX/movzX reg/ref, reg3
  4388. add/sub/or/... reg3/$const, reg3
  4389. }
  4390. begin
  4391. TransferUsedRegs(TmpUsedRegs);
  4392. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4394. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4395. begin
  4396. { by example:
  4397. movswl %si,%eax movswl %si,%eax p
  4398. decl %eax addl %edx,%eax hp1
  4399. movw %ax,%si movw %ax,%si hp2
  4400. ->
  4401. movswl %si,%eax movswl %si,%eax p
  4402. decw %eax addw %edx,%eax hp1
  4403. movw %ax,%si movw %ax,%si hp2
  4404. }
  4405. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4406. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4407. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4408. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4409. { limit size of constants as well to avoid assembler errors, but
  4410. check opsize to avoid overflow when left shifting the 1 }
  4411. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4412. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4413. {$ifdef x86_64}
  4414. { Be careful of, for example:
  4415. movl %reg1,%reg2
  4416. addl %reg3,%reg2
  4417. movq %reg2,%reg4
  4418. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4419. }
  4420. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4421. begin
  4422. taicpu(hp2).changeopsize(S_L);
  4423. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4424. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4425. end;
  4426. {$endif x86_64}
  4427. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4428. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4429. if taicpu(p).oper[0]^.typ=top_reg then
  4430. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4431. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4432. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4433. {
  4434. ->
  4435. movswl %si,%eax movswl %si,%eax p
  4436. decw %si addw %dx,%si hp1
  4437. movw %ax,%si movw %ax,%si hp2
  4438. }
  4439. case taicpu(hp1).ops of
  4440. 1:
  4441. begin
  4442. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4443. if taicpu(hp1).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. 2:
  4447. begin
  4448. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4449. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4450. (taicpu(hp1).opcode<>A_SHL) and
  4451. (taicpu(hp1).opcode<>A_SHR) and
  4452. (taicpu(hp1).opcode<>A_SAR) then
  4453. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4454. end;
  4455. else
  4456. internalerror(2018111801);
  4457. end;
  4458. {
  4459. ->
  4460. decw %si addw %dx,%si p
  4461. }
  4462. RemoveInstruction(hp2);
  4463. end;
  4464. end;
  4465. end;
  4466. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4467. GetNextInstruction(hp1, hp2) and
  4468. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4469. MatchOperand(Taicpu(p).oper[0]^,0) and
  4470. (Taicpu(p).oper[1]^.typ = top_reg) and
  4471. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4472. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4473. { mov reg1,0
  4474. bts reg1,operand1 --> mov reg1,operand2
  4475. or reg1,operand2 bts reg1,operand1}
  4476. begin
  4477. Taicpu(hp2).opcode:=A_MOV;
  4478. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4479. asml.remove(hp1);
  4480. insertllitem(hp2,hp2.next,hp1);
  4481. RemoveCurrentp(p, hp1);
  4482. Result:=true;
  4483. exit;
  4484. end;
  4485. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4487. GetNextInstruction(hp1, hp2) and
  4488. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4489. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4490. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4491. { change
  4492. mov reg1,reg2
  4493. sub reg3,reg2
  4494. cmp reg3,reg1
  4495. into
  4496. mov reg1,reg2
  4497. sub reg3,reg2
  4498. }
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4501. RemoveInstruction(hp2);
  4502. Result:=true;
  4503. exit;
  4504. end;
  4505. {
  4506. mov ref,reg0
  4507. <op> reg0,reg1
  4508. dealloc reg0
  4509. to
  4510. <op> ref,reg1
  4511. }
  4512. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4513. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4514. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4515. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4516. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4517. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4518. begin
  4519. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4520. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4521. RemoveCurrentp(p, hp1);
  4522. Result:=true;
  4523. exit;
  4524. end;
  4525. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4526. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4527. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4528. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4529. begin
  4530. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4531. {$ifdef x86_64}
  4532. { Convert:
  4533. movq x(ref),%reg64
  4534. shrq y,%reg64
  4535. To:
  4536. movl x+4(ref),%reg32
  4537. shrl y-32,%reg32 (Remove if y = 32)
  4538. }
  4539. if (taicpu(p).opsize = S_Q) and
  4540. (taicpu(hp1).opcode = A_SHR) and
  4541. (taicpu(hp1).oper[0]^.val >= 32) then
  4542. begin
  4543. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4544. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4545. { Convert to 32-bit }
  4546. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4547. taicpu(p).opsize := S_L;
  4548. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4549. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4550. if (taicpu(hp1).oper[0]^.val = 32) then
  4551. begin
  4552. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4553. RemoveInstruction(hp1);
  4554. end
  4555. else
  4556. begin
  4557. { This will potentially open up more arithmetic operations since
  4558. the peephole optimizer now has a big hint that only the lower
  4559. 32 bits are currently in use (and opcodes are smaller in size) }
  4560. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4561. taicpu(hp1).opsize := S_L;
  4562. Dec(taicpu(hp1).oper[0]^.val, 32);
  4563. DebugMsg(SPeepholeOptimization + PreMessage +
  4564. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4565. end;
  4566. Result := True;
  4567. Exit;
  4568. end;
  4569. {$endif x86_64}
  4570. { Convert:
  4571. movl x(ref),%reg
  4572. shrl $24,%reg
  4573. To:
  4574. movzbl x+3(ref),%reg
  4575. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4576. Also accept sar instead of shr, but convert to movsx instead of movzx
  4577. }
  4578. if taicpu(hp1).opcode = A_SHR then
  4579. MovUnaligned := A_MOVZX
  4580. else
  4581. MovUnaligned := A_MOVSX;
  4582. NewSize := S_NO;
  4583. NewOffset := 0;
  4584. case taicpu(p).opsize of
  4585. S_B:
  4586. { No valid combinations };
  4587. S_W:
  4588. if (taicpu(hp1).oper[0]^.val = 8) then
  4589. begin
  4590. NewSize := S_BW;
  4591. NewOffset := 1;
  4592. end;
  4593. S_L:
  4594. case taicpu(hp1).oper[0]^.val of
  4595. 16:
  4596. begin
  4597. NewSize := S_WL;
  4598. NewOffset := 2;
  4599. end;
  4600. 24:
  4601. begin
  4602. NewSize := S_BL;
  4603. NewOffset := 3;
  4604. end;
  4605. else
  4606. ;
  4607. end;
  4608. {$ifdef x86_64}
  4609. S_Q:
  4610. case taicpu(hp1).oper[0]^.val of
  4611. 32:
  4612. begin
  4613. if taicpu(hp1).opcode = A_SAR then
  4614. begin
  4615. { 32-bit to 64-bit is a distinct instruction }
  4616. MovUnaligned := A_MOVSXD;
  4617. NewSize := S_LQ;
  4618. NewOffset := 4;
  4619. end
  4620. else
  4621. { Should have been handled by MovShr2Mov above }
  4622. InternalError(2022081811);
  4623. end;
  4624. 48:
  4625. begin
  4626. NewSize := S_WQ;
  4627. NewOffset := 6;
  4628. end;
  4629. 56:
  4630. begin
  4631. NewSize := S_BQ;
  4632. NewOffset := 7;
  4633. end;
  4634. else
  4635. ;
  4636. end;
  4637. {$endif x86_64}
  4638. else
  4639. InternalError(2022081810);
  4640. end;
  4641. if (NewSize <> S_NO) and
  4642. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4643. begin
  4644. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4645. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4646. debug_op2str(MovUnaligned);
  4647. {$ifdef x86_64}
  4648. if MovUnaligned <> A_MOVSXD then
  4649. { Don't add size suffix for MOVSXD }
  4650. {$endif x86_64}
  4651. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4652. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4653. taicpu(p).opcode := MovUnaligned;
  4654. taicpu(p).opsize := NewSize;
  4655. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4656. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4657. RemoveInstruction(hp1);
  4658. Result := True;
  4659. Exit;
  4660. end;
  4661. end;
  4662. { Backward optimisation shared with OptPass2MOV }
  4663. if FuncMov2Func(p, hp1) then
  4664. begin
  4665. Result := True;
  4666. Exit;
  4667. end;
  4668. end;
  4669. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4670. var
  4671. hp1 : tai;
  4672. begin
  4673. Result:=false;
  4674. if taicpu(p).ops <> 2 then
  4675. exit;
  4676. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4677. GetNextInstruction(p,hp1) then
  4678. begin
  4679. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4680. (taicpu(hp1).ops = 2) then
  4681. begin
  4682. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4683. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4684. { movXX reg1, mem1 or movXX mem1, reg1
  4685. movXX mem2, reg2 movXX reg2, mem2}
  4686. begin
  4687. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4688. { movXX reg1, mem1 or movXX mem1, reg1
  4689. movXX mem2, reg1 movXX reg2, mem1}
  4690. begin
  4691. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4692. begin
  4693. { Removes the second statement from
  4694. movXX reg1, mem1/reg2
  4695. movXX mem1/reg2, reg1
  4696. }
  4697. if taicpu(p).oper[0]^.typ=top_reg then
  4698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4699. { Removes the second statement from
  4700. movXX mem1/reg1, reg2
  4701. movXX reg2, mem1/reg1
  4702. }
  4703. if (taicpu(p).oper[1]^.typ=top_reg) and
  4704. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4705. begin
  4706. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4707. RemoveInstruction(hp1);
  4708. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4709. Result:=true;
  4710. exit;
  4711. end
  4712. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4713. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4716. RemoveInstruction(hp1);
  4717. Result:=true;
  4718. exit;
  4719. end;
  4720. end
  4721. end;
  4722. end;
  4723. end;
  4724. end;
  4725. end;
  4726. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4727. var
  4728. hp1 : tai;
  4729. begin
  4730. result:=false;
  4731. { replace
  4732. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4733. MovX %mreg2,%mreg1
  4734. dealloc %mreg2
  4735. by
  4736. <Op>X %mreg2,%mreg1
  4737. ?
  4738. }
  4739. if GetNextInstruction(p,hp1) and
  4740. { we mix single and double opperations here because we assume that the compiler
  4741. generates vmovapd only after double operations and vmovaps only after single operations }
  4742. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4745. (taicpu(p).oper[0]^.typ=top_reg) then
  4746. begin
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4750. begin
  4751. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4753. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4754. RemoveInstruction(hp1);
  4755. result:=true;
  4756. end;
  4757. end;
  4758. end;
  4759. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4760. var
  4761. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4762. JumpLabel, JumpLabel_dist: TAsmLabel;
  4763. FirstValue, SecondValue: TCGInt;
  4764. TempBool: Boolean;
  4765. begin
  4766. Result := False;
  4767. if (taicpu(p).oper[0]^.typ = top_const) and
  4768. (taicpu(p).oper[0]^.val <> -1) then
  4769. begin
  4770. { Convert unsigned maximum constants to -1 to aid optimisation }
  4771. case taicpu(p).opsize of
  4772. S_B:
  4773. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4774. begin
  4775. taicpu(p).oper[0]^.val := -1;
  4776. Result := True;
  4777. Exit;
  4778. end;
  4779. S_W:
  4780. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4781. begin
  4782. taicpu(p).oper[0]^.val := -1;
  4783. Result := True;
  4784. Exit;
  4785. end;
  4786. S_L:
  4787. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. {$ifdef x86_64}
  4794. S_Q:
  4795. { Storing anything greater than $7FFFFFFF is not possible so do
  4796. nothing };
  4797. {$endif x86_64}
  4798. else
  4799. InternalError(2021121001);
  4800. end;
  4801. end;
  4802. if GetNextInstruction(p, hp1) and
  4803. TrySwapMovCmp(p, hp1) then
  4804. begin
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. if MatchInstruction(hp1, A_Jcc, []) then
  4809. begin
  4810. TempBool := True;
  4811. if DoJumpOptimizations(hp1, TempBool) or
  4812. not TempBool then
  4813. begin
  4814. Result := True;
  4815. if Assigned(hp1) then
  4816. begin
  4817. if (hp1.typ in [ait_align]) then
  4818. SkipAligns(hp1, hp1);
  4819. { CollapseZeroDistJump will be set to the label after the
  4820. jump if it optimises, whether or not it's live or dead }
  4821. if (hp1.typ in [ait_label]) and
  4822. not (tai_label(hp1).labsym.is_used) then
  4823. GetNextInstruction(hp1, hp1);
  4824. end;
  4825. TransferUsedRegs(TmpUsedRegs);
  4826. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4827. if not Assigned(hp1) or
  4828. (
  4829. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4830. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4831. ) then
  4832. begin
  4833. { No more conditional jumps; conditional statement is no longer required }
  4834. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4835. RemoveCurrentP(p);
  4836. end;
  4837. Exit;
  4838. end;
  4839. end;
  4840. { Search for:
  4841. test $x,(reg/ref)
  4842. jne @lbl1
  4843. test $y,(reg/ref) (same register or reference)
  4844. jne @lbl1
  4845. Change to:
  4846. test $(x or y),(reg/ref)
  4847. jne @lbl1
  4848. (Note, this doesn't work with je instead of jne)
  4849. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4850. Also search for:
  4851. test $x,(reg/ref)
  4852. je @lbl1
  4853. ...
  4854. test $y,(reg/ref)
  4855. je/jne @lbl2
  4856. If (x or y) = x, then the second jump is deterministic
  4857. }
  4858. if (
  4859. (
  4860. (taicpu(p).oper[0]^.typ = top_const) or
  4861. (
  4862. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4863. (taicpu(p).oper[0]^.typ = top_reg) and
  4864. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4865. )
  4866. ) and
  4867. MatchInstruction(hp1, A_JCC, [])
  4868. ) then
  4869. begin
  4870. if (taicpu(p).oper[0]^.typ = top_reg) and
  4871. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4872. FirstValue := -1
  4873. else
  4874. FirstValue := taicpu(p).oper[0]^.val;
  4875. { If we have several test/jne's in a row, it might be the case that
  4876. the second label doesn't go to the same location, but the one
  4877. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4878. so accommodate for this with a while loop.
  4879. }
  4880. hp1_last := hp1;
  4881. while (
  4882. (
  4883. (taicpu(p).oper[1]^.typ = top_reg) and
  4884. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4885. ) or GetNextInstruction(hp1_last, p_dist)
  4886. ) and (p_dist.typ = ait_instruction) do
  4887. begin
  4888. if (
  4889. (
  4890. (taicpu(p_dist).opcode = A_TEST) and
  4891. (
  4892. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4893. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4894. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4895. )
  4896. ) or
  4897. (
  4898. { cmp 0,%reg = test %reg,%reg }
  4899. (taicpu(p_dist).opcode = A_CMP) and
  4900. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4901. )
  4902. ) and
  4903. { Make sure the destination operands are actually the same }
  4904. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4905. GetNextInstruction(p_dist, hp1_dist) and
  4906. MatchInstruction(hp1_dist, A_JCC, []) then
  4907. begin
  4908. if
  4909. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4910. (
  4911. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4912. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4913. ) then
  4914. SecondValue := -1
  4915. else
  4916. SecondValue := taicpu(p_dist).oper[0]^.val;
  4917. { If both of the TEST constants are identical, delete the
  4918. second TEST that is unnecessary (be careful though, just
  4919. in case the flags are modified in between) }
  4920. if (FirstValue = SecondValue) then
  4921. begin
  4922. { We have to check the entire range }
  4923. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4924. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4925. begin
  4926. { Since the second jump's condition is a subset of the first, we
  4927. know it will never branch because the first jump dominates it.
  4928. Get it out of the way now rather than wait for the jump
  4929. optimisations for a speed boost. }
  4930. if IsJumpToLabel(taicpu(hp1_dist)) then
  4931. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4932. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4933. RemoveInstruction(hp1_dist);
  4934. Result := True;
  4935. end
  4936. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4937. begin
  4938. { If the inverse of the first condition is a subset of the second,
  4939. the second one will definitely branch if the first one doesn't }
  4940. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4941. { We can remove the TEST instruction too }
  4942. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4943. RemoveInstruction(p_dist);
  4944. MakeUnconditional(taicpu(hp1_dist));
  4945. RemoveDeadCodeAfterJump(hp1_dist);
  4946. { Since the jump is now unconditional, we can't
  4947. continue any further with this particular
  4948. optimisation. The original TEST is still intact
  4949. though, so there might be something else we can
  4950. do }
  4951. Include(OptsToCheck, aoc_ForceNewIteration);
  4952. Break;
  4953. end;
  4954. if Result or
  4955. { If a jump wasn't removed or made unconditional, only
  4956. remove the identical TEST instruction if the flags
  4957. weren't modified }
  4958. TempBool then
  4959. begin
  4960. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4961. RemoveInstruction(p_dist);
  4962. { If the jump was removed or made unconditional, we
  4963. don't need to allocate NR_DEFAULTFLAGS over the
  4964. entire range }
  4965. if not Result then
  4966. begin
  4967. { Mark the flags as 'in use' over the entire range }
  4968. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4969. { Speed gain - continue search from the Jcc instruction }
  4970. hp1_last := hp1_dist;
  4971. { Only the TEST instruction was removed, and the
  4972. original was unchanged, so we can safely do
  4973. another iteration of the while loop }
  4974. Include(OptsToCheck, aoc_ForceNewIteration);
  4975. Continue;
  4976. end;
  4977. Exit;
  4978. end;
  4979. end;
  4980. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4981. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4982. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4983. then the second jump will never branch, so it can also be
  4984. removed regardless of where it goes }
  4985. (
  4986. (FirstValue = -1) or
  4987. (SecondValue = -1) or
  4988. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4989. ) and
  4990. (
  4991. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  4992. { Always adjacent under -O2 and under }
  4993. not(cs_opt_level3 in current_settings.optimizerswitches) or
  4994. (
  4995. GetNextInstruction(hp1, hp1_last) and
  4996. (hp1_last = p_dist)
  4997. )
  4998. ) then
  4999. begin
  5000. { Same jump location... can be a register since nothing's changed }
  5001. { If any of the entries are equivalent to test %reg,%reg, then the
  5002. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5003. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5004. if IsJumpToLabel(taicpu(hp1_dist)) then
  5005. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5006. { Only remove the second test if no jumps or other conditional instructions follow }
  5007. TransferUsedRegs(TmpUsedRegs);
  5008. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5009. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5010. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5011. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5012. begin
  5013. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5014. RemoveInstruction(p_dist);
  5015. { Remove the first jump, not the second, to keep
  5016. any register deallocations between the second
  5017. TEST/JNE pair in the same place. Aids future
  5018. optimisation. }
  5019. RemoveInstruction(hp1);
  5020. end
  5021. else
  5022. begin
  5023. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5024. { Remove second jump in this instance }
  5025. RemoveInstruction(hp1_dist);
  5026. end;
  5027. Result := True;
  5028. Exit;
  5029. end;
  5030. end;
  5031. if { If -O2 and under, it may stop on any old instruction }
  5032. (cs_opt_level3 in current_settings.optimizerswitches) and
  5033. (taicpu(p).oper[1]^.typ = top_reg) and
  5034. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5035. begin
  5036. hp1_last := p_dist;
  5037. Continue;
  5038. end;
  5039. Break;
  5040. end;
  5041. end;
  5042. { Search for:
  5043. test %reg,%reg
  5044. j(c1) @lbl1
  5045. ...
  5046. @lbl:
  5047. test %reg,%reg (same register)
  5048. j(c2) @lbl2
  5049. If c2 is a subset of c1, change to:
  5050. test %reg,%reg
  5051. j(c1) @lbl2
  5052. (@lbl1 may become a dead label as a result)
  5053. }
  5054. if (taicpu(p).oper[1]^.typ = top_reg) and
  5055. (taicpu(p).oper[0]^.typ = top_reg) and
  5056. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5057. MatchInstruction(hp1, A_JCC, []) and
  5058. IsJumpToLabel(taicpu(hp1)) then
  5059. begin
  5060. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5061. p_label := nil;
  5062. if Assigned(JumpLabel) then
  5063. p_label := getlabelwithsym(JumpLabel);
  5064. if Assigned(p_label) and
  5065. GetNextInstruction(p_label, p_dist) and
  5066. MatchInstruction(p_dist, A_TEST, []) and
  5067. { It's fine if the second test uses smaller sub-registers }
  5068. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5069. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5070. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5071. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5072. GetNextInstruction(p_dist, hp1_dist) and
  5073. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5074. begin
  5075. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5076. if JumpLabel = JumpLabel_dist then
  5077. { This is an infinite loop }
  5078. Exit;
  5079. { Best optimisation when the first condition is a subset (or equal) of the second }
  5080. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5081. begin
  5082. { Any registers used here will already be allocated }
  5083. if Assigned(JumpLabel) then
  5084. JumpLabel.DecRefs;
  5085. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5086. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5087. Result := True;
  5088. Exit;
  5089. end;
  5090. end;
  5091. end;
  5092. end;
  5093. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5094. var
  5095. hp1, hp2: tai;
  5096. ActiveReg: TRegister;
  5097. OldOffset: asizeint;
  5098. ThisConst: TCGInt;
  5099. function RegDeallocated: Boolean;
  5100. begin
  5101. TransferUsedRegs(TmpUsedRegs);
  5102. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5103. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5104. end;
  5105. begin
  5106. result:=false;
  5107. hp1 := nil;
  5108. { replace
  5109. addX const,%reg1
  5110. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5111. dealloc %reg1
  5112. by
  5113. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5114. }
  5115. if MatchOpType(taicpu(p),top_const,top_reg) then
  5116. begin
  5117. ActiveReg := taicpu(p).oper[1]^.reg;
  5118. { Ensures the entire register was updated }
  5119. if (taicpu(p).opsize >= S_L) and
  5120. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5121. MatchInstruction(hp1,A_LEA,[]) and
  5122. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5123. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5124. (
  5125. { Cover the case where the register in the reference is also the destination register }
  5126. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5127. (
  5128. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5129. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5130. RegDeallocated
  5131. )
  5132. ) then
  5133. begin
  5134. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5135. {$push}
  5136. {$R-}{$Q-}
  5137. { Explicitly disable overflow checking for these offset calculation
  5138. as those do not matter for the final result }
  5139. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5140. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5141. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5142. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5143. {$pop}
  5144. {$ifdef x86_64}
  5145. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5146. begin
  5147. { Overflow; abort }
  5148. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5149. end
  5150. else
  5151. {$endif x86_64}
  5152. begin
  5153. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5154. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5155. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5156. RemoveCurrentP(p, hp1)
  5157. else
  5158. RemoveCurrentP(p);
  5159. result:=true;
  5160. Exit;
  5161. end;
  5162. end;
  5163. if (
  5164. { Save calling GetNextInstructionUsingReg again }
  5165. Assigned(hp1) or
  5166. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5167. ) and
  5168. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5169. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5170. begin
  5171. if taicpu(hp1).oper[0]^.typ = top_const then
  5172. begin
  5173. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5174. if taicpu(hp1).opcode = A_ADD then
  5175. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5176. else
  5177. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5178. Result := True;
  5179. { Handle any overflows }
  5180. case taicpu(p).opsize of
  5181. S_B:
  5182. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5183. S_W:
  5184. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5185. S_L:
  5186. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5187. {$ifdef x86_64}
  5188. S_Q:
  5189. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5190. { Overflow; abort }
  5191. Result := False
  5192. else
  5193. taicpu(p).oper[0]^.val := ThisConst;
  5194. {$endif x86_64}
  5195. else
  5196. InternalError(2021102610);
  5197. end;
  5198. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5199. if Result then
  5200. begin
  5201. if (taicpu(p).oper[0]^.val < 0) and
  5202. (
  5203. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5204. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5205. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5206. ) then
  5207. begin
  5208. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5209. taicpu(p).opcode := A_SUB;
  5210. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5211. end
  5212. else
  5213. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5214. RemoveInstruction(hp1);
  5215. end;
  5216. end
  5217. else
  5218. begin
  5219. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5220. TransferUsedRegs(TmpUsedRegs);
  5221. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5222. hp2 := p;
  5223. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5224. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5225. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5226. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5227. begin
  5228. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5229. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5230. Asml.Remove(p);
  5231. Asml.InsertAfter(p, hp1);
  5232. p := hp1;
  5233. Result := True;
  5234. Exit;
  5235. end;
  5236. end;
  5237. end;
  5238. if DoArithCombineOpt(p) then
  5239. Result:=true;
  5240. end;
  5241. end;
  5242. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5243. var
  5244. hp1, hp2: tai;
  5245. ref: Integer;
  5246. saveref: treference;
  5247. offsetcalc: Int64;
  5248. TempReg: TRegister;
  5249. Multiple: TCGInt;
  5250. Adjacent, IntermediateRegDiscarded: Boolean;
  5251. begin
  5252. Result:=false;
  5253. { play save and throw an error if LEA uses a seg register prefix,
  5254. this is most likely an error somewhere else }
  5255. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5256. internalerror(2022022001);
  5257. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5258. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5259. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5260. (
  5261. { do not mess with leas accessing the stack pointer
  5262. unless it's a null operation }
  5263. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5264. (
  5265. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5266. (taicpu(p).oper[0]^.ref^.offset = 0)
  5267. )
  5268. ) and
  5269. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5270. begin
  5271. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5272. begin
  5273. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5274. begin
  5275. taicpu(p).opcode := A_MOV;
  5276. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5277. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5278. end
  5279. else
  5280. begin
  5281. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5282. RemoveCurrentP(p);
  5283. end;
  5284. Result:=true;
  5285. exit;
  5286. end
  5287. else if (
  5288. { continue to use lea to adjust the stack pointer,
  5289. it is the recommended way, but only if not optimizing for size }
  5290. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5291. (cs_opt_size in current_settings.optimizerswitches)
  5292. ) and
  5293. { If the flags register is in use, don't change the instruction
  5294. to an ADD otherwise this will scramble the flags. [Kit] }
  5295. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5296. ConvertLEA(taicpu(p)) then
  5297. begin
  5298. Result:=true;
  5299. exit;
  5300. end;
  5301. end;
  5302. { Don't optimise if the stack or frame pointer is the destination register }
  5303. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5304. Exit;
  5305. if GetNextInstruction(p,hp1) and
  5306. (hp1.typ=ait_instruction) then
  5307. begin
  5308. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5309. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5310. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5311. begin
  5312. TransferUsedRegs(TmpUsedRegs);
  5313. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5314. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5315. begin
  5316. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5317. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5318. RemoveInstruction(hp1);
  5319. result:=true;
  5320. exit;
  5321. end;
  5322. end;
  5323. { changes
  5324. lea <ref1>, reg1
  5325. <op> ...,<ref. with reg1>,...
  5326. to
  5327. <op> ...,<ref1>,... }
  5328. { find a reference which uses reg1 }
  5329. 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
  5330. ref:=0
  5331. 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
  5332. ref:=1
  5333. else
  5334. ref:=-1;
  5335. if (ref<>-1) and
  5336. { reg1 must be either the base or the index }
  5337. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5338. begin
  5339. { reg1 can be removed from the reference }
  5340. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5341. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5342. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5343. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5344. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5345. else
  5346. Internalerror(2019111201);
  5347. { check if the can insert all data of the lea into the second instruction }
  5348. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5349. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5350. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5351. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5352. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5353. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5354. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5355. {$ifdef x86_64}
  5356. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5357. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5358. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5359. )
  5360. {$endif x86_64}
  5361. then
  5362. begin
  5363. { reg1 might not used by the second instruction after it is remove from the reference }
  5364. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5365. begin
  5366. TransferUsedRegs(TmpUsedRegs);
  5367. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5368. { reg1 is not updated so it might not be used afterwards }
  5369. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5370. begin
  5371. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5372. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5373. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5374. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5375. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5376. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5377. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5378. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5379. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5380. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5381. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5382. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5383. RemoveCurrentP(p, hp1);
  5384. result:=true;
  5385. exit;
  5386. end
  5387. end;
  5388. end;
  5389. { recover }
  5390. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5391. end;
  5392. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5393. if Adjacent or
  5394. { Check further ahead (up to 2 instructions ahead for -O2) }
  5395. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5396. begin
  5397. { Check common LEA/LEA conditions }
  5398. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5399. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5400. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5401. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5402. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5403. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5404. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5405. (
  5406. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5407. calling it (since it calls GetNextInstruction) }
  5408. Adjacent or
  5409. (
  5410. (
  5411. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5412. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5413. ) and (
  5414. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5415. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5416. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5417. )
  5418. )
  5419. ) then
  5420. begin
  5421. TransferUsedRegs(TmpUsedRegs);
  5422. hp2 := p;
  5423. repeat
  5424. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5425. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5426. IntermediateRegDiscarded :=
  5427. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5428. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5429. { changes
  5430. lea offset1(regX,scale), reg1
  5431. lea offset2(reg1,reg1), reg2
  5432. to
  5433. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5434. and
  5435. lea offset1(regX,scale1), reg1
  5436. lea offset2(reg1,scale2), reg2
  5437. to
  5438. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5439. and
  5440. lea offset1(regX,scale1), reg1
  5441. lea offset2(reg3,reg1,scale2), reg2
  5442. to
  5443. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5444. ... so long as the final scale does not exceed 8
  5445. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5446. }
  5447. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5448. (
  5449. { Don't optimise if size is a concern and the intermediate register remains in use }
  5450. IntermediateRegDiscarded or
  5451. not (cs_opt_size in current_settings.optimizerswitches)
  5452. ) and
  5453. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5454. (
  5455. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5456. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5457. ) and (
  5458. (
  5459. { lea (reg1,scale2), reg2 variant }
  5460. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5461. (
  5462. Adjacent or
  5463. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5464. ) and
  5465. (
  5466. (
  5467. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5468. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5469. ) or (
  5470. { lea (regX,regX), reg1 variant }
  5471. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5472. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5473. )
  5474. )
  5475. ) or (
  5476. { lea (reg1,reg1), reg1 variant }
  5477. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5478. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5479. )
  5480. ) then
  5481. begin
  5482. { Make everything homogeneous to make calculations easier }
  5483. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5484. begin
  5485. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5486. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5487. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5488. else
  5489. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5490. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5491. end;
  5492. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5493. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5494. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5495. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5496. begin
  5497. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5498. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5499. begin
  5500. { Put the register to change in the index register }
  5501. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5502. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5503. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5504. end;
  5505. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5506. begin
  5507. { Just to prevent miscalculations }
  5508. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5509. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5510. else
  5511. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5512. end
  5513. else
  5514. begin
  5515. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5516. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5517. end;
  5518. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5519. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5520. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5521. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5522. if IntermediateRegDiscarded then
  5523. begin
  5524. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5525. RemoveCurrentP(p);
  5526. end
  5527. else
  5528. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5529. result:=true;
  5530. exit;
  5531. end;
  5532. end;
  5533. { changes
  5534. lea offset1(regX), reg1
  5535. lea offset2(reg1), reg2
  5536. to
  5537. lea offset1+offset2(regX), reg2 }
  5538. if (
  5539. { Don't optimise if size is a concern and the intermediate register remains in use }
  5540. IntermediateRegDiscarded or
  5541. not (cs_opt_size in current_settings.optimizerswitches)
  5542. ) and
  5543. (
  5544. (
  5545. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5546. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5547. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5548. ) or (
  5549. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5550. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5551. (
  5552. (
  5553. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5554. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5555. ) or (
  5556. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5557. (
  5558. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5559. (
  5560. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5561. (
  5562. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5563. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5564. )
  5565. )
  5566. )
  5567. )
  5568. )
  5569. )
  5570. ) then
  5571. begin
  5572. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5573. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5574. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5575. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5576. begin
  5577. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5578. begin
  5579. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5580. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5581. { if the register is used as index and base, we have to increase for base as well
  5582. and adapt base }
  5583. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5584. begin
  5585. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5586. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5587. end;
  5588. end
  5589. else
  5590. begin
  5591. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5592. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5593. end;
  5594. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5595. begin
  5596. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5597. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5598. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5599. end;
  5600. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5601. if IntermediateRegDiscarded then
  5602. begin
  5603. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5604. RemoveCurrentP(p);
  5605. end
  5606. else
  5607. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5608. result:=true;
  5609. exit;
  5610. end;
  5611. end;
  5612. end;
  5613. { Change:
  5614. leal/q $x(%reg1),%reg2
  5615. ...
  5616. shll/q $y,%reg2
  5617. To:
  5618. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5619. }
  5620. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5621. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5622. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5623. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5624. (taicpu(hp1).oper[0]^.val <= 3) then
  5625. begin
  5626. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5627. TransferUsedRegs(TmpUsedRegs);
  5628. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5629. if
  5630. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5631. (this works even if scalefactor is zero) }
  5632. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5633. { Ensure offset doesn't go out of bounds }
  5634. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5635. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5636. (
  5637. (
  5638. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5639. (
  5640. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5641. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5642. (
  5643. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5644. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5645. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5646. )
  5647. )
  5648. ) or (
  5649. (
  5650. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5651. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5652. ) and
  5653. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5654. )
  5655. ) then
  5656. begin
  5657. repeat
  5658. with taicpu(p).oper[0]^.ref^ do
  5659. begin
  5660. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5661. if index = base then
  5662. begin
  5663. if Multiple > 4 then
  5664. { Optimisation will no longer work because resultant
  5665. scale factor will exceed 8 }
  5666. Break;
  5667. base := NR_NO;
  5668. scalefactor := 2;
  5669. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5670. end
  5671. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5672. begin
  5673. { Scale factor only works on the index register }
  5674. index := base;
  5675. base := NR_NO;
  5676. end;
  5677. { For safety }
  5678. if scalefactor <= 1 then
  5679. begin
  5680. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5681. scalefactor := Multiple;
  5682. end
  5683. else
  5684. begin
  5685. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5686. scalefactor := scalefactor * Multiple;
  5687. end;
  5688. offset := offset * Multiple;
  5689. end;
  5690. RemoveInstruction(hp1);
  5691. Result := True;
  5692. Exit;
  5693. { This repeat..until loop exists for the benefit of Break }
  5694. until True;
  5695. end;
  5696. end;
  5697. end;
  5698. end;
  5699. end;
  5700. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5701. var
  5702. hp1 : tai;
  5703. SubInstr: Boolean;
  5704. ThisConst: TCGInt;
  5705. const
  5706. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5707. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5708. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5709. begin
  5710. Result := False;
  5711. if taicpu(p).oper[0]^.typ <> top_const then
  5712. { Should have been confirmed before calling }
  5713. InternalError(2021102601);
  5714. SubInstr := (taicpu(p).opcode = A_SUB);
  5715. if GetLastInstruction(p, hp1) and
  5716. (hp1.typ = ait_instruction) and
  5717. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5718. begin
  5719. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5720. { Bad size }
  5721. InternalError(2022042001);
  5722. case taicpu(hp1).opcode Of
  5723. A_INC:
  5724. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5725. begin
  5726. if SubInstr then
  5727. ThisConst := taicpu(p).oper[0]^.val - 1
  5728. else
  5729. ThisConst := taicpu(p).oper[0]^.val + 1;
  5730. end
  5731. else
  5732. Exit;
  5733. A_DEC:
  5734. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5735. begin
  5736. if SubInstr then
  5737. ThisConst := taicpu(p).oper[0]^.val + 1
  5738. else
  5739. ThisConst := taicpu(p).oper[0]^.val - 1;
  5740. end
  5741. else
  5742. Exit;
  5743. A_SUB:
  5744. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5745. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5746. begin
  5747. if SubInstr then
  5748. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5749. else
  5750. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5751. end
  5752. else
  5753. Exit;
  5754. A_ADD:
  5755. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5756. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5757. begin
  5758. if SubInstr then
  5759. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5760. else
  5761. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5762. end
  5763. else
  5764. Exit;
  5765. else
  5766. Exit;
  5767. end;
  5768. { Check that the values are in range }
  5769. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5770. { Overflow; abort }
  5771. Exit;
  5772. if (ThisConst = 0) then
  5773. begin
  5774. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5775. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5776. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5777. RemoveInstruction(hp1);
  5778. hp1 := tai(p.next);
  5779. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5780. if not GetLastInstruction(hp1, p) then
  5781. p := hp1;
  5782. end
  5783. else
  5784. begin
  5785. if taicpu(hp1).opercnt=1 then
  5786. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5787. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5788. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5789. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5790. else
  5791. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5792. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5793. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5794. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5795. RemoveInstruction(hp1);
  5796. taicpu(p).loadconst(0, ThisConst);
  5797. end;
  5798. Result := True;
  5799. end;
  5800. end;
  5801. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5802. begin
  5803. Result := False;
  5804. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5805. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5806. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5807. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5808. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5809. (
  5810. (
  5811. (taicpu(hp1).opcode = A_TEST)
  5812. ) or (
  5813. (taicpu(hp1).opcode = A_CMP) and
  5814. { A sanity check more than anything }
  5815. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5816. )
  5817. ) then
  5818. begin
  5819. { change
  5820. mov mem, %reg
  5821. ...
  5822. cmp/test x, %reg / test %reg,%reg
  5823. (reg deallocated)
  5824. to
  5825. cmp/test x, mem / cmp 0, mem
  5826. }
  5827. TransferUsedRegs(TmpUsedRegs);
  5828. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5829. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5830. begin
  5831. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5832. if (taicpu(hp1).opcode = A_TEST) and
  5833. (
  5834. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5835. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5836. ) then
  5837. begin
  5838. taicpu(hp1).opcode := A_CMP;
  5839. taicpu(hp1).loadconst(0, 0);
  5840. end;
  5841. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5842. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5843. RemoveCurrentP(p);
  5844. if (p <> hp1) then
  5845. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5846. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5847. { Make sure the flags are allocated across the CMP instruction }
  5848. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5849. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5850. Result := True;
  5851. Exit;
  5852. end;
  5853. end;
  5854. end;
  5855. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5856. var
  5857. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5858. ThisReg, SecondReg: TRegister;
  5859. JumpLoc: TAsmLabel;
  5860. NewSize: TOpSize;
  5861. begin
  5862. Result := False;
  5863. {
  5864. Convert:
  5865. j<c> .L1
  5866. .L2:
  5867. mov 1,reg
  5868. jmp .L3 (or ret, although it might not be a RET yet)
  5869. .L1:
  5870. mov 0,reg
  5871. jmp .L3 (or ret)
  5872. ( As long as .L3 <> .L1 or .L2)
  5873. To:
  5874. mov 0,reg
  5875. set<not(c)> reg
  5876. jmp .L3 (or ret)
  5877. .L2:
  5878. mov 1,reg
  5879. jmp .L3 (or ret)
  5880. .L1:
  5881. mov 0,reg
  5882. jmp .L3 (or ret)
  5883. }
  5884. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5885. Exit;
  5886. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5887. if GetNextInstruction(hp_label, hp2) and
  5888. MatchInstruction(hp2,A_MOV,[]) and
  5889. (taicpu(hp2).oper[0]^.typ = top_const) and
  5890. (
  5891. (
  5892. (taicpu(hp2).oper[1]^.typ = top_reg)
  5893. {$ifdef i386}
  5894. { Under i386, ESI, EDI, EBP and ESP
  5895. don't have an 8-bit representation }
  5896. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5897. {$endif i386}
  5898. ) or (
  5899. {$ifdef i386}
  5900. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5901. {$endif i386}
  5902. (taicpu(hp2).opsize = S_B)
  5903. )
  5904. ) and
  5905. GetNextInstruction(hp2, hp3) and
  5906. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5907. (
  5908. (taicpu(hp3).opcode=A_RET) or
  5909. (
  5910. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5911. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5912. )
  5913. ) and
  5914. GetNextInstruction(hp3, hp4) and
  5915. SkipAligns(hp4, hp4) and
  5916. (hp4.typ=ait_label) and
  5917. (tai_label(hp4).labsym=JumpLoc) and
  5918. (
  5919. not (cs_opt_size in current_settings.optimizerswitches) or
  5920. { If the initial jump is the label's only reference, then it will
  5921. become a dead label if the other conditions are met and hence
  5922. remove at least 2 instructions, including a jump }
  5923. (JumpLoc.getrefs = 1)
  5924. ) and
  5925. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5926. that will be optimised out }
  5927. GetNextInstruction(hp4, hp5) and
  5928. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5929. (taicpu(hp5).oper[0]^.typ = top_const) and
  5930. (
  5931. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5932. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5933. ) and
  5934. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5935. GetNextInstruction(hp5,hp6) and
  5936. (
  5937. (hp6.typ<>ait_label) or
  5938. SkipLabels(hp6, hp6)
  5939. ) and
  5940. (hp6.typ=ait_instruction) then
  5941. begin
  5942. { First, let's look at the two jumps that are hp3 and hp6 }
  5943. if not
  5944. (
  5945. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5946. (
  5947. (taicpu(hp6).opcode=A_RET) or
  5948. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5949. )
  5950. ) then
  5951. { If condition is False, then the JMP/RET instructions matched conventionally }
  5952. begin
  5953. { See if one of the jumps can be instantly converted into a RET }
  5954. if (taicpu(hp3).opcode=A_JMP) then
  5955. begin
  5956. { Reuse hp5 }
  5957. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5958. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5959. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5960. Exit;
  5961. if MatchInstruction(hp5, A_RET, []) then
  5962. begin
  5963. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5964. ConvertJumpToRET(hp3, hp5);
  5965. Result := True;
  5966. end
  5967. else
  5968. Exit;
  5969. end;
  5970. if (taicpu(hp6).opcode=A_JMP) then
  5971. begin
  5972. { Reuse hp5 }
  5973. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5974. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5975. Exit;
  5976. if MatchInstruction(hp5, A_RET, []) then
  5977. begin
  5978. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5979. ConvertJumpToRET(hp6, hp5);
  5980. Result := True;
  5981. end
  5982. else
  5983. Exit;
  5984. end;
  5985. if not
  5986. (
  5987. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5988. (
  5989. (taicpu(hp6).opcode=A_RET) or
  5990. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5991. )
  5992. ) then
  5993. { Still doesn't match }
  5994. Exit;
  5995. end;
  5996. if (taicpu(hp2).oper[0]^.val = 1) then
  5997. begin
  5998. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5999. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6000. end
  6001. else
  6002. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6003. if taicpu(hp2).opsize=S_B then
  6004. begin
  6005. if taicpu(hp2).oper[1]^.typ = top_reg then
  6006. begin
  6007. SecondReg := taicpu(hp2).oper[1]^.reg;
  6008. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6009. end
  6010. else
  6011. begin
  6012. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6013. SecondReg := NR_NO;
  6014. end;
  6015. hp_pos := p;
  6016. hp_allocstart := hp4;
  6017. end
  6018. else
  6019. begin
  6020. { Will be a register because the size can't be S_B otherwise }
  6021. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6022. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6023. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6024. if (cs_opt_size in current_settings.optimizerswitches) then
  6025. begin
  6026. { Favour using MOVZX when optimising for size }
  6027. case taicpu(hp2).opsize of
  6028. S_W:
  6029. NewSize := S_BW;
  6030. S_L:
  6031. NewSize := S_BL;
  6032. {$ifdef x86_64}
  6033. S_Q:
  6034. begin
  6035. NewSize := S_BL;
  6036. { Will implicitly zero-extend to 64-bit }
  6037. setsubreg(SecondReg, R_SUBD);
  6038. end;
  6039. {$endif x86_64}
  6040. else
  6041. InternalError(2022101301);
  6042. end;
  6043. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6044. { Inserting it right before p will guarantee that the flags are also tracked }
  6045. Asml.InsertBefore(hp5, p);
  6046. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6047. hp_pos := hp5;
  6048. hp_allocstart := hp4;
  6049. end
  6050. else
  6051. begin
  6052. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6053. { Inserting it right before p will guarantee that the flags are also tracked }
  6054. Asml.InsertBefore(hp5, p);
  6055. hp_pos := p;
  6056. hp_allocstart := hp5;
  6057. end;
  6058. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6059. end;
  6060. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6061. taicpu(hp4).condition := taicpu(p).condition;
  6062. asml.InsertBefore(hp4, hp_pos);
  6063. if taicpu(hp3).is_jmp then
  6064. begin
  6065. JumpLoc.decrefs;
  6066. MakeUnconditional(taicpu(p));
  6067. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6068. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6069. end
  6070. else
  6071. ConvertJumpToRET(p, hp3);
  6072. if SecondReg <> NR_NO then
  6073. { Ensure the destination register is allocated over this region }
  6074. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6075. if (JumpLoc.getrefs = 0) then
  6076. RemoveDeadCodeAfterJump(hp3);
  6077. Result:=true;
  6078. exit;
  6079. end;
  6080. end;
  6081. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6082. var
  6083. hp1, hp2: tai;
  6084. ActiveReg: TRegister;
  6085. OldOffset: asizeint;
  6086. ThisConst: TCGInt;
  6087. function RegDeallocated: Boolean;
  6088. begin
  6089. TransferUsedRegs(TmpUsedRegs);
  6090. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6091. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6092. end;
  6093. begin
  6094. Result:=false;
  6095. hp1 := nil;
  6096. { replace
  6097. subX const,%reg1
  6098. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6099. dealloc %reg1
  6100. by
  6101. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6102. }
  6103. if MatchOpType(taicpu(p),top_const,top_reg) then
  6104. begin
  6105. ActiveReg := taicpu(p).oper[1]^.reg;
  6106. { Ensures the entire register was updated }
  6107. if (taicpu(p).opsize >= S_L) and
  6108. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6109. MatchInstruction(hp1,A_LEA,[]) and
  6110. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6111. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6112. (
  6113. { Cover the case where the register in the reference is also the destination register }
  6114. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6115. (
  6116. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6117. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6118. RegDeallocated
  6119. )
  6120. ) then
  6121. begin
  6122. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6123. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6124. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6125. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6126. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6127. {$ifdef x86_64}
  6128. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6129. begin
  6130. { Overflow; abort }
  6131. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6132. end
  6133. else
  6134. {$endif x86_64}
  6135. begin
  6136. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6137. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6138. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6139. RemoveCurrentP(p, hp1)
  6140. else
  6141. RemoveCurrentP(p);
  6142. result:=true;
  6143. Exit;
  6144. end;
  6145. end;
  6146. if (
  6147. { Save calling GetNextInstructionUsingReg again }
  6148. Assigned(hp1) or
  6149. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6150. ) and
  6151. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6152. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6153. begin
  6154. if taicpu(hp1).oper[0]^.typ = top_const then
  6155. begin
  6156. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6157. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6158. Result := True;
  6159. { Handle any overflows }
  6160. case taicpu(p).opsize of
  6161. S_B:
  6162. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6163. S_W:
  6164. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6165. S_L:
  6166. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6167. {$ifdef x86_64}
  6168. S_Q:
  6169. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6170. { Overflow; abort }
  6171. Result := False
  6172. else
  6173. taicpu(p).oper[0]^.val := ThisConst;
  6174. {$endif x86_64}
  6175. else
  6176. InternalError(2021102611);
  6177. end;
  6178. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6179. if Result then
  6180. begin
  6181. if (taicpu(p).oper[0]^.val < 0) and
  6182. (
  6183. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6184. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6185. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6186. ) then
  6187. begin
  6188. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6189. taicpu(p).opcode := A_SUB;
  6190. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6191. end
  6192. else
  6193. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6194. RemoveInstruction(hp1);
  6195. end;
  6196. end
  6197. else
  6198. begin
  6199. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6200. TransferUsedRegs(TmpUsedRegs);
  6201. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6202. hp2 := p;
  6203. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6204. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6205. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6206. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6207. begin
  6208. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6209. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6210. Asml.Remove(p);
  6211. Asml.InsertAfter(p, hp1);
  6212. p := hp1;
  6213. Result := True;
  6214. Exit;
  6215. end;
  6216. end;
  6217. end;
  6218. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6219. { * change "sub/add const1, reg" or "dec reg" followed by
  6220. "sub const2, reg" to one "sub ..., reg" }
  6221. {$ifdef i386}
  6222. if (taicpu(p).oper[0]^.val = 2) and
  6223. (ActiveReg = NR_ESP) and
  6224. { Don't do the sub/push optimization if the sub }
  6225. { comes from setting up the stack frame (JM) }
  6226. (not(GetLastInstruction(p,hp1)) or
  6227. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6228. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6229. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6230. begin
  6231. hp1 := tai(p.next);
  6232. while Assigned(hp1) and
  6233. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6234. not RegReadByInstruction(NR_ESP,hp1) and
  6235. not RegModifiedByInstruction(NR_ESP,hp1) do
  6236. hp1 := tai(hp1.next);
  6237. if Assigned(hp1) and
  6238. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6239. begin
  6240. taicpu(hp1).changeopsize(S_L);
  6241. if taicpu(hp1).oper[0]^.typ=top_reg then
  6242. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6243. hp1 := tai(p.next);
  6244. RemoveCurrentp(p, hp1);
  6245. Result:=true;
  6246. exit;
  6247. end;
  6248. end;
  6249. {$endif i386}
  6250. if DoArithCombineOpt(p) then
  6251. Result:=true;
  6252. end;
  6253. end;
  6254. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6255. var
  6256. TmpBool1,TmpBool2 : Boolean;
  6257. tmpref : treference;
  6258. hp1,hp2: tai;
  6259. mask, shiftval: tcgint;
  6260. begin
  6261. Result:=false;
  6262. { All these optimisations work on "shl/sal const,%reg" }
  6263. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6264. Exit;
  6265. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6266. (taicpu(p).oper[0]^.val <= 3) then
  6267. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6268. begin
  6269. { should we check the next instruction? }
  6270. TmpBool1 := True;
  6271. { have we found an add/sub which could be
  6272. integrated in the lea? }
  6273. TmpBool2 := False;
  6274. reference_reset(tmpref,2,[]);
  6275. TmpRef.index := taicpu(p).oper[1]^.reg;
  6276. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6277. while TmpBool1 and
  6278. GetNextInstruction(p, hp1) and
  6279. (tai(hp1).typ = ait_instruction) and
  6280. ((((taicpu(hp1).opcode = A_ADD) or
  6281. (taicpu(hp1).opcode = A_SUB)) and
  6282. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6283. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6284. (((taicpu(hp1).opcode = A_INC) or
  6285. (taicpu(hp1).opcode = A_DEC)) and
  6286. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6287. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6288. ((taicpu(hp1).opcode = A_LEA) and
  6289. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6290. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6291. (not GetNextInstruction(hp1,hp2) or
  6292. not instrReadsFlags(hp2)) Do
  6293. begin
  6294. TmpBool1 := False;
  6295. if taicpu(hp1).opcode=A_LEA then
  6296. begin
  6297. if (TmpRef.base = NR_NO) and
  6298. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6299. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6300. { Segment register isn't a concern here }
  6301. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6302. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6303. begin
  6304. TmpBool1 := True;
  6305. TmpBool2 := True;
  6306. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6307. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6308. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6309. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6310. RemoveInstruction(hp1);
  6311. end
  6312. end
  6313. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6314. begin
  6315. TmpBool1 := True;
  6316. TmpBool2 := True;
  6317. case taicpu(hp1).opcode of
  6318. A_ADD:
  6319. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6320. A_SUB:
  6321. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6322. else
  6323. internalerror(2019050536);
  6324. end;
  6325. RemoveInstruction(hp1);
  6326. end
  6327. else
  6328. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6329. (((taicpu(hp1).opcode = A_ADD) and
  6330. (TmpRef.base = NR_NO)) or
  6331. (taicpu(hp1).opcode = A_INC) or
  6332. (taicpu(hp1).opcode = A_DEC)) then
  6333. begin
  6334. TmpBool1 := True;
  6335. TmpBool2 := True;
  6336. case taicpu(hp1).opcode of
  6337. A_ADD:
  6338. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6339. A_INC:
  6340. inc(TmpRef.offset);
  6341. A_DEC:
  6342. dec(TmpRef.offset);
  6343. else
  6344. internalerror(2019050535);
  6345. end;
  6346. RemoveInstruction(hp1);
  6347. end;
  6348. end;
  6349. if TmpBool2
  6350. {$ifndef x86_64}
  6351. or
  6352. ((current_settings.optimizecputype < cpu_Pentium2) and
  6353. (taicpu(p).oper[0]^.val <= 3) and
  6354. not(cs_opt_size in current_settings.optimizerswitches))
  6355. {$endif x86_64}
  6356. then
  6357. begin
  6358. if not(TmpBool2) and
  6359. (taicpu(p).oper[0]^.val=1) then
  6360. begin
  6361. taicpu(p).opcode := A_ADD;
  6362. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6363. end
  6364. else
  6365. begin
  6366. taicpu(p).opcode := A_LEA;
  6367. taicpu(p).loadref(0, TmpRef);
  6368. end;
  6369. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6370. Result := True;
  6371. end;
  6372. end
  6373. {$ifndef x86_64}
  6374. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6375. begin
  6376. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6377. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6378. (unlike shl, which is only Tairable in the U pipe) }
  6379. if taicpu(p).oper[0]^.val=1 then
  6380. begin
  6381. taicpu(p).opcode := A_ADD;
  6382. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6383. Result := True;
  6384. end
  6385. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6386. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6387. else if (taicpu(p).opsize = S_L) and
  6388. (taicpu(p).oper[0]^.val<= 3) then
  6389. begin
  6390. reference_reset(tmpref,2,[]);
  6391. TmpRef.index := taicpu(p).oper[1]^.reg;
  6392. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6393. taicpu(p).opcode := A_LEA;
  6394. taicpu(p).loadref(0, TmpRef);
  6395. Result := True;
  6396. end;
  6397. end
  6398. {$endif x86_64}
  6399. else if
  6400. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6401. (
  6402. (
  6403. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6404. SetAndTest(hp1, hp2)
  6405. {$ifdef x86_64}
  6406. ) or
  6407. (
  6408. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6409. GetNextInstruction(hp1, hp2) and
  6410. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6411. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6412. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6413. {$endif x86_64}
  6414. )
  6415. ) and
  6416. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6417. begin
  6418. { Change:
  6419. shl x, %reg1
  6420. mov -(1<<x), %reg2
  6421. and %reg2, %reg1
  6422. Or:
  6423. shl x, %reg1
  6424. and -(1<<x), %reg1
  6425. To just:
  6426. shl x, %reg1
  6427. Since the and operation only zeroes bits that are already zero from the shl operation
  6428. }
  6429. case taicpu(p).oper[0]^.val of
  6430. 8:
  6431. mask:=$FFFFFFFFFFFFFF00;
  6432. 16:
  6433. mask:=$FFFFFFFFFFFF0000;
  6434. 32:
  6435. mask:=$FFFFFFFF00000000;
  6436. 63:
  6437. { Constant pre-calculated to prevent overflow errors with Int64 }
  6438. mask:=$8000000000000000;
  6439. else
  6440. begin
  6441. if taicpu(p).oper[0]^.val >= 64 then
  6442. { Shouldn't happen realistically, since the register
  6443. is guaranteed to be set to zero at this point }
  6444. mask := 0
  6445. else
  6446. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6447. end;
  6448. end;
  6449. if taicpu(hp1).oper[0]^.val = mask then
  6450. begin
  6451. { Everything checks out, perform the optimisation, as long as
  6452. the FLAGS register isn't being used}
  6453. TransferUsedRegs(TmpUsedRegs);
  6454. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6455. {$ifdef x86_64}
  6456. if (hp1 <> hp2) then
  6457. begin
  6458. { "shl/mov/and" version }
  6459. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6460. { Don't do the optimisation if the FLAGS register is in use }
  6461. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6462. begin
  6463. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6464. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6465. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6466. begin
  6467. RemoveInstruction(hp1);
  6468. Result := True;
  6469. end;
  6470. { Only set Result to True if the 'mov' instruction was removed }
  6471. RemoveInstruction(hp2);
  6472. end;
  6473. end
  6474. else
  6475. {$endif x86_64}
  6476. begin
  6477. { "shl/and" version }
  6478. { Don't do the optimisation if the FLAGS register is in use }
  6479. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6480. begin
  6481. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6482. RemoveInstruction(hp1);
  6483. Result := True;
  6484. end;
  6485. end;
  6486. Exit;
  6487. end
  6488. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6489. begin
  6490. { Even if the mask doesn't allow for its removal, we might be
  6491. able to optimise the mask for the "shl/and" version, which
  6492. may permit other peephole optimisations }
  6493. {$ifdef DEBUG_AOPTCPU}
  6494. mask := taicpu(hp1).oper[0]^.val and mask;
  6495. if taicpu(hp1).oper[0]^.val <> mask then
  6496. begin
  6497. DebugMsg(
  6498. SPeepholeOptimization +
  6499. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6500. ' to $' + debug_tostr(mask) +
  6501. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6502. taicpu(hp1).oper[0]^.val := mask;
  6503. end;
  6504. {$else DEBUG_AOPTCPU}
  6505. { If debugging is off, just set the operand even if it's the same }
  6506. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6507. {$endif DEBUG_AOPTCPU}
  6508. end;
  6509. end;
  6510. {
  6511. change
  6512. shl/sal const,reg
  6513. <op> ...(...,reg,1),...
  6514. into
  6515. <op> ...(...,reg,1 shl const),...
  6516. if const in 1..3
  6517. }
  6518. if MatchOpType(taicpu(p), top_const, top_reg) and
  6519. (taicpu(p).oper[0]^.val in [1..3]) and
  6520. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6521. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6522. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6523. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6524. MatchOpType(taicpu(hp1),top_ref))
  6525. ) and
  6526. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6527. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6528. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6529. begin
  6530. TransferUsedRegs(TmpUsedRegs);
  6531. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6532. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6533. begin
  6534. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6535. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6536. RemoveCurrentP(p);
  6537. Result:=true;
  6538. exit;
  6539. end;
  6540. end;
  6541. if MatchOpType(taicpu(p), top_const, top_reg) and
  6542. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6543. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6544. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6545. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6546. begin
  6547. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6548. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6549. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6550. {$ifdef x86_64}
  6551. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6552. {$endif x86_64}
  6553. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6554. begin
  6555. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6556. taicpu(hp1).opcode:=A_MOV;
  6557. taicpu(hp1).oper[0]^.val:=0;
  6558. end
  6559. else
  6560. begin
  6561. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6562. taicpu(hp1).oper[0]^.val:=shiftval;
  6563. end;
  6564. RemoveCurrentP(p);
  6565. Result:=true;
  6566. exit;
  6567. end;
  6568. end;
  6569. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6570. begin
  6571. case shr_size of
  6572. S_B:
  6573. { No valid combinations }
  6574. Result := False;
  6575. S_W:
  6576. Result := (Shift >= 8) and (movz_size = S_BW);
  6577. S_L:
  6578. Result :=
  6579. (Shift >= 24) { Any opsize is valid for this shift } or
  6580. ((Shift >= 16) and (movz_size = S_WL));
  6581. {$ifdef x86_64}
  6582. S_Q:
  6583. Result :=
  6584. (Shift >= 56) { Any opsize is valid for this shift } or
  6585. ((Shift >= 48) and (movz_size = S_WL));
  6586. {$endif x86_64}
  6587. else
  6588. InternalError(2022081510);
  6589. end;
  6590. end;
  6591. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6592. var
  6593. hp1, hp2: tai;
  6594. Shift: TCGInt;
  6595. LimitSize: Topsize;
  6596. DoNotMerge: Boolean;
  6597. begin
  6598. Result := False;
  6599. { All these optimisations work on "shr const,%reg" }
  6600. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6601. Exit;
  6602. DoNotMerge := False;
  6603. Shift := taicpu(p).oper[0]^.val;
  6604. LimitSize := taicpu(p).opsize;
  6605. hp1 := p;
  6606. repeat
  6607. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6608. Exit;
  6609. case taicpu(hp1).opcode of
  6610. A_TEST, A_CMP, A_Jcc:
  6611. { Skip over conditional jumps and relevant comparisons }
  6612. Continue;
  6613. A_MOVZX:
  6614. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6615. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6616. begin
  6617. { Since the original register is being read as is, subsequent
  6618. SHRs must not be merged at this point }
  6619. DoNotMerge := True;
  6620. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6621. begin
  6622. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6623. begin
  6624. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6625. taicpu(hp1).opcode := A_MOV;
  6626. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6627. case taicpu(hp1).opsize of
  6628. S_BW:
  6629. taicpu(hp1).opsize := S_W;
  6630. S_BL, S_WL:
  6631. taicpu(hp1).opsize := S_L;
  6632. else
  6633. InternalError(2022081503);
  6634. end;
  6635. { p itself hasn't changed, so no need to set Result to True }
  6636. Include(OptsToCheck, aoc_ForceNewIteration);
  6637. { See if there's anything afterwards that can be
  6638. optimised, since the input register hasn't changed }
  6639. Continue;
  6640. end;
  6641. { NOTE: If the MOVZX instruction reads and writes the same
  6642. register, defer this to the post-peephole optimisation stage }
  6643. Exit;
  6644. end;
  6645. end;
  6646. A_SHL, A_SAL, A_SHR:
  6647. if (taicpu(hp1).opsize <= LimitSize) and
  6648. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6649. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6650. begin
  6651. { Make sure the sizes don't exceed the register size limit
  6652. (measured by the shift value falling below the limit) }
  6653. if taicpu(hp1).opsize < LimitSize then
  6654. LimitSize := taicpu(hp1).opsize;
  6655. if taicpu(hp1).opcode = A_SHR then
  6656. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6657. else
  6658. begin
  6659. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6660. DoNotMerge := True;
  6661. end;
  6662. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6663. Exit;
  6664. { Since we've established that the combined shift is within
  6665. limits, we can actually combine the adjacent SHR
  6666. instructions even if they're different sizes }
  6667. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6668. begin
  6669. hp2 := tai(hp1.Previous);
  6670. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6671. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6672. RemoveInstruction(hp1);
  6673. hp1 := hp2;
  6674. { Though p has changed, only the constant has, and its
  6675. effects can still be detected on the next iteration of
  6676. the repeat..until loop }
  6677. Include(OptsToCheck, aoc_ForceNewIteration);
  6678. end;
  6679. { Move onto the next instruction }
  6680. Continue;
  6681. end;
  6682. else
  6683. ;
  6684. end;
  6685. Break;
  6686. until False;
  6687. end;
  6688. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6689. var
  6690. CurrentRef: TReference;
  6691. FullReg: TRegister;
  6692. hp1, hp2: tai;
  6693. begin
  6694. Result := False;
  6695. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6696. Exit;
  6697. { We assume you've checked if the operand is actually a reference by
  6698. this point. If it isn't, you'll most likely get an access violation }
  6699. CurrentRef := first_mov.oper[1]^.ref^;
  6700. { Memory must be aligned }
  6701. if (CurrentRef.offset mod 4) <> 0 then
  6702. Exit;
  6703. Inc(CurrentRef.offset);
  6704. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6705. if MatchOperand(second_mov.oper[0]^, 0) and
  6706. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6707. GetNextInstruction(second_mov, hp1) and
  6708. (hp1.typ = ait_instruction) and
  6709. (taicpu(hp1).opcode = A_MOV) and
  6710. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6711. (taicpu(hp1).oper[0]^.val = 0) then
  6712. begin
  6713. Inc(CurrentRef.offset);
  6714. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6715. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6716. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6717. begin
  6718. case taicpu(hp1).opsize of
  6719. S_B:
  6720. if GetNextInstruction(hp1, hp2) and
  6721. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6722. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6723. (taicpu(hp2).oper[0]^.val = 0) then
  6724. begin
  6725. Inc(CurrentRef.offset);
  6726. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6727. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6728. (taicpu(hp2).opsize = S_B) then
  6729. begin
  6730. RemoveInstruction(hp1);
  6731. RemoveInstruction(hp2);
  6732. first_mov.opsize := S_L;
  6733. if first_mov.oper[0]^.typ = top_reg then
  6734. begin
  6735. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6736. { Reuse second_mov as a MOVZX instruction }
  6737. second_mov.opcode := A_MOVZX;
  6738. second_mov.opsize := S_BL;
  6739. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6740. second_mov.loadreg(1, FullReg);
  6741. first_mov.oper[0]^.reg := FullReg;
  6742. asml.Remove(second_mov);
  6743. asml.InsertBefore(second_mov, first_mov);
  6744. end
  6745. else
  6746. { It's a value }
  6747. begin
  6748. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6749. RemoveInstruction(second_mov);
  6750. end;
  6751. Result := True;
  6752. Exit;
  6753. end;
  6754. end;
  6755. S_W:
  6756. begin
  6757. RemoveInstruction(hp1);
  6758. first_mov.opsize := S_L;
  6759. if first_mov.oper[0]^.typ = top_reg then
  6760. begin
  6761. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6762. { Reuse second_mov as a MOVZX instruction }
  6763. second_mov.opcode := A_MOVZX;
  6764. second_mov.opsize := S_BL;
  6765. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6766. second_mov.loadreg(1, FullReg);
  6767. first_mov.oper[0]^.reg := FullReg;
  6768. asml.Remove(second_mov);
  6769. asml.InsertBefore(second_mov, first_mov);
  6770. end
  6771. else
  6772. { It's a value }
  6773. begin
  6774. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6775. RemoveInstruction(second_mov);
  6776. end;
  6777. Result := True;
  6778. Exit;
  6779. end;
  6780. else
  6781. ;
  6782. end;
  6783. end;
  6784. end;
  6785. end;
  6786. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6787. { returns true if a "continue" should be done after this optimization }
  6788. var
  6789. hp1, hp2, hp3: tai;
  6790. begin
  6791. Result := false;
  6792. hp3 := nil;
  6793. if MatchOpType(taicpu(p),top_ref) and
  6794. GetNextInstruction(p, hp1) and
  6795. (hp1.typ = ait_instruction) and
  6796. (((taicpu(hp1).opcode = A_FLD) and
  6797. (taicpu(p).opcode = A_FSTP)) or
  6798. ((taicpu(p).opcode = A_FISTP) and
  6799. (taicpu(hp1).opcode = A_FILD))) and
  6800. MatchOpType(taicpu(hp1),top_ref) and
  6801. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6802. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6803. begin
  6804. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6805. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6806. GetNextInstruction(hp1, hp2) and
  6807. (((hp2.typ = ait_instruction) and
  6808. IsExitCode(hp2) and
  6809. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6810. not(assigned(current_procinfo.procdef.funcretsym) and
  6811. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6812. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6813. { fstp <temp>
  6814. fld <temp>
  6815. <dealloc> <temp>
  6816. }
  6817. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6818. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6819. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6820. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6821. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6822. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6823. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6824. )
  6825. )
  6826. ) then
  6827. begin
  6828. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6829. RemoveInstruction(hp1);
  6830. RemoveCurrentP(p, hp2);
  6831. { first case: exit code }
  6832. if hp2.typ = ait_instruction then
  6833. RemoveLastDeallocForFuncRes(p);
  6834. Result := true;
  6835. end
  6836. else
  6837. { we can do this only in fast math mode as fstp is rounding ...
  6838. ... still disabled as it breaks the compiler and/or rtl }
  6839. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6840. { ... or if another fstp equal to the first one follows }
  6841. GetNextInstruction(hp1,hp2) and
  6842. (hp2.typ = ait_instruction) and
  6843. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6844. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6845. begin
  6846. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6847. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6848. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6849. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6850. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6851. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6852. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6853. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6854. ) then
  6855. begin
  6856. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6857. RemoveCurrentP(p,hp2);
  6858. RemoveInstruction(hp1);
  6859. Result := true;
  6860. end
  6861. else if { fst can't store an extended/comp value }
  6862. (taicpu(p).opsize <> S_FX) and
  6863. (taicpu(p).opsize <> S_IQ) then
  6864. begin
  6865. if (taicpu(p).opcode = A_FSTP) then
  6866. taicpu(p).opcode := A_FST
  6867. else
  6868. taicpu(p).opcode := A_FIST;
  6869. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6870. RemoveInstruction(hp1);
  6871. Result := true;
  6872. end;
  6873. end;
  6874. end;
  6875. end;
  6876. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6877. var
  6878. hp1, hp2, hp3: tai;
  6879. begin
  6880. result:=false;
  6881. if MatchOpType(taicpu(p),top_reg) and
  6882. GetNextInstruction(p, hp1) and
  6883. (hp1.typ = Ait_Instruction) and
  6884. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6885. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6886. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6887. { change to
  6888. fld reg fxxx reg,st
  6889. fxxxp st, st1 (hp1)
  6890. Remark: non commutative operations must be reversed!
  6891. }
  6892. begin
  6893. case taicpu(hp1).opcode Of
  6894. A_FMULP,A_FADDP,
  6895. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6896. begin
  6897. case taicpu(hp1).opcode Of
  6898. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6899. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6900. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6901. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6902. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6903. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6904. else
  6905. internalerror(2019050534);
  6906. end;
  6907. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6908. taicpu(hp1).oper[1]^.reg := NR_ST;
  6909. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6910. RemoveCurrentP(p, hp1);
  6911. Result:=true;
  6912. exit;
  6913. end;
  6914. else
  6915. ;
  6916. end;
  6917. end
  6918. else
  6919. if MatchOpType(taicpu(p),top_ref) and
  6920. GetNextInstruction(p, hp2) and
  6921. (hp2.typ = Ait_Instruction) and
  6922. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6923. (taicpu(p).opsize in [S_FS, S_FL]) and
  6924. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6925. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6926. if GetLastInstruction(p, hp1) and
  6927. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6928. MatchOpType(taicpu(hp1),top_ref) and
  6929. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6930. if ((taicpu(hp2).opcode = A_FMULP) or
  6931. (taicpu(hp2).opcode = A_FADDP)) then
  6932. { change to
  6933. fld/fst mem1 (hp1) fld/fst mem1
  6934. fld mem1 (p) fadd/
  6935. faddp/ fmul st, st
  6936. fmulp st, st1 (hp2) }
  6937. begin
  6938. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6939. RemoveCurrentP(p, hp1);
  6940. if (taicpu(hp2).opcode = A_FADDP) then
  6941. taicpu(hp2).opcode := A_FADD
  6942. else
  6943. taicpu(hp2).opcode := A_FMUL;
  6944. taicpu(hp2).oper[1]^.reg := NR_ST;
  6945. end
  6946. else
  6947. { change to
  6948. fld/fst mem1 (hp1) fld/fst mem1
  6949. fld mem1 (p) fld st
  6950. }
  6951. begin
  6952. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6953. taicpu(p).changeopsize(S_FL);
  6954. taicpu(p).loadreg(0,NR_ST);
  6955. end
  6956. else
  6957. begin
  6958. case taicpu(hp2).opcode Of
  6959. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6960. { change to
  6961. fld/fst mem1 (hp1) fld/fst mem1
  6962. fld mem2 (p) fxxx mem2
  6963. fxxxp st, st1 (hp2) }
  6964. begin
  6965. case taicpu(hp2).opcode Of
  6966. A_FADDP: taicpu(p).opcode := A_FADD;
  6967. A_FMULP: taicpu(p).opcode := A_FMUL;
  6968. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6969. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6970. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6971. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6972. else
  6973. internalerror(2019050533);
  6974. end;
  6975. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6976. RemoveInstruction(hp2);
  6977. end
  6978. else
  6979. ;
  6980. end
  6981. end
  6982. end;
  6983. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6984. begin
  6985. Result := condition_in(cond1, cond2) or
  6986. { Not strictly subsets due to the actual flags checked, but because we're
  6987. comparing integers, E is a subset of AE and GE and their aliases }
  6988. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6989. end;
  6990. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6991. var
  6992. v: TCGInt;
  6993. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6994. FirstMatch, TempBool: Boolean;
  6995. NewReg: TRegister;
  6996. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6997. begin
  6998. Result:=false;
  6999. { All these optimisations need a next instruction }
  7000. if not GetNextInstruction(p, hp1) then
  7001. Exit;
  7002. { Search for:
  7003. cmp ###,###
  7004. j(c1) @lbl1
  7005. ...
  7006. @lbl:
  7007. cmp ###,### (same comparison as above)
  7008. j(c2) @lbl2
  7009. If c1 is a subset of c2, change to:
  7010. cmp ###,###
  7011. j(c1) @lbl2
  7012. (@lbl1 may become a dead label as a result)
  7013. }
  7014. { Also handle cases where there are multiple jumps in a row }
  7015. p_jump := hp1;
  7016. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7017. begin
  7018. if IsJumpToLabel(taicpu(p_jump)) then
  7019. begin
  7020. { Do jump optimisations first in case the condition becomes
  7021. unnecessary }
  7022. TempBool := True;
  7023. if DoJumpOptimizations(p_jump, TempBool) or
  7024. not TempBool then
  7025. begin
  7026. if Assigned(p_jump) then
  7027. begin
  7028. hp1 := p_jump;
  7029. if (p_jump.typ in [ait_align]) then
  7030. SkipAligns(p_jump, p_jump);
  7031. { CollapseZeroDistJump will be set to the label after the
  7032. jump if it optimises, whether or not it's live or dead }
  7033. if (p_jump.typ in [ait_label]) and
  7034. not (tai_label(p_jump).labsym.is_used) then
  7035. GetNextInstruction(p_jump, p_jump);
  7036. end;
  7037. TransferUsedRegs(TmpUsedRegs);
  7038. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7039. if not Assigned(p_jump) or
  7040. (
  7041. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7042. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7043. ) then
  7044. begin
  7045. { No more conditional jumps; conditional statement is no longer required }
  7046. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7047. RemoveCurrentP(p);
  7048. Result := True;
  7049. Exit;
  7050. end;
  7051. hp1 := p_jump;
  7052. Include(OptsToCheck, aoc_ForceNewIteration);
  7053. Continue;
  7054. end;
  7055. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7056. if GetNextInstruction(p_jump, hp2) and
  7057. (
  7058. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7059. not TempBool
  7060. ) then
  7061. begin
  7062. hp1 := p_jump;
  7063. Include(OptsToCheck, aoc_ForceNewIteration);
  7064. Continue;
  7065. end;
  7066. p_label := nil;
  7067. if Assigned(JumpLabel) then
  7068. p_label := getlabelwithsym(JumpLabel);
  7069. if Assigned(p_label) and
  7070. GetNextInstruction(p_label, p_dist) and
  7071. MatchInstruction(p_dist, A_CMP, []) and
  7072. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7073. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7074. GetNextInstruction(p_dist, hp1_dist) and
  7075. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7076. begin
  7077. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7078. if JumpLabel = JumpLabel_dist then
  7079. { This is an infinite loop }
  7080. Exit;
  7081. { Best optimisation when the first condition is a subset (or equal) of the second }
  7082. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7083. begin
  7084. { Any registers used here will already be allocated }
  7085. if Assigned(JumpLabel) then
  7086. JumpLabel.DecRefs;
  7087. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7088. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7089. Result := True;
  7090. { Don't exit yet. Since p and p_jump haven't actually been
  7091. removed, we can check for more on this iteration }
  7092. end
  7093. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7094. GetNextInstruction(hp1_dist, hp1_label) and
  7095. SkipAligns(hp1_label, hp1_label) and
  7096. (hp1_label.typ = ait_label) then
  7097. begin
  7098. JumpLabel_far := tai_label(hp1_label).labsym;
  7099. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7100. { This is an infinite loop }
  7101. Exit;
  7102. if Assigned(JumpLabel_far) then
  7103. begin
  7104. { In this situation, if the first jump branches, the second one will never,
  7105. branch so change the destination label to after the second jump }
  7106. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7107. if Assigned(JumpLabel) then
  7108. JumpLabel.DecRefs;
  7109. JumpLabel_far.IncRefs;
  7110. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7111. Result := True;
  7112. { Don't exit yet. Since p and p_jump haven't actually been
  7113. removed, we can check for more on this iteration }
  7114. Continue;
  7115. end;
  7116. end;
  7117. end;
  7118. end;
  7119. { Search for:
  7120. cmp ###,###
  7121. j(c1) @lbl1
  7122. cmp ###,### (same as first)
  7123. Remove second cmp
  7124. }
  7125. if GetNextInstruction(p_jump, hp2) and
  7126. (
  7127. (
  7128. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7129. (
  7130. (
  7131. MatchOpType(taicpu(p), top_const, top_reg) and
  7132. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7133. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7134. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7135. ) or (
  7136. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7137. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7138. )
  7139. )
  7140. ) or (
  7141. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7142. MatchOperand(taicpu(p).oper[0]^, 0) and
  7143. (taicpu(p).oper[1]^.typ = top_reg) and
  7144. MatchInstruction(hp2, A_TEST, []) and
  7145. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7146. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7147. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7148. )
  7149. ) then
  7150. begin
  7151. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7152. RemoveInstruction(hp2);
  7153. Result := True;
  7154. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7155. end;
  7156. GetNextInstruction(p_jump, p_jump);
  7157. end;
  7158. if (
  7159. { Don't call GetNextInstruction again if we already have it }
  7160. (hp1 = p_jump) or
  7161. GetNextInstruction(p, hp1)
  7162. ) and
  7163. MatchInstruction(hp1, A_Jcc, []) and
  7164. IsJumpToLabel(taicpu(hp1)) and
  7165. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7166. GetNextInstruction(hp1, hp2) then
  7167. begin
  7168. {
  7169. cmp x, y (or "cmp y, x")
  7170. je @lbl
  7171. mov x, y
  7172. @lbl:
  7173. (x and y can be constants, registers or references)
  7174. Change to:
  7175. mov x, y (x and y will always be equal in the end)
  7176. @lbl: (may beceome a dead label)
  7177. Also:
  7178. cmp x, y (or "cmp y, x")
  7179. jne @lbl
  7180. mov x, y
  7181. @lbl:
  7182. (x and y can be constants, registers or references)
  7183. Change to:
  7184. Absolutely nothing! (Except @lbl if it's still live)
  7185. }
  7186. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7187. (
  7188. (
  7189. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7190. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7191. ) or (
  7192. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7193. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7194. )
  7195. ) and
  7196. GetNextInstruction(hp2, hp1_label) and
  7197. SkipAligns(hp1_label, hp1_label) and
  7198. (hp1_label.typ = ait_label) and
  7199. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7200. begin
  7201. tai_label(hp1_label).labsym.DecRefs;
  7202. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7203. begin
  7204. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7205. RemoveInstruction(hp2);
  7206. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7207. end
  7208. else
  7209. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7210. RemoveInstruction(hp1);
  7211. RemoveCurrentp(p, hp2);
  7212. Result := True;
  7213. Exit;
  7214. end;
  7215. {
  7216. Try to optimise the following:
  7217. cmp $x,### ($x and $y can be registers or constants)
  7218. je @lbl1 (only reference)
  7219. cmp $y,### (### are identical)
  7220. @Lbl:
  7221. sete %reg1
  7222. Change to:
  7223. cmp $x,###
  7224. sete %reg2 (allocate new %reg2)
  7225. cmp $y,###
  7226. sete %reg1
  7227. orb %reg2,%reg1
  7228. (dealloc %reg2)
  7229. This adds an instruction (so don't perform under -Os), but it removes
  7230. a conditional branch.
  7231. }
  7232. if not (cs_opt_size in current_settings.optimizerswitches) and
  7233. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7234. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7235. { The first operand of CMP instructions can only be a register or
  7236. immediate anyway, so no need to check }
  7237. GetNextInstruction(hp2, p_label) and
  7238. (p_label.typ = ait_label) and
  7239. (tai_label(p_label).labsym.getrefs = 1) and
  7240. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7241. GetNextInstruction(p_label, p_dist) and
  7242. MatchInstruction(p_dist, A_SETcc, []) and
  7243. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7244. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7245. begin
  7246. TransferUsedRegs(TmpUsedRegs);
  7247. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7248. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7249. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7250. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7251. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7252. { Get the instruction after the SETcc instruction so we can
  7253. allocate a new register over the entire range }
  7254. GetNextInstruction(p_dist, hp1_dist) then
  7255. begin
  7256. { Register can appear in p if it's not used afterwards, so only
  7257. allocate between hp1 and hp1_dist }
  7258. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7259. if NewReg <> NR_NO then
  7260. begin
  7261. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7262. { Change the jump instruction into a SETcc instruction }
  7263. taicpu(hp1).opcode := A_SETcc;
  7264. taicpu(hp1).opsize := S_B;
  7265. taicpu(hp1).loadreg(0, NewReg);
  7266. { This is now a dead label }
  7267. tai_label(p_label).labsym.decrefs;
  7268. { Prefer adding before the next instruction so the FLAGS
  7269. register is deallicated first }
  7270. AsmL.InsertBefore(
  7271. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7272. hp1_dist
  7273. );
  7274. Result := True;
  7275. { Don't exit yet, as p wasn't changed and hp1, while
  7276. modified, is still intact and might be optimised by the
  7277. SETcc optimisation below }
  7278. end;
  7279. end;
  7280. end;
  7281. end;
  7282. if taicpu(p).oper[0]^.typ = top_const then
  7283. begin
  7284. if (taicpu(p).oper[0]^.val = 0) and
  7285. (taicpu(p).oper[1]^.typ = top_reg) and
  7286. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7287. begin
  7288. hp2 := p;
  7289. FirstMatch := True;
  7290. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7291. anything meaningful once it's converted to "test %reg,%reg";
  7292. additionally, some jumps will always (or never) branch, so
  7293. evaluate every jump immediately following the
  7294. comparison, optimising the conditions if possible.
  7295. Similarly with SETcc... those that are always set to 0 or 1
  7296. are changed to MOV instructions }
  7297. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7298. (
  7299. GetNextInstruction(hp2, hp1) and
  7300. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7301. ) do
  7302. begin
  7303. FirstMatch := False;
  7304. case taicpu(hp1).condition of
  7305. C_B, C_C, C_NAE, C_O:
  7306. { For B/NAE:
  7307. Will never branch since an unsigned integer can never be below zero
  7308. For C/O:
  7309. Result cannot overflow because 0 is being subtracted
  7310. }
  7311. begin
  7312. if taicpu(hp1).opcode = A_Jcc then
  7313. begin
  7314. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7315. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7316. RemoveInstruction(hp1);
  7317. { Since hp1 was deleted, hp2 must not be updated }
  7318. Continue;
  7319. end
  7320. else
  7321. begin
  7322. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7323. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7324. taicpu(hp1).opcode := A_MOV;
  7325. taicpu(hp1).ops := 2;
  7326. taicpu(hp1).condition := C_None;
  7327. taicpu(hp1).opsize := S_B;
  7328. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7329. taicpu(hp1).loadconst(0, 0);
  7330. end;
  7331. end;
  7332. C_BE, C_NA:
  7333. begin
  7334. { Will only branch if equal to zero }
  7335. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7336. taicpu(hp1).condition := C_E;
  7337. end;
  7338. C_A, C_NBE:
  7339. begin
  7340. { Will only branch if not equal to zero }
  7341. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7342. taicpu(hp1).condition := C_NE;
  7343. end;
  7344. C_AE, C_NB, C_NC, C_NO:
  7345. begin
  7346. { Will always branch }
  7347. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7348. if taicpu(hp1).opcode = A_Jcc then
  7349. begin
  7350. MakeUnconditional(taicpu(hp1));
  7351. { Any jumps/set that follow will now be dead code }
  7352. RemoveDeadCodeAfterJump(taicpu(hp1));
  7353. Break;
  7354. end
  7355. else
  7356. begin
  7357. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7358. taicpu(hp1).opcode := A_MOV;
  7359. taicpu(hp1).ops := 2;
  7360. taicpu(hp1).condition := C_None;
  7361. taicpu(hp1).opsize := S_B;
  7362. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7363. taicpu(hp1).loadconst(0, 1);
  7364. end;
  7365. end;
  7366. C_None:
  7367. InternalError(2020012201);
  7368. C_P, C_PE, C_NP, C_PO:
  7369. { We can't handle parity checks and they should never be generated
  7370. after a general-purpose CMP (it's used in some floating-point
  7371. comparisons that don't use CMP) }
  7372. InternalError(2020012202);
  7373. else
  7374. { Zero/Equality, Sign, their complements and all of the
  7375. signed comparisons do not need to be converted };
  7376. end;
  7377. hp2 := hp1;
  7378. end;
  7379. { Convert the instruction to a TEST }
  7380. taicpu(p).opcode := A_TEST;
  7381. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7382. Result := True;
  7383. Exit;
  7384. end
  7385. else if (taicpu(p).oper[0]^.val = 1) and
  7386. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7387. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7388. begin
  7389. { Convert; To:
  7390. cmp $1,r/m cmp $0,r/m
  7391. jl @lbl jle @lbl
  7392. (Also do inverted conditions)
  7393. }
  7394. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7395. taicpu(p).oper[0]^.val := 0;
  7396. if taicpu(hp1).condition in [C_L, C_NGE] then
  7397. taicpu(hp1).condition := C_LE
  7398. else
  7399. taicpu(hp1).condition := C_NLE;
  7400. { If the instruction is now "cmp $0,%reg", convert it to a
  7401. TEST (and effectively do the work of the "cmp $0,%reg" in
  7402. the block above)
  7403. }
  7404. if (taicpu(p).oper[1]^.typ = top_reg) then
  7405. begin
  7406. taicpu(p).opcode := A_TEST;
  7407. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7408. end;
  7409. Result := True;
  7410. Exit;
  7411. end
  7412. else if (taicpu(p).oper[1]^.typ = top_reg)
  7413. {$ifdef x86_64}
  7414. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7415. {$endif x86_64}
  7416. then
  7417. begin
  7418. { cmp register,$8000 neg register
  7419. je target --> jo target
  7420. .... only if register is deallocated before jump.}
  7421. case Taicpu(p).opsize of
  7422. S_B: v:=$80;
  7423. S_W: v:=$8000;
  7424. S_L: v:=qword($80000000);
  7425. else
  7426. internalerror(2013112905);
  7427. end;
  7428. if (taicpu(p).oper[0]^.val=v) and
  7429. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7430. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7431. begin
  7432. TransferUsedRegs(TmpUsedRegs);
  7433. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7434. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7435. begin
  7436. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7437. Taicpu(p).opcode:=A_NEG;
  7438. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7439. Taicpu(p).clearop(1);
  7440. Taicpu(p).ops:=1;
  7441. if Taicpu(hp1).condition=C_E then
  7442. Taicpu(hp1).condition:=C_O
  7443. else
  7444. Taicpu(hp1).condition:=C_NO;
  7445. Result:=true;
  7446. exit;
  7447. end;
  7448. end;
  7449. end;
  7450. end;
  7451. if TrySwapMovCmp(p, hp1) then
  7452. begin
  7453. Result := True;
  7454. Exit;
  7455. end;
  7456. end;
  7457. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7458. var
  7459. hp1: tai;
  7460. begin
  7461. {
  7462. remove the second (v)pxor from
  7463. pxor reg,reg
  7464. ...
  7465. pxor reg,reg
  7466. }
  7467. Result:=false;
  7468. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7469. MatchOpType(taicpu(p),top_reg,top_reg) and
  7470. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7471. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7472. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7473. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7474. begin
  7475. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7476. RemoveInstruction(hp1);
  7477. Result:=true;
  7478. Exit;
  7479. end
  7480. {
  7481. replace
  7482. pxor reg1,reg1
  7483. movapd/s reg1,reg2
  7484. dealloc reg1
  7485. by
  7486. pxor reg2,reg2
  7487. }
  7488. else if GetNextInstruction(p,hp1) and
  7489. { we mix single and double opperations here because we assume that the compiler
  7490. generates vmovapd only after double operations and vmovaps only after single operations }
  7491. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7492. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7493. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7494. (taicpu(p).oper[0]^.typ=top_reg) then
  7495. begin
  7496. TransferUsedRegs(TmpUsedRegs);
  7497. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7498. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7499. begin
  7500. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7501. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7502. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7503. RemoveInstruction(hp1);
  7504. result:=true;
  7505. end;
  7506. end;
  7507. end;
  7508. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7509. var
  7510. hp1: tai;
  7511. begin
  7512. {
  7513. remove the second (v)pxor from
  7514. (v)pxor reg,reg
  7515. ...
  7516. (v)pxor reg,reg
  7517. }
  7518. Result:=false;
  7519. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7520. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7521. begin
  7522. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7523. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7524. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7525. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7526. begin
  7527. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7528. RemoveInstruction(hp1);
  7529. Result:=true;
  7530. Exit;
  7531. end;
  7532. {$ifdef x86_64}
  7533. {
  7534. replace
  7535. vpxor reg1,reg1,reg1
  7536. vmov reg,mem
  7537. by
  7538. movq $0,mem
  7539. }
  7540. if GetNextInstruction(p,hp1) and
  7541. MatchInstruction(hp1,A_VMOVSD,[]) and
  7542. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7543. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7544. begin
  7545. TransferUsedRegs(TmpUsedRegs);
  7546. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7547. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7548. begin
  7549. taicpu(hp1).loadconst(0,0);
  7550. taicpu(hp1).opcode:=A_MOV;
  7551. taicpu(hp1).opsize:=S_Q;
  7552. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7553. RemoveCurrentP(p);
  7554. result:=true;
  7555. Exit;
  7556. end;
  7557. end;
  7558. {$endif x86_64}
  7559. end
  7560. {
  7561. replace
  7562. vpxor reg1,reg1,reg2
  7563. by
  7564. vpxor reg2,reg2,reg2
  7565. to avoid unncessary data dependencies
  7566. }
  7567. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7568. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7569. begin
  7570. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7571. { avoid unncessary data dependency }
  7572. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7573. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7574. result:=true;
  7575. exit;
  7576. end;
  7577. Result:=OptPass1VOP(p);
  7578. end;
  7579. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7580. var
  7581. hp1 : tai;
  7582. begin
  7583. result:=false;
  7584. { replace
  7585. IMul const,%mreg1,%mreg2
  7586. Mov %reg2,%mreg3
  7587. dealloc %mreg3
  7588. by
  7589. Imul const,%mreg1,%mreg23
  7590. }
  7591. if (taicpu(p).ops=3) and
  7592. GetNextInstruction(p,hp1) and
  7593. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7594. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7595. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7596. begin
  7597. TransferUsedRegs(TmpUsedRegs);
  7598. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7599. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7600. begin
  7601. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7602. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7603. RemoveInstruction(hp1);
  7604. result:=true;
  7605. end;
  7606. end;
  7607. end;
  7608. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7609. var
  7610. hp1 : tai;
  7611. begin
  7612. result:=false;
  7613. { replace
  7614. IMul %reg0,%reg1,%reg2
  7615. Mov %reg2,%reg3
  7616. dealloc %reg2
  7617. by
  7618. Imul %reg0,%reg1,%reg3
  7619. }
  7620. if GetNextInstruction(p,hp1) and
  7621. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7622. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7623. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7624. begin
  7625. TransferUsedRegs(TmpUsedRegs);
  7626. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7627. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7628. begin
  7629. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7630. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7631. RemoveInstruction(hp1);
  7632. result:=true;
  7633. end;
  7634. end;
  7635. end;
  7636. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7637. var
  7638. hp1: tai;
  7639. begin
  7640. Result:=false;
  7641. { get rid of
  7642. (v)cvtss2sd reg0,<reg1,>reg2
  7643. (v)cvtss2sd reg2,<reg2,>reg0
  7644. }
  7645. if GetNextInstruction(p,hp1) and
  7646. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7647. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7648. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7649. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7650. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7651. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7652. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7653. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7654. )
  7655. ) then
  7656. begin
  7657. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7658. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7659. begin
  7660. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7661. RemoveCurrentP(p);
  7662. RemoveInstruction(hp1);
  7663. end
  7664. else
  7665. begin
  7666. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7667. if taicpu(hp1).opcode=A_CVTSD2SS then
  7668. begin
  7669. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7670. taicpu(p).opcode:=A_MOVAPS;
  7671. end
  7672. else
  7673. begin
  7674. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7675. taicpu(p).opcode:=A_VMOVAPS;
  7676. end;
  7677. taicpu(p).ops:=2;
  7678. RemoveInstruction(hp1);
  7679. end;
  7680. Result:=true;
  7681. Exit;
  7682. end;
  7683. end;
  7684. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7685. var
  7686. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7687. ThisReg: TRegister;
  7688. begin
  7689. Result := False;
  7690. if not GetNextInstruction(p,hp1) then
  7691. Exit;
  7692. {
  7693. convert
  7694. j<c> .L1
  7695. mov 1,reg
  7696. jmp .L2
  7697. .L1
  7698. mov 0,reg
  7699. .L2
  7700. into
  7701. mov 0,reg
  7702. set<not(c)> reg
  7703. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7704. would destroy the flag contents
  7705. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7706. executed at the same time as a previous comparison.
  7707. set<not(c)> reg
  7708. movzx reg, reg
  7709. }
  7710. if MatchInstruction(hp1,A_MOV,[]) and
  7711. (taicpu(hp1).oper[0]^.typ = top_const) and
  7712. (
  7713. (
  7714. (taicpu(hp1).oper[1]^.typ = top_reg)
  7715. {$ifdef i386}
  7716. { Under i386, ESI, EDI, EBP and ESP
  7717. don't have an 8-bit representation }
  7718. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7719. {$endif i386}
  7720. ) or (
  7721. {$ifdef i386}
  7722. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7723. {$endif i386}
  7724. (taicpu(hp1).opsize = S_B)
  7725. )
  7726. ) and
  7727. GetNextInstruction(hp1,hp2) and
  7728. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7729. GetNextInstruction(hp2,hp3) and
  7730. SkipAligns(hp3, hp3) and
  7731. (hp3.typ=ait_label) and
  7732. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7733. GetNextInstruction(hp3,hp4) and
  7734. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7735. (taicpu(hp4).oper[0]^.typ = top_const) and
  7736. (
  7737. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7738. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7739. ) and
  7740. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7741. GetNextInstruction(hp4,hp5) and
  7742. SkipAligns(hp5, hp5) and
  7743. (hp5.typ=ait_label) and
  7744. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7745. begin
  7746. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7747. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7748. tai_label(hp3).labsym.DecRefs;
  7749. { If this isn't the only reference to the middle label, we can
  7750. still make a saving - only that the first jump and everything
  7751. that follows will remain. }
  7752. if (tai_label(hp3).labsym.getrefs = 0) then
  7753. begin
  7754. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7755. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7756. else
  7757. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7758. { remove jump, first label and second MOV (also catching any aligns) }
  7759. repeat
  7760. if not GetNextInstruction(hp2, hp3) then
  7761. InternalError(2021040810);
  7762. RemoveInstruction(hp2);
  7763. hp2 := hp3;
  7764. until hp2 = hp5;
  7765. { Don't decrement reference count before the removal loop
  7766. above, otherwise GetNextInstruction won't stop on the
  7767. the label }
  7768. tai_label(hp5).labsym.DecRefs;
  7769. end
  7770. else
  7771. begin
  7772. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7773. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7774. else
  7775. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7776. end;
  7777. taicpu(p).opcode:=A_SETcc;
  7778. taicpu(p).opsize:=S_B;
  7779. taicpu(p).is_jmp:=False;
  7780. if taicpu(hp1).opsize=S_B then
  7781. begin
  7782. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7783. if taicpu(hp1).oper[1]^.typ = top_reg then
  7784. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7785. RemoveInstruction(hp1);
  7786. end
  7787. else
  7788. begin
  7789. { Will be a register because the size can't be S_B otherwise }
  7790. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7791. taicpu(p).loadreg(0, ThisReg);
  7792. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7793. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7794. begin
  7795. case taicpu(hp1).opsize of
  7796. S_W:
  7797. taicpu(hp1).opsize := S_BW;
  7798. S_L:
  7799. taicpu(hp1).opsize := S_BL;
  7800. {$ifdef x86_64}
  7801. S_Q:
  7802. begin
  7803. taicpu(hp1).opsize := S_BL;
  7804. { Change the destination register to 32-bit }
  7805. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7806. end;
  7807. {$endif x86_64}
  7808. else
  7809. InternalError(2021040820);
  7810. end;
  7811. taicpu(hp1).opcode := A_MOVZX;
  7812. taicpu(hp1).loadreg(0, ThisReg);
  7813. end
  7814. else
  7815. begin
  7816. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7817. { hp1 is already a MOV instruction with the correct register }
  7818. taicpu(hp1).loadconst(0, 0);
  7819. { Inserting it right before p will guarantee that the flags are also tracked }
  7820. asml.Remove(hp1);
  7821. asml.InsertBefore(hp1, p);
  7822. end;
  7823. end;
  7824. Result:=true;
  7825. exit;
  7826. end
  7827. else if (hp1.typ = ait_label) then
  7828. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7829. end;
  7830. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7831. var
  7832. hp1, hp2, hp3: tai;
  7833. SourceRef, TargetRef: TReference;
  7834. CurrentReg: TRegister;
  7835. begin
  7836. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7837. if not UseAVX then
  7838. InternalError(2021100501);
  7839. Result := False;
  7840. { Look for the following to simplify:
  7841. vmovdqa/u x(mem1), %xmmreg
  7842. vmovdqa/u %xmmreg, y(mem2)
  7843. vmovdqa/u x+16(mem1), %xmmreg
  7844. vmovdqa/u %xmmreg, y+16(mem2)
  7845. Change to:
  7846. vmovdqa/u x(mem1), %ymmreg
  7847. vmovdqa/u %ymmreg, y(mem2)
  7848. vpxor %ymmreg, %ymmreg, %ymmreg
  7849. ( The VPXOR instruction is to zero the upper half, thus removing the
  7850. need to call the potentially expensive VZEROUPPER instruction. Other
  7851. peephole optimisations can remove VPXOR if it's unnecessary )
  7852. }
  7853. TransferUsedRegs(TmpUsedRegs);
  7854. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7855. { NOTE: In the optimisations below, if the references dictate that an
  7856. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7857. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7858. if (taicpu(p).opsize = S_XMM) and
  7859. MatchOpType(taicpu(p), top_ref, top_reg) and
  7860. GetNextInstruction(p, hp1) and
  7861. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7862. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7863. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7864. begin
  7865. SourceRef := taicpu(p).oper[0]^.ref^;
  7866. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7867. if GetNextInstruction(hp1, hp2) and
  7868. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7869. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7870. begin
  7871. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7872. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7873. Inc(SourceRef.offset, 16);
  7874. { Reuse the register in the first block move }
  7875. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7876. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7877. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7878. begin
  7879. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7880. Inc(TargetRef.offset, 16);
  7881. if GetNextInstruction(hp2, hp3) and
  7882. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7883. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7884. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7885. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7886. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7887. begin
  7888. { Update the register tracking to the new size }
  7889. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7890. { Remember that the offsets are 16 ahead }
  7891. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7892. if not (
  7893. ((SourceRef.offset mod 32) = 16) and
  7894. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7895. ) then
  7896. taicpu(p).opcode := A_VMOVDQU;
  7897. taicpu(p).opsize := S_YMM;
  7898. taicpu(p).oper[1]^.reg := CurrentReg;
  7899. if not (
  7900. ((TargetRef.offset mod 32) = 16) and
  7901. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7902. ) then
  7903. taicpu(hp1).opcode := A_VMOVDQU;
  7904. taicpu(hp1).opsize := S_YMM;
  7905. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7906. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7907. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7908. if (pi_uses_ymm in current_procinfo.flags) then
  7909. RemoveInstruction(hp2)
  7910. else
  7911. begin
  7912. taicpu(hp2).opcode := A_VPXOR;
  7913. taicpu(hp2).opsize := S_YMM;
  7914. taicpu(hp2).loadreg(0, CurrentReg);
  7915. taicpu(hp2).loadreg(1, CurrentReg);
  7916. taicpu(hp2).loadreg(2, CurrentReg);
  7917. taicpu(hp2).ops := 3;
  7918. end;
  7919. RemoveInstruction(hp3);
  7920. Result := True;
  7921. Exit;
  7922. end;
  7923. end
  7924. else
  7925. begin
  7926. { See if the next references are 16 less rather than 16 greater }
  7927. Dec(SourceRef.offset, 32); { -16 the other way }
  7928. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7929. begin
  7930. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7931. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7932. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7933. GetNextInstruction(hp2, hp3) and
  7934. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7935. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7936. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7937. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7938. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7939. begin
  7940. { Update the register tracking to the new size }
  7941. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7942. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7943. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7944. if not(
  7945. ((SourceRef.offset mod 32) = 0) and
  7946. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7947. ) then
  7948. taicpu(hp2).opcode := A_VMOVDQU;
  7949. taicpu(hp2).opsize := S_YMM;
  7950. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7951. if not (
  7952. ((TargetRef.offset mod 32) = 0) and
  7953. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7954. ) then
  7955. taicpu(hp3).opcode := A_VMOVDQU;
  7956. taicpu(hp3).opsize := S_YMM;
  7957. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7958. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7959. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7960. if (pi_uses_ymm in current_procinfo.flags) then
  7961. RemoveInstruction(hp1)
  7962. else
  7963. begin
  7964. taicpu(hp1).opcode := A_VPXOR;
  7965. taicpu(hp1).opsize := S_YMM;
  7966. taicpu(hp1).loadreg(0, CurrentReg);
  7967. taicpu(hp1).loadreg(1, CurrentReg);
  7968. taicpu(hp1).loadreg(2, CurrentReg);
  7969. taicpu(hp1).ops := 3;
  7970. Asml.Remove(hp1);
  7971. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7972. end;
  7973. RemoveCurrentP(p, hp2);
  7974. Result := True;
  7975. Exit;
  7976. end;
  7977. end;
  7978. end;
  7979. end;
  7980. end;
  7981. end;
  7982. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7983. var
  7984. hp2, hp3, first_assignment: tai;
  7985. IncCount, OperIdx: Integer;
  7986. OrigLabel: TAsmLabel;
  7987. begin
  7988. Count := 0;
  7989. Result := False;
  7990. first_assignment := nil;
  7991. if (LoopCount >= 20) then
  7992. begin
  7993. { Guard against infinite loops }
  7994. Exit;
  7995. end;
  7996. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7997. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7998. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7999. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8000. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8001. Exit;
  8002. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8003. {
  8004. change
  8005. jmp .L1
  8006. ...
  8007. .L1:
  8008. mov ##, ## ( multiple movs possible )
  8009. jmp/ret
  8010. into
  8011. mov ##, ##
  8012. jmp/ret
  8013. }
  8014. if not Assigned(hp1) then
  8015. begin
  8016. hp1 := GetLabelWithSym(OrigLabel);
  8017. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8018. Exit;
  8019. end;
  8020. hp2 := hp1;
  8021. while Assigned(hp2) do
  8022. begin
  8023. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8024. SkipLabels(hp2,hp2);
  8025. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8026. Break;
  8027. case taicpu(hp2).opcode of
  8028. A_MOVSD:
  8029. begin
  8030. if taicpu(hp2).ops = 0 then
  8031. { Wrong MOVSD }
  8032. Break;
  8033. Inc(Count);
  8034. if Count >= 5 then
  8035. { Too many to be worthwhile }
  8036. Break;
  8037. GetNextInstruction(hp2, hp2);
  8038. Continue;
  8039. end;
  8040. A_MOV,
  8041. A_MOVD,
  8042. A_MOVQ,
  8043. A_MOVSX,
  8044. {$ifdef x86_64}
  8045. A_MOVSXD,
  8046. {$endif x86_64}
  8047. A_MOVZX,
  8048. A_MOVAPS,
  8049. A_MOVUPS,
  8050. A_MOVSS,
  8051. A_MOVAPD,
  8052. A_MOVUPD,
  8053. A_MOVDQA,
  8054. A_MOVDQU,
  8055. A_VMOVSS,
  8056. A_VMOVAPS,
  8057. A_VMOVUPS,
  8058. A_VMOVSD,
  8059. A_VMOVAPD,
  8060. A_VMOVUPD,
  8061. A_VMOVDQA,
  8062. A_VMOVDQU:
  8063. begin
  8064. Inc(Count);
  8065. if Count >= 5 then
  8066. { Too many to be worthwhile }
  8067. Break;
  8068. GetNextInstruction(hp2, hp2);
  8069. Continue;
  8070. end;
  8071. A_JMP:
  8072. begin
  8073. { Guard against infinite loops }
  8074. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8075. Exit;
  8076. { Analyse this jump first in case it also duplicates assignments }
  8077. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8078. begin
  8079. { Something did change! }
  8080. Result := True;
  8081. Inc(Count, IncCount);
  8082. if Count >= 5 then
  8083. begin
  8084. { Too many to be worthwhile }
  8085. Exit;
  8086. end;
  8087. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8088. Break;
  8089. end;
  8090. Result := True;
  8091. Break;
  8092. end;
  8093. A_RET:
  8094. begin
  8095. Result := True;
  8096. Break;
  8097. end;
  8098. else
  8099. Break;
  8100. end;
  8101. end;
  8102. if Result then
  8103. begin
  8104. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8105. if Count = 0 then
  8106. begin
  8107. Result := False;
  8108. Exit;
  8109. end;
  8110. hp3 := p;
  8111. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8112. while True do
  8113. begin
  8114. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8115. SkipLabels(hp1,hp1);
  8116. if (hp1.typ <> ait_instruction) then
  8117. InternalError(2021040720);
  8118. case taicpu(hp1).opcode of
  8119. A_JMP:
  8120. begin
  8121. { Change the original jump to the new destination }
  8122. OrigLabel.decrefs;
  8123. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8124. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8125. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8126. if not Assigned(first_assignment) then
  8127. InternalError(2021040810)
  8128. else
  8129. p := first_assignment;
  8130. Exit;
  8131. end;
  8132. A_RET:
  8133. begin
  8134. { Now change the jump into a RET instruction }
  8135. ConvertJumpToRET(p, hp1);
  8136. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8137. if not Assigned(first_assignment) then
  8138. InternalError(2021040811)
  8139. else
  8140. p := first_assignment;
  8141. Exit;
  8142. end;
  8143. else
  8144. begin
  8145. { Duplicate the MOV instruction }
  8146. hp3:=tai(hp1.getcopy);
  8147. if first_assignment = nil then
  8148. first_assignment := hp3;
  8149. asml.InsertBefore(hp3, p);
  8150. { Make sure the compiler knows about any final registers written here }
  8151. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8152. with taicpu(hp3).oper[OperIdx]^ do
  8153. begin
  8154. case typ of
  8155. top_ref:
  8156. begin
  8157. if (ref^.base <> NR_NO) and
  8158. (getsupreg(ref^.base) <> RS_ESP) and
  8159. (getsupreg(ref^.base) <> RS_EBP)
  8160. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8161. then
  8162. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8163. if (ref^.index <> NR_NO) and
  8164. (getsupreg(ref^.index) <> RS_ESP) and
  8165. (getsupreg(ref^.index) <> RS_EBP)
  8166. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8167. (ref^.index <> ref^.base) then
  8168. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8169. end;
  8170. top_reg:
  8171. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8172. else
  8173. ;
  8174. end;
  8175. end;
  8176. end;
  8177. end;
  8178. if not GetNextInstruction(hp1, hp1) then
  8179. { Should have dropped out earlier }
  8180. InternalError(2021040710);
  8181. end;
  8182. end;
  8183. end;
  8184. const
  8185. WriteOp: array[0..3] of set of TInsChange = (
  8186. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8187. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8188. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8189. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8190. RegWriteFlags: array[0..7] of set of TInsChange = (
  8191. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8192. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8193. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8194. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8195. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8196. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8197. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8198. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8199. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8200. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8201. var
  8202. hp2: tai;
  8203. X: Integer;
  8204. begin
  8205. { If we have something like:
  8206. op ###,###
  8207. mov ###,###
  8208. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8209. interfere in regards to what they write to.
  8210. NOTE: p must be a 2-operand instruction
  8211. }
  8212. Result := False;
  8213. if (hp1.typ <> ait_instruction) or
  8214. taicpu(hp1).is_jmp or
  8215. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8216. Exit;
  8217. { NOP is a pipeline fence, likely marking the beginning of the function
  8218. epilogue, so drop out. Similarly, drop out if POP or RET are
  8219. encountered }
  8220. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8221. Exit;
  8222. if (taicpu(hp1).opcode = A_MOVSD) and
  8223. (taicpu(hp1).ops = 0) then
  8224. { Wrong MOVSD }
  8225. Exit;
  8226. { Check for writes to specific registers first }
  8227. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8228. for X := 0 to 7 do
  8229. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8230. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8231. Exit;
  8232. for X := 0 to taicpu(hp1).ops - 1 do
  8233. begin
  8234. { Check to see if this operand writes to something }
  8235. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8236. { And matches something in the CMP/TEST instruction }
  8237. (
  8238. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8239. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8240. (
  8241. { If it's a register, make sure the register written to doesn't
  8242. appear in the cmp instruction as part of a reference }
  8243. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8244. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8245. )
  8246. ) then
  8247. Exit;
  8248. end;
  8249. { Check p to make sure it doesn't write to something that affects hp1 }
  8250. { Check for writes to specific registers first }
  8251. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8252. for X := 0 to 7 do
  8253. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8254. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8255. Exit;
  8256. for X := 0 to taicpu(p).ops - 1 do
  8257. begin
  8258. { Check to see if this operand writes to something }
  8259. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8260. { And matches something in hp1 }
  8261. (taicpu(p).oper[X]^.typ = top_reg) and
  8262. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8263. Exit;
  8264. end;
  8265. { The instruction can be safely moved }
  8266. asml.Remove(hp1);
  8267. { Try to insert after the last instructions where the FLAGS register is not
  8268. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8269. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8270. asml.InsertBefore(hp1, hp2)
  8271. { Failing that, try to insert after the last instructions where the
  8272. FLAGS register is not yet in use }
  8273. else if GetLastInstruction(p, hp2) and
  8274. (
  8275. (hp2.typ <> ait_instruction) or
  8276. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8277. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8278. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8279. ) then
  8280. asml.InsertAfter(hp1, hp2)
  8281. else
  8282. { Note, if p.Previous is nil (even if it should logically never be the
  8283. case), FindRegAllocBackward immediately exits with False and so we
  8284. safely land here (we can't just pass p because FindRegAllocBackward
  8285. immediately exits on an instruction). [Kit] }
  8286. asml.InsertBefore(hp1, p);
  8287. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8288. { We can't trust UsedRegs because we're looking backwards, although we
  8289. know the registers are allocated after p at the very least, so manually
  8290. create tai_regalloc objects if needed }
  8291. for X := 0 to taicpu(hp1).ops - 1 do
  8292. case taicpu(hp1).oper[X]^.typ of
  8293. top_reg:
  8294. begin
  8295. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8296. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8297. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8298. end;
  8299. top_ref:
  8300. begin
  8301. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8302. begin
  8303. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8304. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8305. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8306. end;
  8307. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8308. begin
  8309. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8310. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8311. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8312. end;
  8313. end;
  8314. else
  8315. ;
  8316. end;
  8317. Result := True;
  8318. end;
  8319. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8320. var
  8321. hp2: tai;
  8322. X: Integer;
  8323. begin
  8324. { If we have something like:
  8325. cmp ###,%reg1
  8326. mov 0,%reg2
  8327. And no modified registers are shared, move the instruction to before
  8328. the comparison as this means it can be optimised without worrying
  8329. about the FLAGS register. (CMP/MOV is generated by
  8330. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8331. As long as the second instruction doesn't use the flags or one of the
  8332. registers used by CMP or TEST (also check any references that use the
  8333. registers), then it can be moved prior to the comparison.
  8334. }
  8335. Result := False;
  8336. if not TrySwapMovOp(p, hp1) then
  8337. Exit;
  8338. if taicpu(hp1).opcode = A_LEA then
  8339. { The flags will be overwritten by the CMP/TEST instruction }
  8340. ConvertLEA(taicpu(hp1));
  8341. Result := True;
  8342. { Can we move it one further back? }
  8343. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8344. { Check to see if CMP/TEST is a comparison against zero }
  8345. (
  8346. (
  8347. (taicpu(p).opcode = A_CMP) and
  8348. MatchOperand(taicpu(p).oper[0]^, 0)
  8349. ) or
  8350. (
  8351. (taicpu(p).opcode = A_TEST) and
  8352. (
  8353. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8354. MatchOperand(taicpu(p).oper[0]^, -1)
  8355. )
  8356. )
  8357. ) and
  8358. { These instructions set the zero flag if the result is zero }
  8359. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8360. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8361. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8362. TrySwapMovOp(hp2, hp1);
  8363. end;
  8364. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8365. function IsXCHGAcceptable: Boolean; inline;
  8366. begin
  8367. { Always accept if optimising for size }
  8368. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8369. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8370. than 3, so it becomes a saving compared to three MOVs with two of
  8371. them able to execute simultaneously. [Kit] }
  8372. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8373. end;
  8374. var
  8375. NewRef: TReference;
  8376. hp1, hp2, hp3, hp4: Tai;
  8377. {$ifndef x86_64}
  8378. OperIdx: Integer;
  8379. {$endif x86_64}
  8380. NewInstr : Taicpu;
  8381. NewAligh : Tai_align;
  8382. DestLabel: TAsmLabel;
  8383. TempTracking: TAllUsedRegs;
  8384. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8385. var
  8386. NextInstr: tai;
  8387. begin
  8388. Result := False;
  8389. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8390. if not GetNextInstruction(InputInstr, NextInstr) or
  8391. (
  8392. { The FLAGS register isn't always tracked properly, so do not
  8393. perform this optimisation if a conditional statement follows }
  8394. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8395. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8396. ) then
  8397. begin
  8398. reference_reset(NewRef, 1, []);
  8399. NewRef.base := taicpu(p).oper[0]^.reg;
  8400. NewRef.scalefactor := 1;
  8401. if taicpu(InputInstr).opcode = A_ADD then
  8402. begin
  8403. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8404. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8405. end
  8406. else
  8407. begin
  8408. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8409. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8410. end;
  8411. taicpu(p).opcode := A_LEA;
  8412. taicpu(p).loadref(0, NewRef);
  8413. RemoveInstruction(InputInstr);
  8414. Result := True;
  8415. end;
  8416. end;
  8417. begin
  8418. Result:=false;
  8419. { This optimisation adds an instruction, so only do it for speed }
  8420. if not (cs_opt_size in current_settings.optimizerswitches) and
  8421. MatchOpType(taicpu(p), top_const, top_reg) and
  8422. (taicpu(p).oper[0]^.val = 0) then
  8423. begin
  8424. { To avoid compiler warning }
  8425. DestLabel := nil;
  8426. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8427. InternalError(2021040750);
  8428. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8429. Exit;
  8430. case hp1.typ of
  8431. ait_align,
  8432. ait_label:
  8433. begin
  8434. { Change:
  8435. mov $0,%reg mov $0,%reg
  8436. @Lbl1: @Lbl1:
  8437. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8438. je @Lbl2 jne @Lbl2
  8439. To: To:
  8440. mov $0,%reg mov $0,%reg
  8441. jmp @Lbl2 jmp @Lbl3
  8442. (align) (align)
  8443. @Lbl1: @Lbl1:
  8444. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8445. je @Lbl2 je @Lbl2
  8446. @Lbl3: <-- Only if label exists
  8447. (Not if it's optimised for size)
  8448. }
  8449. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8450. Exit;
  8451. if (hp2.typ = ait_instruction) and
  8452. (
  8453. { Register sizes must exactly match }
  8454. (
  8455. (taicpu(hp2).opcode = A_CMP) and
  8456. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8457. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8458. ) or (
  8459. (taicpu(hp2).opcode = A_TEST) and
  8460. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8461. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8462. )
  8463. ) and GetNextInstruction(hp2, hp3) and
  8464. (hp3.typ = ait_instruction) and
  8465. (taicpu(hp3).opcode = A_JCC) and
  8466. (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
  8467. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8468. begin
  8469. { Check condition of jump }
  8470. { Always true? }
  8471. if condition_in(C_E, taicpu(hp3).condition) then
  8472. begin
  8473. { Copy label symbol and obtain matching label entry for the
  8474. conditional jump, as this will be our destination}
  8475. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8476. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8477. Result := True;
  8478. end
  8479. { Always false? }
  8480. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8481. begin
  8482. { This is only worth it if there's a jump to take }
  8483. case hp2.typ of
  8484. ait_instruction:
  8485. begin
  8486. if taicpu(hp2).opcode = A_JMP then
  8487. begin
  8488. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8489. { An unconditional jump follows the conditional jump which will always be false,
  8490. so use this jump's destination for the new jump }
  8491. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8492. Result := True;
  8493. end
  8494. else if taicpu(hp2).opcode = A_JCC then
  8495. begin
  8496. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8497. if condition_in(C_E, taicpu(hp2).condition) then
  8498. begin
  8499. { A second conditional jump follows the conditional jump which will always be false,
  8500. while the second jump is always True, so use this jump's destination for the new jump }
  8501. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8502. Result := True;
  8503. end;
  8504. { Don't risk it if the jump isn't always true (Result remains False) }
  8505. end;
  8506. end;
  8507. else
  8508. { If anything else don't optimise };
  8509. end;
  8510. end;
  8511. if Result then
  8512. begin
  8513. { Just so we have something to insert as a paremeter}
  8514. reference_reset(NewRef, 1, []);
  8515. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8516. { Now actually load the correct parameter (this also
  8517. increases the reference count) }
  8518. NewInstr.loadsymbol(0, DestLabel, 0);
  8519. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8520. begin
  8521. { Get instruction before original label (may not be p under -O3) }
  8522. if not GetLastInstruction(hp1, hp2) then
  8523. { Shouldn't fail here }
  8524. InternalError(2021040701);
  8525. { Before the aligns too }
  8526. while (hp2.typ = ait_align) do
  8527. if not GetLastInstruction(hp2, hp2) then
  8528. { Shouldn't fail here }
  8529. InternalError(2021040702);
  8530. end
  8531. else
  8532. hp2 := p;
  8533. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8534. AsmL.InsertAfter(NewInstr, hp2);
  8535. { Add new alignment field }
  8536. (* AsmL.InsertAfter(
  8537. cai_align.create_max(
  8538. current_settings.alignment.jumpalign,
  8539. current_settings.alignment.jumpalignskipmax
  8540. ),
  8541. NewInstr
  8542. ); *)
  8543. end;
  8544. Exit;
  8545. end;
  8546. end;
  8547. else
  8548. ;
  8549. end;
  8550. end;
  8551. if not GetNextInstruction(p, hp1) then
  8552. Exit;
  8553. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8554. and DoMovCmpMemOpt(p, hp1) then
  8555. begin
  8556. Result := True;
  8557. Exit;
  8558. end
  8559. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8560. begin
  8561. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8562. further, but we can't just put this jump optimisation in pass 1
  8563. because it tends to perform worse when conditional jumps are
  8564. nearby (e.g. when converting CMOV instructions). [Kit] }
  8565. CopyUsedRegs(TempTracking);
  8566. UpdateUsedRegs(tai(p.Next));
  8567. if OptPass2JMP(hp1) then
  8568. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8569. Result := OptPass1MOV(p);
  8570. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8571. returned True and the instruction is still a MOV, thus checking
  8572. the optimisations below }
  8573. { If OptPass2JMP returned False, no optimisations were done to
  8574. the jump and there are no further optimisations that can be done
  8575. to the MOV instruction on this pass }
  8576. { Restore register state }
  8577. RestoreUsedRegs(TempTracking);
  8578. ReleaseUsedRegs(TempTracking);
  8579. end
  8580. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8581. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8582. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8583. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8584. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8585. begin
  8586. { Change:
  8587. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8588. addl/q $x,%reg2 subl/q $x,%reg2
  8589. To:
  8590. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8591. }
  8592. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8593. { be lazy, checking separately for sub would be slightly better }
  8594. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8595. begin
  8596. TransferUsedRegs(TmpUsedRegs);
  8597. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8598. if TryMovArith2Lea(hp1) then
  8599. begin
  8600. Result := True;
  8601. Exit;
  8602. end
  8603. end
  8604. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8605. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8606. { Same as above, but also adds or subtracts to %reg2 in between.
  8607. It's still valid as long as the flags aren't in use }
  8608. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8609. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8610. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8611. { be lazy, checking separately for sub would be slightly better }
  8612. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8613. begin
  8614. TransferUsedRegs(TmpUsedRegs);
  8615. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8616. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8617. if TryMovArith2Lea(hp2) then
  8618. begin
  8619. Result := True;
  8620. Exit;
  8621. end;
  8622. end;
  8623. end
  8624. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8625. {$ifdef x86_64}
  8626. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8627. {$else x86_64}
  8628. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8629. {$endif x86_64}
  8630. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8631. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8632. { mov reg1, reg2 mov reg1, reg2
  8633. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8634. begin
  8635. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8636. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8637. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8638. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8639. TransferUsedRegs(TmpUsedRegs);
  8640. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8641. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8642. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8643. then
  8644. begin
  8645. RemoveCurrentP(p, hp1);
  8646. Result:=true;
  8647. end;
  8648. exit;
  8649. end
  8650. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8651. IsXCHGAcceptable and
  8652. { XCHG doesn't support 8-byte registers }
  8653. (taicpu(p).opsize <> S_B) and
  8654. MatchInstruction(hp1, A_MOV, []) and
  8655. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8656. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8657. GetNextInstruction(hp1, hp2) and
  8658. MatchInstruction(hp2, A_MOV, []) and
  8659. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8660. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8661. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8662. begin
  8663. { mov %reg1,%reg2
  8664. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8665. mov %reg2,%reg3
  8666. (%reg2 not used afterwards)
  8667. Note that xchg takes 3 cycles to execute, and generally mov's take
  8668. only one cycle apiece, but the first two mov's can be executed in
  8669. parallel, only taking 2 cycles overall. Older processors should
  8670. therefore only optimise for size. [Kit]
  8671. }
  8672. TransferUsedRegs(TmpUsedRegs);
  8673. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8674. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8675. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8676. begin
  8677. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8678. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8679. taicpu(hp1).opcode := A_XCHG;
  8680. RemoveCurrentP(p, hp1);
  8681. RemoveInstruction(hp2);
  8682. Result := True;
  8683. Exit;
  8684. end;
  8685. end
  8686. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8687. MatchInstruction(hp1, A_SAR, []) then
  8688. begin
  8689. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8690. begin
  8691. { the use of %edx also covers the opsize being S_L }
  8692. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8693. begin
  8694. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8695. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8696. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8697. begin
  8698. { Change:
  8699. movl %eax,%edx
  8700. sarl $31,%edx
  8701. To:
  8702. cltd
  8703. }
  8704. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8705. RemoveInstruction(hp1);
  8706. taicpu(p).opcode := A_CDQ;
  8707. taicpu(p).opsize := S_NO;
  8708. taicpu(p).clearop(1);
  8709. taicpu(p).clearop(0);
  8710. taicpu(p).ops:=0;
  8711. Result := True;
  8712. end
  8713. else if (cs_opt_size in current_settings.optimizerswitches) and
  8714. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8715. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8716. begin
  8717. { Change:
  8718. movl %edx,%eax
  8719. sarl $31,%edx
  8720. To:
  8721. movl %edx,%eax
  8722. cltd
  8723. Note that this creates a dependency between the two instructions,
  8724. so only perform if optimising for size.
  8725. }
  8726. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8727. taicpu(hp1).opcode := A_CDQ;
  8728. taicpu(hp1).opsize := S_NO;
  8729. taicpu(hp1).clearop(1);
  8730. taicpu(hp1).clearop(0);
  8731. taicpu(hp1).ops:=0;
  8732. end;
  8733. {$ifndef x86_64}
  8734. end
  8735. { Don't bother if CMOV is supported, because a more optimal
  8736. sequence would have been generated for the Abs() intrinsic }
  8737. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8738. { the use of %eax also covers the opsize being S_L }
  8739. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8740. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8741. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8742. GetNextInstruction(hp1, hp2) and
  8743. MatchInstruction(hp2, A_XOR, [S_L]) and
  8744. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8745. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8746. GetNextInstruction(hp2, hp3) and
  8747. MatchInstruction(hp3, A_SUB, [S_L]) and
  8748. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8749. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8750. begin
  8751. { Change:
  8752. movl %eax,%edx
  8753. sarl $31,%eax
  8754. xorl %eax,%edx
  8755. subl %eax,%edx
  8756. (Instruction that uses %edx)
  8757. (%eax deallocated)
  8758. (%edx deallocated)
  8759. To:
  8760. cltd
  8761. xorl %edx,%eax <-- Note the registers have swapped
  8762. subl %edx,%eax
  8763. (Instruction that uses %eax) <-- %eax rather than %edx
  8764. }
  8765. TransferUsedRegs(TmpUsedRegs);
  8766. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8767. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8768. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8769. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8770. begin
  8771. if GetNextInstruction(hp3, hp4) and
  8772. not RegModifiedByInstruction(NR_EDX, hp4) and
  8773. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8774. begin
  8775. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8776. taicpu(p).opcode := A_CDQ;
  8777. taicpu(p).clearop(1);
  8778. taicpu(p).clearop(0);
  8779. taicpu(p).ops:=0;
  8780. RemoveInstruction(hp1);
  8781. taicpu(hp2).loadreg(0, NR_EDX);
  8782. taicpu(hp2).loadreg(1, NR_EAX);
  8783. taicpu(hp3).loadreg(0, NR_EDX);
  8784. taicpu(hp3).loadreg(1, NR_EAX);
  8785. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8786. { Convert references in the following instruction (hp4) from %edx to %eax }
  8787. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8788. with taicpu(hp4).oper[OperIdx]^ do
  8789. case typ of
  8790. top_reg:
  8791. if getsupreg(reg) = RS_EDX then
  8792. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8793. top_ref:
  8794. begin
  8795. if getsupreg(reg) = RS_EDX then
  8796. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8797. if getsupreg(reg) = RS_EDX then
  8798. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8799. end;
  8800. else
  8801. ;
  8802. end;
  8803. end;
  8804. end;
  8805. {$else x86_64}
  8806. end;
  8807. end
  8808. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8809. { the use of %rdx also covers the opsize being S_Q }
  8810. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8811. begin
  8812. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8813. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8814. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8815. begin
  8816. { Change:
  8817. movq %rax,%rdx
  8818. sarq $63,%rdx
  8819. To:
  8820. cqto
  8821. }
  8822. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8823. RemoveInstruction(hp1);
  8824. taicpu(p).opcode := A_CQO;
  8825. taicpu(p).opsize := S_NO;
  8826. taicpu(p).clearop(1);
  8827. taicpu(p).clearop(0);
  8828. taicpu(p).ops:=0;
  8829. Result := True;
  8830. end
  8831. else if (cs_opt_size in current_settings.optimizerswitches) and
  8832. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8833. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8834. begin
  8835. { Change:
  8836. movq %rdx,%rax
  8837. sarq $63,%rdx
  8838. To:
  8839. movq %rdx,%rax
  8840. cqto
  8841. Note that this creates a dependency between the two instructions,
  8842. so only perform if optimising for size.
  8843. }
  8844. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8845. taicpu(hp1).opcode := A_CQO;
  8846. taicpu(hp1).opsize := S_NO;
  8847. taicpu(hp1).clearop(1);
  8848. taicpu(hp1).clearop(0);
  8849. taicpu(hp1).ops:=0;
  8850. {$endif x86_64}
  8851. end;
  8852. end;
  8853. end
  8854. else if MatchInstruction(hp1, A_MOV, []) and
  8855. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8856. { Though "GetNextInstruction" could be factored out, along with
  8857. the instructions that depend on hp2, it is an expensive call that
  8858. should be delayed for as long as possible, hence we do cheaper
  8859. checks first that are likely to be False. [Kit] }
  8860. begin
  8861. if (
  8862. (
  8863. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8864. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8865. (
  8866. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8867. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8868. )
  8869. ) or
  8870. (
  8871. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8872. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8873. (
  8874. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8875. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8876. )
  8877. )
  8878. ) and
  8879. GetNextInstruction(hp1, hp2) and
  8880. MatchInstruction(hp2, A_SAR, []) and
  8881. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8882. begin
  8883. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8884. begin
  8885. { Change:
  8886. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8887. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8888. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8889. To:
  8890. movl r/m,%eax <- Note the change in register
  8891. cltd
  8892. }
  8893. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8894. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8895. taicpu(p).loadreg(1, NR_EAX);
  8896. taicpu(hp1).opcode := A_CDQ;
  8897. taicpu(hp1).clearop(1);
  8898. taicpu(hp1).clearop(0);
  8899. taicpu(hp1).ops:=0;
  8900. RemoveInstruction(hp2);
  8901. (*
  8902. {$ifdef x86_64}
  8903. end
  8904. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8905. { This code sequence does not get generated - however it might become useful
  8906. if and when 128-bit signed integer types make an appearance, so the code
  8907. is kept here for when it is eventually needed. [Kit] }
  8908. (
  8909. (
  8910. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8911. (
  8912. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8913. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8914. )
  8915. ) or
  8916. (
  8917. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8918. (
  8919. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8920. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8921. )
  8922. )
  8923. ) and
  8924. GetNextInstruction(hp1, hp2) and
  8925. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8926. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8927. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8928. begin
  8929. { Change:
  8930. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8931. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8932. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8933. To:
  8934. movq r/m,%rax <- Note the change in register
  8935. cqto
  8936. }
  8937. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8938. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8939. taicpu(p).loadreg(1, NR_RAX);
  8940. taicpu(hp1).opcode := A_CQO;
  8941. taicpu(hp1).clearop(1);
  8942. taicpu(hp1).clearop(0);
  8943. taicpu(hp1).ops:=0;
  8944. RemoveInstruction(hp2);
  8945. {$endif x86_64}
  8946. *)
  8947. end;
  8948. end;
  8949. {$ifdef x86_64}
  8950. end
  8951. else if (taicpu(p).opsize = S_L) and
  8952. (taicpu(p).oper[1]^.typ = top_reg) and
  8953. (
  8954. MatchInstruction(hp1, A_MOV,[]) and
  8955. (taicpu(hp1).opsize = S_L) and
  8956. (taicpu(hp1).oper[1]^.typ = top_reg)
  8957. ) and (
  8958. GetNextInstruction(hp1, hp2) and
  8959. (tai(hp2).typ=ait_instruction) and
  8960. (taicpu(hp2).opsize = S_Q) and
  8961. (
  8962. (
  8963. MatchInstruction(hp2, A_ADD,[]) and
  8964. (taicpu(hp2).opsize = S_Q) and
  8965. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8966. (
  8967. (
  8968. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8969. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8970. ) or (
  8971. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8972. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8973. )
  8974. )
  8975. ) or (
  8976. MatchInstruction(hp2, A_LEA,[]) and
  8977. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8978. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8979. (
  8980. (
  8981. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8982. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8983. ) or (
  8984. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8985. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8986. )
  8987. ) and (
  8988. (
  8989. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8990. ) or (
  8991. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8992. )
  8993. )
  8994. )
  8995. )
  8996. ) and (
  8997. GetNextInstruction(hp2, hp3) and
  8998. MatchInstruction(hp3, A_SHR,[]) and
  8999. (taicpu(hp3).opsize = S_Q) and
  9000. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9001. (taicpu(hp3).oper[0]^.val = 1) and
  9002. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9003. ) then
  9004. begin
  9005. { Change movl x, reg1d movl x, reg1d
  9006. movl y, reg2d movl y, reg2d
  9007. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9008. shrq $1, reg1q shrq $1, reg1q
  9009. ( reg1d and reg2d can be switched around in the first two instructions )
  9010. To movl x, reg1d
  9011. addl y, reg1d
  9012. rcrl $1, reg1d
  9013. This corresponds to the common expression (x + y) shr 1, where
  9014. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9015. smaller code, but won't account for x + y causing an overflow). [Kit]
  9016. }
  9017. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9018. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9019. { Change first MOV command to have the same register as the final output }
  9020. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9021. else
  9022. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9023. { Change second MOV command to an ADD command. This is easier than
  9024. converting the existing command because it means we don't have to
  9025. touch 'y', which might be a complicated reference, and also the
  9026. fact that the third command might either be ADD or LEA. [Kit] }
  9027. taicpu(hp1).opcode := A_ADD;
  9028. { Delete old ADD/LEA instruction }
  9029. RemoveInstruction(hp2);
  9030. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9031. taicpu(hp3).opcode := A_RCR;
  9032. taicpu(hp3).changeopsize(S_L);
  9033. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9034. {$endif x86_64}
  9035. end;
  9036. if FuncMov2Func(p, hp1) then
  9037. begin
  9038. Result := True;
  9039. Exit;
  9040. end;
  9041. end;
  9042. {$push}
  9043. {$q-}{$r-}
  9044. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9045. var
  9046. ThisReg: TRegister;
  9047. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9048. TargetSubReg: TSubRegister;
  9049. hp1, hp2: tai;
  9050. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9051. { Store list of found instructions so we don't have to call
  9052. GetNextInstructionUsingReg multiple times }
  9053. InstrList: array of taicpu;
  9054. InstrMax, Index: Integer;
  9055. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9056. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9057. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9058. WorkingValue: TCgInt;
  9059. PreMessage: string;
  9060. { Data flow analysis }
  9061. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9062. BitwiseOnly, OrXorUsed,
  9063. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9064. function CheckOverflowConditions: Boolean;
  9065. begin
  9066. Result := True;
  9067. if (TestValSignedMax > SignedUpperLimit) then
  9068. UpperSignedOverflow := True;
  9069. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9070. LowerSignedOverflow := True;
  9071. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9072. LowerUnsignedOverflow := True;
  9073. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9074. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9075. begin
  9076. { Absolute overflow }
  9077. Result := False;
  9078. Exit;
  9079. end;
  9080. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9081. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9082. ShiftDownOverflow := True;
  9083. if (TestValMin < 0) or (TestValMax < 0) then
  9084. begin
  9085. LowerUnsignedOverflow := True;
  9086. UpperUnsignedOverflow := True;
  9087. end;
  9088. end;
  9089. function AdjustInitialLoadAndSize: Boolean;
  9090. begin
  9091. Result := False;
  9092. if not p_removed then
  9093. begin
  9094. if TargetSize = MinSize then
  9095. begin
  9096. { Convert the input MOVZX to a MOV }
  9097. if (taicpu(p).oper[0]^.typ = top_reg) and
  9098. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9099. begin
  9100. { Or remove it completely! }
  9101. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9102. RemoveCurrentP(p);
  9103. p_removed := True;
  9104. end
  9105. else
  9106. begin
  9107. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9108. taicpu(p).opcode := A_MOV;
  9109. taicpu(p).oper[1]^.reg := ThisReg;
  9110. taicpu(p).opsize := TargetSize;
  9111. end;
  9112. Result := True;
  9113. end
  9114. else if TargetSize <> MaxSize then
  9115. begin
  9116. case MaxSize of
  9117. S_L:
  9118. if TargetSize = S_W then
  9119. begin
  9120. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9121. taicpu(p).opsize := S_BW;
  9122. taicpu(p).oper[1]^.reg := ThisReg;
  9123. Result := True;
  9124. end
  9125. else
  9126. InternalError(2020112341);
  9127. S_W:
  9128. if TargetSize = S_L then
  9129. begin
  9130. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9131. taicpu(p).opsize := S_BL;
  9132. taicpu(p).oper[1]^.reg := ThisReg;
  9133. Result := True;
  9134. end
  9135. else
  9136. InternalError(2020112342);
  9137. else
  9138. ;
  9139. end;
  9140. end
  9141. else if not hp1_removed and not RegInUse then
  9142. begin
  9143. { If we have something like:
  9144. movzbl (oper),%regd
  9145. add x, %regd
  9146. movzbl %regb, %regd
  9147. We can reduce the register size to the input of the final
  9148. movzbl instruction. Overflows won't have any effect.
  9149. }
  9150. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9151. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9152. begin
  9153. TargetSize := S_B;
  9154. setsubreg(ThisReg, R_SUBL);
  9155. Result := True;
  9156. end
  9157. else if (taicpu(p).opsize = S_WL) and
  9158. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9159. begin
  9160. TargetSize := S_W;
  9161. setsubreg(ThisReg, R_SUBW);
  9162. Result := True;
  9163. end;
  9164. if Result then
  9165. begin
  9166. { Convert the input MOVZX to a MOV }
  9167. if (taicpu(p).oper[0]^.typ = top_reg) and
  9168. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9169. begin
  9170. { Or remove it completely! }
  9171. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9172. RemoveCurrentP(p);
  9173. p_removed := True;
  9174. end
  9175. else
  9176. begin
  9177. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9178. taicpu(p).opcode := A_MOV;
  9179. taicpu(p).oper[1]^.reg := ThisReg;
  9180. taicpu(p).opsize := TargetSize;
  9181. end;
  9182. end;
  9183. end;
  9184. end;
  9185. end;
  9186. procedure AdjustFinalLoad;
  9187. begin
  9188. if not LowerUnsignedOverflow then
  9189. begin
  9190. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9191. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9192. begin
  9193. { Convert the output MOVZX to a MOV }
  9194. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9195. begin
  9196. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9197. if (MinSize = S_B) or
  9198. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9199. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9200. begin
  9201. { Remove it completely! }
  9202. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9203. { Be careful; if p = hp1 and p was also removed, p
  9204. will become a dangling pointer }
  9205. if p = hp1 then
  9206. begin
  9207. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9208. p_removed := True;
  9209. end
  9210. else
  9211. RemoveInstruction(hp1);
  9212. hp1_removed := True;
  9213. end;
  9214. end
  9215. else
  9216. begin
  9217. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9218. taicpu(hp1).opcode := A_MOV;
  9219. taicpu(hp1).oper[0]^.reg := ThisReg;
  9220. taicpu(hp1).opsize := TargetSize;
  9221. end;
  9222. end
  9223. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9224. begin
  9225. { Need to change the size of the output }
  9226. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9227. taicpu(hp1).oper[0]^.reg := ThisReg;
  9228. taicpu(hp1).opsize := S_BL;
  9229. end;
  9230. end;
  9231. end;
  9232. function CompressInstructions: Boolean;
  9233. var
  9234. LocalIndex: Integer;
  9235. begin
  9236. Result := False;
  9237. { The objective here is to try to find a combination that
  9238. removes one of the MOV/Z instructions. }
  9239. if (
  9240. (taicpu(p).oper[0]^.typ <> top_reg) or
  9241. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9242. ) and
  9243. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9244. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9245. begin
  9246. { Make a preference to remove the second MOVZX instruction }
  9247. case taicpu(hp1).opsize of
  9248. S_BL, S_WL:
  9249. begin
  9250. TargetSize := S_L;
  9251. TargetSubReg := R_SUBD;
  9252. end;
  9253. S_BW:
  9254. begin
  9255. TargetSize := S_W;
  9256. TargetSubReg := R_SUBW;
  9257. end;
  9258. else
  9259. InternalError(2020112302);
  9260. end;
  9261. end
  9262. else
  9263. begin
  9264. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9265. begin
  9266. { Exceeded lower bound but not upper bound }
  9267. TargetSize := MaxSize;
  9268. end
  9269. else if not LowerUnsignedOverflow then
  9270. begin
  9271. { Size didn't exceed lower bound }
  9272. TargetSize := MinSize;
  9273. end
  9274. else
  9275. Exit;
  9276. end;
  9277. case TargetSize of
  9278. S_B:
  9279. TargetSubReg := R_SUBL;
  9280. S_W:
  9281. TargetSubReg := R_SUBW;
  9282. S_L:
  9283. TargetSubReg := R_SUBD;
  9284. else
  9285. InternalError(2020112350);
  9286. end;
  9287. { Update the register to its new size }
  9288. setsubreg(ThisReg, TargetSubReg);
  9289. RegInUse := False;
  9290. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9291. begin
  9292. { Check to see if the active register is used afterwards;
  9293. if not, we can change it and make a saving. }
  9294. TransferUsedRegs(TmpUsedRegs);
  9295. { The target register may be marked as in use to cross
  9296. a jump to a distant label, so exclude it }
  9297. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9298. hp2 := p;
  9299. repeat
  9300. { Explicitly check for the excluded register (don't include the first
  9301. instruction as it may be reading from here }
  9302. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9303. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9304. begin
  9305. RegInUse := True;
  9306. Break;
  9307. end;
  9308. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9309. if not GetNextInstruction(hp2, hp2) then
  9310. InternalError(2020112340);
  9311. until (hp2 = hp1);
  9312. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9313. { We might still be able to get away with this }
  9314. RegInUse := not
  9315. (
  9316. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9317. (hp2.typ = ait_instruction) and
  9318. (
  9319. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9320. instruction that doesn't actually contain ThisReg }
  9321. (cs_opt_level3 in current_settings.optimizerswitches) or
  9322. RegInInstruction(ThisReg, hp2)
  9323. ) and
  9324. RegLoadedWithNewValue(ThisReg, hp2)
  9325. );
  9326. if not RegInUse then
  9327. begin
  9328. { Force the register size to the same as this instruction so it can be removed}
  9329. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9330. begin
  9331. TargetSize := S_L;
  9332. TargetSubReg := R_SUBD;
  9333. end
  9334. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9335. begin
  9336. TargetSize := S_W;
  9337. TargetSubReg := R_SUBW;
  9338. end;
  9339. ThisReg := taicpu(hp1).oper[1]^.reg;
  9340. setsubreg(ThisReg, TargetSubReg);
  9341. RegChanged := True;
  9342. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9343. TransferUsedRegs(TmpUsedRegs);
  9344. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9345. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9346. if p = hp1 then
  9347. begin
  9348. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9349. p_removed := True;
  9350. end
  9351. else
  9352. RemoveInstruction(hp1);
  9353. hp1_removed := True;
  9354. { Instruction will become "mov %reg,%reg" }
  9355. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9356. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9357. begin
  9358. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9359. RemoveCurrentP(p);
  9360. p_removed := True;
  9361. end
  9362. else
  9363. taicpu(p).oper[1]^.reg := ThisReg;
  9364. Result := True;
  9365. end
  9366. else
  9367. begin
  9368. if TargetSize <> MaxSize then
  9369. begin
  9370. { Since the register is in use, we have to force it to
  9371. MaxSize otherwise part of it may become undefined later on }
  9372. TargetSize := MaxSize;
  9373. case TargetSize of
  9374. S_B:
  9375. TargetSubReg := R_SUBL;
  9376. S_W:
  9377. TargetSubReg := R_SUBW;
  9378. S_L:
  9379. TargetSubReg := R_SUBD;
  9380. else
  9381. InternalError(2020112351);
  9382. end;
  9383. setsubreg(ThisReg, TargetSubReg);
  9384. end;
  9385. AdjustFinalLoad;
  9386. end;
  9387. end
  9388. else
  9389. AdjustFinalLoad;
  9390. Result := AdjustInitialLoadAndSize or Result;
  9391. { Now go through every instruction we found and change the
  9392. size. If TargetSize = MaxSize, then almost no changes are
  9393. needed and Result can remain False if it hasn't been set
  9394. yet.
  9395. If RegChanged is True, then the register requires changing
  9396. and so the point about TargetSize = MaxSize doesn't apply. }
  9397. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9398. begin
  9399. for LocalIndex := 0 to InstrMax do
  9400. begin
  9401. { If p_removed is true, then the original MOV/Z was removed
  9402. and removing the AND instruction may not be safe if it
  9403. appears first }
  9404. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9405. InternalError(2020112310);
  9406. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9407. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9408. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9409. InstrList[LocalIndex].opsize := TargetSize;
  9410. end;
  9411. Result := True;
  9412. end;
  9413. end;
  9414. begin
  9415. Result := False;
  9416. p_removed := False;
  9417. hp1_removed := False;
  9418. ThisReg := taicpu(p).oper[1]^.reg;
  9419. { Check for:
  9420. movs/z ###,%ecx (or %cx or %rcx)
  9421. ...
  9422. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9423. (dealloc %ecx)
  9424. Change to:
  9425. mov ###,%cl (if ### = %cl, then remove completely)
  9426. ...
  9427. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9428. }
  9429. if (getsupreg(ThisReg) = RS_ECX) and
  9430. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9431. (hp1.typ = ait_instruction) and
  9432. (
  9433. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9434. instruction that doesn't actually contain ECX }
  9435. (cs_opt_level3 in current_settings.optimizerswitches) or
  9436. RegInInstruction(NR_ECX, hp1) or
  9437. (
  9438. { It's common for the shift/rotate's read/write register to be
  9439. initialised in between, so under -O2 and under, search ahead
  9440. one more instruction
  9441. }
  9442. GetNextInstruction(hp1, hp1) and
  9443. (hp1.typ = ait_instruction) and
  9444. RegInInstruction(NR_ECX, hp1)
  9445. )
  9446. ) and
  9447. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9448. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9449. begin
  9450. TransferUsedRegs(TmpUsedRegs);
  9451. hp2 := p;
  9452. repeat
  9453. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9454. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9455. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9456. begin
  9457. case taicpu(p).opsize of
  9458. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9459. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9460. begin
  9461. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9462. RemoveCurrentP(p);
  9463. end
  9464. else
  9465. begin
  9466. taicpu(p).opcode := A_MOV;
  9467. taicpu(p).opsize := S_B;
  9468. taicpu(p).oper[1]^.reg := NR_CL;
  9469. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9470. end;
  9471. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9472. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9473. begin
  9474. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9475. RemoveCurrentP(p);
  9476. end
  9477. else
  9478. begin
  9479. taicpu(p).opcode := A_MOV;
  9480. taicpu(p).opsize := S_W;
  9481. taicpu(p).oper[1]^.reg := NR_CX;
  9482. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9483. end;
  9484. {$ifdef x86_64}
  9485. S_LQ:
  9486. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9487. begin
  9488. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9489. RemoveCurrentP(p);
  9490. end
  9491. else
  9492. begin
  9493. taicpu(p).opcode := A_MOV;
  9494. taicpu(p).opsize := S_L;
  9495. taicpu(p).oper[1]^.reg := NR_ECX;
  9496. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9497. end;
  9498. {$endif x86_64}
  9499. else
  9500. InternalError(2021120401);
  9501. end;
  9502. Result := True;
  9503. Exit;
  9504. end;
  9505. end;
  9506. { This is anything but quick! }
  9507. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9508. Exit;
  9509. SetLength(InstrList, 0);
  9510. InstrMax := -1;
  9511. case taicpu(p).opsize of
  9512. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9513. begin
  9514. {$if defined(i386) or defined(i8086)}
  9515. { If the target size is 8-bit, make sure we can actually encode it }
  9516. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9517. Exit;
  9518. {$endif i386 or i8086}
  9519. LowerLimit := $FF;
  9520. SignedLowerLimit := $7F;
  9521. SignedLowerLimitBottom := -128;
  9522. MinSize := S_B;
  9523. if taicpu(p).opsize = S_BW then
  9524. begin
  9525. MaxSize := S_W;
  9526. UpperLimit := $FFFF;
  9527. SignedUpperLimit := $7FFF;
  9528. SignedUpperLimitBottom := -32768;
  9529. end
  9530. else
  9531. begin
  9532. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9533. MaxSize := S_L;
  9534. UpperLimit := $FFFFFFFF;
  9535. SignedUpperLimit := $7FFFFFFF;
  9536. SignedUpperLimitBottom := -2147483648;
  9537. end;
  9538. end;
  9539. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9540. begin
  9541. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9542. LowerLimit := $FFFF;
  9543. SignedLowerLimit := $7FFF;
  9544. SignedLowerLimitBottom := -32768;
  9545. UpperLimit := $FFFFFFFF;
  9546. SignedUpperLimit := $7FFFFFFF;
  9547. SignedUpperLimitBottom := -2147483648;
  9548. MinSize := S_W;
  9549. MaxSize := S_L;
  9550. end;
  9551. {$ifdef x86_64}
  9552. S_LQ:
  9553. begin
  9554. { Both the lower and upper limits are set to 32-bit. If a limit
  9555. is breached, then optimisation is impossible }
  9556. LowerLimit := $FFFFFFFF;
  9557. SignedLowerLimit := $7FFFFFFF;
  9558. SignedLowerLimitBottom := -2147483648;
  9559. UpperLimit := $FFFFFFFF;
  9560. SignedUpperLimit := $7FFFFFFF;
  9561. SignedUpperLimitBottom := -2147483648;
  9562. MinSize := S_L;
  9563. MaxSize := S_L;
  9564. end;
  9565. {$endif x86_64}
  9566. else
  9567. InternalError(2020112301);
  9568. end;
  9569. TestValMin := 0;
  9570. TestValMax := LowerLimit;
  9571. TestValSignedMax := SignedLowerLimit;
  9572. TryShiftDownLimit := LowerLimit;
  9573. TryShiftDown := S_NO;
  9574. ShiftDownOverflow := False;
  9575. RegChanged := False;
  9576. BitwiseOnly := True;
  9577. OrXorUsed := False;
  9578. UpperSignedOverflow := False;
  9579. LowerSignedOverflow := False;
  9580. UpperUnsignedOverflow := False;
  9581. LowerUnsignedOverflow := False;
  9582. hp1 := p;
  9583. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9584. (hp1.typ = ait_instruction) and
  9585. (
  9586. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9587. instruction that doesn't actually contain ThisReg }
  9588. (cs_opt_level3 in current_settings.optimizerswitches) or
  9589. { This allows this Movx optimisation to work through the SETcc instructions
  9590. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9591. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9592. skip over these SETcc instructions). }
  9593. (taicpu(hp1).opcode = A_SETcc) or
  9594. RegInInstruction(ThisReg, hp1)
  9595. ) do
  9596. begin
  9597. case taicpu(hp1).opcode of
  9598. A_INC,A_DEC:
  9599. begin
  9600. { Has to be an exact match on the register }
  9601. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9602. Break;
  9603. if taicpu(hp1).opcode = A_INC then
  9604. begin
  9605. Inc(TestValMin);
  9606. Inc(TestValMax);
  9607. Inc(TestValSignedMax);
  9608. end
  9609. else
  9610. begin
  9611. Dec(TestValMin);
  9612. Dec(TestValMax);
  9613. Dec(TestValSignedMax);
  9614. end;
  9615. end;
  9616. A_TEST, A_CMP:
  9617. begin
  9618. if (
  9619. { Too high a risk of non-linear behaviour that breaks DFA
  9620. here, unless it's cmp $0,%reg, which is equivalent to
  9621. test %reg,%reg }
  9622. OrXorUsed and
  9623. (taicpu(hp1).opcode = A_CMP) and
  9624. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9625. ) or
  9626. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9627. { Has to be an exact match on the register }
  9628. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9629. (
  9630. { Permit "test %reg,%reg" }
  9631. (taicpu(hp1).opcode = A_TEST) and
  9632. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9633. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9634. ) or
  9635. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9636. { Make sure the comparison value is not smaller than the
  9637. smallest allowed signed value for the minimum size (e.g.
  9638. -128 for 8-bit) }
  9639. not (
  9640. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9641. { Is it in the negative range? }
  9642. (
  9643. (taicpu(hp1).oper[0]^.val < 0) and
  9644. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9645. )
  9646. ) then
  9647. Break;
  9648. { Check to see if the active register is used afterwards }
  9649. TransferUsedRegs(TmpUsedRegs);
  9650. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9651. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9652. begin
  9653. { Make sure the comparison or any previous instructions
  9654. hasn't pushed the test values outside of the range of
  9655. MinSize }
  9656. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9657. begin
  9658. { Exceeded lower bound but not upper bound }
  9659. Exit;
  9660. end
  9661. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9662. begin
  9663. { Size didn't exceed lower bound }
  9664. TargetSize := MinSize;
  9665. end
  9666. else
  9667. Break;
  9668. case TargetSize of
  9669. S_B:
  9670. TargetSubReg := R_SUBL;
  9671. S_W:
  9672. TargetSubReg := R_SUBW;
  9673. S_L:
  9674. TargetSubReg := R_SUBD;
  9675. else
  9676. InternalError(2021051002);
  9677. end;
  9678. if TargetSize <> MaxSize then
  9679. begin
  9680. { Update the register to its new size }
  9681. setsubreg(ThisReg, TargetSubReg);
  9682. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9683. taicpu(hp1).oper[1]^.reg := ThisReg;
  9684. taicpu(hp1).opsize := TargetSize;
  9685. { Convert the input MOVZX to a MOV if necessary }
  9686. AdjustInitialLoadAndSize;
  9687. if (InstrMax >= 0) then
  9688. begin
  9689. for Index := 0 to InstrMax do
  9690. begin
  9691. { If p_removed is true, then the original MOV/Z was removed
  9692. and removing the AND instruction may not be safe if it
  9693. appears first }
  9694. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9695. InternalError(2020112311);
  9696. if InstrList[Index].oper[0]^.typ = top_reg then
  9697. InstrList[Index].oper[0]^.reg := ThisReg;
  9698. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9699. InstrList[Index].opsize := MinSize;
  9700. end;
  9701. end;
  9702. Result := True;
  9703. end;
  9704. Exit;
  9705. end;
  9706. end;
  9707. A_SETcc:
  9708. begin
  9709. { This allows this Movx optimisation to work through the SETcc instructions
  9710. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9711. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9712. skip over these SETcc instructions). }
  9713. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9714. { Of course, break out if the current register is used }
  9715. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9716. Break
  9717. else
  9718. { We must use Continue so the instruction doesn't get added
  9719. to InstrList }
  9720. Continue;
  9721. end;
  9722. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9723. begin
  9724. if
  9725. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9726. { Has to be an exact match on the register }
  9727. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9728. (
  9729. (
  9730. (taicpu(hp1).oper[0]^.typ = top_const) and
  9731. (
  9732. (
  9733. (taicpu(hp1).opcode = A_SHL) and
  9734. (
  9735. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9736. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9737. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9738. )
  9739. ) or (
  9740. (taicpu(hp1).opcode <> A_SHL) and
  9741. (
  9742. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9743. { Is it in the negative range? }
  9744. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9745. )
  9746. )
  9747. )
  9748. ) or (
  9749. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9750. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9751. )
  9752. ) then
  9753. Break;
  9754. { Only process OR and XOR if there are only bitwise operations,
  9755. since otherwise they can too easily fool the data flow
  9756. analysis (they can cause non-linear behaviour) }
  9757. case taicpu(hp1).opcode of
  9758. A_ADD:
  9759. begin
  9760. if OrXorUsed then
  9761. { Too high a risk of non-linear behaviour that breaks DFA here }
  9762. Break
  9763. else
  9764. BitwiseOnly := False;
  9765. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9766. begin
  9767. TestValMin := TestValMin * 2;
  9768. TestValMax := TestValMax * 2;
  9769. TestValSignedMax := TestValSignedMax * 2;
  9770. end
  9771. else
  9772. begin
  9773. WorkingValue := taicpu(hp1).oper[0]^.val;
  9774. TestValMin := TestValMin + WorkingValue;
  9775. TestValMax := TestValMax + WorkingValue;
  9776. TestValSignedMax := TestValSignedMax + WorkingValue;
  9777. end;
  9778. end;
  9779. A_SUB:
  9780. begin
  9781. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9782. begin
  9783. TestValMin := 0;
  9784. TestValMax := 0;
  9785. TestValSignedMax := 0;
  9786. end
  9787. else
  9788. begin
  9789. if OrXorUsed then
  9790. { Too high a risk of non-linear behaviour that breaks DFA here }
  9791. Break
  9792. else
  9793. BitwiseOnly := False;
  9794. WorkingValue := taicpu(hp1).oper[0]^.val;
  9795. TestValMin := TestValMin - WorkingValue;
  9796. TestValMax := TestValMax - WorkingValue;
  9797. TestValSignedMax := TestValSignedMax - WorkingValue;
  9798. end;
  9799. end;
  9800. A_AND:
  9801. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9802. begin
  9803. { we might be able to go smaller if AND appears first }
  9804. if InstrMax = -1 then
  9805. case MinSize of
  9806. S_B:
  9807. ;
  9808. S_W:
  9809. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9810. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9811. begin
  9812. TryShiftDown := S_B;
  9813. TryShiftDownLimit := $FF;
  9814. end;
  9815. S_L:
  9816. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9817. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9818. begin
  9819. TryShiftDown := S_B;
  9820. TryShiftDownLimit := $FF;
  9821. end
  9822. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9823. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9824. begin
  9825. TryShiftDown := S_W;
  9826. TryShiftDownLimit := $FFFF;
  9827. end;
  9828. else
  9829. InternalError(2020112320);
  9830. end;
  9831. WorkingValue := taicpu(hp1).oper[0]^.val;
  9832. TestValMin := TestValMin and WorkingValue;
  9833. TestValMax := TestValMax and WorkingValue;
  9834. TestValSignedMax := TestValSignedMax and WorkingValue;
  9835. end;
  9836. A_OR:
  9837. begin
  9838. if not BitwiseOnly then
  9839. Break;
  9840. OrXorUsed := True;
  9841. WorkingValue := taicpu(hp1).oper[0]^.val;
  9842. TestValMin := TestValMin or WorkingValue;
  9843. TestValMax := TestValMax or WorkingValue;
  9844. TestValSignedMax := TestValSignedMax or WorkingValue;
  9845. end;
  9846. A_XOR:
  9847. begin
  9848. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9849. begin
  9850. TestValMin := 0;
  9851. TestValMax := 0;
  9852. TestValSignedMax := 0;
  9853. end
  9854. else
  9855. begin
  9856. if not BitwiseOnly then
  9857. Break;
  9858. OrXorUsed := True;
  9859. WorkingValue := taicpu(hp1).oper[0]^.val;
  9860. TestValMin := TestValMin xor WorkingValue;
  9861. TestValMax := TestValMax xor WorkingValue;
  9862. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9863. end;
  9864. end;
  9865. A_SHL:
  9866. begin
  9867. BitwiseOnly := False;
  9868. WorkingValue := taicpu(hp1).oper[0]^.val;
  9869. TestValMin := TestValMin shl WorkingValue;
  9870. TestValMax := TestValMax shl WorkingValue;
  9871. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9872. end;
  9873. A_SHR,
  9874. { The first instruction was MOVZX, so the value won't be negative }
  9875. A_SAR:
  9876. begin
  9877. if InstrMax <> -1 then
  9878. BitwiseOnly := False
  9879. else
  9880. { we might be able to go smaller if SHR appears first }
  9881. case MinSize of
  9882. S_B:
  9883. ;
  9884. S_W:
  9885. if (taicpu(hp1).oper[0]^.val >= 8) then
  9886. begin
  9887. TryShiftDown := S_B;
  9888. TryShiftDownLimit := $FF;
  9889. TryShiftDownSignedLimit := $7F;
  9890. TryShiftDownSignedLimitLower := -128;
  9891. end;
  9892. S_L:
  9893. if (taicpu(hp1).oper[0]^.val >= 24) then
  9894. begin
  9895. TryShiftDown := S_B;
  9896. TryShiftDownLimit := $FF;
  9897. TryShiftDownSignedLimit := $7F;
  9898. TryShiftDownSignedLimitLower := -128;
  9899. end
  9900. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9901. begin
  9902. TryShiftDown := S_W;
  9903. TryShiftDownLimit := $FFFF;
  9904. TryShiftDownSignedLimit := $7FFF;
  9905. TryShiftDownSignedLimitLower := -32768;
  9906. end;
  9907. else
  9908. InternalError(2020112321);
  9909. end;
  9910. WorkingValue := taicpu(hp1).oper[0]^.val;
  9911. if taicpu(hp1).opcode = A_SAR then
  9912. begin
  9913. TestValMin := SarInt64(TestValMin, WorkingValue);
  9914. TestValMax := SarInt64(TestValMax, WorkingValue);
  9915. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9916. end
  9917. else
  9918. begin
  9919. TestValMin := TestValMin shr WorkingValue;
  9920. TestValMax := TestValMax shr WorkingValue;
  9921. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9922. end;
  9923. end;
  9924. else
  9925. InternalError(2020112303);
  9926. end;
  9927. end;
  9928. (*
  9929. A_IMUL:
  9930. case taicpu(hp1).ops of
  9931. 2:
  9932. begin
  9933. if not MatchOpType(hp1, top_reg, top_reg) or
  9934. { Has to be an exact match on the register }
  9935. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9936. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9937. Break;
  9938. TestValMin := TestValMin * TestValMin;
  9939. TestValMax := TestValMax * TestValMax;
  9940. TestValSignedMax := TestValSignedMax * TestValMax;
  9941. end;
  9942. 3:
  9943. begin
  9944. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9945. { Has to be an exact match on the register }
  9946. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9947. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9948. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9949. { Is it in the negative range? }
  9950. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9951. Break;
  9952. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9953. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9954. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9955. end;
  9956. else
  9957. Break;
  9958. end;
  9959. A_IDIV:
  9960. case taicpu(hp1).ops of
  9961. 3:
  9962. begin
  9963. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9964. { Has to be an exact match on the register }
  9965. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9966. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9967. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9968. { Is it in the negative range? }
  9969. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9970. Break;
  9971. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9972. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9973. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9974. end;
  9975. else
  9976. Break;
  9977. end;
  9978. *)
  9979. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9980. begin
  9981. { If there are no instructions in between, then we might be able to make a saving }
  9982. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9983. Break;
  9984. { We have something like:
  9985. movzbw %dl,%dx
  9986. ...
  9987. movswl %dx,%edx
  9988. Change the latter to a zero-extension then enter the
  9989. A_MOVZX case branch.
  9990. }
  9991. {$ifdef x86_64}
  9992. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9993. begin
  9994. { this becomes a zero extension from 32-bit to 64-bit, but
  9995. the upper 32 bits are already zero, so just delete the
  9996. instruction }
  9997. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9998. RemoveInstruction(hp1);
  9999. Result := True;
  10000. Exit;
  10001. end
  10002. else
  10003. {$endif x86_64}
  10004. begin
  10005. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10006. taicpu(hp1).opcode := A_MOVZX;
  10007. {$ifdef x86_64}
  10008. case taicpu(hp1).opsize of
  10009. S_BQ:
  10010. begin
  10011. taicpu(hp1).opsize := S_BL;
  10012. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10013. end;
  10014. S_WQ:
  10015. begin
  10016. taicpu(hp1).opsize := S_WL;
  10017. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10018. end;
  10019. S_LQ:
  10020. begin
  10021. taicpu(hp1).opcode := A_MOV;
  10022. taicpu(hp1).opsize := S_L;
  10023. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10024. { In this instance, we need to break out because the
  10025. instruction is no longer MOVZX or MOVSXD }
  10026. Result := True;
  10027. Exit;
  10028. end;
  10029. else
  10030. ;
  10031. end;
  10032. {$endif x86_64}
  10033. Result := CompressInstructions;
  10034. Exit;
  10035. end;
  10036. end;
  10037. A_MOVZX:
  10038. begin
  10039. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10040. Break;
  10041. if (InstrMax = -1) then
  10042. begin
  10043. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10044. begin
  10045. { Optimise around i40003 }
  10046. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10047. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10048. {$ifndef x86_64}
  10049. and (
  10050. (taicpu(p).oper[0]^.typ <> top_reg) or
  10051. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10052. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10053. )
  10054. {$endif not x86_64}
  10055. then
  10056. begin
  10057. if (taicpu(p).oper[0]^.typ = top_reg) then
  10058. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10059. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10060. taicpu(p).opsize := S_BL;
  10061. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10062. RemoveInstruction(hp1);
  10063. Result := True;
  10064. Exit;
  10065. end;
  10066. end
  10067. else
  10068. begin
  10069. { Will return false if the second parameter isn't ThisReg
  10070. (can happen on -O2 and under) }
  10071. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10072. begin
  10073. { The two MOVZX instructions are adjacent, so remove the first one }
  10074. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10075. RemoveCurrentP(p);
  10076. Result := True;
  10077. Exit;
  10078. end;
  10079. Break;
  10080. end;
  10081. end;
  10082. Result := CompressInstructions;
  10083. Exit;
  10084. end;
  10085. else
  10086. { This includes ADC, SBB and IDIV }
  10087. Break;
  10088. end;
  10089. if not CheckOverflowConditions then
  10090. Break;
  10091. { Contains highest index (so instruction count - 1) }
  10092. Inc(InstrMax);
  10093. if InstrMax > High(InstrList) then
  10094. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10095. InstrList[InstrMax] := taicpu(hp1);
  10096. end;
  10097. end;
  10098. {$pop}
  10099. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10100. var
  10101. hp1 : tai;
  10102. begin
  10103. Result:=false;
  10104. if (taicpu(p).ops >= 2) and
  10105. ((taicpu(p).oper[0]^.typ = top_const) or
  10106. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10107. (taicpu(p).oper[1]^.typ = top_reg) and
  10108. ((taicpu(p).ops = 2) or
  10109. ((taicpu(p).oper[2]^.typ = top_reg) and
  10110. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10111. GetLastInstruction(p,hp1) and
  10112. MatchInstruction(hp1,A_MOV,[]) and
  10113. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10114. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10115. begin
  10116. TransferUsedRegs(TmpUsedRegs);
  10117. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10118. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10119. { change
  10120. mov reg1,reg2
  10121. imul y,reg2 to imul y,reg1,reg2 }
  10122. begin
  10123. taicpu(p).ops := 3;
  10124. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10125. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10126. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10127. RemoveInstruction(hp1);
  10128. result:=true;
  10129. end;
  10130. end;
  10131. end;
  10132. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10133. var
  10134. ThisLabel: TAsmLabel;
  10135. begin
  10136. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10137. ThisLabel.decrefs;
  10138. taicpu(p).condition := C_None;
  10139. taicpu(p).opcode := A_RET;
  10140. taicpu(p).is_jmp := false;
  10141. taicpu(p).ops := taicpu(ret_p).ops;
  10142. case taicpu(ret_p).ops of
  10143. 0:
  10144. taicpu(p).clearop(0);
  10145. 1:
  10146. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10147. else
  10148. internalerror(2016041301);
  10149. end;
  10150. { If the original label is now dead, it might turn out that the label
  10151. immediately follows p. As a result, everything beyond it, which will
  10152. be just some final register configuration and a RET instruction, is
  10153. now dead code. [Kit] }
  10154. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10155. running RemoveDeadCodeAfterJump for each RET instruction, because
  10156. this optimisation rarely happens and most RETs appear at the end of
  10157. routines where there is nothing that can be stripped. [Kit] }
  10158. if not ThisLabel.is_used then
  10159. RemoveDeadCodeAfterJump(p);
  10160. end;
  10161. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10162. var
  10163. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10164. Unconditional, PotentialModified: Boolean;
  10165. OperPtr: POper;
  10166. NewRef: TReference;
  10167. InstrList: array of taicpu;
  10168. InstrMax, Index: Integer;
  10169. const
  10170. {$ifdef DEBUG_AOPTCPU}
  10171. SNoFlags: shortstring = ' so the flags aren''t modified';
  10172. {$else DEBUG_AOPTCPU}
  10173. SNoFlags = '';
  10174. {$endif DEBUG_AOPTCPU}
  10175. begin
  10176. Result:=false;
  10177. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10178. begin
  10179. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10180. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10181. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10182. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10183. GetNextInstruction(hp1, hp2) and
  10184. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10185. { Change from: To:
  10186. set(C) %reg j(~C) label
  10187. test %reg,%reg/cmp $0,%reg
  10188. je label
  10189. set(C) %reg j(C) label
  10190. test %reg,%reg/cmp $0,%reg
  10191. jne label
  10192. (Also do something similar with sete/setne instead of je/jne)
  10193. }
  10194. begin
  10195. { Before we do anything else, we need to check the instructions
  10196. in between SETcc and TEST to make sure they don't modify the
  10197. FLAGS register - if -O2 or under, there won't be any
  10198. instructions between SET and TEST }
  10199. TransferUsedRegs(TmpUsedRegs);
  10200. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10201. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10202. begin
  10203. next := p;
  10204. SetLength(InstrList, 0);
  10205. InstrMax := -1;
  10206. PotentialModified := False;
  10207. { Make a note of every instruction that modifies the FLAGS
  10208. register }
  10209. while GetNextInstruction(next, next) and (next <> hp1) do
  10210. begin
  10211. if next.typ <> ait_instruction then
  10212. { GetNextInstructionUsingReg should have returned False }
  10213. InternalError(2021051701);
  10214. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10215. begin
  10216. case taicpu(next).opcode of
  10217. A_SETcc,
  10218. A_CMOVcc,
  10219. A_Jcc:
  10220. begin
  10221. if PotentialModified then
  10222. { Not safe because the flags were modified earlier }
  10223. Exit
  10224. else
  10225. { Condition is the same as the initial SETcc, so this is safe
  10226. (don't add to instruction list though) }
  10227. Continue;
  10228. end;
  10229. A_ADD:
  10230. begin
  10231. if (taicpu(next).opsize = S_B) or
  10232. { LEA doesn't support 8-bit operands }
  10233. (taicpu(next).oper[1]^.typ <> top_reg) or
  10234. { Must write to a register }
  10235. (taicpu(next).oper[0]^.typ = top_ref) then
  10236. { Require a constant or a register }
  10237. Exit;
  10238. PotentialModified := True;
  10239. end;
  10240. A_SUB:
  10241. begin
  10242. if (taicpu(next).opsize = S_B) or
  10243. { LEA doesn't support 8-bit operands }
  10244. (taicpu(next).oper[1]^.typ <> top_reg) or
  10245. { Must write to a register }
  10246. (taicpu(next).oper[0]^.typ <> top_const) or
  10247. (taicpu(next).oper[0]^.val = $80000000) then
  10248. { Can't subtract a register with LEA - also
  10249. check that the value isn't -2^31, as this
  10250. can't be negated }
  10251. Exit;
  10252. PotentialModified := True;
  10253. end;
  10254. A_SAL,
  10255. A_SHL:
  10256. begin
  10257. if (taicpu(next).opsize = S_B) or
  10258. { LEA doesn't support 8-bit operands }
  10259. (taicpu(next).oper[1]^.typ <> top_reg) or
  10260. { Must write to a register }
  10261. (taicpu(next).oper[0]^.typ <> top_const) or
  10262. (taicpu(next).oper[0]^.val < 0) or
  10263. (taicpu(next).oper[0]^.val > 3) then
  10264. Exit;
  10265. PotentialModified := True;
  10266. end;
  10267. A_IMUL:
  10268. begin
  10269. if (taicpu(next).ops <> 3) or
  10270. (taicpu(next).oper[1]^.typ <> top_reg) or
  10271. { Must write to a register }
  10272. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10273. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10274. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10275. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10276. Exit
  10277. else
  10278. PotentialModified := True;
  10279. end;
  10280. else
  10281. { Don't know how to change this, so abort }
  10282. Exit;
  10283. end;
  10284. { Contains highest index (so instruction count - 1) }
  10285. Inc(InstrMax);
  10286. if InstrMax > High(InstrList) then
  10287. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10288. InstrList[InstrMax] := taicpu(next);
  10289. end;
  10290. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10291. end;
  10292. if not Assigned(next) or (next <> hp1) then
  10293. { It should be equal to hp1 }
  10294. InternalError(2021051702);
  10295. { Cycle through each instruction and check to see if we can
  10296. change them to versions that don't modify the flags }
  10297. if (InstrMax >= 0) then
  10298. begin
  10299. for Index := 0 to InstrMax do
  10300. case InstrList[Index].opcode of
  10301. A_ADD:
  10302. begin
  10303. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10304. InstrList[Index].opcode := A_LEA;
  10305. reference_reset(NewRef, 1, []);
  10306. NewRef.base := InstrList[Index].oper[1]^.reg;
  10307. if InstrList[Index].oper[0]^.typ = top_reg then
  10308. begin
  10309. NewRef.index := InstrList[Index].oper[0]^.reg;
  10310. NewRef.scalefactor := 1;
  10311. end
  10312. else
  10313. NewRef.offset := InstrList[Index].oper[0]^.val;
  10314. InstrList[Index].loadref(0, NewRef);
  10315. end;
  10316. A_SUB:
  10317. begin
  10318. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10319. InstrList[Index].opcode := A_LEA;
  10320. reference_reset(NewRef, 1, []);
  10321. NewRef.base := InstrList[Index].oper[1]^.reg;
  10322. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10323. InstrList[Index].loadref(0, NewRef);
  10324. end;
  10325. A_SHL,
  10326. A_SAL:
  10327. begin
  10328. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10329. InstrList[Index].opcode := A_LEA;
  10330. reference_reset(NewRef, 1, []);
  10331. NewRef.index := InstrList[Index].oper[1]^.reg;
  10332. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10333. InstrList[Index].loadref(0, NewRef);
  10334. end;
  10335. A_IMUL:
  10336. begin
  10337. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10338. InstrList[Index].opcode := A_LEA;
  10339. reference_reset(NewRef, 1, []);
  10340. NewRef.index := InstrList[Index].oper[1]^.reg;
  10341. case InstrList[Index].oper[0]^.val of
  10342. 2, 4, 8:
  10343. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10344. else {3, 5 and 9}
  10345. begin
  10346. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10347. NewRef.base := InstrList[Index].oper[1]^.reg;
  10348. end;
  10349. end;
  10350. InstrList[Index].loadref(0, NewRef);
  10351. end;
  10352. else
  10353. InternalError(2021051710);
  10354. end;
  10355. end;
  10356. { Mark the FLAGS register as used across this whole block }
  10357. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10358. end;
  10359. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10360. JumpC := taicpu(hp2).condition;
  10361. Unconditional := False;
  10362. if conditions_equal(JumpC, C_E) then
  10363. SetC := inverse_cond(taicpu(p).condition)
  10364. else if conditions_equal(JumpC, C_NE) then
  10365. SetC := taicpu(p).condition
  10366. else
  10367. { We've got something weird here (and inefficent) }
  10368. begin
  10369. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10370. SetC := C_NONE;
  10371. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10372. if condition_in(C_AE, JumpC) then
  10373. Unconditional := True
  10374. else
  10375. { Not sure what to do with this jump - drop out }
  10376. Exit;
  10377. end;
  10378. RemoveInstruction(hp1);
  10379. if Unconditional then
  10380. MakeUnconditional(taicpu(hp2))
  10381. else
  10382. begin
  10383. if SetC = C_NONE then
  10384. InternalError(2018061402);
  10385. taicpu(hp2).SetCondition(SetC);
  10386. end;
  10387. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10388. TmpUsedRegs }
  10389. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10390. begin
  10391. RemoveCurrentp(p, hp2);
  10392. if taicpu(hp2).opcode = A_SETcc then
  10393. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10394. else
  10395. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10396. end
  10397. else
  10398. if taicpu(hp2).opcode = A_SETcc then
  10399. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10400. else
  10401. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10402. Result := True;
  10403. end
  10404. else if
  10405. { Make sure the instructions are adjacent }
  10406. (
  10407. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10408. GetNextInstruction(p, hp1)
  10409. ) and
  10410. MatchInstruction(hp1, A_MOV, [S_B]) and
  10411. { Writing to memory is allowed }
  10412. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10413. begin
  10414. {
  10415. Watch out for sequences such as:
  10416. set(c)b %regb
  10417. movb %regb,(ref)
  10418. movb $0,1(ref)
  10419. movb $0,2(ref)
  10420. movb $0,3(ref)
  10421. Much more efficient to turn it into:
  10422. movl $0,%regl
  10423. set(c)b %regb
  10424. movl %regl,(ref)
  10425. Or:
  10426. set(c)b %regb
  10427. movzbl %regb,%regl
  10428. movl %regl,(ref)
  10429. }
  10430. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10431. GetNextInstruction(hp1, hp2) and
  10432. MatchInstruction(hp2, A_MOV, [S_B]) and
  10433. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10434. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10435. begin
  10436. { Don't do anything else except set Result to True }
  10437. end
  10438. else
  10439. begin
  10440. if taicpu(p).oper[0]^.typ = top_reg then
  10441. begin
  10442. TransferUsedRegs(TmpUsedRegs);
  10443. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10444. end;
  10445. { If it's not a register, it's a memory address }
  10446. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10447. begin
  10448. { Even if the register is still in use, we can minimise the
  10449. pipeline stall by changing the MOV into another SETcc. }
  10450. taicpu(hp1).opcode := A_SETcc;
  10451. taicpu(hp1).condition := taicpu(p).condition;
  10452. if taicpu(hp1).oper[1]^.typ = top_ref then
  10453. begin
  10454. { Swapping the operand pointers like this is probably a
  10455. bit naughty, but it is far faster than using loadoper
  10456. to transfer the reference from oper[1] to oper[0] if
  10457. you take into account the extra procedure calls and
  10458. the memory allocation and deallocation required }
  10459. OperPtr := taicpu(hp1).oper[1];
  10460. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10461. taicpu(hp1).oper[0] := OperPtr;
  10462. end
  10463. else
  10464. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10465. taicpu(hp1).clearop(1);
  10466. taicpu(hp1).ops := 1;
  10467. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10468. end
  10469. else
  10470. begin
  10471. if taicpu(hp1).oper[1]^.typ = top_reg then
  10472. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10473. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10474. RemoveInstruction(hp1);
  10475. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10476. end
  10477. end;
  10478. Result := True;
  10479. end;
  10480. end;
  10481. end;
  10482. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10483. var
  10484. hp1: tai;
  10485. Count: Integer;
  10486. OrigLabel: TAsmLabel;
  10487. begin
  10488. result := False;
  10489. { Sometimes, the optimisations below can permit this }
  10490. RemoveDeadCodeAfterJump(p);
  10491. 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
  10492. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10493. begin
  10494. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10495. { Also a side-effect of optimisations }
  10496. if CollapseZeroDistJump(p, OrigLabel) then
  10497. begin
  10498. Result := True;
  10499. Exit;
  10500. end;
  10501. hp1 := GetLabelWithSym(OrigLabel);
  10502. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10503. begin
  10504. if taicpu(hp1).opcode = A_RET then
  10505. begin
  10506. {
  10507. change
  10508. jmp .L1
  10509. ...
  10510. .L1:
  10511. ret
  10512. into
  10513. ret
  10514. }
  10515. begin
  10516. ConvertJumpToRET(p, hp1);
  10517. result:=true;
  10518. end;
  10519. end
  10520. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10521. not (cs_opt_size in current_settings.optimizerswitches) and
  10522. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10523. begin
  10524. Result := True;
  10525. Exit;
  10526. end;
  10527. end;
  10528. end;
  10529. end;
  10530. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10531. begin
  10532. Result := assigned(p) and
  10533. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10534. (taicpu(p).oper[1]^.typ = top_reg) and
  10535. (
  10536. (taicpu(p).oper[0]^.typ = top_reg) or
  10537. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10538. it is not expected that this can cause a seg. violation }
  10539. (
  10540. (taicpu(p).oper[0]^.typ = top_ref) and
  10541. { TODO: Can we detect which references become constants at this
  10542. stage so we don't have to do a blanket ban? }
  10543. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10544. (
  10545. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10546. (
  10547. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10548. not RefModified and
  10549. { If the reference also appears in the condition, then we know it's safe, otherwise
  10550. any kind of access violation would have occurred already }
  10551. Assigned(cond_p) and
  10552. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10553. (cond_p.typ = ait_instruction) and
  10554. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10555. { Just consider 2-operand comparison instructions for now to be safe }
  10556. (taicpu(cond_p).ops = 2) and
  10557. (
  10558. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10559. (
  10560. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10561. { Don't risk identical registers but different offsets, as we may have constructs
  10562. such as buffer streams with things like length fields that indicate whether
  10563. any more data follows. And there are probably some contrived examples where
  10564. writing to offsets behind the one being read also lead to access violations }
  10565. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10566. (
  10567. { Check that we're not modifying a register that appears in the reference }
  10568. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10569. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10570. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10571. )
  10572. )
  10573. )
  10574. )
  10575. )
  10576. )
  10577. );
  10578. end;
  10579. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10580. begin
  10581. { Update integer registers, ignoring deallocations }
  10582. repeat
  10583. while assigned(p) and
  10584. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10585. (p.typ = ait_label) or
  10586. ((p.typ = ait_marker) and
  10587. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10588. p := tai(p.next);
  10589. while assigned(p) and
  10590. (p.typ=ait_RegAlloc) Do
  10591. begin
  10592. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10593. begin
  10594. case tai_regalloc(p).ratype of
  10595. ra_alloc :
  10596. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10597. else
  10598. ;
  10599. end;
  10600. end;
  10601. p := tai(p.next);
  10602. end;
  10603. until not(assigned(p)) or
  10604. (not(p.typ in SkipInstr) and
  10605. not((p.typ = ait_label) and
  10606. labelCanBeSkipped(tai_label(p))));
  10607. end;
  10608. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10609. var
  10610. hp1,hp2: tai;
  10611. carryadd_opcode : TAsmOp;
  10612. symbol: TAsmSymbol;
  10613. increg, tmpreg: TRegister;
  10614. RefModified: Boolean;
  10615. {$ifndef i8086}
  10616. { Code and variables specific to CMOV optimisations }
  10617. hp3,hp4,hp5,
  10618. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10619. l, c, w, x : Longint;
  10620. condition, second_condition : TAsmCond;
  10621. FoundMatchingJump, RegMatch: Boolean;
  10622. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10623. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10624. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10625. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10626. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10627. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10628. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10629. new register to store the constant }
  10630. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10631. var
  10632. RegSize: TSubRegister;
  10633. CurrentVal: TCGInt;
  10634. ANewReg: TRegister;
  10635. X: ShortInt;
  10636. begin
  10637. Result := False;
  10638. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10639. Exit;
  10640. if StoredCount >= MAX_CMOV_REGISTERS then
  10641. { Arrays are full }
  10642. Exit;
  10643. { Remember that CMOV can't encode 8-bit registers }
  10644. case taicpu(p).opsize of
  10645. S_W:
  10646. RegSize := R_SUBW;
  10647. S_L:
  10648. RegSize := R_SUBD;
  10649. {$ifdef x86_64}
  10650. S_Q:
  10651. RegSize := R_SUBQ;
  10652. {$endif x86_64}
  10653. else
  10654. InternalError(2021100401);
  10655. end;
  10656. { See if the value has already been reserved for another CMOV instruction }
  10657. CurrentVal := taicpu(p).oper[0]^.val;
  10658. for X := 0 to StoredCount - 1 do
  10659. if ConstVals[X] = CurrentVal then
  10660. begin
  10661. ConstRegs[StoredCount] := ConstRegs[X];
  10662. ConstSizes[StoredCount] := RegSize;
  10663. ConstVals[StoredCount] := CurrentVal;
  10664. Result := True;
  10665. Inc(StoredCount);
  10666. { Don't increase CMOVCount this time, since we're re-using a register }
  10667. Exit;
  10668. end;
  10669. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10670. if ANewReg = NR_NO then
  10671. { No free registers }
  10672. Exit;
  10673. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10674. up vying for the same register }
  10675. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10676. ConstRegs[StoredCount] := ANewReg;
  10677. ConstSizes[StoredCount] := RegSize;
  10678. ConstVals[StoredCount] := CurrentVal;
  10679. Inc(StoredCount);
  10680. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10681. MOV required adds complexity and will cause diminishing returns
  10682. sooner than normal. This is more of an approximate weighting than
  10683. anything else. }
  10684. Inc(CMOVCount);
  10685. Result := True;
  10686. end;
  10687. {$endif i8086}
  10688. begin
  10689. result:=false;
  10690. if GetNextInstruction(p,hp1) then
  10691. begin
  10692. if (hp1.typ=ait_label) then
  10693. begin
  10694. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10695. Exit;
  10696. end
  10697. else if (hp1.typ<>ait_instruction) then
  10698. Exit;
  10699. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10700. if (
  10701. (
  10702. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10703. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10704. (Taicpu(hp1).oper[0]^.val=1)
  10705. ) or
  10706. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10707. ) and
  10708. GetNextInstruction(hp1,hp2) and
  10709. SkipAligns(hp2, hp2) and
  10710. (hp2.typ = ait_label) and
  10711. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10712. { jb @@1 cmc
  10713. inc/dec operand --> adc/sbb operand,0
  10714. @@1:
  10715. ... and ...
  10716. jnb @@1
  10717. inc/dec operand --> adc/sbb operand,0
  10718. @@1: }
  10719. begin
  10720. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10721. begin
  10722. case taicpu(hp1).opcode of
  10723. A_INC,
  10724. A_ADD:
  10725. carryadd_opcode:=A_ADC;
  10726. A_DEC,
  10727. A_SUB:
  10728. carryadd_opcode:=A_SBB;
  10729. else
  10730. InternalError(2021011001);
  10731. end;
  10732. Taicpu(p).clearop(0);
  10733. Taicpu(p).ops:=0;
  10734. Taicpu(p).is_jmp:=false;
  10735. Taicpu(p).opcode:=A_CMC;
  10736. Taicpu(p).condition:=C_NONE;
  10737. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10738. Taicpu(hp1).ops:=2;
  10739. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10740. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10741. else
  10742. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10743. Taicpu(hp1).loadconst(0,0);
  10744. Taicpu(hp1).opcode:=carryadd_opcode;
  10745. result:=true;
  10746. exit;
  10747. end
  10748. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10749. begin
  10750. case taicpu(hp1).opcode of
  10751. A_INC,
  10752. A_ADD:
  10753. carryadd_opcode:=A_ADC;
  10754. A_DEC,
  10755. A_SUB:
  10756. carryadd_opcode:=A_SBB;
  10757. else
  10758. InternalError(2021011002);
  10759. end;
  10760. Taicpu(hp1).ops:=2;
  10761. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10762. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10763. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10764. else
  10765. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10766. Taicpu(hp1).loadconst(0,0);
  10767. Taicpu(hp1).opcode:=carryadd_opcode;
  10768. RemoveCurrentP(p, hp1);
  10769. result:=true;
  10770. exit;
  10771. end
  10772. {
  10773. jcc @@1 setcc tmpreg
  10774. inc/dec/add/sub operand -> (movzx tmpreg)
  10775. @@1: add/sub tmpreg,operand
  10776. While this increases code size slightly, it makes the code much faster if the
  10777. jump is unpredictable
  10778. }
  10779. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10780. begin
  10781. { search for an available register which is volatile }
  10782. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10783. if increg <> NR_NO then
  10784. begin
  10785. { We don't need to check if tmpreg is in hp1 or not, because
  10786. it will be marked as in use at p (if not, this is
  10787. indictive of a compiler bug). }
  10788. TAsmLabel(symbol).decrefs;
  10789. Taicpu(p).clearop(0);
  10790. Taicpu(p).ops:=1;
  10791. Taicpu(p).is_jmp:=false;
  10792. Taicpu(p).opcode:=A_SETcc;
  10793. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10794. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10795. Taicpu(p).loadreg(0,increg);
  10796. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10797. begin
  10798. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10799. R_SUBW:
  10800. begin
  10801. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10802. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10803. end;
  10804. R_SUBD:
  10805. begin
  10806. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10807. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10808. end;
  10809. {$ifdef x86_64}
  10810. R_SUBQ:
  10811. begin
  10812. { MOVZX doesn't have a 64-bit variant, because
  10813. the 32-bit version implicitly zeroes the
  10814. upper 32-bits of the destination register }
  10815. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10816. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10817. setsubreg(tmpreg, R_SUBQ);
  10818. end;
  10819. {$endif x86_64}
  10820. else
  10821. Internalerror(2020030601);
  10822. end;
  10823. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10824. asml.InsertAfter(hp2,p);
  10825. end
  10826. else
  10827. tmpreg := increg;
  10828. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10829. begin
  10830. Taicpu(hp1).ops:=2;
  10831. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10832. end;
  10833. Taicpu(hp1).loadreg(0,tmpreg);
  10834. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10835. Result := True;
  10836. { p is no longer a Jcc instruction, so exit }
  10837. Exit;
  10838. end;
  10839. end;
  10840. end;
  10841. { Detect the following:
  10842. jmp<cond> @Lbl1
  10843. jmp @Lbl2
  10844. ...
  10845. @Lbl1:
  10846. ret
  10847. Change to:
  10848. jmp<inv_cond> @Lbl2
  10849. ret
  10850. }
  10851. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10852. begin
  10853. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10854. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10855. MatchInstruction(hp2,A_RET,[S_NO]) then
  10856. begin
  10857. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10858. { Change label address to that of the unconditional jump }
  10859. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10860. TAsmLabel(symbol).DecRefs;
  10861. taicpu(hp1).opcode := A_RET;
  10862. taicpu(hp1).is_jmp := false;
  10863. taicpu(hp1).ops := taicpu(hp2).ops;
  10864. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10865. case taicpu(hp2).ops of
  10866. 0:
  10867. taicpu(hp1).clearop(0);
  10868. 1:
  10869. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10870. else
  10871. internalerror(2016041302);
  10872. end;
  10873. end;
  10874. {$ifndef i8086}
  10875. end
  10876. {
  10877. convert
  10878. j<c> .L1
  10879. mov 1,reg
  10880. jmp .L2
  10881. .L1
  10882. mov 0,reg
  10883. .L2
  10884. into
  10885. mov 0,reg
  10886. set<not(c)> reg
  10887. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10888. would destroy the flag contents
  10889. }
  10890. else if MatchInstruction(hp1,A_MOV,[]) and
  10891. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10892. {$ifdef i386}
  10893. (
  10894. { Under i386, ESI, EDI, EBP and ESP
  10895. don't have an 8-bit representation }
  10896. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10897. ) and
  10898. {$endif i386}
  10899. (taicpu(hp1).oper[0]^.val=1) and
  10900. GetNextInstruction(hp1,hp2) and
  10901. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10902. GetNextInstruction(hp2,hp3) and
  10903. { skip align }
  10904. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10905. (hp3.typ=ait_label) and
  10906. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10907. (tai_label(hp3).labsym.getrefs=1) and
  10908. GetNextInstruction(hp3,hp4) and
  10909. MatchInstruction(hp4,A_MOV,[]) and
  10910. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10911. (taicpu(hp4).oper[0]^.val=0) and
  10912. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10913. GetNextInstruction(hp4,hp5) and
  10914. (hp5.typ=ait_label) and
  10915. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10916. (tai_label(hp5).labsym.getrefs=1) then
  10917. begin
  10918. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10919. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10920. { remove last label }
  10921. RemoveInstruction(hp5);
  10922. { remove second label }
  10923. RemoveInstruction(hp3);
  10924. { if align is present remove it }
  10925. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10926. RemoveInstruction(hp3);
  10927. { remove jmp }
  10928. RemoveInstruction(hp2);
  10929. if taicpu(hp1).opsize=S_B then
  10930. RemoveInstruction(hp1)
  10931. else
  10932. taicpu(hp1).loadconst(0,0);
  10933. taicpu(hp4).opcode:=A_SETcc;
  10934. taicpu(hp4).opsize:=S_B;
  10935. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10936. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10937. taicpu(hp4).opercnt:=1;
  10938. taicpu(hp4).ops:=1;
  10939. taicpu(hp4).freeop(1);
  10940. RemoveCurrentP(p);
  10941. Result:=true;
  10942. exit;
  10943. end
  10944. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10945. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10946. begin
  10947. { check for
  10948. jCC xxx
  10949. <several movs>
  10950. xxx:
  10951. Also spot:
  10952. Jcc xxx
  10953. <several movs>
  10954. jmp xxx
  10955. Change to:
  10956. <several cmovs with inverted condition>
  10957. jmp xxx (only for the 2nd case)
  10958. }
  10959. hp2 := p;
  10960. hp_lblxxx := hp1;
  10961. hp_flagalloc := nil;
  10962. hp_stop := nil;
  10963. FoundMatchingJump := False;
  10964. { Remember the first instruction in the first block of MOVs }
  10965. hpmov1 := hp1;
  10966. TransferUsedRegs(TmpUsedRegs);
  10967. while assigned(hp_lblxxx) and
  10968. { stop on labels }
  10969. (hp_lblxxx.typ <> ait_label) do
  10970. begin
  10971. { Keep track of all integer registers that are used }
  10972. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10973. if hp_lblxxx.typ = ait_instruction then
  10974. begin
  10975. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10976. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10977. begin
  10978. hp_stop := hp_lblxxx;
  10979. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10980. begin
  10981. { We found Jcc xxx; <several movs>; Jmp xxx }
  10982. FoundMatchingJump := True;
  10983. Break;
  10984. end;
  10985. { If it's not the jump we're looking for, it's
  10986. possibly the "if..else" variant }
  10987. end
  10988. { Check to see if we have a valid MOV instruction instead }
  10989. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10990. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10991. Break
  10992. else
  10993. { This will be a valid MOV }
  10994. hp_stop := hp_lblxxx;
  10995. end;
  10996. hp2 := hp_lblxxx;
  10997. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10998. end;
  10999. { Just make sure the last MOV is included if there's no jump }
  11000. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11001. hp_stop := hp_lblxxx;
  11002. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11003. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11004. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11005. jmp yyy; xxx:; movs; yyy:" variation }
  11006. if assigned(hp_lblxxx) and
  11007. (
  11008. { If we found JMP xxx, we don't actually need a label
  11009. (hp_lblxxx is the JMP instruction instead) }
  11010. FoundMatchingJump or
  11011. { Make sure we actually have the right label }
  11012. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11013. ) then
  11014. begin
  11015. { Use TmpUsedRegs to track registers that we reserve }
  11016. { When allocating temporary registers, try to look one
  11017. instruction back, as defining them before a CMP or TEST
  11018. instruction will be faster, and also avoid picking a
  11019. register that was only just deallocated }
  11020. if GetLastInstruction(p, hp_prev) and
  11021. 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
  11022. begin
  11023. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11024. for l := 0 to 1 do
  11025. with taicpu(hp_prev).oper[l]^ do
  11026. case typ of
  11027. top_reg:
  11028. if getregtype(reg) = R_INTREGISTER then
  11029. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11030. top_ref:
  11031. begin
  11032. if
  11033. {$ifdef x86_64}
  11034. (ref^.base <> NR_RIP) and
  11035. {$endif x86_64}
  11036. (ref^.base <> NR_NO) then
  11037. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11038. if (ref^.index <> NR_NO) then
  11039. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11040. end
  11041. else
  11042. ;
  11043. end;
  11044. { When inserting instructions before hp_prev, try to insert
  11045. them before the allocation of the FLAGS register }
  11046. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11047. { If not found, set it equal to hp_prev so it's something sensible }
  11048. hp_flagalloc := hp_prev;
  11049. hp_prev2 := nil;
  11050. { When dealing with a comparison against zero, take
  11051. note of the instruction before it to see if we can
  11052. move instructions further back in order to benefit
  11053. PostPeepholeOptTestOr.
  11054. }
  11055. if (
  11056. (
  11057. (taicpu(hp_prev).opcode = A_CMP) and
  11058. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11059. ) or
  11060. (
  11061. (taicpu(hp_prev).opcode = A_TEST) and
  11062. (
  11063. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11064. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11065. )
  11066. )
  11067. ) and
  11068. GetLastInstruction(hp_prev, hp_prev2) then
  11069. begin
  11070. if (hp_prev2.typ = ait_instruction) and
  11071. { These instructions set the zero flag if the result is zero }
  11072. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11073. begin
  11074. { Also mark all the registers in this previous instruction
  11075. as 'in use', even if they've just been deallocated }
  11076. for l := 0 to 1 do
  11077. with taicpu(hp_prev2).oper[l]^ do
  11078. case typ of
  11079. top_reg:
  11080. if getregtype(reg) = R_INTREGISTER then
  11081. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11082. top_ref:
  11083. begin
  11084. if
  11085. {$ifdef x86_64}
  11086. (ref^.base <> NR_RIP) and
  11087. {$endif x86_64}
  11088. (ref^.base <> NR_NO) then
  11089. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11090. if (ref^.index <> NR_NO) then
  11091. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11092. end
  11093. else
  11094. ;
  11095. end;
  11096. end
  11097. else
  11098. { Unsuitable instruction }
  11099. hp_prev2 := nil;
  11100. end;
  11101. end
  11102. else
  11103. begin
  11104. hp_prev := p;
  11105. { When inserting instructions before hp_prev, try to insert
  11106. them before the allocation of the FLAGS register }
  11107. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11108. { If not found, set it equal to p so it's something sensible }
  11109. hp_flagalloc := p;
  11110. hp_prev2 := nil;
  11111. end;
  11112. l := 0;
  11113. c := 0;
  11114. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11115. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11116. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11117. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11118. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11119. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11120. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11121. RefModified := False;
  11122. while assigned(hp1) and
  11123. { Stop on the label we found }
  11124. (hp1 <> hp_lblxxx) do
  11125. begin
  11126. case hp1.typ of
  11127. ait_instruction:
  11128. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11129. begin
  11130. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11131. begin
  11132. Inc(l);
  11133. { MOV instruction will be writing to a register }
  11134. if Assigned(hp_prev) and
  11135. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11136. (hp_prev.typ = ait_instruction) and
  11137. (taicpu(hp_prev).ops = 2) and
  11138. (
  11139. (
  11140. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11141. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11142. ) or
  11143. (
  11144. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11145. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11146. )
  11147. ) then
  11148. { It is no longer safe to use the reference in the condition.
  11149. this prevents problems such as:
  11150. mov (%reg),%reg
  11151. mov (%reg),...
  11152. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11153. (fixes #40165)
  11154. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11155. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11156. }
  11157. RefModified := True;
  11158. end
  11159. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11160. { CMOV with constants grows the code size }
  11161. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11162. begin
  11163. { Register was reserved by TryCMOVConst and
  11164. stored on ConstRegs[c] }
  11165. end
  11166. else
  11167. Break;
  11168. end
  11169. else
  11170. Break;
  11171. else
  11172. ;
  11173. end;
  11174. GetNextInstruction(hp1,hp1);
  11175. end;
  11176. if (hp1 = hp_lblxxx) then
  11177. begin
  11178. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11179. begin
  11180. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11181. TmpUsedRegs[R_INTREGISTER].Clear;
  11182. x := 0;
  11183. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11184. condition := inverse_cond(taicpu(p).condition);
  11185. UpdateUsedRegs(tai(p.next));
  11186. hp1 := hpmov1;
  11187. repeat
  11188. if not Assigned(hp1) then
  11189. InternalError(2018062900);
  11190. if (hp1.typ = ait_instruction) then
  11191. begin
  11192. { Extra safeguard }
  11193. if (taicpu(hp1).opcode <> A_MOV) then
  11194. InternalError(2018062901);
  11195. if taicpu(hp1).oper[0]^.typ = top_const then
  11196. begin
  11197. if x >= MAX_CMOV_REGISTERS then
  11198. InternalError(2021100410);
  11199. { If it's in TmpUsedRegs, then this register
  11200. is being used more than once and hence has
  11201. already had its value defined (it gets
  11202. added to UsedRegs through AllocRegBetween
  11203. below) }
  11204. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11205. begin
  11206. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11207. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11208. asml.InsertBefore(hp_new, hp_flagalloc);
  11209. if Assigned(hp_prev2) then
  11210. TrySwapMovOp(hp_prev2, hp_new);
  11211. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11212. ConstMovs[X] := hp_new;
  11213. end
  11214. else
  11215. { We just need an instruction between hp_prev and hp1
  11216. where we know the register is marked as in use }
  11217. hp_new := hpmov1;
  11218. { Keep track of largest write for this register so it can be optimised later }
  11219. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11220. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11221. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11222. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11223. Inc(x);
  11224. end;
  11225. taicpu(hp1).opcode := A_CMOVcc;
  11226. taicpu(hp1).condition := condition;
  11227. end;
  11228. UpdateUsedRegs(tai(hp1.next));
  11229. GetNextInstruction(hp1, hp1);
  11230. until (hp1 = hp_lblxxx);
  11231. { Update initialisation MOVs to the smallest possible size }
  11232. for c := 0 to x - 1 do
  11233. if Assigned(ConstMovs[c]) then
  11234. begin
  11235. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11236. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11237. end;
  11238. hp2 := hp_lblxxx;
  11239. repeat
  11240. if not Assigned(hp2) then
  11241. InternalError(2018062910);
  11242. case hp2.typ of
  11243. ait_label:
  11244. { What we expected - break out of the loop (it won't be a dead label at the top of
  11245. a cluster because that was optimised at an earlier stage) }
  11246. Break;
  11247. ait_align:
  11248. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11249. begin
  11250. hp2 := tai(hp2.Next);
  11251. Continue;
  11252. end;
  11253. ait_instruction:
  11254. begin
  11255. if taicpu(hp2).opcode<>A_JMP then
  11256. InternalError(2018062912);
  11257. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11258. Break;
  11259. end
  11260. else
  11261. begin
  11262. { Might be a comment or temporary allocation entry }
  11263. if not (hp2.typ in SkipInstr) then
  11264. InternalError(2018062911);
  11265. hp2 := tai(hp2.Next);
  11266. Continue;
  11267. end;
  11268. end;
  11269. until False;
  11270. { Now we can safely decrement the reference count }
  11271. tasmlabel(symbol).decrefs;
  11272. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11273. { Remove the original jump }
  11274. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11275. if hp2.typ=ait_instruction then
  11276. begin
  11277. p := hp2;
  11278. Result := True;
  11279. end
  11280. else
  11281. begin
  11282. UpdateUsedRegs(tai(hp2.next));
  11283. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11284. { Remove the label if this is its final reference }
  11285. if (tasmlabel(symbol).getrefs=0) then
  11286. begin
  11287. { Make sure the aligns get stripped too }
  11288. hp1 := tai(hp_lblxxx.Previous);
  11289. while Assigned(hp1) and (hp1.typ = ait_align) do
  11290. begin
  11291. hp_lblxxx := hp1;
  11292. hp1 := tai(hp_lblxxx.Previous);
  11293. end;
  11294. StripLabelFast(hp_lblxxx);
  11295. end;
  11296. end;
  11297. Exit;
  11298. end;
  11299. end
  11300. else if assigned(hp_lblxxx) and
  11301. { check further for
  11302. jCC xxx
  11303. <several movs 1>
  11304. jmp yyy
  11305. xxx:
  11306. <several movs 2>
  11307. yyy:
  11308. }
  11309. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11310. { hp1 should be pointing to jmp yyy }
  11311. MatchInstruction(hp1, A_JMP, []) and
  11312. { real label and jump, no further references to the
  11313. label are allowed }
  11314. (TAsmLabel(symbol).getrefs=1) and
  11315. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11316. begin
  11317. hp_jump := hp1;
  11318. { Don't set c to zero }
  11319. l := 0;
  11320. w := 0;
  11321. GetNextInstruction(hp_lblxxx, hpmov2);
  11322. hp2 := hp_lblxxx;
  11323. hp_lblyyy := hpmov2;
  11324. while assigned(hp_lblyyy) and
  11325. { stop on labels }
  11326. (hp_lblyyy.typ <> ait_label) do
  11327. begin
  11328. { Keep track of all integer registers that are used }
  11329. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11330. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11331. Break;
  11332. hp2 := hp_lblyyy;
  11333. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11334. end;
  11335. { Analyse the second batch of MOVs to see if the setup is valid }
  11336. RefModified := False;
  11337. hp1 := hpmov2;
  11338. while assigned(hp1) and
  11339. (hp1 <> hp_lblyyy) do
  11340. begin
  11341. case hp1.typ of
  11342. ait_instruction:
  11343. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11344. begin
  11345. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11346. begin
  11347. Inc(l);
  11348. { MOV instruction will be writing to a register }
  11349. if Assigned(hp_prev) and
  11350. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11351. (hp_prev.typ = ait_instruction) and
  11352. (taicpu(hp_prev).ops = 2) and
  11353. (
  11354. (
  11355. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11356. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11357. ) or
  11358. (
  11359. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11360. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11361. )
  11362. ) then
  11363. { It is no longer safe to use the reference in the condition.
  11364. this prevents problems such as:
  11365. mov (%reg),%reg
  11366. mov (%reg),...
  11367. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11368. (fixes #40165)
  11369. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11370. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11371. }
  11372. RefModified := True;
  11373. end
  11374. else if not (cs_opt_size in current_settings.optimizerswitches)
  11375. { CMOV with constants grows the code size }
  11376. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11377. begin
  11378. { Register was reserved by TryCMOVConst and
  11379. stored on ConstRegs[c] }
  11380. end
  11381. else
  11382. Break;
  11383. end
  11384. else
  11385. Break;
  11386. else
  11387. ;
  11388. end;
  11389. GetNextInstruction(hp1,hp1);
  11390. end;
  11391. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11392. TmpUsedRegs[R_INTREGISTER].Clear;
  11393. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11394. (hp1 = hp_lblyyy) and
  11395. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11396. begin
  11397. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11398. second_condition := taicpu(p).condition;
  11399. condition := inverse_cond(taicpu(p).condition);
  11400. UpdateUsedRegs(tai(p.next));
  11401. { Scan through the first set of MOVs to update UsedRegs,
  11402. but don't process them yet }
  11403. hp1 := hpmov1;
  11404. repeat
  11405. if not Assigned(hp1) then
  11406. InternalError(2018062901);
  11407. UpdateUsedRegs(tai(hp1.next));
  11408. GetNextInstruction(hp1, hp1);
  11409. until (hp1 = hp_lblxxx);
  11410. UpdateUsedRegs(tai(hp_lblxxx.next));
  11411. { Process the second set of MOVs first,
  11412. because if a destination register is
  11413. shared between the first and second MOV
  11414. sets, it is more efficient to turn the
  11415. first one into a MOV instruction and place
  11416. it before the CMP if possible, but we
  11417. won't know which registers are shared
  11418. until we've processed at least one list,
  11419. so we might as well make it the second
  11420. one since that won't be modified again. }
  11421. hp1 := hpmov2;
  11422. repeat
  11423. if not Assigned(hp1) then
  11424. InternalError(2018062902);
  11425. if (hp1.typ = ait_instruction) then
  11426. begin
  11427. { Extra safeguard }
  11428. if (taicpu(hp1).opcode <> A_MOV) then
  11429. InternalError(2018062903);
  11430. if taicpu(hp1).oper[0]^.typ = top_const then
  11431. begin
  11432. RegMatch := False;
  11433. for x := 0 to c - 1 do
  11434. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11435. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11436. begin
  11437. RegMatch := True;
  11438. { If it's in TmpUsedRegs, then this register
  11439. is being used more than once and hence has
  11440. already had its value defined (it gets
  11441. added to UsedRegs through AllocRegBetween
  11442. below) }
  11443. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11444. begin
  11445. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11446. asml.InsertBefore(hp_new, hp_flagalloc);
  11447. if Assigned(hp_prev2) then
  11448. TrySwapMovOp(hp_prev2, hp_new);
  11449. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11450. ConstMovs[X] := hp_new;
  11451. end
  11452. else
  11453. { We just need an instruction between hp_prev and hp1
  11454. where we know the register is marked as in use }
  11455. hp_new := hpmov2;
  11456. { Keep track of largest write for this register so it can be optimised later }
  11457. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11458. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11459. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11460. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11461. Break;
  11462. end;
  11463. if not RegMatch then
  11464. InternalError(2021100411);
  11465. end;
  11466. taicpu(hp1).opcode := A_CMOVcc;
  11467. taicpu(hp1).condition := second_condition;
  11468. { Store these writes to search for
  11469. duplicates later on }
  11470. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11471. Inc(w);
  11472. end;
  11473. UpdateUsedRegs(tai(hp1.next));
  11474. GetNextInstruction(hp1, hp1);
  11475. until (hp1 = hp_lblyyy);
  11476. { Now do the first set of MOVs }
  11477. hp1 := hpmov1;
  11478. repeat
  11479. if not Assigned(hp1) then
  11480. InternalError(2018062904);
  11481. if (hp1.typ = ait_instruction) then
  11482. begin
  11483. RegMatch := False;
  11484. { Extra safeguard }
  11485. if (taicpu(hp1).opcode <> A_MOV) then
  11486. InternalError(2018062905);
  11487. { Search through the RegWrites list to see
  11488. if there are any opposing CMOV pairs that
  11489. write to the same register }
  11490. for x := 0 to w - 1 do
  11491. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11492. begin
  11493. { We have a match. Keep this as a MOV }
  11494. { Move ahead in preparation }
  11495. GetNextInstruction(hp1, hp1);
  11496. RegMatch := True;
  11497. Break;
  11498. end;
  11499. if RegMatch then
  11500. Continue;
  11501. if taicpu(hp1).oper[0]^.typ = top_const then
  11502. begin
  11503. RegMatch := False;
  11504. for x := 0 to c - 1 do
  11505. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11506. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11507. begin
  11508. RegMatch := True;
  11509. { If it's in TmpUsedRegs, then this register
  11510. is being used more than once and hence has
  11511. already had its value defined (it gets
  11512. added to UsedRegs through AllocRegBetween
  11513. below) }
  11514. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11515. begin
  11516. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11517. asml.InsertBefore(hp_new, hp_flagalloc);
  11518. if Assigned(hp_prev2) then
  11519. TrySwapMovOp(hp_prev2, hp_new);
  11520. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11521. ConstMovs[X] := hp_new;
  11522. end
  11523. else
  11524. { We just need an instruction between hp_prev and hp1
  11525. where we know the register is marked as in use }
  11526. hp_new := hpmov1;
  11527. { Keep track of largest write for this register so it can be optimised later }
  11528. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11529. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11530. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11531. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11532. Break;
  11533. end;
  11534. if not RegMatch then
  11535. InternalError(2021100412);
  11536. end;
  11537. taicpu(hp1).opcode := A_CMOVcc;
  11538. taicpu(hp1).condition := condition;
  11539. end;
  11540. GetNextInstruction(hp1, hp1);
  11541. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11542. { Update initialisation MOVs to the smallest possible size }
  11543. for x := 0 to c - 1 do
  11544. if Assigned(ConstMovs[x]) then
  11545. begin
  11546. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11547. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11548. end;
  11549. UpdateUsedRegs(tai(hp_jump.next));
  11550. UpdateUsedRegs(tai(hp_lblyyy.next));
  11551. { Get first instruction after label }
  11552. hp1 := p;
  11553. GetNextInstruction(hp_lblyyy, p);
  11554. { Don't dereference yet, as doing so will cause
  11555. GetNextInstruction to skip the label and
  11556. optional align marker. [Kit] }
  11557. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11558. { remove Jcc }
  11559. RemoveInstruction(hp1);
  11560. { Now we can safely decrement it }
  11561. tasmlabel(symbol).decrefs;
  11562. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11563. { Make sure the aligns get stripped too }
  11564. hp1 := tai(hp_lblxxx.Previous);
  11565. while Assigned(hp1) and (hp1.typ = ait_align) do
  11566. begin
  11567. hp_lblxxx := hp1;
  11568. hp1 := tai(hp_lblxxx.Previous);
  11569. end;
  11570. StripLabelFast(hp_lblxxx);
  11571. { remove jmp }
  11572. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11573. RemoveInstruction(hp_jump);
  11574. { As before, now we can safely decrement it }
  11575. TAsmLabel(symbol).decrefs;
  11576. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11577. if TAsmLabel(symbol).getrefs = 0 then
  11578. begin
  11579. { Make sure the aligns get stripped too }
  11580. hp1 := tai(hp_lblyyy.Previous);
  11581. while Assigned(hp1) and (hp1.typ = ait_align) do
  11582. begin
  11583. hp_lblyyy := hp1;
  11584. hp1 := tai(hp_lblyyy.Previous);
  11585. end;
  11586. StripLabelFast(hp_lblyyy);
  11587. end;
  11588. if Assigned(p) then
  11589. result := True;
  11590. exit;
  11591. end;
  11592. end;
  11593. end;
  11594. {$endif i8086}
  11595. end;
  11596. end;
  11597. end;
  11598. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11599. var
  11600. hp1,hp2,hp3: tai;
  11601. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11602. NewSize: TOpSize;
  11603. NewRegSize: TSubRegister;
  11604. Limit: TCgInt;
  11605. SwapOper: POper;
  11606. begin
  11607. result:=false;
  11608. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11609. GetNextInstruction(p,hp1) and
  11610. (hp1.typ = ait_instruction);
  11611. if reg_and_hp1_is_instr and
  11612. (
  11613. (taicpu(hp1).opcode <> A_LEA) or
  11614. { If the LEA instruction can be converted into an arithmetic instruction,
  11615. it may be possible to then fold it. }
  11616. (
  11617. { If the flags register is in use, don't change the instruction
  11618. to an ADD otherwise this will scramble the flags. [Kit] }
  11619. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11620. ConvertLEA(taicpu(hp1))
  11621. )
  11622. ) and
  11623. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11624. GetNextInstruction(hp1,hp2) and
  11625. MatchInstruction(hp2,A_MOV,[]) and
  11626. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11627. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11628. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11629. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11630. {$ifdef i386}
  11631. { not all registers have byte size sub registers on i386 }
  11632. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11633. {$endif i386}
  11634. (((taicpu(hp1).ops=2) and
  11635. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11636. ((taicpu(hp1).ops=1) and
  11637. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11638. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11639. begin
  11640. { change movsX/movzX reg/ref, reg2
  11641. add/sub/or/... reg3/$const, reg2
  11642. mov reg2 reg/ref
  11643. to add/sub/or/... reg3/$const, reg/ref }
  11644. { by example:
  11645. movswl %si,%eax movswl %si,%eax p
  11646. decl %eax addl %edx,%eax hp1
  11647. movw %ax,%si movw %ax,%si hp2
  11648. ->
  11649. movswl %si,%eax movswl %si,%eax p
  11650. decw %eax addw %edx,%eax hp1
  11651. movw %ax,%si movw %ax,%si hp2
  11652. }
  11653. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11654. {
  11655. ->
  11656. movswl %si,%eax movswl %si,%eax p
  11657. decw %si addw %dx,%si hp1
  11658. movw %ax,%si movw %ax,%si hp2
  11659. }
  11660. case taicpu(hp1).ops of
  11661. 1:
  11662. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11663. 2:
  11664. begin
  11665. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11666. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11667. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11668. end;
  11669. else
  11670. internalerror(2008042702);
  11671. end;
  11672. {
  11673. ->
  11674. decw %si addw %dx,%si p
  11675. }
  11676. DebugMsg(SPeepholeOptimization + 'var3',p);
  11677. RemoveCurrentP(p, hp1);
  11678. RemoveInstruction(hp2);
  11679. Result := True;
  11680. Exit;
  11681. end;
  11682. if reg_and_hp1_is_instr and
  11683. (taicpu(hp1).opcode = A_MOV) and
  11684. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11685. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11686. {$ifdef x86_64}
  11687. { check for implicit extension to 64 bit }
  11688. or
  11689. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11690. (taicpu(hp1).opsize=S_Q) and
  11691. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11692. )
  11693. {$endif x86_64}
  11694. )
  11695. then
  11696. begin
  11697. { change
  11698. movx %reg1,%reg2
  11699. mov %reg2,%reg3
  11700. dealloc %reg2
  11701. into
  11702. movx %reg,%reg3
  11703. }
  11704. TransferUsedRegs(TmpUsedRegs);
  11705. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11706. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11707. begin
  11708. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11709. {$ifdef x86_64}
  11710. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11711. (taicpu(hp1).opsize=S_Q) then
  11712. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11713. else
  11714. {$endif x86_64}
  11715. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11716. RemoveInstruction(hp1);
  11717. Result := True;
  11718. Exit;
  11719. end;
  11720. end;
  11721. if reg_and_hp1_is_instr and
  11722. ((taicpu(hp1).opcode=A_MOV) or
  11723. (taicpu(hp1).opcode=A_ADD) or
  11724. (taicpu(hp1).opcode=A_SUB) or
  11725. (taicpu(hp1).opcode=A_CMP) or
  11726. (taicpu(hp1).opcode=A_OR) or
  11727. (taicpu(hp1).opcode=A_XOR) or
  11728. (taicpu(hp1).opcode=A_AND)
  11729. ) and
  11730. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11731. begin
  11732. AndTest := (taicpu(hp1).opcode=A_AND) and
  11733. GetNextInstruction(hp1, hp2) and
  11734. (hp2.typ = ait_instruction) and
  11735. (
  11736. (
  11737. (taicpu(hp2).opcode=A_TEST) and
  11738. (
  11739. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11740. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11741. (
  11742. { If the AND and TEST instructions share a constant, this is also valid }
  11743. (taicpu(hp1).oper[0]^.typ = top_const) and
  11744. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11745. )
  11746. ) and
  11747. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11748. ) or
  11749. (
  11750. (taicpu(hp2).opcode=A_CMP) and
  11751. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11752. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11753. )
  11754. );
  11755. { change
  11756. movx (oper),%reg2
  11757. and $x,%reg2
  11758. test %reg2,%reg2
  11759. dealloc %reg2
  11760. into
  11761. op %reg1,%reg3
  11762. if the second op accesses only the bits stored in reg1
  11763. }
  11764. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11765. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11766. (taicpu(hp1).oper[0]^.typ = top_const) and
  11767. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11768. AndTest then
  11769. begin
  11770. { Check if the AND constant is in range }
  11771. case taicpu(p).opsize of
  11772. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11773. begin
  11774. NewSize := S_B;
  11775. Limit := $FF;
  11776. end;
  11777. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11778. begin
  11779. NewSize := S_W;
  11780. Limit := $FFFF;
  11781. end;
  11782. {$ifdef x86_64}
  11783. S_LQ:
  11784. begin
  11785. NewSize := S_L;
  11786. Limit := $FFFFFFFF;
  11787. end;
  11788. {$endif x86_64}
  11789. else
  11790. InternalError(2021120303);
  11791. end;
  11792. if (
  11793. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11794. { Check for negative operands }
  11795. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11796. ) and
  11797. GetNextInstruction(hp2,hp3) and
  11798. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11799. (taicpu(hp3).condition in [C_E,C_NE]) then
  11800. begin
  11801. TransferUsedRegs(TmpUsedRegs);
  11802. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11803. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11804. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11805. begin
  11806. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11807. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11808. taicpu(hp1).opcode := A_TEST;
  11809. taicpu(hp1).opsize := NewSize;
  11810. RemoveInstruction(hp2);
  11811. RemoveCurrentP(p, hp1);
  11812. Result:=true;
  11813. exit;
  11814. end;
  11815. end;
  11816. end;
  11817. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11818. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11819. (taicpu(hp1).opsize=S_B)) or
  11820. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11821. (taicpu(hp1).opsize=S_W))
  11822. {$ifdef x86_64}
  11823. or ((taicpu(p).opsize=S_LQ) and
  11824. (taicpu(hp1).opsize=S_L))
  11825. {$endif x86_64}
  11826. ) and
  11827. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11828. begin
  11829. { change
  11830. movx %reg1,%reg2
  11831. op %reg2,%reg3
  11832. dealloc %reg2
  11833. into
  11834. op %reg1,%reg3
  11835. if the second op accesses only the bits stored in reg1
  11836. }
  11837. TransferUsedRegs(TmpUsedRegs);
  11838. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11839. if AndTest then
  11840. begin
  11841. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11842. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11843. end
  11844. else
  11845. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11846. if not RegUsed then
  11847. begin
  11848. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11849. if taicpu(p).oper[0]^.typ=top_reg then
  11850. begin
  11851. case taicpu(hp1).opsize of
  11852. S_B:
  11853. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11854. S_W:
  11855. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11856. S_L:
  11857. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11858. else
  11859. Internalerror(2020102301);
  11860. end;
  11861. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11862. end
  11863. else
  11864. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11865. RemoveCurrentP(p);
  11866. if AndTest then
  11867. RemoveInstruction(hp2);
  11868. result:=true;
  11869. exit;
  11870. end;
  11871. end
  11872. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11873. (
  11874. { Bitwise operations only }
  11875. (taicpu(hp1).opcode=A_AND) or
  11876. (taicpu(hp1).opcode=A_TEST) or
  11877. (
  11878. (taicpu(hp1).oper[0]^.typ = top_const) and
  11879. (
  11880. (taicpu(hp1).opcode=A_OR) or
  11881. (taicpu(hp1).opcode=A_XOR)
  11882. )
  11883. )
  11884. ) and
  11885. (
  11886. (taicpu(hp1).oper[0]^.typ = top_const) or
  11887. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11888. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11889. ) then
  11890. begin
  11891. { change
  11892. movx %reg2,%reg2
  11893. op const,%reg2
  11894. into
  11895. op const,%reg2 (smaller version)
  11896. movx %reg2,%reg2
  11897. also change
  11898. movx %reg1,%reg2
  11899. and/test (oper),%reg2
  11900. dealloc %reg2
  11901. into
  11902. and/test (oper),%reg1
  11903. }
  11904. case taicpu(p).opsize of
  11905. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11906. begin
  11907. NewSize := S_B;
  11908. NewRegSize := R_SUBL;
  11909. Limit := $FF;
  11910. end;
  11911. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11912. begin
  11913. NewSize := S_W;
  11914. NewRegSize := R_SUBW;
  11915. Limit := $FFFF;
  11916. end;
  11917. {$ifdef x86_64}
  11918. S_LQ:
  11919. begin
  11920. NewSize := S_L;
  11921. NewRegSize := R_SUBD;
  11922. Limit := $FFFFFFFF;
  11923. end;
  11924. {$endif x86_64}
  11925. else
  11926. Internalerror(2021120302);
  11927. end;
  11928. TransferUsedRegs(TmpUsedRegs);
  11929. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11930. if AndTest then
  11931. begin
  11932. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11933. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11934. end
  11935. else
  11936. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11937. if
  11938. (
  11939. (taicpu(p).opcode = A_MOVZX) and
  11940. (
  11941. (taicpu(hp1).opcode=A_AND) or
  11942. (taicpu(hp1).opcode=A_TEST)
  11943. ) and
  11944. not (
  11945. { If both are references, then the final instruction will have
  11946. both operands as references, which is not allowed }
  11947. (taicpu(p).oper[0]^.typ = top_ref) and
  11948. (taicpu(hp1).oper[0]^.typ = top_ref)
  11949. ) and
  11950. not RegUsed
  11951. ) or
  11952. (
  11953. (
  11954. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11955. not RegUsed
  11956. ) and
  11957. (taicpu(p).oper[0]^.typ = top_reg) and
  11958. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11959. (taicpu(hp1).oper[0]^.typ = top_const) and
  11960. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11961. ) then
  11962. begin
  11963. {$if defined(i386) or defined(i8086)}
  11964. { If the target size is 8-bit, make sure we can actually encode it }
  11965. 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
  11966. Exit;
  11967. {$endif i386 or i8086}
  11968. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11969. taicpu(hp1).opsize := NewSize;
  11970. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11971. if AndTest then
  11972. begin
  11973. RemoveInstruction(hp2);
  11974. if not RegUsed then
  11975. begin
  11976. taicpu(hp1).opcode := A_TEST;
  11977. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11978. begin
  11979. { Make sure the reference is the second operand }
  11980. SwapOper := taicpu(hp1).oper[0];
  11981. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11982. taicpu(hp1).oper[1] := SwapOper;
  11983. end;
  11984. end;
  11985. end;
  11986. case taicpu(hp1).oper[0]^.typ of
  11987. top_reg:
  11988. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11989. top_const:
  11990. { For the AND/TEST case }
  11991. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11992. else
  11993. ;
  11994. end;
  11995. if RegUsed then
  11996. begin
  11997. AsmL.Remove(p);
  11998. AsmL.InsertAfter(p, hp1);
  11999. p := hp1;
  12000. end
  12001. else
  12002. RemoveCurrentP(p, hp1);
  12003. result:=true;
  12004. exit;
  12005. end;
  12006. end;
  12007. end;
  12008. if reg_and_hp1_is_instr and
  12009. (taicpu(p).oper[0]^.typ = top_reg) and
  12010. (
  12011. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12012. ) and
  12013. (taicpu(hp1).oper[0]^.typ = top_const) and
  12014. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12015. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12016. { Minimum shift value allowed is the bit difference between the sizes }
  12017. (taicpu(hp1).oper[0]^.val >=
  12018. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12019. 8 * (
  12020. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12021. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12022. )
  12023. ) then
  12024. begin
  12025. { For:
  12026. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12027. shl/sal ##, %reg1
  12028. Remove the movsx/movzx instruction if the shift overwrites the
  12029. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12030. }
  12031. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12032. RemoveCurrentP(p, hp1);
  12033. Result := True;
  12034. Exit;
  12035. end
  12036. else if reg_and_hp1_is_instr and
  12037. (taicpu(p).oper[0]^.typ = top_reg) and
  12038. (
  12039. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12040. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12041. ) and
  12042. (taicpu(hp1).oper[0]^.typ = top_const) and
  12043. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12044. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12045. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12046. (taicpu(hp1).oper[0]^.val <
  12047. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12048. 8 * (
  12049. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12050. )
  12051. ) then
  12052. begin
  12053. { For:
  12054. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12055. sar ##, %reg1 shr ##, %reg1
  12056. Move the shift to before the movx instruction if the shift value
  12057. is not too large.
  12058. }
  12059. asml.Remove(hp1);
  12060. asml.InsertBefore(hp1, p);
  12061. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12062. case taicpu(p).opsize of
  12063. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12064. taicpu(hp1).opsize := S_B;
  12065. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12066. taicpu(hp1).opsize := S_W;
  12067. {$ifdef x86_64}
  12068. S_LQ:
  12069. taicpu(hp1).opsize := S_L;
  12070. {$endif}
  12071. else
  12072. InternalError(2020112401);
  12073. end;
  12074. if (taicpu(hp1).opcode = A_SHR) then
  12075. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12076. else
  12077. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12078. Result := True;
  12079. end;
  12080. if reg_and_hp1_is_instr and
  12081. (taicpu(p).oper[0]^.typ = top_reg) and
  12082. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12083. (
  12084. (taicpu(hp1).opcode = taicpu(p).opcode)
  12085. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12086. {$ifdef x86_64}
  12087. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12088. {$endif x86_64}
  12089. ) then
  12090. begin
  12091. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12092. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12093. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12094. begin
  12095. {
  12096. For example:
  12097. movzbw %al,%ax
  12098. movzwl %ax,%eax
  12099. Compress into:
  12100. movzbl %al,%eax
  12101. }
  12102. RegUsed := False;
  12103. case taicpu(p).opsize of
  12104. S_BW:
  12105. case taicpu(hp1).opsize of
  12106. S_WL:
  12107. begin
  12108. taicpu(p).opsize := S_BL;
  12109. RegUsed := True;
  12110. end;
  12111. {$ifdef x86_64}
  12112. S_WQ:
  12113. begin
  12114. if taicpu(p).opcode = A_MOVZX then
  12115. begin
  12116. taicpu(p).opsize := S_BL;
  12117. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12118. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12119. end
  12120. else
  12121. taicpu(p).opsize := S_BQ;
  12122. RegUsed := True;
  12123. end;
  12124. {$endif x86_64}
  12125. else
  12126. ;
  12127. end;
  12128. {$ifdef x86_64}
  12129. S_BL:
  12130. case taicpu(hp1).opsize of
  12131. S_LQ:
  12132. begin
  12133. if taicpu(p).opcode = A_MOVZX then
  12134. begin
  12135. taicpu(p).opsize := S_BL;
  12136. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12137. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12138. end
  12139. else
  12140. taicpu(p).opsize := S_BQ;
  12141. RegUsed := True;
  12142. end;
  12143. else
  12144. ;
  12145. end;
  12146. S_WL:
  12147. case taicpu(hp1).opsize of
  12148. S_LQ:
  12149. begin
  12150. if taicpu(p).opcode = A_MOVZX then
  12151. begin
  12152. taicpu(p).opsize := S_WL;
  12153. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12154. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12155. end
  12156. else
  12157. taicpu(p).opsize := S_WQ;
  12158. RegUsed := True;
  12159. end;
  12160. else
  12161. ;
  12162. end;
  12163. {$endif x86_64}
  12164. else
  12165. ;
  12166. end;
  12167. if RegUsed then
  12168. begin
  12169. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12170. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12171. RemoveInstruction(hp1);
  12172. Result := True;
  12173. Exit;
  12174. end;
  12175. end;
  12176. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12177. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12178. GetNextInstruction(hp1, hp2) and
  12179. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12180. (
  12181. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12182. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12183. {$ifdef x86_64}
  12184. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12185. {$endif x86_64}
  12186. ) and
  12187. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12188. (
  12189. (
  12190. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12191. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12192. ) or
  12193. (
  12194. { Only allow the operands in reverse order for TEST instructions }
  12195. (taicpu(hp2).opcode = A_TEST) and
  12196. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12197. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12198. )
  12199. ) then
  12200. begin
  12201. {
  12202. For example:
  12203. movzbl %al,%eax
  12204. movzbl (ref),%edx
  12205. andl %edx,%eax
  12206. (%edx deallocated)
  12207. Change to:
  12208. andb (ref),%al
  12209. movzbl %al,%eax
  12210. Rules are:
  12211. - First two instructions have the same opcode and opsize
  12212. - First instruction's operands are the same super-register
  12213. - Second instruction operates on a different register
  12214. - Third instruction is AND, OR, XOR or TEST
  12215. - Third instruction's operands are the destination registers of the first two instructions
  12216. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12217. - Second instruction's destination register is deallocated afterwards
  12218. }
  12219. TransferUsedRegs(TmpUsedRegs);
  12220. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12221. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12222. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12223. begin
  12224. case taicpu(p).opsize of
  12225. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12226. NewSize := S_B;
  12227. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12228. NewSize := S_W;
  12229. {$ifdef x86_64}
  12230. S_LQ:
  12231. NewSize := S_L;
  12232. {$endif x86_64}
  12233. else
  12234. InternalError(2021120301);
  12235. end;
  12236. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12237. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12238. taicpu(hp2).opsize := NewSize;
  12239. RemoveInstruction(hp1);
  12240. { With TEST, it's best to keep the MOVX instruction at the top }
  12241. if (taicpu(hp2).opcode <> A_TEST) then
  12242. begin
  12243. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12244. asml.Remove(p);
  12245. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12246. asml.InsertAfter(p, hp2);
  12247. p := hp2;
  12248. end
  12249. else
  12250. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12251. Result := True;
  12252. Exit;
  12253. end;
  12254. end;
  12255. end;
  12256. if taicpu(p).opcode=A_MOVZX then
  12257. begin
  12258. { removes superfluous And's after movzx's }
  12259. if reg_and_hp1_is_instr and
  12260. (taicpu(hp1).opcode = A_AND) and
  12261. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12262. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12263. {$ifdef x86_64}
  12264. { check for implicit extension to 64 bit }
  12265. or
  12266. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12267. (taicpu(hp1).opsize=S_Q) and
  12268. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12269. )
  12270. {$endif x86_64}
  12271. )
  12272. then
  12273. begin
  12274. case taicpu(p).opsize Of
  12275. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12276. if (taicpu(hp1).oper[0]^.val = $ff) then
  12277. begin
  12278. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12279. RemoveInstruction(hp1);
  12280. Result:=true;
  12281. exit;
  12282. end;
  12283. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12284. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12285. begin
  12286. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12287. RemoveInstruction(hp1);
  12288. Result:=true;
  12289. exit;
  12290. end;
  12291. {$ifdef x86_64}
  12292. S_LQ:
  12293. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12294. begin
  12295. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12296. RemoveInstruction(hp1);
  12297. Result:=true;
  12298. exit;
  12299. end;
  12300. {$endif x86_64}
  12301. else
  12302. ;
  12303. end;
  12304. { we cannot get rid of the and, but can we get rid of the movz ?}
  12305. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12306. begin
  12307. case taicpu(p).opsize Of
  12308. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12309. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12310. begin
  12311. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12312. RemoveCurrentP(p,hp1);
  12313. Result:=true;
  12314. exit;
  12315. end;
  12316. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12317. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12318. begin
  12319. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12320. RemoveCurrentP(p,hp1);
  12321. Result:=true;
  12322. exit;
  12323. end;
  12324. {$ifdef x86_64}
  12325. S_LQ:
  12326. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12327. begin
  12328. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12329. RemoveCurrentP(p,hp1);
  12330. Result:=true;
  12331. exit;
  12332. end;
  12333. {$endif x86_64}
  12334. else
  12335. ;
  12336. end;
  12337. end;
  12338. end;
  12339. { changes some movzx constructs to faster synonyms (all examples
  12340. are given with eax/ax, but are also valid for other registers)}
  12341. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12342. begin
  12343. case taicpu(p).opsize of
  12344. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12345. (the machine code is equivalent to movzbl %al,%eax), but the
  12346. code generator still generates that assembler instruction and
  12347. it is silently converted. This should probably be checked.
  12348. [Kit] }
  12349. S_BW:
  12350. begin
  12351. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12352. (
  12353. not IsMOVZXAcceptable
  12354. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12355. or (
  12356. (cs_opt_size in current_settings.optimizerswitches) and
  12357. (taicpu(p).oper[1]^.reg = NR_AX)
  12358. )
  12359. ) then
  12360. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12361. begin
  12362. DebugMsg(SPeepholeOptimization + 'var7',p);
  12363. taicpu(p).opcode := A_AND;
  12364. taicpu(p).changeopsize(S_W);
  12365. taicpu(p).loadConst(0,$ff);
  12366. Result := True;
  12367. end
  12368. else if not IsMOVZXAcceptable and
  12369. GetNextInstruction(p, hp1) and
  12370. (tai(hp1).typ = ait_instruction) and
  12371. (taicpu(hp1).opcode = A_AND) and
  12372. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12373. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12374. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12375. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12376. begin
  12377. DebugMsg(SPeepholeOptimization + 'var8',p);
  12378. taicpu(p).opcode := A_MOV;
  12379. taicpu(p).changeopsize(S_W);
  12380. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12381. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12382. Result := True;
  12383. end;
  12384. end;
  12385. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12386. S_BL:
  12387. if not IsMOVZXAcceptable then
  12388. begin
  12389. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12390. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12391. begin
  12392. DebugMsg(SPeepholeOptimization + 'var9',p);
  12393. taicpu(p).opcode := A_AND;
  12394. taicpu(p).changeopsize(S_L);
  12395. taicpu(p).loadConst(0,$ff);
  12396. Result := True;
  12397. end
  12398. else if GetNextInstruction(p, hp1) and
  12399. (tai(hp1).typ = ait_instruction) and
  12400. (taicpu(hp1).opcode = A_AND) and
  12401. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12402. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12403. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12404. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12405. begin
  12406. DebugMsg(SPeepholeOptimization + 'var10',p);
  12407. taicpu(p).opcode := A_MOV;
  12408. taicpu(p).changeopsize(S_L);
  12409. { do not use R_SUBWHOLE
  12410. as movl %rdx,%eax
  12411. is invalid in assembler PM }
  12412. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12413. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12414. Result := True;
  12415. end;
  12416. end;
  12417. {$endif i8086}
  12418. S_WL:
  12419. if not IsMOVZXAcceptable then
  12420. begin
  12421. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12422. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12423. begin
  12424. DebugMsg(SPeepholeOptimization + 'var11',p);
  12425. taicpu(p).opcode := A_AND;
  12426. taicpu(p).changeopsize(S_L);
  12427. taicpu(p).loadConst(0,$ffff);
  12428. Result := True;
  12429. end
  12430. else if GetNextInstruction(p, hp1) and
  12431. (tai(hp1).typ = ait_instruction) and
  12432. (taicpu(hp1).opcode = A_AND) and
  12433. (taicpu(hp1).oper[0]^.typ = top_const) and
  12434. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12435. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12436. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12437. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12438. begin
  12439. DebugMsg(SPeepholeOptimization + 'var12',p);
  12440. taicpu(p).opcode := A_MOV;
  12441. taicpu(p).changeopsize(S_L);
  12442. { do not use R_SUBWHOLE
  12443. as movl %rdx,%eax
  12444. is invalid in assembler PM }
  12445. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12446. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12447. Result := True;
  12448. end;
  12449. end;
  12450. else
  12451. InternalError(2017050705);
  12452. end;
  12453. end
  12454. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12455. begin
  12456. if GetNextInstruction(p, hp1) and
  12457. (tai(hp1).typ = ait_instruction) and
  12458. (taicpu(hp1).opcode = A_AND) and
  12459. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12460. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12461. begin
  12462. //taicpu(p).opcode := A_MOV;
  12463. case taicpu(p).opsize Of
  12464. S_BL:
  12465. begin
  12466. DebugMsg(SPeepholeOptimization + 'var13',p);
  12467. taicpu(hp1).changeopsize(S_L);
  12468. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12469. end;
  12470. S_WL:
  12471. begin
  12472. DebugMsg(SPeepholeOptimization + 'var14',p);
  12473. taicpu(hp1).changeopsize(S_L);
  12474. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12475. end;
  12476. S_BW:
  12477. begin
  12478. DebugMsg(SPeepholeOptimization + 'var15',p);
  12479. taicpu(hp1).changeopsize(S_W);
  12480. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12481. end;
  12482. else
  12483. Internalerror(2017050704)
  12484. end;
  12485. Result := True;
  12486. end;
  12487. end;
  12488. end;
  12489. end;
  12490. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12491. var
  12492. hp1, hp2 : tai;
  12493. MaskLength : Cardinal;
  12494. MaskedBits : TCgInt;
  12495. ActiveReg : TRegister;
  12496. begin
  12497. Result:=false;
  12498. { There are no optimisations for reference targets }
  12499. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12500. Exit;
  12501. while GetNextInstruction(p, hp1) and
  12502. (hp1.typ = ait_instruction) do
  12503. begin
  12504. if (taicpu(p).oper[0]^.typ = top_const) then
  12505. begin
  12506. case taicpu(hp1).opcode of
  12507. A_AND:
  12508. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12509. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12510. { the second register must contain the first one, so compare their subreg types }
  12511. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12512. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12513. { change
  12514. and const1, reg
  12515. and const2, reg
  12516. to
  12517. and (const1 and const2), reg
  12518. }
  12519. begin
  12520. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12521. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12522. RemoveCurrentP(p, hp1);
  12523. Result:=true;
  12524. exit;
  12525. end;
  12526. A_CMP:
  12527. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12528. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12529. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12530. { Just check that the condition on the next instruction is compatible }
  12531. GetNextInstruction(hp1, hp2) and
  12532. (hp2.typ = ait_instruction) and
  12533. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12534. then
  12535. { change
  12536. and 2^n, reg
  12537. cmp 2^n, reg
  12538. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12539. to
  12540. and 2^n, reg
  12541. test reg, reg
  12542. j(~c) / set(~c) / cmov(~c)
  12543. }
  12544. begin
  12545. { Keep TEST instruction in, rather than remove it, because
  12546. it may trigger other optimisations such as MovAndTest2Test }
  12547. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12548. taicpu(hp1).opcode := A_TEST;
  12549. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12550. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12551. Result := True;
  12552. Exit;
  12553. end
  12554. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12555. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12556. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12557. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12558. { change
  12559. and $ff/$ff/$ffff, reg
  12560. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12561. dealloc reg
  12562. to
  12563. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12564. }
  12565. begin
  12566. TransferUsedRegs(TmpUsedRegs);
  12567. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12568. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12569. begin
  12570. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12571. case taicpu(p).oper[0]^.val of
  12572. $ff:
  12573. begin
  12574. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12575. taicpu(hp1).opsize:=S_B;
  12576. end;
  12577. $ffff:
  12578. begin
  12579. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12580. taicpu(hp1).opsize:=S_W;
  12581. end;
  12582. $ffffffff:
  12583. begin
  12584. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12585. taicpu(hp1).opsize:=S_L;
  12586. end;
  12587. else
  12588. Internalerror(2023030401);
  12589. end;
  12590. RemoveCurrentP(p);
  12591. Result := True;
  12592. Exit;
  12593. end;
  12594. end;
  12595. A_MOVZX:
  12596. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12597. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12598. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12599. (
  12600. (
  12601. (taicpu(p).opsize=S_W) and
  12602. (taicpu(hp1).opsize=S_BW)
  12603. ) or
  12604. (
  12605. (taicpu(p).opsize=S_L) and
  12606. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12607. )
  12608. {$ifdef x86_64}
  12609. or
  12610. (
  12611. (taicpu(p).opsize=S_Q) and
  12612. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12613. )
  12614. {$endif x86_64}
  12615. ) then
  12616. begin
  12617. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12618. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12619. ) or
  12620. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12621. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12622. then
  12623. begin
  12624. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12625. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12626. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12627. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12628. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12629. }
  12630. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12631. RemoveInstruction(hp1);
  12632. { See if there are other optimisations possible }
  12633. Continue;
  12634. end;
  12635. end;
  12636. A_SHL:
  12637. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12638. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12639. begin
  12640. {$ifopt R+}
  12641. {$define RANGE_WAS_ON}
  12642. {$R-}
  12643. {$endif}
  12644. { get length of potential and mask }
  12645. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12646. { really a mask? }
  12647. {$ifdef RANGE_WAS_ON}
  12648. {$R+}
  12649. {$endif}
  12650. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12651. { unmasked part shifted out? }
  12652. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12653. begin
  12654. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12655. RemoveCurrentP(p, hp1);
  12656. Result:=true;
  12657. exit;
  12658. end;
  12659. end;
  12660. A_SHR:
  12661. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12662. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12663. (taicpu(hp1).oper[0]^.val <= 63) then
  12664. begin
  12665. { Does SHR combined with the AND cover all the bits?
  12666. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12667. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12668. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12669. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12670. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12671. begin
  12672. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12673. RemoveCurrentP(p, hp1);
  12674. Result := True;
  12675. Exit;
  12676. end;
  12677. end;
  12678. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12679. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12680. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12681. begin
  12682. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12683. (
  12684. (
  12685. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12686. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12687. ) or (
  12688. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12689. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12690. {$ifdef x86_64}
  12691. ) or (
  12692. (taicpu(hp1).opsize = S_LQ) and
  12693. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12694. {$endif x86_64}
  12695. )
  12696. ) then
  12697. begin
  12698. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12699. begin
  12700. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12701. RemoveInstruction(hp1);
  12702. { See if there are other optimisations possible }
  12703. Continue;
  12704. end;
  12705. { The super-registers are the same though.
  12706. Note that this change by itself doesn't improve
  12707. code speed, but it opens up other optimisations. }
  12708. {$ifdef x86_64}
  12709. { Convert 64-bit register to 32-bit }
  12710. case taicpu(hp1).opsize of
  12711. S_BQ:
  12712. begin
  12713. taicpu(hp1).opsize := S_BL;
  12714. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12715. end;
  12716. S_WQ:
  12717. begin
  12718. taicpu(hp1).opsize := S_WL;
  12719. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12720. end
  12721. else
  12722. ;
  12723. end;
  12724. {$endif x86_64}
  12725. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12726. taicpu(hp1).opcode := A_MOVZX;
  12727. { See if there are other optimisations possible }
  12728. Continue;
  12729. end;
  12730. end;
  12731. else
  12732. ;
  12733. end;
  12734. end
  12735. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12736. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12737. begin
  12738. {$ifdef x86_64}
  12739. if (taicpu(p).opsize = S_Q) then
  12740. begin
  12741. { Never necessary }
  12742. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12743. RemoveCurrentP(p, hp1);
  12744. Result := True;
  12745. Exit;
  12746. end;
  12747. {$endif x86_64}
  12748. { Forward check to determine necessity of and %reg,%reg }
  12749. TransferUsedRegs(TmpUsedRegs);
  12750. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12751. { Saves on a bunch of dereferences }
  12752. ActiveReg := taicpu(p).oper[1]^.reg;
  12753. case taicpu(hp1).opcode of
  12754. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12755. if (
  12756. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12757. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12758. ) and
  12759. (
  12760. (taicpu(hp1).opcode <> A_MOV) or
  12761. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12762. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12763. ) and
  12764. not (
  12765. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12766. (taicpu(hp1).opcode = A_MOV) and
  12767. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12768. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12769. ) and
  12770. (
  12771. (
  12772. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12773. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12774. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12775. ) or
  12776. (
  12777. {$ifdef x86_64}
  12778. (
  12779. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12780. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12781. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12782. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12783. ) and
  12784. {$endif x86_64}
  12785. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12786. )
  12787. ) then
  12788. begin
  12789. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12790. RemoveCurrentP(p, hp1);
  12791. Result := True;
  12792. Exit;
  12793. end;
  12794. A_ADD,
  12795. A_AND,
  12796. A_BSF,
  12797. A_BSR,
  12798. A_BTC,
  12799. A_BTR,
  12800. A_BTS,
  12801. A_OR,
  12802. A_SUB,
  12803. A_XOR:
  12804. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12805. if (
  12806. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12807. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12808. ) and
  12809. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12810. begin
  12811. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12812. RemoveCurrentP(p, hp1);
  12813. Result := True;
  12814. Exit;
  12815. end;
  12816. A_CMP,
  12817. A_TEST:
  12818. if (
  12819. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12820. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12821. ) and
  12822. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12823. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12824. begin
  12825. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12826. RemoveCurrentP(p, hp1);
  12827. Result := True;
  12828. Exit;
  12829. end;
  12830. A_BSWAP,
  12831. A_NEG,
  12832. A_NOT:
  12833. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12834. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12835. begin
  12836. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12837. RemoveCurrentP(p, hp1);
  12838. Result := True;
  12839. Exit;
  12840. end;
  12841. else
  12842. ;
  12843. end;
  12844. end;
  12845. if (taicpu(hp1).is_jmp) and
  12846. (taicpu(hp1).opcode<>A_JMP) and
  12847. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12848. begin
  12849. { change
  12850. and x, reg
  12851. jxx
  12852. to
  12853. test x, reg
  12854. jxx
  12855. if reg is deallocated before the
  12856. jump, but only if it's a conditional jump (PFV)
  12857. }
  12858. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12859. taicpu(p).opcode := A_TEST;
  12860. Exit;
  12861. end;
  12862. Break;
  12863. end;
  12864. { Lone AND tests }
  12865. if (taicpu(p).oper[0]^.typ = top_const) then
  12866. begin
  12867. {
  12868. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12869. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12870. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12871. }
  12872. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12873. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12874. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12875. begin
  12876. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12877. if taicpu(p).opsize = S_L then
  12878. begin
  12879. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12880. Result := True;
  12881. end;
  12882. end;
  12883. end;
  12884. { Backward check to determine necessity of and %reg,%reg }
  12885. if (taicpu(p).oper[0]^.typ = top_reg) and
  12886. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12887. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12888. GetLastInstruction(p, hp2) and
  12889. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12890. { Check size of adjacent instruction to determine if the AND is
  12891. effectively a null operation }
  12892. (
  12893. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12894. { Note: Don't include S_Q }
  12895. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12896. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12897. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12898. ) then
  12899. begin
  12900. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12901. { If GetNextInstruction returned False, hp1 will be nil }
  12902. RemoveCurrentP(p, hp1);
  12903. Result := True;
  12904. Exit;
  12905. end;
  12906. end;
  12907. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12908. var
  12909. hp1, hp2: tai;
  12910. NewRef: TReference;
  12911. Distance: Cardinal;
  12912. TempTracking: TAllUsedRegs;
  12913. { This entire nested function is used in an if-statement below, but we
  12914. want to avoid all the used reg transfers and GetNextInstruction calls
  12915. until we really have to check }
  12916. function MemRegisterNotUsedLater: Boolean; inline;
  12917. var
  12918. hp2: tai;
  12919. begin
  12920. TransferUsedRegs(TmpUsedRegs);
  12921. hp2 := p;
  12922. repeat
  12923. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12924. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12925. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12926. end;
  12927. begin
  12928. Result := False;
  12929. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12930. (taicpu(p).oper[1]^.typ = top_reg) then
  12931. begin
  12932. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12933. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12934. (hp1.typ <> ait_instruction) or
  12935. not
  12936. (
  12937. (cs_opt_level3 in current_settings.optimizerswitches) or
  12938. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12939. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12940. ) then
  12941. Exit;
  12942. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12943. addq $x, %rax
  12944. movq %rax, %rdx
  12945. sarq $63, %rdx
  12946. (%rax still in use)
  12947. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12948. leaq $x(%rax),%rdx
  12949. addq $x, %rax
  12950. sarq $63, %rdx
  12951. ...which is okay since it breaks the dependency chain between
  12952. addq and movq, but if OptPass2MOV is called first:
  12953. addq $x, %rax
  12954. cqto
  12955. ...which is better in all ways, taking only 2 cycles to execute
  12956. and much smaller in code size.
  12957. }
  12958. { The extra register tracking is quite strenuous }
  12959. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12960. MatchInstruction(hp1, A_MOV, []) then
  12961. begin
  12962. { Update the register tracking to the MOV instruction }
  12963. CopyUsedRegs(TempTracking);
  12964. hp2 := p;
  12965. repeat
  12966. UpdateUsedRegs(tai(hp2.Next));
  12967. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12968. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12969. OptPass2ADD get called again }
  12970. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12971. begin
  12972. { Reset the tracking to the current instruction }
  12973. RestoreUsedRegs(TempTracking);
  12974. ReleaseUsedRegs(TempTracking);
  12975. Result := True;
  12976. Exit;
  12977. end;
  12978. { Reset the tracking to the current instruction }
  12979. RestoreUsedRegs(TempTracking);
  12980. ReleaseUsedRegs(TempTracking);
  12981. { If OptPass2MOV returned True, we don't need to set Result to
  12982. True if hp1 didn't change because the ADD instruction didn't
  12983. get modified and we'll be evaluating hp1 again when the
  12984. peephole optimizer reaches it }
  12985. end;
  12986. { Change:
  12987. add %reg2,%reg1
  12988. (%reg2 not modified in between)
  12989. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12990. To:
  12991. mov/s/z #(%reg1,%reg2),%reg1
  12992. }
  12993. if (taicpu(p).oper[0]^.typ = top_reg) and
  12994. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12995. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12996. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12997. (
  12998. (
  12999. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13000. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13001. { r/esp cannot be an index }
  13002. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13003. ) or (
  13004. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13005. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13006. )
  13007. ) and (
  13008. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13009. (
  13010. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13011. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13012. MemRegisterNotUsedLater
  13013. )
  13014. ) then
  13015. begin
  13016. if (
  13017. { Instructions are guaranteed to be adjacent on -O2 and under }
  13018. (cs_opt_level3 in current_settings.optimizerswitches) and
  13019. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13020. ) then
  13021. begin
  13022. { If the other register is used in between, move the MOV
  13023. instruction to right after the ADD instruction so a
  13024. saving can still be made }
  13025. Asml.Remove(hp1);
  13026. Asml.InsertAfter(hp1, p);
  13027. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13028. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13029. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13030. RemoveCurrentp(p, hp1);
  13031. end
  13032. else
  13033. begin
  13034. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13035. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13036. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13037. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13038. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13039. { hp1 may not be the immediate next instruction under -O3 }
  13040. RemoveCurrentp(p)
  13041. else
  13042. RemoveCurrentp(p, hp1);
  13043. end;
  13044. Result := True;
  13045. Exit;
  13046. end;
  13047. { Change:
  13048. addl/q $x,%reg1
  13049. movl/q %reg1,%reg2
  13050. To:
  13051. leal/q $x(%reg1),%reg2
  13052. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13053. Breaks the dependency chain.
  13054. }
  13055. if (taicpu(p).oper[0]^.typ = top_const) and
  13056. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13057. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13058. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13059. (
  13060. { Instructions are guaranteed to be adjacent on -O2 and under }
  13061. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13062. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13063. ) then
  13064. begin
  13065. TransferUsedRegs(TmpUsedRegs);
  13066. hp2 := p;
  13067. repeat
  13068. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13069. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13070. if (
  13071. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13072. not (cs_opt_size in current_settings.optimizerswitches) or
  13073. (
  13074. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13075. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13076. )
  13077. ) then
  13078. begin
  13079. { Change the MOV instruction to a LEA instruction, and update the
  13080. first operand }
  13081. reference_reset(NewRef, 1, []);
  13082. NewRef.base := taicpu(p).oper[1]^.reg;
  13083. NewRef.scalefactor := 1;
  13084. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13085. taicpu(hp1).opcode := A_LEA;
  13086. taicpu(hp1).loadref(0, NewRef);
  13087. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13088. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13089. begin
  13090. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13091. { Move what is now the LEA instruction to before the ADD instruction }
  13092. Asml.Remove(hp1);
  13093. Asml.InsertBefore(hp1, p);
  13094. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13095. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13096. p := hp1;
  13097. end
  13098. else
  13099. begin
  13100. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13101. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13102. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13103. { hp1 may not be the immediate next instruction under -O3 }
  13104. RemoveCurrentp(p)
  13105. else
  13106. RemoveCurrentp(p, hp1);
  13107. end;
  13108. Result := True;
  13109. end;
  13110. end;
  13111. end;
  13112. end;
  13113. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13114. var
  13115. SubReg: TSubRegister;
  13116. begin
  13117. Result:=false;
  13118. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13119. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13120. with taicpu(p).oper[0]^.ref^ do
  13121. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13122. begin
  13123. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13124. begin
  13125. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13126. taicpu(p).opcode := A_ADD;
  13127. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13128. Result := True;
  13129. end
  13130. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13131. begin
  13132. if (base <> NR_NO) then
  13133. begin
  13134. if (scalefactor <= 1) then
  13135. begin
  13136. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13137. taicpu(p).opcode := A_ADD;
  13138. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13139. Result := True;
  13140. end;
  13141. end
  13142. else
  13143. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13144. if (scalefactor in [2, 4, 8]) then
  13145. begin
  13146. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13147. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13148. taicpu(p).opcode := A_SHL;
  13149. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13150. Result := True;
  13151. end;
  13152. end;
  13153. end;
  13154. end;
  13155. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13156. var
  13157. hp1, hp2: tai;
  13158. NewRef: TReference;
  13159. Distance: Cardinal;
  13160. TempTracking: TAllUsedRegs;
  13161. begin
  13162. Result := False;
  13163. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13164. MatchOpType(taicpu(p),top_const,top_reg) then
  13165. begin
  13166. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13167. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13168. (hp1.typ <> ait_instruction) or
  13169. not
  13170. (
  13171. (cs_opt_level3 in current_settings.optimizerswitches) or
  13172. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13173. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13174. ) then
  13175. Exit;
  13176. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13177. subq $x, %rax
  13178. movq %rax, %rdx
  13179. sarq $63, %rdx
  13180. (%rax still in use)
  13181. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13182. leaq $-x(%rax),%rdx
  13183. movq $x, %rax
  13184. sarq $63, %rdx
  13185. ...which is okay since it breaks the dependency chain between
  13186. subq and movq, but if OptPass2MOV is called first:
  13187. subq $x, %rax
  13188. cqto
  13189. ...which is better in all ways, taking only 2 cycles to execute
  13190. and much smaller in code size.
  13191. }
  13192. { The extra register tracking is quite strenuous }
  13193. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13194. MatchInstruction(hp1, A_MOV, []) then
  13195. begin
  13196. { Update the register tracking to the MOV instruction }
  13197. CopyUsedRegs(TempTracking);
  13198. hp2 := p;
  13199. repeat
  13200. UpdateUsedRegs(tai(hp2.Next));
  13201. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13202. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13203. OptPass2SUB get called again }
  13204. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13205. begin
  13206. { Reset the tracking to the current instruction }
  13207. RestoreUsedRegs(TempTracking);
  13208. ReleaseUsedRegs(TempTracking);
  13209. Result := True;
  13210. Exit;
  13211. end;
  13212. { Reset the tracking to the current instruction }
  13213. RestoreUsedRegs(TempTracking);
  13214. ReleaseUsedRegs(TempTracking);
  13215. { If OptPass2MOV returned True, we don't need to set Result to
  13216. True if hp1 didn't change because the SUB instruction didn't
  13217. get modified and we'll be evaluating hp1 again when the
  13218. peephole optimizer reaches it }
  13219. end;
  13220. { Change:
  13221. subl/q $x,%reg1
  13222. movl/q %reg1,%reg2
  13223. To:
  13224. leal/q $-x(%reg1),%reg2
  13225. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13226. Breaks the dependency chain and potentially permits the removal of
  13227. a CMP instruction if one follows.
  13228. }
  13229. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13230. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13231. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13232. (
  13233. { Instructions are guaranteed to be adjacent on -O2 and under }
  13234. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13235. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13236. ) then
  13237. begin
  13238. TransferUsedRegs(TmpUsedRegs);
  13239. hp2 := p;
  13240. repeat
  13241. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13242. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13243. if (
  13244. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13245. not (cs_opt_size in current_settings.optimizerswitches) or
  13246. (
  13247. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13248. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13249. )
  13250. ) then
  13251. begin
  13252. { Change the MOV instruction to a LEA instruction, and update the
  13253. first operand }
  13254. reference_reset(NewRef, 1, []);
  13255. NewRef.base := taicpu(p).oper[1]^.reg;
  13256. NewRef.scalefactor := 1;
  13257. NewRef.offset := -taicpu(p).oper[0]^.val;
  13258. taicpu(hp1).opcode := A_LEA;
  13259. taicpu(hp1).loadref(0, NewRef);
  13260. TransferUsedRegs(TmpUsedRegs);
  13261. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13262. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13263. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13264. begin
  13265. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13266. { Move what is now the LEA instruction to before the SUB instruction }
  13267. Asml.Remove(hp1);
  13268. Asml.InsertBefore(hp1, p);
  13269. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13270. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13271. p := hp1;
  13272. end
  13273. else
  13274. begin
  13275. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13276. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13277. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13278. { hp1 may not be the immediate next instruction under -O3 }
  13279. RemoveCurrentp(p)
  13280. else
  13281. RemoveCurrentp(p, hp1);
  13282. end;
  13283. Result := True;
  13284. end;
  13285. end;
  13286. end;
  13287. end;
  13288. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13289. begin
  13290. { we can skip all instructions not messing with the stack pointer }
  13291. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13292. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13293. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13294. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13295. ({(taicpu(hp1).ops=0) or }
  13296. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13297. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13298. ) and }
  13299. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13300. )
  13301. ) do
  13302. GetNextInstruction(hp1,hp1);
  13303. Result:=assigned(hp1);
  13304. end;
  13305. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13306. var
  13307. hp1, hp2, hp3, hp4, hp5: tai;
  13308. begin
  13309. Result:=false;
  13310. hp5:=nil;
  13311. { replace
  13312. leal(q) x(<stackpointer>),<stackpointer>
  13313. call procname
  13314. leal(q) -x(<stackpointer>),<stackpointer>
  13315. ret
  13316. by
  13317. jmp procname
  13318. but do it only on level 4 because it destroys stack back traces
  13319. }
  13320. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13321. MatchOpType(taicpu(p),top_ref,top_reg) and
  13322. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13323. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13324. { the -8 or -24 are not required, but bail out early if possible,
  13325. higher values are unlikely }
  13326. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13327. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13328. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13329. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13330. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13331. GetNextInstruction(p, hp1) and
  13332. { Take a copy of hp1 }
  13333. SetAndTest(hp1, hp4) and
  13334. { trick to skip label }
  13335. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13336. SkipSimpleInstructions(hp1) and
  13337. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13338. GetNextInstruction(hp1, hp2) and
  13339. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13340. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13341. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13342. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13343. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13344. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13345. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13346. { Segment register will be NR_NO }
  13347. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13348. GetNextInstruction(hp2, hp3) and
  13349. { trick to skip label }
  13350. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13351. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13352. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13353. SetAndTest(hp3,hp5) and
  13354. GetNextInstruction(hp3,hp3) and
  13355. MatchInstruction(hp3,A_RET,[S_NO])
  13356. )
  13357. ) and
  13358. (taicpu(hp3).ops=0) then
  13359. begin
  13360. taicpu(hp1).opcode := A_JMP;
  13361. taicpu(hp1).is_jmp := true;
  13362. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13363. RemoveCurrentP(p, hp4);
  13364. RemoveInstruction(hp2);
  13365. RemoveInstruction(hp3);
  13366. if Assigned(hp5) then
  13367. begin
  13368. AsmL.Remove(hp5);
  13369. ASmL.InsertBefore(hp5,hp1)
  13370. end;
  13371. Result:=true;
  13372. end;
  13373. end;
  13374. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13375. {$ifdef x86_64}
  13376. var
  13377. hp1, hp2, hp3, hp4, hp5: tai;
  13378. {$endif x86_64}
  13379. begin
  13380. Result:=false;
  13381. {$ifdef x86_64}
  13382. hp5:=nil;
  13383. { replace
  13384. push %rax
  13385. call procname
  13386. pop %rcx
  13387. ret
  13388. by
  13389. jmp procname
  13390. but do it only on level 4 because it destroys stack back traces
  13391. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13392. for all supported calling conventions
  13393. }
  13394. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13395. MatchOpType(taicpu(p),top_reg) and
  13396. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13397. GetNextInstruction(p, hp1) and
  13398. { Take a copy of hp1 }
  13399. SetAndTest(hp1, hp4) and
  13400. { trick to skip label }
  13401. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13402. SkipSimpleInstructions(hp1) and
  13403. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13404. GetNextInstruction(hp1, hp2) and
  13405. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13406. MatchOpType(taicpu(hp2),top_reg) and
  13407. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13408. GetNextInstruction(hp2, hp3) and
  13409. { trick to skip label }
  13410. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13411. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13412. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13413. SetAndTest(hp3,hp5) and
  13414. GetNextInstruction(hp3,hp3) and
  13415. MatchInstruction(hp3,A_RET,[S_NO])
  13416. )
  13417. ) and
  13418. (taicpu(hp3).ops=0) then
  13419. begin
  13420. taicpu(hp1).opcode := A_JMP;
  13421. taicpu(hp1).is_jmp := true;
  13422. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13423. RemoveCurrentP(p, hp4);
  13424. RemoveInstruction(hp2);
  13425. RemoveInstruction(hp3);
  13426. if Assigned(hp5) then
  13427. begin
  13428. AsmL.Remove(hp5);
  13429. ASmL.InsertBefore(hp5,hp1)
  13430. end;
  13431. Result:=true;
  13432. end;
  13433. {$endif x86_64}
  13434. end;
  13435. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13436. var
  13437. Value, RegName: string;
  13438. begin
  13439. Result:=false;
  13440. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13441. begin
  13442. case taicpu(p).oper[0]^.val of
  13443. 0:
  13444. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13445. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13446. begin
  13447. { change "mov $0,%reg" into "xor %reg,%reg" }
  13448. taicpu(p).opcode := A_XOR;
  13449. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13450. Result := True;
  13451. {$ifdef x86_64}
  13452. end
  13453. else if (taicpu(p).opsize = S_Q) then
  13454. begin
  13455. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13456. { The actual optimization }
  13457. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13458. taicpu(p).changeopsize(S_L);
  13459. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13460. Result := True;
  13461. end;
  13462. $1..$FFFFFFFF:
  13463. begin
  13464. { Code size reduction by J. Gareth "Kit" Moreton }
  13465. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13466. case taicpu(p).opsize of
  13467. S_Q:
  13468. begin
  13469. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13470. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13471. { The actual optimization }
  13472. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13473. taicpu(p).changeopsize(S_L);
  13474. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13475. Result := True;
  13476. end;
  13477. else
  13478. { Do nothing };
  13479. end;
  13480. {$endif x86_64}
  13481. end;
  13482. -1:
  13483. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13484. if (cs_opt_size in current_settings.optimizerswitches) and
  13485. (taicpu(p).opsize <> S_B) and
  13486. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13487. begin
  13488. { change "mov $-1,%reg" into "or $-1,%reg" }
  13489. { NOTES:
  13490. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13491. - This operation creates a false dependency on the register, so only do it when optimising for size
  13492. - 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
  13493. }
  13494. taicpu(p).opcode := A_OR;
  13495. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13496. Result := True;
  13497. end;
  13498. else
  13499. { Do nothing };
  13500. end;
  13501. end;
  13502. end;
  13503. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13504. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13505. begin
  13506. Result := False;
  13507. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13508. Exit;
  13509. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13510. so don't bother optimising }
  13511. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13512. Exit;
  13513. if (taicpu(p).oper[0]^.typ <> top_const) or
  13514. { If the value can fit into an 8-bit signed integer, a smaller
  13515. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13516. falls within this range }
  13517. (
  13518. (taicpu(p).oper[0]^.val > -128) and
  13519. (taicpu(p).oper[0]^.val <= 127)
  13520. ) then
  13521. Exit;
  13522. { If we're optimising for size, this is acceptable }
  13523. if (cs_opt_size in current_settings.optimizerswitches) then
  13524. Exit(True);
  13525. if (taicpu(p).oper[1]^.typ = top_reg) and
  13526. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13527. Exit(True);
  13528. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13529. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13530. Exit(True);
  13531. end;
  13532. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13533. var
  13534. hp1: tai;
  13535. Value: TCGInt;
  13536. begin
  13537. Result := False;
  13538. if MatchOpType(taicpu(p), top_const, top_reg) then
  13539. begin
  13540. { Detect:
  13541. andw x, %ax (0 <= x < $8000)
  13542. ...
  13543. movzwl %ax,%eax
  13544. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13545. }
  13546. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13547. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13548. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13549. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13550. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13551. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13552. begin
  13553. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13554. taicpu(hp1).opcode := A_CWDE;
  13555. taicpu(hp1).clearop(0);
  13556. taicpu(hp1).clearop(1);
  13557. taicpu(hp1).ops := 0;
  13558. { A change was made, but not with p, so don't set Result, but
  13559. notify the compiler that a change was made }
  13560. Include(OptsToCheck, aoc_ForceNewIteration);
  13561. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13562. end;
  13563. end;
  13564. { If "not x" is a power of 2 (popcnt = 1), change:
  13565. and $x, %reg/ref
  13566. To:
  13567. btr lb(x), %reg/ref
  13568. }
  13569. if IsBTXAcceptable(p) and
  13570. (
  13571. { Make sure a TEST doesn't follow that plays with the register }
  13572. not GetNextInstruction(p, hp1) or
  13573. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13574. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13575. ) then
  13576. begin
  13577. {$push}{$R-}{$Q-}
  13578. { Value is a sign-extended 32-bit integer - just correct it
  13579. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13580. checks to see if this operand is an immediate. }
  13581. Value := not taicpu(p).oper[0]^.val;
  13582. {$pop}
  13583. {$ifdef x86_64}
  13584. if taicpu(p).opsize = S_L then
  13585. {$endif x86_64}
  13586. Value := Value and $FFFFFFFF;
  13587. if (PopCnt(QWord(Value)) = 1) then
  13588. begin
  13589. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13590. taicpu(p).opcode := A_BTR;
  13591. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13592. Result := True;
  13593. Exit;
  13594. end;
  13595. end;
  13596. end;
  13597. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13598. begin
  13599. Result := False;
  13600. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13601. Exit;
  13602. { Convert:
  13603. movswl %ax,%eax -> cwtl
  13604. movslq %eax,%rax -> cdqe
  13605. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13606. refer to the same opcode and depends only on the assembler's
  13607. current operand-size attribute. [Kit]
  13608. }
  13609. with taicpu(p) do
  13610. case opsize of
  13611. S_WL:
  13612. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13613. begin
  13614. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13615. opcode := A_CWDE;
  13616. clearop(0);
  13617. clearop(1);
  13618. ops := 0;
  13619. Result := True;
  13620. end;
  13621. {$ifdef x86_64}
  13622. S_LQ:
  13623. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13624. begin
  13625. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13626. opcode := A_CDQE;
  13627. clearop(0);
  13628. clearop(1);
  13629. ops := 0;
  13630. Result := True;
  13631. end;
  13632. {$endif x86_64}
  13633. else
  13634. ;
  13635. end;
  13636. end;
  13637. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13638. var
  13639. hp1, hp2: tai;
  13640. IdentityMask, Shift: TCGInt;
  13641. LimitSize: Topsize;
  13642. DoNotMerge: Boolean;
  13643. begin
  13644. Result := False;
  13645. { All these optimisations work on "shr const,%reg" }
  13646. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13647. Exit;
  13648. DoNotMerge := False;
  13649. Shift := taicpu(p).oper[0]^.val;
  13650. LimitSize := taicpu(p).opsize;
  13651. hp1 := p;
  13652. repeat
  13653. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13654. Break;
  13655. { Detect:
  13656. shr x, %reg
  13657. and y, %reg
  13658. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13659. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13660. }
  13661. case taicpu(hp1).opcode of
  13662. A_AND:
  13663. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13664. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13665. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13666. begin
  13667. { Make sure the FLAGS register isn't in use }
  13668. TransferUsedRegs(TmpUsedRegs);
  13669. hp2 := p;
  13670. repeat
  13671. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13672. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13673. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13674. begin
  13675. { Generate the identity mask }
  13676. case taicpu(p).opsize of
  13677. S_B:
  13678. IdentityMask := $FF shr Shift;
  13679. S_W:
  13680. IdentityMask := $FFFF shr Shift;
  13681. S_L:
  13682. IdentityMask := $FFFFFFFF shr Shift;
  13683. {$ifdef x86_64}
  13684. S_Q:
  13685. { We need to force the operands to be unsigned 64-bit
  13686. integers otherwise the wrong value is generated }
  13687. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13688. {$endif x86_64}
  13689. else
  13690. InternalError(2022081501);
  13691. end;
  13692. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13693. begin
  13694. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13695. { All the possible 1 bits are covered, so we can remove the AND }
  13696. hp2 := tai(hp1.Previous);
  13697. RemoveInstruction(hp1);
  13698. { p wasn't actually changed, so don't set Result to True,
  13699. but a change was nonetheless made elsewhere }
  13700. Include(OptsToCheck, aoc_ForceNewIteration);
  13701. { Do another pass in case other AND or MOVZX instructions
  13702. follow }
  13703. hp1 := hp2;
  13704. Continue;
  13705. end;
  13706. end;
  13707. end;
  13708. A_TEST, A_CMP, A_Jcc:
  13709. { Skip over conditional jumps and relevant comparisons }
  13710. Continue;
  13711. A_MOVZX:
  13712. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13713. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13714. begin
  13715. { Since the original register is being read as is, subsequent
  13716. SHRs must not be merged at this point }
  13717. DoNotMerge := True;
  13718. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13719. begin
  13720. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13721. begin
  13722. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13723. { All the possible 1 bits are covered, so we can remove the AND }
  13724. hp2 := tai(hp1.Previous);
  13725. RemoveInstruction(hp1);
  13726. hp1 := hp2;
  13727. end
  13728. else { Different register target }
  13729. begin
  13730. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13731. taicpu(hp1).opcode := A_MOV;
  13732. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13733. case taicpu(hp1).opsize of
  13734. S_BW:
  13735. taicpu(hp1).opsize := S_W;
  13736. S_BL, S_WL:
  13737. taicpu(hp1).opsize := S_L;
  13738. else
  13739. InternalError(2022081503);
  13740. end;
  13741. end;
  13742. end
  13743. else if (Shift > 0) and
  13744. (taicpu(p).opsize = S_W) and
  13745. (taicpu(hp1).opsize = S_WL) and
  13746. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13747. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13748. begin
  13749. { Detect:
  13750. shr x, %ax (x > 0)
  13751. ...
  13752. movzwl %ax,%eax
  13753. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13754. }
  13755. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13756. taicpu(hp1).opcode := A_CWDE;
  13757. taicpu(hp1).clearop(0);
  13758. taicpu(hp1).clearop(1);
  13759. taicpu(hp1).ops := 0;
  13760. end;
  13761. { Move onto the next instruction }
  13762. Continue;
  13763. end;
  13764. A_SHL, A_SAL, A_SHR:
  13765. if (taicpu(hp1).opsize <= LimitSize) and
  13766. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13767. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13768. begin
  13769. { Make sure the sizes don't exceed the register size limit
  13770. (measured by the shift value falling below the limit) }
  13771. if taicpu(hp1).opsize < LimitSize then
  13772. LimitSize := taicpu(hp1).opsize;
  13773. if taicpu(hp1).opcode = A_SHR then
  13774. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13775. else
  13776. begin
  13777. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13778. DoNotMerge := True;
  13779. end;
  13780. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13781. Break;
  13782. { Since we've established that the combined shift is within
  13783. limits, we can actually combine the adjacent SHR
  13784. instructions even if they're different sizes }
  13785. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13786. begin
  13787. hp2 := tai(hp1.Previous);
  13788. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13789. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13790. RemoveInstruction(hp1);
  13791. hp1 := hp2;
  13792. end;
  13793. { Move onto the next instruction }
  13794. Continue;
  13795. end;
  13796. else
  13797. ;
  13798. end;
  13799. Break;
  13800. until False;
  13801. { Detect the following (looking backwards):
  13802. shr %cl,%reg
  13803. shr x, %reg
  13804. Swap the two SHR instructions to minimise a pipeline stall.
  13805. }
  13806. if GetLastInstruction(p, hp1) and
  13807. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13808. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13809. { First operand will be %cl }
  13810. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13811. { Just to be sure }
  13812. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13813. begin
  13814. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13815. { Moving the entries this way ensures the register tracking remains correct }
  13816. Asml.Remove(p);
  13817. Asml.InsertBefore(p, hp1);
  13818. p := hp1;
  13819. { Don't set Result to True because the current instruction is now
  13820. "shr %cl,%reg" and there's nothing more we can do with it }
  13821. end;
  13822. end;
  13823. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13824. var
  13825. hp1, hp2: tai;
  13826. Opposite, SecondOpposite: TAsmOp;
  13827. NewCond: TAsmCond;
  13828. begin
  13829. Result := False;
  13830. { Change:
  13831. add/sub 128,(dest)
  13832. To:
  13833. sub/add -128,(dest)
  13834. This generaally takes fewer bytes to encode because -128 can be stored
  13835. in a signed byte, whereas +128 cannot.
  13836. }
  13837. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13838. begin
  13839. if taicpu(p).opcode = A_ADD then
  13840. Opposite := A_SUB
  13841. else
  13842. Opposite := A_ADD;
  13843. { Be careful if the flags are in use, because the CF flag inverts
  13844. when changing from ADD to SUB and vice versa }
  13845. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13846. GetNextInstruction(p, hp1) then
  13847. begin
  13848. TransferUsedRegs(TmpUsedRegs);
  13849. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13850. hp2 := hp1;
  13851. { Scan ahead to check if everything's safe }
  13852. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13853. begin
  13854. if (hp1.typ <> ait_instruction) then
  13855. { Probably unsafe since the flags are still in use }
  13856. Exit;
  13857. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13858. { Stop searching at an unconditional jump }
  13859. Break;
  13860. if not
  13861. (
  13862. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13863. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13864. ) and
  13865. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13866. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13867. Exit;
  13868. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13869. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13870. { Move to the next instruction }
  13871. GetNextInstruction(hp1, hp1);
  13872. end;
  13873. while Assigned(hp2) and (hp2 <> hp1) do
  13874. begin
  13875. NewCond := C_None;
  13876. case taicpu(hp2).condition of
  13877. C_A, C_NBE:
  13878. NewCond := C_BE;
  13879. C_B, C_C, C_NAE:
  13880. NewCond := C_AE;
  13881. C_AE, C_NB, C_NC:
  13882. NewCond := C_B;
  13883. C_BE, C_NA:
  13884. NewCond := C_A;
  13885. else
  13886. { No change needed };
  13887. end;
  13888. if NewCond <> C_None then
  13889. begin
  13890. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13891. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13892. taicpu(hp2).condition := NewCond;
  13893. end
  13894. else
  13895. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13896. begin
  13897. { Because of the flipping of the carry bit, to ensure
  13898. the operation remains equivalent, ADC becomes SBB
  13899. and vice versa, and the constant is not-inverted.
  13900. If multiple ADCs or SBBs appear in a row, each one
  13901. changed causes the carry bit to invert, so they all
  13902. need to be flipped }
  13903. if taicpu(hp2).opcode = A_ADC then
  13904. SecondOpposite := A_SBB
  13905. else
  13906. SecondOpposite := A_ADC;
  13907. if taicpu(hp2).oper[0]^.typ <> top_const then
  13908. { Should have broken out of this optimisation already }
  13909. InternalError(2021112901);
  13910. 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]^) + ' -> ' +
  13911. 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);
  13912. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13913. taicpu(hp2).opcode := SecondOpposite;
  13914. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13915. end;
  13916. { Move to the next instruction }
  13917. GetNextInstruction(hp2, hp2);
  13918. end;
  13919. if (hp2 <> hp1) then
  13920. InternalError(2021111501);
  13921. end;
  13922. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13923. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13924. taicpu(p).opcode := Opposite;
  13925. taicpu(p).oper[0]^.val := -128;
  13926. { No further optimisations can be made on this instruction, so move
  13927. onto the next one to save time }
  13928. p := tai(p.Next);
  13929. UpdateUsedRegs(p);
  13930. Result := True;
  13931. Exit;
  13932. end;
  13933. { Detect:
  13934. add/sub %reg2,(dest)
  13935. add/sub x, (dest)
  13936. (dest can be a register or a reference)
  13937. Swap the instructions to minimise a pipeline stall. This reverses the
  13938. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13939. optimisations could be made.
  13940. }
  13941. if (taicpu(p).oper[0]^.typ = top_reg) and
  13942. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13943. (
  13944. (
  13945. (taicpu(p).oper[1]^.typ = top_reg) and
  13946. { We can try searching further ahead if we're writing to a register }
  13947. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13948. ) or
  13949. (
  13950. (taicpu(p).oper[1]^.typ = top_ref) and
  13951. GetNextInstruction(p, hp1)
  13952. )
  13953. ) and
  13954. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13955. (taicpu(hp1).oper[0]^.typ = top_const) and
  13956. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13957. begin
  13958. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13959. TransferUsedRegs(TmpUsedRegs);
  13960. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13961. hp2 := p;
  13962. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13963. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13964. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13965. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13966. begin
  13967. asml.remove(hp1);
  13968. asml.InsertBefore(hp1, p);
  13969. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13970. Result := True;
  13971. end;
  13972. end;
  13973. end;
  13974. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13975. var
  13976. hp1: tai;
  13977. begin
  13978. Result:=false;
  13979. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13980. while GetNextInstruction(p, hp1) and
  13981. TrySwapMovCmp(p, hp1) do
  13982. begin
  13983. if MatchInstruction(hp1, A_MOV, []) then
  13984. begin
  13985. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13986. begin
  13987. { A little hacky, but since CMP doesn't read the flags, only
  13988. modify them, it's safe if they get scrambled by MOV -> XOR }
  13989. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13990. Result := PostPeepholeOptMov(hp1);
  13991. {$ifdef x86_64}
  13992. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13993. { Used to shrink instruction size }
  13994. PostPeepholeOptXor(hp1);
  13995. {$endif x86_64}
  13996. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13997. end
  13998. else
  13999. begin
  14000. Result := PostPeepholeOptMov(hp1);
  14001. {$ifdef x86_64}
  14002. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14003. { Used to shrink instruction size }
  14004. PostPeepholeOptXor(hp1);
  14005. {$endif x86_64}
  14006. end;
  14007. end;
  14008. { Enabling this flag is actually a null operation, but it marks
  14009. the code as 'modified' during this pass }
  14010. Include(OptsToCheck, aoc_ForceNewIteration);
  14011. end;
  14012. { change "cmp $0, %reg" to "test %reg, %reg" }
  14013. if MatchOpType(taicpu(p),top_const,top_reg) and
  14014. (taicpu(p).oper[0]^.val = 0) then
  14015. begin
  14016. taicpu(p).opcode := A_TEST;
  14017. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14018. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14019. Result:=true;
  14020. end;
  14021. end;
  14022. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14023. var
  14024. IsTestConstX, IsValid : Boolean;
  14025. hp1,hp2 : tai;
  14026. begin
  14027. Result:=false;
  14028. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14029. if (taicpu(p).opcode = A_TEST) then
  14030. while GetNextInstruction(p, hp1) and
  14031. TrySwapMovCmp(p, hp1) do
  14032. begin
  14033. if MatchInstruction(hp1, A_MOV, []) then
  14034. begin
  14035. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14036. begin
  14037. { A little hacky, but since TEST doesn't read the flags, only
  14038. modify them, it's safe if they get scrambled by MOV -> XOR }
  14039. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14040. Result := PostPeepholeOptMov(hp1);
  14041. {$ifdef x86_64}
  14042. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14043. { Used to shrink instruction size }
  14044. PostPeepholeOptXor(hp1);
  14045. {$endif x86_64}
  14046. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14047. end
  14048. else
  14049. begin
  14050. Result := PostPeepholeOptMov(hp1);
  14051. {$ifdef x86_64}
  14052. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14053. { Used to shrink instruction size }
  14054. PostPeepholeOptXor(hp1);
  14055. {$endif x86_64}
  14056. end;
  14057. end;
  14058. { Enabling this flag is actually a null operation, but it marks
  14059. the code as 'modified' during this pass }
  14060. Include(OptsToCheck, aoc_ForceNewIteration);
  14061. end;
  14062. { If x is a power of 2 (popcnt = 1), change:
  14063. or $x, %reg/ref
  14064. To:
  14065. bts lb(x), %reg/ref
  14066. }
  14067. if (taicpu(p).opcode = A_OR) and
  14068. IsBTXAcceptable(p) and
  14069. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14070. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14071. (
  14072. { Don't optimise if a test instruction follows }
  14073. not GetNextInstruction(p, hp1) or
  14074. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14075. ) then
  14076. begin
  14077. 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);
  14078. taicpu(p).opcode := A_BTS;
  14079. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14080. Result := True;
  14081. Exit;
  14082. end;
  14083. { If x is a power of 2 (popcnt = 1), change:
  14084. test $x, %reg/ref
  14085. je / sete / cmove (or jne / setne)
  14086. To:
  14087. bt lb(x), %reg/ref
  14088. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14089. }
  14090. if (taicpu(p).opcode = A_TEST) and
  14091. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14092. (taicpu(p).oper[0]^.typ = top_const) and
  14093. (
  14094. (cs_opt_size in current_settings.optimizerswitches) or
  14095. (
  14096. (taicpu(p).oper[1]^.typ = top_reg) and
  14097. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14098. ) or
  14099. (
  14100. (taicpu(p).oper[1]^.typ <> top_reg) and
  14101. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14102. )
  14103. ) and
  14104. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14105. { For sizes less than S_L, the byte size is equal or larger with BT,
  14106. so don't bother optimising }
  14107. (taicpu(p).opsize >= S_L) then
  14108. begin
  14109. IsValid := True;
  14110. { Check the next set of instructions, watching the FLAGS register
  14111. and the conditions used }
  14112. TransferUsedRegs(TmpUsedRegs);
  14113. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14114. hp1 := p;
  14115. hp2 := nil;
  14116. while GetNextInstruction(hp1, hp1) do
  14117. begin
  14118. if not Assigned(hp2) then
  14119. { The first instruction after TEST }
  14120. hp2 := hp1;
  14121. if (hp1.typ <> ait_instruction) then
  14122. begin
  14123. { If the flags are no longer in use, everything is fine }
  14124. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14125. IsValid := False;
  14126. Break;
  14127. end;
  14128. case taicpu(hp1).condition of
  14129. C_None:
  14130. begin
  14131. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14132. { Something is not quite normal, so play safe and don't change }
  14133. IsValid := False;
  14134. Break;
  14135. end;
  14136. C_E, C_Z, C_NE, C_NZ:
  14137. { This is fine };
  14138. else
  14139. begin
  14140. { Unsupported condition }
  14141. IsValid := False;
  14142. Break;
  14143. end;
  14144. end;
  14145. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14146. end;
  14147. if IsValid then
  14148. begin
  14149. while hp2 <> hp1 do
  14150. begin
  14151. case taicpu(hp2).condition of
  14152. C_Z, C_E:
  14153. taicpu(hp2).condition := C_NC;
  14154. C_NZ, C_NE:
  14155. taicpu(hp2).condition := C_C;
  14156. else
  14157. { Should not get this by this point }
  14158. InternalError(2022110701);
  14159. end;
  14160. GetNextInstruction(hp2, hp2);
  14161. end;
  14162. 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);
  14163. taicpu(p).opcode := A_BT;
  14164. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14165. Result := True;
  14166. Exit;
  14167. end;
  14168. end;
  14169. { removes the line marked with (x) from the sequence
  14170. and/or/xor/add/sub/... $x, %y
  14171. test/or %y, %y | test $-1, %y (x)
  14172. j(n)z _Label
  14173. as the first instruction already adjusts the ZF
  14174. %y operand may also be a reference }
  14175. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14176. MatchOperand(taicpu(p).oper[0]^,-1);
  14177. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14178. GetLastInstruction(p, hp1) and
  14179. (tai(hp1).typ = ait_instruction) and
  14180. GetNextInstruction(p,hp2) and
  14181. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14182. case taicpu(hp1).opcode Of
  14183. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14184. { These two instructions set the zero flag if the result is zero }
  14185. A_POPCNT, A_LZCNT:
  14186. begin
  14187. if (
  14188. { With POPCNT, an input of zero will set the zero flag
  14189. because the population count of zero is zero }
  14190. (taicpu(hp1).opcode = A_POPCNT) and
  14191. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14192. (
  14193. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14194. { Faster than going through the second half of the 'or'
  14195. condition below }
  14196. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14197. )
  14198. ) or (
  14199. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14200. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14201. { and in case of carry for A(E)/B(E)/C/NC }
  14202. (
  14203. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14204. (
  14205. (taicpu(hp1).opcode <> A_ADD) and
  14206. (taicpu(hp1).opcode <> A_SUB) and
  14207. (taicpu(hp1).opcode <> A_LZCNT)
  14208. )
  14209. )
  14210. ) then
  14211. begin
  14212. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14213. RemoveCurrentP(p, hp2);
  14214. Result:=true;
  14215. Exit;
  14216. end;
  14217. end;
  14218. A_SHL, A_SAL, A_SHR, A_SAR:
  14219. begin
  14220. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14221. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14222. { therefore, it's only safe to do this optimization for }
  14223. { shifts by a (nonzero) constant }
  14224. (taicpu(hp1).oper[0]^.typ = top_const) and
  14225. (taicpu(hp1).oper[0]^.val <> 0) and
  14226. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14227. { and in case of carry for A(E)/B(E)/C/NC }
  14228. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14229. begin
  14230. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14231. RemoveCurrentP(p, hp2);
  14232. Result:=true;
  14233. Exit;
  14234. end;
  14235. end;
  14236. A_DEC, A_INC, A_NEG:
  14237. begin
  14238. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14239. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14240. { and in case of carry for A(E)/B(E)/C/NC }
  14241. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14242. begin
  14243. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14244. RemoveCurrentP(p, hp2);
  14245. Result:=true;
  14246. Exit;
  14247. end;
  14248. end;
  14249. A_ANDN, A_BZHI:
  14250. begin
  14251. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14252. { Only the zero and sign flags are consistent with what the result is }
  14253. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14254. begin
  14255. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14256. RemoveCurrentP(p, hp2);
  14257. Result:=true;
  14258. Exit;
  14259. end;
  14260. end;
  14261. A_BEXTR:
  14262. begin
  14263. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14264. { Only the zero flag is set }
  14265. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14266. begin
  14267. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14268. RemoveCurrentP(p, hp2);
  14269. Result:=true;
  14270. Exit;
  14271. end;
  14272. end;
  14273. else
  14274. ;
  14275. end; { case }
  14276. { change "test $-1,%reg" into "test %reg,%reg" }
  14277. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14278. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14279. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14280. if MatchInstruction(p, A_OR, []) and
  14281. { Can only match if they're both registers }
  14282. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14283. begin
  14284. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14285. taicpu(p).opcode := A_TEST;
  14286. { No need to set Result to True, as we've done all the optimisations we can }
  14287. end;
  14288. end;
  14289. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14290. var
  14291. hp1,hp3 : tai;
  14292. {$ifndef x86_64}
  14293. hp2 : taicpu;
  14294. {$endif x86_64}
  14295. begin
  14296. Result:=false;
  14297. hp3:=nil;
  14298. {$ifndef x86_64}
  14299. { don't do this on modern CPUs, this really hurts them due to
  14300. broken call/ret pairing }
  14301. if (current_settings.optimizecputype < cpu_Pentium2) and
  14302. not(cs_create_pic in current_settings.moduleswitches) and
  14303. GetNextInstruction(p, hp1) and
  14304. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14305. MatchOpType(taicpu(hp1),top_ref) and
  14306. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14307. begin
  14308. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14309. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14310. InsertLLItem(p.previous, p, hp2);
  14311. taicpu(p).opcode := A_JMP;
  14312. taicpu(p).is_jmp := true;
  14313. RemoveInstruction(hp1);
  14314. Result:=true;
  14315. end
  14316. else
  14317. {$endif x86_64}
  14318. { replace
  14319. call procname
  14320. ret
  14321. by
  14322. jmp procname
  14323. but do it only on level 4 because it destroys stack back traces
  14324. else if the subroutine is marked as no return, remove the ret
  14325. }
  14326. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14327. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14328. GetNextInstruction(p, hp1) and
  14329. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14330. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14331. SetAndTest(hp1,hp3) and
  14332. GetNextInstruction(hp1,hp1) and
  14333. MatchInstruction(hp1,A_RET,[S_NO])
  14334. )
  14335. ) and
  14336. (taicpu(hp1).ops=0) then
  14337. begin
  14338. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14339. { we might destroy stack alignment here if we do not do a call }
  14340. (target_info.stackalign<=sizeof(SizeUInt)) then
  14341. begin
  14342. taicpu(p).opcode := A_JMP;
  14343. taicpu(p).is_jmp := true;
  14344. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14345. end
  14346. else
  14347. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14348. RemoveInstruction(hp1);
  14349. if Assigned(hp3) then
  14350. begin
  14351. AsmL.Remove(hp3);
  14352. AsmL.InsertBefore(hp3,p)
  14353. end;
  14354. Result:=true;
  14355. end;
  14356. end;
  14357. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14358. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14359. begin
  14360. case OpSize of
  14361. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14362. Result := (Val <= $FF) and (Val >= -128);
  14363. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14364. Result := (Val <= $FFFF) and (Val >= -32768);
  14365. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14366. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14367. else
  14368. Result := True;
  14369. end;
  14370. end;
  14371. var
  14372. hp1, hp2 : tai;
  14373. SizeChange: Boolean;
  14374. PreMessage: string;
  14375. begin
  14376. Result := False;
  14377. if (taicpu(p).oper[0]^.typ = top_reg) and
  14378. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14379. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14380. begin
  14381. { Change (using movzbl %al,%eax as an example):
  14382. movzbl %al, %eax movzbl %al, %eax
  14383. cmpl x, %eax testl %eax,%eax
  14384. To:
  14385. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14386. movzbl %al, %eax movzbl %al, %eax
  14387. Smaller instruction and minimises pipeline stall as the CPU
  14388. doesn't have to wait for the register to get zero-extended. [Kit]
  14389. Also allow if the smaller of the two registers is being checked,
  14390. as this still removes the false dependency.
  14391. }
  14392. if
  14393. (
  14394. (
  14395. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14396. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14397. ) or (
  14398. { If MatchOperand returns True, they must both be registers }
  14399. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14400. )
  14401. ) and
  14402. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14403. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14404. begin
  14405. 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);
  14406. asml.Remove(hp1);
  14407. asml.InsertBefore(hp1, p);
  14408. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14409. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14410. begin
  14411. taicpu(hp1).opcode := A_TEST;
  14412. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14413. end;
  14414. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14415. case taicpu(p).opsize of
  14416. S_BW, S_BL:
  14417. begin
  14418. SizeChange := taicpu(hp1).opsize <> S_B;
  14419. taicpu(hp1).changeopsize(S_B);
  14420. end;
  14421. S_WL:
  14422. begin
  14423. SizeChange := taicpu(hp1).opsize <> S_W;
  14424. taicpu(hp1).changeopsize(S_W);
  14425. end
  14426. else
  14427. InternalError(2020112701);
  14428. end;
  14429. UpdateUsedRegs(tai(p.Next));
  14430. { Check if the register is used aferwards - if not, we can
  14431. remove the movzx instruction completely }
  14432. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14433. begin
  14434. { Hp1 is a better position than p for debugging purposes }
  14435. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14436. RemoveCurrentp(p, hp1);
  14437. Result := True;
  14438. end;
  14439. if SizeChange then
  14440. DebugMsg(SPeepholeOptimization + PreMessage +
  14441. 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)
  14442. else
  14443. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14444. Exit;
  14445. end;
  14446. { Change (using movzwl %ax,%eax as an example):
  14447. movzwl %ax, %eax
  14448. movb %al, (dest) (Register is smaller than read register in movz)
  14449. To:
  14450. movb %al, (dest) (Move one back to avoid a false dependency)
  14451. movzwl %ax, %eax
  14452. }
  14453. if (taicpu(hp1).opcode = A_MOV) and
  14454. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14455. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14456. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14457. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14458. begin
  14459. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14460. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14461. asml.Remove(hp1);
  14462. asml.InsertBefore(hp1, p);
  14463. if taicpu(hp1).oper[1]^.typ = top_reg then
  14464. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14465. { Check if the register is used aferwards - if not, we can
  14466. remove the movzx instruction completely }
  14467. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14468. begin
  14469. { Hp1 is a better position than p for debugging purposes }
  14470. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14471. RemoveCurrentp(p, hp1);
  14472. Result := True;
  14473. end;
  14474. Exit;
  14475. end;
  14476. end;
  14477. end;
  14478. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14479. var
  14480. hp1: tai;
  14481. {$ifdef x86_64}
  14482. PreMessage, RegName: string;
  14483. {$endif x86_64}
  14484. begin
  14485. Result := False;
  14486. { If x is a power of 2 (popcnt = 1), change:
  14487. xor $x, %reg/ref
  14488. To:
  14489. btc lb(x), %reg/ref
  14490. }
  14491. if IsBTXAcceptable(p) and
  14492. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14493. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14494. (
  14495. { Don't optimise if a test instruction follows }
  14496. not GetNextInstruction(p, hp1) or
  14497. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14498. ) then
  14499. begin
  14500. 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);
  14501. taicpu(p).opcode := A_BTC;
  14502. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14503. Result := True;
  14504. Exit;
  14505. end;
  14506. {$ifdef x86_64}
  14507. { Code size reduction by J. Gareth "Kit" Moreton }
  14508. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14509. as this removes the REX prefix }
  14510. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14511. Exit;
  14512. if taicpu(p).oper[0]^.typ <> top_reg then
  14513. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14514. InternalError(2018011500);
  14515. case taicpu(p).opsize of
  14516. S_Q:
  14517. begin
  14518. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14519. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14520. { The actual optimization }
  14521. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14522. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14523. taicpu(p).changeopsize(S_L);
  14524. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14525. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14526. end;
  14527. else
  14528. ;
  14529. end;
  14530. {$endif x86_64}
  14531. end;
  14532. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14533. var
  14534. XReg: TRegister;
  14535. begin
  14536. Result := False;
  14537. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14538. Smaller encoding and slightly faster on some platforms (also works for
  14539. ZMM-sized registers) }
  14540. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14541. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14542. begin
  14543. XReg := taicpu(p).oper[0]^.reg;
  14544. if (taicpu(p).oper[1]^.reg = XReg) then
  14545. begin
  14546. taicpu(p).changeopsize(S_XMM);
  14547. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14548. if (cs_opt_size in current_settings.optimizerswitches) then
  14549. begin
  14550. { Change input registers to %xmm0 to reduce size. Note that
  14551. there's a risk of a false dependency doing this, so only
  14552. optimise for size here }
  14553. XReg := NR_XMM0;
  14554. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14555. end
  14556. else
  14557. begin
  14558. setsubreg(XReg, R_SUBMMX);
  14559. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14560. end;
  14561. taicpu(p).oper[0]^.reg := XReg;
  14562. taicpu(p).oper[1]^.reg := XReg;
  14563. Result := True;
  14564. end;
  14565. end;
  14566. end;
  14567. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14568. var
  14569. OperIdx: Integer;
  14570. begin
  14571. for OperIdx := 0 to p.ops - 1 do
  14572. if p.oper[OperIdx]^.typ = top_ref then
  14573. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14574. end;
  14575. end.